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).
If you're missing an example, you're welcome to request one. Priority will be given to github sponsors.
API Clients
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).
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
*/// 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>;
};
constAPI_KEY = 'xxx';
constAPI_SECRET = 'yyy';
const client = newRestClientV5({
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);
});
WebSockets
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.
WebSocket Subscriptions - Consuming events
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';constAPI_KEY = 'xxx';
constPRIVATE_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
*
* Only the "V5" "market" is supported here.
*/// 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 = newWebsocketClient(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('error', (err) => {
console.error('error', err);
});
ws.on('reconnect', ({ wsKey }) => {
console.log('ws automatically reconnecting.... ', wsKey);
});
ws.on('reconnected', (data) => {
console.log('ws has reconnected ', data?.wsKey);
});
Websocket API - Sending orders via WebSockets
Bybit supports sending, amending and cancelling orders over a WebSocket connection. The WebsocketClient fully supports Bybit's WebSocket 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 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 = newWebsocketClient(
{
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 usedasyncfunctionmain() {
/**
* 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 workflowmain();
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 = newWebsocketClient();
const wsClientGroup2 = newWebsocketClient();
// 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).
Logging
Customise logging
Pass a custom logger (or mutate the imported DefaultLogger class) which supports the log methods silly, debug, notice, info, warning 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 = newWebsocketClient({ key: 'xxx', secret: 'yyy' }, customLogger);
Debug HTTP requests
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.
Browser Usage
Import
This is the "modern" way, allowing the package to be directly imported into frontend projects with full typescript support.
Declare this in the global context of your application (ex: in polyfills for angular)
(windowas any).global = window;
Webpack
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.
Contributions & Thanks
Have my projects helped you? Share the love, there are many ways you can show your thanks:
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 15,464 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 0 open source maintainers collaborating on the project.
Package last updated on 17 Feb 2025
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.
Newly introduced telemetry in devenv 1.4 sparked a backlash over privacy concerns, leading to the removal of its AI-powered feature after strong community pushback.
TC39 met in Seattle and advanced 9 JavaScript proposals, including three to Stage 4, introducing new features and enhancements for a future ECMAScript release.