Use this file to discover all available pages before exploring further.
Bybit’s WebSocket API lets you create, amend, and cancel orders over a persistent WebSocket connection instead of HTTP. Because the connection is already established, round-trip latency is significantly lower than a REST call — there is no TCP handshake, TLS negotiation, or HTTP overhead per request. The bybit-api SDK implements this with two approaches: the high-level WebsocketAPIClient (recommended) and the lower-level sendWSAPIRequest method on WebsocketClient.
Lower latency than REST: no per-request connection setup.
Same parameters as the corresponding REST endpoints — existing REST code can often be adapted with minimal changes.
Automatic auth: credentials are signed and sent once when the connection opens, then reused for every subsequent request.
Promise-driven: each sendWSAPIRequest call returns a Promise that resolves when the matching response arrives, making error handling natural with try/catch.
As of January 2025, Bybit’s demo trading environment does not support the WebSocket API. Use testnet: true or a real account. Do not set demoTrading: true when using WS API operations.
WebsocketAPIClient wraps WebsocketClient and exposes dedicated, fully-typed methods for every supported WS API operation. Each method returns a Promise — use await just as you would with a REST client.
When true, the client attaches default console.log handlers for open, reconnect, reconnected, authenticated, and exception events. Disable this if you want to attach your own handlers via wsClient.getWSClient().on(...).
Normally the connection opens automatically when you make your first WS API request. To eliminate cold-start latency on the first call, connect in advance:
// Ensure the WS API connection is open and authenticated before the first requestawait wsClient.getWSClient().connectWSAPI();// Now the first request executes immediatelyconst response = await wsClient.submitNewOrder({ ... });
For direct access to the underlying WS API transport, use sendWSAPIRequest on WebsocketClient. This provides the same Promise-based interface but requires you to construct the wsKey and operation arguments explicitly. It is useful if you want finer control over events or prefer not to use WebsocketAPIClient.
Instead of awaiting each call, you can fire requests without blocking and handle all responses and exceptions in the shared event listeners. This is the most raw form of the WS API.
import { DefaultLogger, WebsocketClient, WS_KEY_MAP } from 'bybit-api';const wsClient = new WebsocketClient({ key: process.env.API_KEY, secret: process.env.API_SECRET,});// All command responses arrive herewsClient.on('response', (data) => { console.log('Command response:', JSON.stringify(data, null, 2));});// All errors and rejected commands arrive herewsClient.on('exception', (data) => { console.error('Command exception:', data);});async function main() { await wsClient.connectWSAPI(); // Fire-and-forget — result arrives on the 'response' event // Always attach a .catch() to prevent unhandled promise rejection warnings wsClient .sendWSAPIRequest(WS_KEY_MAP.v5PrivateTrade, 'order.create', { symbol: 'BTCUSDT', side: 'Buy', orderType: 'Limit', price: '50000', qty: '1', category: 'linear', }) .catch((e) => console.error('Create order exception:', e)); // Amend the order a few seconds later setTimeout(() => { wsClient .sendWSAPIRequest(WS_KEY_MAP.v5PrivateTrade, 'order.amend', { symbol: 'BTCUSDT', category: 'linear', orderId: '1234567', price: '55000', }) .catch((e) => console.error('Amend exception:', e)); }, 3_000); // Cancel the order setTimeout(() => { wsClient .sendWSAPIRequest(WS_KEY_MAP.v5PrivateTrade, 'order.cancel', { category: 'linear', symbol: 'BTCUSDT', orderId: '1234567', }) .catch((e) => console.error('Cancel exception:', e)); }, 6_000);}main();
Even in fire-and-forget mode, always chain .catch() on each sendWSAPIRequest call. Without it, a rejected promise (e.g. from a disconnection) will throw an unhandled rejection warning in Node.js.
Recommended for most users. Dedicated methods per operation, fully typed request and response parameters, default event listeners included. Internally wraps sendWSAPIRequest.
sendWSAPIRequest
For advanced use cases. Direct access to the transport layer. Useful when you want to handle events manually or mix WS API calls with subscription management on the same WebsocketClient instance.
The SDK provides full TypeScript coverage for WS API requests and responses:
Type
Description
WSAPIOperation
Union of all supported operation strings
WsAPITopicRequestParamMap
Maps each operation to its request parameter interface
WsAPIOperationResponseMap
Maps each operation to its response type
WSAPIResponse<TData, TOperation>
Generic response envelope with retCode, retMsg, data, and header
OrderParamsV5
Request parameters for order.create
AmendOrderParamsV5
Request parameters for order.amend
CancelOrderParamsV5
Request parameters for order.cancel
BatchOrderParamsV5
Request parameters for items in order.create-batch
TypeScript will automatically infer the correct parameter and return types from the operation string — passing incorrect request fields produces a compile-time error.