Gathering detailed insights and metrics for bybit-api
Gathering detailed insights and metrics for bybit-api
Gathering detailed insights and metrics for bybit-api
Gathering detailed insights and metrics for bybit-api
bybit-api-node
Complete & robust node.js client for Bybit's REST APIs and WebSockets, with TypeScript & integration tests.
@pxtrn/bybit-api
An unofficial node.js lowlevel wrapper for the Bybit Cryptocurrency Derivative exchange API
@pmeier/bybit-api
An unofficial node.js lowlevel wrapper for the Bybit Cryptocurrency Derivative exchange API
bybit-api-gnome
Forked for Lick Hunter, Complete & robust node.js SDK for Bybit's REST APIs and WebSockets v5, with TypeScript & integration tests.
Node.js SDK for the Bybit APIs and WebSockets, with TypeScript & browser support.
npm install bybit-api
Typescript
Module System
Node Version
NPM Version
v4.2.7: WS subscribe requests are now batched into groups of max 500 topics
Updated on Aug 25, 2025
v4.2.6: fix deduping workflow for websockets introduced in 4.2.5
Updated on Aug 25, 2025
v4.2.5: automatically dedupe subscribe requests
Updated on Aug 25, 2025
v4.2.4: Add full support for RFQ endpoints
Updated on Aug 13, 2025
v4.2.3: Introduce modern token-less publishing workflow
Updated on Aug 12, 2025
Refer to npm for latest releases
Updated on Sep 19, 2022
TypeScript (99.21%)
JavaScript (0.79%)
Total Downloads
668,196
Last Day
652
Last Week
12,052
Last Month
49,555
Last Year
489,735
MIT License
302 Stars
1,194 Commits
100 Forks
12 Watchers
2 Branches
28 Contributors
Updated on Aug 29, 2025
Latest Version
4.2.7
Package Id
bybit-api@4.2.7
Unpacked Size
1.05 MB
Size
214.27 kB
File Count
215
NPM Version
11.5.2
Node Version
22.11.0
Published on
Aug 25, 2025
Cumulative downloads
Total Downloads
Last Day
2.8%
652
Compared to previous day
Last Week
3.1%
12,052
Compared to previous week
Last Month
0.1%
49,555
Compared to previous month
Last Year
404.1%
489,735
Compared to previous year
3
13
5
Professional Node.js, JavaScript & TypeScript SDK for the Bybit REST APIs, WebSocket APIs & WebSocket Events:
reconnected
event when dropped connection is restored.WebsocketAPIClient
and use it like the REST API client. Call functions and await responses.
sendWSAPIRequest(...)
method and await responses
response
and error
events from WebsocketClient's event emitter.sendWSAPIRequest(...)
method.response
and error
events emitted by the client.npm install --save bybit-api
Check out my related JavaScript/TypeScript/Node.js projects:
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 the github repository (see table below for convenient links to each class). TypeScript is definitely recommended, but not required.
The SDK is written in TypeScript, but fully compatible with both TypeScript and pure JavaScript projects. A pure JavaScript version can be built using npm run build
. The output of the build
command is the version published to npm, packaged as a JavaScript module (with types available for you TypeScript users).
Examples for using each client can be found in:
If you're missing an example, you're welcome to request one. Priority will be given to github sponsors.
You should be using the V5 APIs. If you aren't, you should upgrade your project to use the V5 APIs as soon as possible. Bybit used to have several API groups (originally one per product), but the V5 API is currently the latest standard.
Refer to the V5 interface mapping page for more information on which V5 endpoints can be used instead of previous V3 endpoints. To learn more about the V5 API, please read the V5 upgrade guideline.
Here are the available REST clients and the corresponding API groups described in the documentation:
Class | Description |
---|---|
[ V5 API ] | The new unified V5 APIs (successor to previously fragmented APIs for all API groups). |
RestClientV5 | Unified V5 all-in-one REST client for all V5 REST APIs |
WebsocketClient | All WebSocket features (Public & Private consumers for all API categories & the WebSocket API) |
WebsocketAPIClient | Use the WebSocket API like a REST API. Call functions and await responses, powered by WebSockets. |
Create API credentials on Bybit's website:
The following is a minimal example for using the REST clients included with this SDK. For more detailed examples, refer to the examples folder in the repository on GitHub:
1const { RestClientV5 } = require('bybit-api'); 2// or 3// import { RestClientV5 } from 'bybit-api'; 4 5const restClientOptions = { 6 /** supports HMAC & RSA API keys - automatically detected */ 7 /** Your API key */ 8 key: 'apiKeyHere', 9 10 /** Your API secret */ 11 secret: 'apiSecretHere', 12 13 /** Set to `true` to connect to testnet. Uses the live environment by default. */ 14 // testnet: true, 15 16 /** 17 * Set to `true` to use Bybit's V5 demo trading: 18 * https://bybit-exchange.github.io/docs/v5/demo 19 * 20 * Note: to use demo trading, you should have `testnet` disabled. 21 * 22 * You can find a detailed demoTrading example in the examples folder on GitHub. 23 */ 24 // demoTrading: true, 25 26 /** Override the max size of the request window (in ms) */ 27 // recv_window: 5000, // 5000 = 5 seconds 28 29 /** 30 * Enable keep alive for REST API requests (via axios). 31 * See: https://github.com/tiagosiebler/bybit-api/issues/368 32 */ 33 // keepAlive: true, 34 35 /** 36 * When using HTTP KeepAlive, how often to send TCP KeepAlive packets over 37 * sockets being kept alive. Only relevant if keepAlive is set to true. 38 * Default: 1000 (defaults comes from https agent) 39 */ 40 // keepAliveMsecs: 1000, // 1000 = 1 second 41 42 /** 43 * Optionally override API domain used: 44 * apiRegion: 'default' | 'bytick' | 'NL' | 'HK' | 'TK', 45 **/ 46 47 // apiRegion: 'bytick', 48 49 /** Default: false. Enable to parse/include per-API/endpoint rate limits in responses. */ 50 // parseAPIRateLimits: true, 51 52 /** 53 * Allows you to provide a custom "signMessage" function, 54 * e.g. to use node crypto's much faster createHmac method 55 * 56 * Look at examples/fasterHmacSign.ts for a demonstration: 57 */ 58 // customSignMessageFn: (message: string, secret: string) => Promise<string>; 59}; 60 61const API_KEY = 'xxx'; 62const API_SECRET = 'yyy'; 63 64const client = new RestClientV5( 65 { 66 key: API_KEY, 67 secret: API_SECRET, 68 // demoTrading: true, 69 70 // Optional: enable to try parsing rate limit values from responses 71 // parseAPIRateLimits: true 72 }, 73 // requestLibraryOptions 74); 75 76// For public-only API calls, simply don't provide a key & secret or set them to undefined 77// const client = new RestClientV5(); 78 79client 80 .getAccountInfo() 81 .then((result) => { 82 console.log('getAccountInfo result: ', result); 83 }) 84 .catch((err) => { 85 console.error('getAccountInfo error: ', err); 86 }); 87 88client 89 .getOrderbook({ category: 'linear', symbol: 'BTCUSDT' }) 90 .then((result) => { 91 console.log('getOrderBook result: ', result); 92 }) 93 .catch((err) => { 94 console.error('getOrderBook error: ', err); 95 });
The WebsocketClient will automatically use the latest V5 WebSocket endpoints by default. To use a different endpoint, use the market
parameter. Except for the WebSocket API - this can be accessed without any special configuration.
Here's a minimal example for using the websocket client. For more complete examples, look into the ws-* examples in the examples folder in the repo on GitHub.
1const { WebsocketClient } = require('bybit-api'); 2// or 3// import { WebsocketClient } from 'bybit-api'; 4 5const API_KEY = 'xxx'; 6const PRIVATE_KEY = 'yyy'; 7 8const wsConfig = { 9 /** 10 * API credentials are optional. They are only required if you plan on using 11 * any account-specific topics or the WS API 12 * supports HMAC & RSA API keys - automatically detected 13 */ 14 key: 'yourAPIKeyHere', 15 secret: 'yourAPISecretHere', 16 17 /* 18 The following parameters are optional: 19 */ 20 21 /** 22 * Set to `true` to connect to Bybit's testnet environment. 23 * - If demo trading, `testnet` should be set to false! 24 * - If testing a strategy, use demo trading instead. Testnet market 25 * data is very different from real market conditions. 26 */ 27 // testnet: true 28 29 /** 30 * Set to `true` to connect to Bybit's V5 demo trading: 31 * https://bybit-exchange.github.io/docs/v5/demo 32 * 33 * Refer to the examples folder on GitHub for a more detailed demonstration. 34 */ 35 // demoTrading: true, 36 37 // recv window size for websocket authentication (higher latency connections 38 // (VPN) can cause authentication to fail if the recv window is too small) 39 // recvWindow: 5000, 40 41 /** How often to check if the connection is alive (in ms) */ 42 // pingInterval: 10000, 43 44 /** 45 * How long to wait (in ms) for a pong (heartbeat reply) before assuming the 46 * connection is dead 47 */ 48 // pongTimeout: 1000, 49 50 /** Delay in milliseconds before respawning the connection */ 51 // reconnectTimeout: 500, 52 53 // override which URL to use for websocket connections 54 // wsUrl: 'wss://stream.bytick.com/realtime' 55 56 /** 57 * Allows you to provide a custom "signMessage" function, e.g. to use node's 58 * much faster createHmac method 59 * 60 * Look at examples/fasterHmacSign.ts for a demonstration: 61 */ 62 // customSignMessageFn: (message: string, secret: string) => Promise<string>; 63}; 64 65const ws = new WebsocketClient(wsConfig); 66 67// (v5) subscribe to multiple topics at once 68ws.subscribeV5(['orderbook.50.BTCUSDT', 'orderbook.50.ETHUSDT'], 'linear'); 69 70// Or one at a time 71ws.subscribeV5('kline.5.BTCUSDT', 'linear'); 72ws.subscribeV5('kline.5.ETHUSDT', 'linear'); 73 74// Private/public topics can be used in the same WS client instance, even for 75// different API groups (linear, options, spot, etc) 76ws.subscribeV5('position', 'linear'); 77ws.subscribeV5('publicTrade.BTC', 'option'); 78 79/** 80 * The Websocket Client will automatically manage all connectivity & authentication for you. 81 * 82 * If a network issue occurs, it will automatically: 83 * - detect it, 84 * - remove the dead connection, 85 * - replace it with a new one, 86 * - resubscribe to everything you were subscribed to. 87 * 88 * When this happens, you will see the "reconnected" event. 89 */ 90 91// Listen to events coming from websockets. This is the primary data source 92ws.on('update', (data) => { 93 console.log('data received', JSON.stringify(data, null, 2)); 94}); 95 96// Optional: Listen to websocket connection open event 97// (automatic after subscribing to one or more topics) 98ws.on('open', ({ wsKey, event }) => { 99 console.log('connection open for websocket with ID: ', wsKey); 100}); 101 102// Optional: Listen to responses to websocket queries 103// (e.g. the response after subscribing to a topic) 104ws.on('response', (response) => { 105 console.log('response', response); 106}); 107 108// Optional: Listen to connection close event. 109// Unexpected connection closes are automatically reconnected. 110ws.on('close', () => { 111 console.log('connection closed'); 112}); 113 114// Listen to raw error events. Recommended. 115ws.on('exception', (err) => { 116 console.error('exception', err); 117}); 118 119ws.on('reconnect', ({ wsKey }) => { 120 console.log('ws automatically reconnecting.... ', wsKey); 121}); 122 123ws.on('reconnected', (data) => { 124 console.log('ws has reconnected ', data?.wsKey); 125});
Bybit supports sending, amending and cancelling orders over a WebSocket connection. The WebsocketClient fully supports Bybit's WebSocket API via the sendWSAPIRequest(...)
method. There is also a dedicated WebsocketAPIClient, built over the WSClient's sendWSAPIRequest mechanism for a simpler experience.
Links for reference:
Note: as of January 2025, the demo trading environment does not support the WebSocket API.
There are two ways to use the WS API, depending on individual preference:
client.sendWSAPIRequest(wsKey, operation, params)
, fire and forgetclient.on('exception', cb)
and client.on('response', cb)
WebsocketAPIClient
and use it much like a REST API.The below example demonstrates the promise-driven approach, which behaves similar to a REST API. The WebSocket API even accepts the same parameters as the corresponding REST API endpoints, so this approach should be compatible with existing REST implementations.
Connectivity, authentication and connecting requests & responses to promises - these are all handled automatically without additional configuration by the WebsocketClient. The WebsocketAPIClient is a wrapper built on top of this, providing dedicated methods for every available Websocket API command. Each method has fully typed requests & responses. Benefit from the capabilities of the WebSocket API without the complexity of managing asynchronous messaging over WebSockets.
1const { WS_KEY_MAP, WebsocketAPIClient } = require('bybit-api'); 2 3// or 4// import { WS_KEY_MAP, WebsocketAPIClient } from 'bybit-api'; 5 6// Create an instance of the WebsocketAPIClient. This is built on 7// top of the WebsocketClient and will automatically handle WebSocket 8// persistence and authentication for you. 9// supports HMAC & RSA API keys - automatically detected 10const wsClient = new WebsocketAPIClient({ 11 key: 'yourApiKeyHere', 12 secret: 'yourApiSecretHere', 13 14 // Whether to use the testnet environment. 15 // Create testnet API keys here: https://testnet.bybit.com/app/user/api-management 16 // testnet: true, 17 18 // Whether to use the livenet demo trading environment 19 // Note: As of Jan 2025, demo trading only supports consuming events, it does 20 // NOT support the WS API. 21 // demoTrading: false, 22 23 // If you want your own event handlers instead of the default ones with logs, 24 // disable this setting and see ws-api-client example for more details. 25 // attachEventListeners: false 26}); 27 28// This example is wrapped in an async function, so "await" can be used 29async function main() { 30 /** 31 * Optional. Can be used to prepare a connection before sending 32 * commands (e.g. as part of your startup process). 33 * 34 * This is not necessary and will happen automatically when 35 * sending a command, if you aren't connected/authenticated yet. 36 */ 37 // await wsClient.getWSClient().connectWSAPI(); 38 39 try { 40 console.log('Step 1: Create an order'); 41 const response = await wsClient.submitNewOrder({ 42 category: 'linear', 43 symbol: 'BTCUSDT', 44 orderType: 'Limit', 45 qty: '0.001', 46 side: 'Buy', 47 price: '50000', 48 }); 49 console.log('submitNewOrder response: ', response); 50 } catch (e) { 51 console.log('submitNewOrder error: ', e); 52 } 53 54 try { 55 console.log('Step 2: Amend an order'); 56 const response = await wsClient.amendOrder({ 57 category: 'linear', 58 symbol: 'BTCUSDT', 59 orderId: 'b4b9e205-793c-4777-8112-0bf3c2d26b6e', 60 qty: '0.001', 61 price: '60000', 62 }); 63 console.log('amendOrder response: ', response); 64 } catch (e) { 65 console.log('amendOrder error: ', e); 66 } 67 68 try { 69 console.log('Step 3: Cancel an order'); 70 const response = await wsClient.cancelOrder({ 71 category: 'linear', 72 symbol: 'BTCUSDT', 73 orderId: 'b4b9e205-793c-4777-8112-0bf3c2d26b6e', 74 }); 75 console.log('cancelOrder response: ', response); 76 } catch (e) { 77 console.log('cancelOrder error: ', e); 78 } 79} 80 81// Start executing the example workflow 82main();
The WebsocketClient will automatically prepare one connection per API group, for all topics in that API group. Any topics that you subscribe to on that WebSocket client will automatically be added to the same connection.
To spread your subscribed topics over multiple connections, e.g. to reduce the throughput of an individual connectionk, you can make one instance of the WebsocketClient per connection group.
1const wsClientGroup1 = new WebsocketClient(); 2const wsClientGroup2 = new WebsocketClient(); 3 4// Attach event listeners to each WS Client 5// Divide your desired topics into separate groups
Important: do not subscribe to the same topics on both clients or you will receive duplicate messages (once per WS client).
Pass a custom logger (or mutate the imported DefaultLogger class) which supports the log methods trace
, info
and error
, or override methods from the default logger as desired, as in the example below:
1const { WebsocketClient, DefaultLogger } = require('bybit-api'); 2 3// Enable all logging on the trace level (disabled by default) 4const customLogger = { 5 ...DefaultLogger, 6 trace: (...params) => console.log('trace', ...params), 7}; 8 9const wsClient = new WebsocketClient( 10 { key: 'xxx', secret: 'yyy' }, 11 customLogger, 12);
In rare situations, you may want to see the raw HTTP requets being built as well as the API response. These can be enabled by setting the BYBITTRACE
env var to true
.
This is the "modern" way, allowing the package to be directly imported into frontend projects with full typescript support.
1npm install stream-browserify
tsconfig.json
1{ 2 "compilerOptions": { 3 "paths": { 4 "stream": [ 5 "./node_modules/stream-browserify" 6 ] 7}
1(window as any).global = window;
This is the "old" way of using this package on webpages. This will build a minified js bundle that can be pulled in using a script tag on a website.
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 - contributions welcome.
This SDK includes a bundled llms.txt
file in the root of the repository. If you're developing with LLMs, use the included llms.txt
with your LLM - it will significantly improve the LLMs understanding of how to correctly use this SDK.
This file contains AI optimised structure of all the functions in this package, and their parameters for easier use with any learning models or artificial intelligence.
Have my projects helped you? Share the love, there are many ways you can show your thanks:
0xA3Bda8BecaB4DCdA539Dc16F9C54a592553Be06C
Contributions are encouraged, I will review any incoming pull requests. See the issues tab for todo items.
No vulnerabilities found.