Professional Node.js, JavaScript & TypeScript SDK for the Bybit REST APIs and WebSockets:
reconnected
event when dropped connection is restored.response
and error
events from WebsocketClient's event emitter.response
and error
events.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) |
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 = {
/** 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
*/
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.
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)
const result = await client.sendWSAPIRequest(wsKey, operation, params)
, which returns a promiseThe 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 processing requests wrapped in promises - these are all handled automatically by the WebsocketClient without additional configuration.
const { WS_KEY_MAP, WebsocketClient } = require('bybit-api');
// or
// import { WS_KEY_MAP, WebsocketClient } from 'bybit-api';
// Create an instance of the WebsocketClient.
// This will automatically handle connectivity and authentication for you.
const wsClient = new WebsocketClient(
{
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,
}
);
// 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.connectWSAPI();
try {
console.log('Step 1: Create an order');
// The type for `wsAPISubmitOrderResult` is automatically
// resolved to `WSAPIResponse<OrderResultV5, "order.create">`
const wsAPISubmitOrderResult = await wsClient.sendWSAPIRequest(
WS_KEY_MAP.v5PrivateTrade,
'order.create',
{
symbol: 'BTCUSDT',
side: 'Buy',
orderType: 'Limit',
price: '50000',
qty: '1',
category: 'linear',
},
);
console.log(
`Step 1: Order result (order ID: "${wsAPISubmitOrderResult.data.orderId}"): `,
wsAPISubmitOrderResult,
);
} catch (e) {
console.error('Step 1: Order submit exception: ', e);
}
}
// Start executing the example workflow
main();
See the examples/ws-api-promises.ts example for a more detailed explanation.
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).
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 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.
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.