Installations
npm install bybit-api-gnome
Developer Guide
Typescript
Yes
Module System
CommonJS
Node Version
14.18.0
NPM Version
8.19.2
Releases
v3.0.1: Complete integration for all REST API & WebSocket Groups
Published on 19 Sept 2022
Spot clients for REST & Websockets
Published on 15 Aug 2021
Reduced webpack bundle & missing inverse APIs.
Published on 12 Jun 2021
Inverse Futures Support
Published on 06 Mar 2021
Fix custom base URL parameter
Published on 18 Feb 2021
Linear USDT Support
Published on 16 Feb 2021
Contributors
Languages
TypeScript (98.88%)
JavaScript (1.12%)
Developer
Download Statistics
Total Downloads
498
Last Day
1
Last Week
4
Last Month
9
Last Year
140
GitHub Statistics
264 Stars
973 Commits
84 Forks
9 Watching
2 Branches
24 Contributors
Sponsor this package
Package Meta Information
Latest Version
3.3.2
Package Id
bybit-api-gnome@3.3.2
Unpacked Size
21.57 kB
Size
6.99 kB
File Count
4
NPM Version
8.19.2
Node Version
14.18.0
Total Downloads
Cumulative downloads
Total Downloads
498
Last day
0%
1
Compared to previous day
Last week
300%
4
Compared to previous week
Last month
-64%
9
Compared to previous month
Last year
-32.7%
140
Compared to previous year
Daily Downloads
Weekly Downloads
Monthly Downloads
Yearly Downloads
Node.js & Typescript Bybit API SDK
Node.js connector for the Bybit APIs and WebSockets:
- Complete integration with all bybit APIs.
- TypeScript support (with type declarations for most API requests & responses).
- Over 300 end-to-end tests making real API calls & WebSocket connections, validating any changes before they reach npm.
- Robust WebSocket integration with configurable connection heartbeats & automatic reconnect then resubscribe workflows.
- Browser support (via webpack bundle - see "Browser Usage" below).
Installation
npm install --save bybit-api
Issues & Discussion
- Issues? Check the issues tab.
- Discuss & collaborate with other node devs? Join our Node.js Algo Traders engineering community on telegram.
Related projects
Check out my related projects:
- Try my connectors:
- Try my misc utilities:
- Check out my examples:
Documentation
Most methods accept JS objects. These can be populated using parameters specified by Bybit's API documentation, or check the type definition in each class within this repository (see table below for convenient links to each class).
Structure
This connector is fully compatible with both TypeScript and pure JavaScript projects, while the connector is written in TypeScript. A pure JavaScript version can be built using npm run build
, which is also the version published to npm.
The version on npm is the output from the build
command and can be used in projects without TypeScript (although TypeScript is definitely recommended).
- src - the whole connector written in TypeScript
- lib - the JavaScript version of the project (built from TypeScript). This should not be edited directly, as it will be overwritten with each release.
- dist - the webpack bundle of the project for use in browser environments (see guidance on webpack below).
- examples - some implementation examples & demonstrations. Contributions are welcome!
REST API Clients
Each REST API group has a dedicated REST client. To avoid confusion, here are the available REST clients and the corresponding API groups:
Class | Description |
---|---|
[ Derivatives v3 ] | The Derivatives v3 APIs (successor to the Futures V2 APIs) |
UnifiedMarginClient | Derivatives (v3) Unified Margin APIs |
ContractClient | Derivatives (v3) Contract APIs. |
[ Futures v2 ] | The Futures v2 APIs |
InverseClient | Inverse Perpetual Futures (v2) APIs |
LinearClient | USDT Perpetual Futures (v2) APIs |
InverseFuturesClient | Inverse Futures (v2) APIs |
[ Spot ] | The spot APIs |
SpotClientV3 | Spot Market (v3) APIs |
Spot Market (v1) APIs | |
[ USDC Contract ] | The USDC Contract APIs |
USDCPerpetualClient | USDC Perpetual APIs |
USDCOptionClient | USDC Option APIs |
[ Other ] | Other standalone API groups |
AccountAssetClient | Account Asset APIs |
CopyTradingClient | Copy Trading APIs |
WebsocketClient | All WebSocket Events (Public & Private for all API categories) |
Examples for using each client can be found in:
- the examples folder.
- the awesome-crypto-examples repository.
If you're missing an example, you're welcome to request one. Priority will be given to github sponsors.
Usage
Create API credentials on Bybit's website:
All REST clients have can be used in a similar way. However, method names, parameters and responses may vary depending on the API category you're using!
Not sure which function to call or which parameters to use? Click the class name in the table above to look at all the function names (they are in the same order as the official API docs), and check the API docs for a list of endpoints/paramters/responses.
1const { 2 InverseClient, 3 LinearClient, 4 InverseFuturesClient, 5 SpotClient, 6 SpotClientV3, 7 UnifiedMarginClient, 8 USDCOptionClient, 9 USDCPerpetualClient, 10 AccountAssetClient, 11 CopyTradingClient, 12} = require('bybit-api'); 13 14const restClientOptions = { 15 /** Your API key. Optional, if you plan on making private api calls */ 16 key?: string; 17 18 /** Your API secret. Optional, if you plan on making private api calls */ 19 secret?: string; 20 21 /** Set to `true` to connect to testnet. Uses the live environment by default. */ 22 testnet?: boolean; 23 24 /** Override the max size of the request window (in ms) */ 25 recv_window?: number; 26 27 /** Disabled by default. This can help on machines with consistent latency problems. */ 28 enable_time_sync?: boolean; 29 30 /** How often to sync time drift with bybit servers */ 31 sync_interval_ms?: number | string; 32 33 /** Default: false. If true, we'll throw errors if any params are undefined */ 34 strict_param_validation?: boolean; 35 36 /** 37 * Optionally override API protocol + domain 38 * e.g baseUrl: 'https://api.bytick.com' 39 **/ 40 baseUrl?: string; 41 42 /** Default: true. whether to try and post-process request exceptions. */ 43 parse_exceptions?: boolean; 44}; 45 46const API_KEY = 'xxx'; 47const API_SECRET = 'yyy'; 48const useTestnet = false; 49 50const client = new InverseClient({ 51 key: API_KEY, 52 secret: API_SECRET, 53 testnet: useTestnet 54}, 55 // requestLibraryOptions 56); 57 58// For public-only API calls, simply don't provide a key & secret or set them to undefined 59// const client = new InverseClient({}); 60 61client.getApiKeyInfo() 62 .then(result => { 63 console.log("getApiKeyInfo result: ", result); 64 }) 65 .catch(err => { 66 console.error("getApiKeyInfo error: ", err); 67 }); 68 69client.getOrderBook({ symbol: 'BTCUSD' }) 70 .then(result => { 71 console.log("getOrderBook result: ", result); 72 }) 73 .catch(err => { 74 console.error("getOrderBook error: ", err); 75 });
WebSockets
All API groups can be used via a shared WebsocketClient
. However, to listen to multiple API groups at once, you will need to make one WebsocketClient instance per API group.
The WebsocketClient can be configured to a specific API group using the market parameter. These are the currently available API groups:
API Category | Market | Description |
---|---|---|
Unified Margin - Options | market: 'unifiedOption' | The derivatives v3 category for unified margin. Note: public topics only support options topics. If you need USDC/USDT perps, use unifiedPerp instead. |
Unified Margin - Perps | market: 'unifiedPerp' | The derivatives v3 category for unified margin. Note: public topics only support USDT/USDC perpetual topics - use unifiedOption if you need public options topics. |
Futures v2 - Inverse Perps | market: 'inverse' | The inverse v2 perps category. |
Futures v2 - USDT Perps | market: 'linear' | The USDT/linear v2 perps category. |
Futures v2 - Inverse Futures | market: 'inverse' | The inverse futures v2 category uses the same market as inverse perps. |
Spot v3 | market: 'spotv3' | The spot v3 category. |
Spot v1 | market: 'spot' | The older spot v1 category. Use the spotv3 market if possible, as the v1 category does not have automatic re-subscribe if reconnected. |
Copy Trading | market: 'linear' | The copy trading category. Use the linear market to listen to all copy trading topics. |
USDC Perps | market: 'usdcPerp | The USDC perps category. |
USDC Options | market: 'usdcOption' | The USDC options category. |
Contract v3 USDT | market: 'contractUSDT' | The Contract V3 category (USDT perps) |
Contract v3 Inverse | market: 'contractInverse' | The Contract V3 category (inverse perps) |
1const { WebsocketClient } = require('bybit-api'); 2 3const API_KEY = 'xxx'; 4const PRIVATE_KEY = 'yyy'; 5 6const wsConfig = { 7 key: API_KEY, 8 secret: PRIVATE_KEY, 9 10 /* 11 The following parameters are optional: 12 */ 13 14 // defaults to true == livenet 15 // testnet: false 16 17 // NOTE: to listen to multiple markets (spot vs inverse vs linear vs linearfutures) at once, make one WebsocketClient instance per market 18 19 market: 'linear', 20 // market: 'inverse', 21 // market: 'spot', 22 // market: 'spotv3', 23 // market: 'usdcOption', 24 // market: 'usdcPerp', 25 // market: 'unifiedPerp', 26 // market: 'unifiedOption', 27 28 // how long to wait (in ms) before deciding the connection should be terminated & reconnected 29 // pongTimeout: 1000, 30 31 // how often to check (in ms) that WS connection is still alive 32 // pingInterval: 10000, 33 34 // how long to wait before attempting to reconnect (in ms) after connection is closed 35 // reconnectTimeout: 500, 36 37 // config options sent to RestClient (used for time sync). See RestClient docs. 38 // restOptions: { }, 39 40 // config for axios used for HTTP requests. E.g for proxy support 41 // requestOptions: { } 42 43 // override which URL to use for websocket connections 44 // wsUrl: 'wss://stream.bytick.com/realtime' 45}; 46 47const ws = new WebsocketClient(wsConfig); 48 49// subscribe to multiple topics at once 50ws.subscribe(['position', 'execution', 'trade']); 51 52// and/or subscribe to individual topics on demand 53ws.subscribe('kline.BTCUSD.1m'); 54 55// Listen to events coming from websockets. This is the primary data source 56ws.on('update', data => { 57 console.log('update', data); 58}); 59 60// Optional: Listen to websocket connection open event (automatic after subscribing to one or more topics) 61ws.on('open', ({ wsKey, event }) => { 62 console.log('connection open for websocket with ID: ' + wsKey); 63}); 64 65// Optional: Listen to responses to websocket queries (e.g. the response after subscribing to a topic) 66ws.on('response', response => { 67 console.log('response', response); 68}); 69 70// Optional: Listen to connection close event. Unexpected connection closes are automatically reconnected. 71ws.on('close', () => { 72 console.log('connection closed'); 73}); 74 75// Optional: Listen to raw error events. Recommended. 76ws.on('error', err => { 77 console.error('error', err); 78});
See websocket-client.ts for further information.
Customise Logging
Pass a custom logger which supports the log methods silly
, debug
, notice
, info
, warning
and error
, or override methods from the default logger as desired.
1const { WebsocketClient, DefaultLogger } = require('bybit-api'); 2 3// Disable all logging on the silly level 4const customLogger = { 5 ...DefaultLogger, 6 silly: () => {}, 7}; 8 9const ws = new WebsocketClient( 10 { key: 'xxx', secret: 'yyy' }, 11 customLogger 12);
Browser Usage
Build a bundle using webpack:
npm install
npm build
npm pack
The bundle can be found in dist/
. Altough usage should be largely consistent, smaller differences will exist. Documentation is still TODO.
However, note that browser usage will lead to CORS errors due Bybit. See issue #79 for more information & alternative suggestions.
Contributions & Thanks
Donations
tiagosiebler
If you found this project interesting or useful, create accounts with my referral links:
Or buy me a coffee using any of these:
- BTC:
1C6GWZL1XW3jrjpPTS863XtZiXL1aTK7Jk
- ETH (ERC20):
0xd773d8e6a50758e1ada699bb6c4f98bb4abf82da
pixtron
An early generation of this library was started by @pixtron. If this library helps you to trade better on bybit, feel free to donate a coffee to @pixtron:
- BTC
1Fh1158pXXudfM6ZrPJJMR7Y5SgZUz4EdF
- ETH
0x21aEdeC53ab7593b77C9558942f0c9E78131e8d7
- LTC
LNdHSVtG6UWsriMYLJR3qLdfVNKwJ6GSLF
Contributions & Pull Requests
Contributions are encouraged, I will review any incoming pull requests. See the issues tab for todo items.
Star History
No vulnerabilities found.
Reason
30 commit(s) and 12 issue activity found in the last 90 days -- score normalized to 10
Reason
no dangerous workflow patterns detected
Reason
no binaries found in the repo
Reason
license file detected
Details
- Info: project has a license file: LICENSE.md:0
- Info: FSF or OSI recognized license: MIT License: LICENSE.md:0
Reason
Found 9/10 approved changesets -- score normalized to 9
Reason
1 existing vulnerabilities detected
Details
- Warn: Project is vulnerable to: GHSA-3xgq-45jj-v275
Reason
dependency not pinned by hash detected -- score normalized to 6
Details
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/e2etest.yml:19: update your workflow using https://app.stepsecurity.io/secureworkflow/tiagosiebler/bybit-api/e2etest.yml/master?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/e2etest.yml:21: update your workflow using https://app.stepsecurity.io/secureworkflow/tiagosiebler/bybit-api/e2etest.yml/master?enable=pin
- Warn: third-party GitHubAction not pinned by hash: .github/workflows/npmpublish.yml:20: update your workflow using https://app.stepsecurity.io/secureworkflow/tiagosiebler/bybit-api/npmpublish.yml/master?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/npmpublish.yml:29: update your workflow using https://app.stepsecurity.io/secureworkflow/tiagosiebler/bybit-api/npmpublish.yml/master?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/npmpublish.yml:31: update your workflow using https://app.stepsecurity.io/secureworkflow/tiagosiebler/bybit-api/npmpublish.yml/master?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/templates-readme.yml:18: update your workflow using https://app.stepsecurity.io/secureworkflow/tiagosiebler/bybit-api/templates-readme.yml/master?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/templates-readme.yml:20: update your workflow using https://app.stepsecurity.io/secureworkflow/tiagosiebler/bybit-api/templates-readme.yml/master?enable=pin
- Info: 0 out of 6 GitHub-owned GitHubAction dependencies pinned
- Info: 0 out of 1 third-party GitHubAction dependencies pinned
- Info: 3 out of 3 npmCommand dependencies pinned
Reason
detected GitHub workflow tokens with excessive permissions
Details
- Warn: no topLevel permission defined: .github/workflows/e2etest.yml:1
- Info: topLevel 'contents' permission set to 'read': .github/workflows/npmpublish.yml:13
- Warn: topLevel 'contents' permission set to 'write': .github/workflows/templates-readme.yml:7
- Info: no jobLevel write permissions found
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
project is not fuzzed
Details
- Warn: no fuzzer integrations found
Reason
security policy file not detected
Details
- Warn: no security policy file detected
- Warn: no security file to analyze
- Warn: no security file to analyze
- Warn: no security file to analyze
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
- Warn: 0 commits out of 30 are checked with a SAST tool
Score
6.1
/10
Last Scanned on 2025-01-06
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn More