
Product
Socket for Jira Is Now Available
Socket for Jira lets teams turn alerts into Jira tickets with manual creation, automated ticketing rules, and two-way sync.
bybit-api
Advanced tools
Complete & robust Node.js SDK for Bybit's REST APIs and WebSockets, with TypeScript & strong end to end tests.
[!TIP] Upcoming change: As part of the Siebly.io brand, this SDK will soon be hosted under the Siebly.io GitHub organisation. The migration is seamless and requires no user changes.
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 our JavaScript/TypeScript/Node.js SDKs & 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:
const { RestClientV5 } = require('bybit-api');
// or
// import { RestClientV5 } from 'bybit-api';
const restClientOptions = {
/** supports HMAC & RSA API keys - automatically detected */
/** Your API key */
key: 'apiKeyHere',
/** Your API secret */
secret: 'apiSecretHere',
/** Set to `true` to connect to testnet. Uses the live environment by default. */
// testnet: true,
/**
* Set to `true` to use Bybit's V5 demo trading:
* https://bybit-exchange.github.io/docs/v5/demo
*
* Note: to use demo trading, you should have `testnet` disabled.
*
* You can find a detailed demoTrading example in the examples folder on GitHub.
*/
// demoTrading: true,
/** Override the max size of the request window (in ms) */
// recv_window: 5000, // 5000 = 5 seconds
/**
* Enable keep alive for REST API requests (via axios).
* See: https://github.com/tiagosiebler/bybit-api/issues/368
*/
// keepAlive: true,
/**
* When using HTTP KeepAlive, how often to send TCP KeepAlive packets over
* sockets being kept alive. Only relevant if keepAlive is set to true.
* Default: 1000 (defaults comes from https agent)
*/
// keepAliveMsecs: 1000, // 1000 = 1 second
/**
* Optionally override API domain used:
* apiRegion: 'default' | 'bytick' | 'NL' | 'HK' | 'TK',
**/
// apiRegion: 'bytick',
/** Default: false. Enable to parse/include per-API/endpoint rate limits in responses. */
// parseAPIRateLimits: true,
/**
* Allows you to provide a custom "signMessage" function,
* e.g. to use node crypto's much faster createHmac method
*
* Look at examples/fasterHmacSign.ts for a demonstration:
*/
// customSignMessageFn: (message: string, secret: string) => Promise<string>;
};
const API_KEY = 'xxx';
const API_SECRET = 'yyy';
const client = new RestClientV5(
{
key: API_KEY,
secret: API_SECRET,
// demoTrading: true,
// Optional: enable to try parsing rate limit values from responses
// parseAPIRateLimits: true
},
// requestLibraryOptions
);
// For public-only API calls, simply don't provide a key & secret or set them to undefined
// const client = new RestClientV5();
client
.getAccountInfo()
.then((result) => {
console.log('getAccountInfo result: ', result);
})
.catch((err) => {
console.error('getAccountInfo error: ', err);
});
client
.getOrderbook({ category: 'linear', symbol: 'BTCUSDT' })
.then((result) => {
console.log('getOrderBook result: ', result);
})
.catch((err) => {
console.error('getOrderBook error: ', err);
});
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.
const { WebsocketClient } = require('bybit-api');
// or
// import { WebsocketClient } from 'bybit-api';
const API_KEY = 'xxx';
const PRIVATE_KEY = 'yyy';
const wsConfig = {
/**
* API credentials are optional. They are only required if you plan on using
* any account-specific topics or the WS API
* supports HMAC & RSA API keys - automatically detected
*/
key: 'yourAPIKeyHere',
secret: 'yourAPISecretHere',
/*
The following parameters are optional:
*/
/**
* Set to `true` to connect to Bybit's testnet environment.
* - If demo trading, `testnet` should be set to false!
* - If testing a strategy, use demo trading instead. Testnet market
* data is very different from real market conditions.
*/
// testnet: true
/**
* Set to `true` to connect to Bybit's V5 demo trading:
* https://bybit-exchange.github.io/docs/v5/demo
*
* Refer to the examples folder on GitHub for a more detailed demonstration.
*/
// demoTrading: true,
// recv window size for websocket authentication (higher latency connections
// (VPN) can cause authentication to fail if the recv window is too small)
// recvWindow: 5000,
/** How often to check if the connection is alive (in ms) */
// pingInterval: 10000,
/**
* How long to wait (in ms) for a pong (heartbeat reply) before assuming the
* connection is dead
*/
// pongTimeout: 1000,
/** Delay in milliseconds before respawning the connection */
// reconnectTimeout: 500,
// override which URL to use for websocket connections
// wsUrl: 'wss://stream.bytick.com/realtime'
/**
* Allows you to provide a custom "signMessage" function, e.g. to use node's
* much faster createHmac method
*
* Look at examples/fasterHmacSign.ts for a demonstration:
*/
// customSignMessageFn: (message: string, secret: string) => Promise<string>;
};
const ws = new WebsocketClient(wsConfig);
// (v5) subscribe to multiple topics at once
ws.subscribeV5(['orderbook.50.BTCUSDT', 'orderbook.50.ETHUSDT'], 'linear');
// Or one at a time
ws.subscribeV5('kline.5.BTCUSDT', 'linear');
ws.subscribeV5('kline.5.ETHUSDT', 'linear');
// Private/public topics can be used in the same WS client instance, even for
// different API groups (linear, options, spot, etc)
ws.subscribeV5('position', 'linear');
ws.subscribeV5('publicTrade.BTC', 'option');
/**
* The Websocket Client will automatically manage all connectivity & authentication for you.
*
* If a network issue occurs, it will automatically:
* - detect it,
* - remove the dead connection,
* - replace it with a new one,
* - resubscribe to everything you were subscribed to.
*
* When this happens, you will see the "reconnected" event.
*/
// Listen to events coming from websockets. This is the primary data source
ws.on('update', (data) => {
console.log('data received', JSON.stringify(data, null, 2));
});
// Optional: Listen to websocket connection open event
// (automatic after subscribing to one or more topics)
ws.on('open', ({ wsKey, event }) => {
console.log('connection open for websocket with ID: ', wsKey);
});
// Optional: Listen to responses to websocket queries
// (e.g. the response after subscribing to a topic)
ws.on('response', (response) => {
console.log('response', response);
});
// Optional: Listen to connection close event.
// Unexpected connection closes are automatically reconnected.
ws.on('close', () => {
console.log('connection closed');
});
// Listen to raw error events. Recommended.
ws.on('exception', (err) => {
console.error('exception', err);
});
ws.on('reconnect', ({ wsKey }) => {
console.log('ws automatically reconnecting.... ', wsKey);
});
ws.on('reconnected', (data) => {
console.log('ws has reconnected ', data?.wsKey);
});
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.
const { WS_KEY_MAP, WebsocketAPIClient } = require('bybit-api');
// or
// import { WS_KEY_MAP, WebsocketAPIClient } from 'bybit-api';
// Create an instance of the WebsocketAPIClient. This is built on
// top of the WebsocketClient and will automatically handle WebSocket
// persistence and authentication for you.
// supports HMAC & RSA API keys - automatically detected
const wsClient = new WebsocketAPIClient({
key: 'yourApiKeyHere',
secret: 'yourApiSecretHere',
// Whether to use the testnet environment.
// Create testnet API keys here: https://testnet.bybit.com/app/user/api-management
// testnet: true,
// Whether to use the livenet demo trading environment
// Note: As of Jan 2025, demo trading only supports consuming events, it does
// NOT support the WS API.
// demoTrading: false,
// If you want your own event handlers instead of the default ones with logs,
// disable this setting and see ws-api-client example for more details.
// attachEventListeners: false
});
// This example is wrapped in an async function, so "await" can be used
async function main() {
/**
* Optional. Can be used to prepare a connection before sending
* commands (e.g. as part of your startup process).
*
* This is not necessary and will happen automatically when
* sending a command, if you aren't connected/authenticated yet.
*/
// await wsClient.getWSClient().connectWSAPI();
try {
console.log('Step 1: Create an order');
const response = await wsClient.submitNewOrder({
category: 'linear',
symbol: 'BTCUSDT',
orderType: 'Limit',
qty: '0.001',
side: 'Buy',
price: '50000',
});
console.log('submitNewOrder response: ', response);
} catch (e) {
console.log('submitNewOrder error: ', e);
}
try {
console.log('Step 2: Amend an order');
const response = await wsClient.amendOrder({
category: 'linear',
symbol: 'BTCUSDT',
orderId: 'b4b9e205-793c-4777-8112-0bf3c2d26b6e',
qty: '0.001',
price: '60000',
});
console.log('amendOrder response: ', response);
} catch (e) {
console.log('amendOrder error: ', e);
}
try {
console.log('Step 3: Cancel an order');
const response = await wsClient.cancelOrder({
category: 'linear',
symbol: 'BTCUSDT',
orderId: 'b4b9e205-793c-4777-8112-0bf3c2d26b6e',
});
console.log('cancelOrder response: ', response);
} catch (e) {
console.log('cancelOrder error: ', e);
}
}
// Start executing the example workflow
main();
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.
const wsClientGroup1 = new WebsocketClient();
const wsClientGroup2 = new WebsocketClient();
// Attach event listeners to each WS Client
// 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).
By default, this Node.js, JavaScript & TypeScript SDK uses the Bybit Global API & WebSocket domains. For regions where Bybit has dedicated regional domains, including the alternative Bybit Global domain (bytick), these can be configured in the REST Client using the apiRegion property.
The following values are currently supported in this option:
apiRegion: undefined: if missing or undefined, this SDK will default to the Bybit Global domain api.bybit.com.apiRegion: "default": the Bybit Global domain (same behaviour as above).apiRegion: "bytick": the alternative Bybit Global domain api.bytick.com.apiRegion: "NL": the dedicated Bybit Netherlands domain api.bytick.nl.apiRegion: "TK": the dedicated Bybit Turkey domain api.bybit-tr.com.apiRegion: "KZ": the dedicated Bybit Kazakhstan domain api.bybit.kz.apiRegion: "HK": the dedicated Bybit HK domain api.byhkbit.com.apiRegion: "GE": the dedicated Bybit Georgia domain api.bybitgeorgia.ge.apiRegion: "UAE": the dedicated Bybit United Arab Emirates domain api.bybit.ae.apiRegion: "EU": the dedicated Bybit EU/EEA domain api.bybit.eu.New regions will be supported when they become available in the Bybit API. If you notice any regions that have not been added yet, please open a new issue on GitHub.
Below is an example for using this Node.js, TypeScript & JavaScript SDK for Bybit's APIs, using an account registered on the Bybit EU domain:
const { RestClientV5 } = require('bybit-api');
// or
// import { RestClientV5 } from 'bybit-api';
const client = new RestClientV5({
key: API_KEY,
secret: API_SECRET,
// demoTrading: true,
apiRegion: 'EU',
});
client
.getAccountInfo()
.then((result) => {
console.log('getAccountInfo result: ', result);
})
.catch((err) => {
console.error('getAccountInfo error: ', err);
});
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:
const { WebsocketClient, DefaultLogger } = require('bybit-api');
// Enable all logging on the trace level (disabled by default)
const customLogger = {
...DefaultLogger,
trace: (...params) => console.log('trace', ...params),
};
const wsClient = new WebsocketClient(
{ key: 'xxx', secret: 'yyy' },
customLogger,
);
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.
npm install stream-browserify
tsconfig.json
{
"compilerOptions": {
"paths": {
"stream": [
"./node_modules/stream-browserify"
]
}
(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 installnpm buildnpm packThe 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.
FAQs
Complete & robust Node.js SDK for Bybit's REST APIs and WebSockets, with TypeScript & strong end to end tests.
The npm package bybit-api receives a total of 18,534 weekly downloads. As such, bybit-api popularity was classified as popular.
We found that bybit-api demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 2 open source maintainers collaborating on the project.
Did you know?

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Product
Socket for Jira lets teams turn alerts into Jira tickets with manual creation, automated ticketing rules, and two-way sync.

Company News
Socket won two 2026 Reppy Awards from RepVue, ranking in the top 5% of all sales orgs. AE Alexandra Lister shares what it's like to grow a sales career here.

Security News
NIST will stop enriching most CVEs under a new risk-based model, narrowing the NVD's scope as vulnerability submissions continue to surge.