Skip to content

Class: WebsocketClient ​

Extends ​

  • BaseWebsocketClient<WsKey, WsRequestOperationBybit<WsTopic>>

Constructors ​

Constructor ​

ts
new WebsocketClient(options?: WSClientConfigurableOptions, logger?: object): WebsocketClient;

Parameters ​

ParameterTypeDescription
options?WSClientConfigurableOptions-
logger?{ error: (...params: any) => void; info: (...params: any) => void; trace: (..._params: any) => void; }-
logger.error?(...params: any) => void-
logger.info?(...params: any) => void-
logger.trace?(..._params: any) => voidPing/pong events and other raw messages that might be noisy. Enable this while troubleshooting.

Returns ​

WebsocketClient

Overrides ​

BaseWebsocketClient<WsKey, WsRequestOperationBybit<WsTopic>>.constructor

Properties ​

logger ​

ts
logger: object;

error ​

ts
error: (...params: any) => void;
Parameters ​
ParameterType
...paramsany
Returns ​

void

info ​

ts
info: (...params: any) => void;
Parameters ​
ParameterType
...paramsany
Returns ​

void

trace ​

ts
trace: (..._params: any) => void;

Ping/pong events and other raw messages that might be noisy. Enable this while troubleshooting.

Parameters ​
ParameterType
..._paramsany
Returns ​

void

Inherited from ​

BaseWebsocketClient.logger

Methods ​

assertIsAuthenticated() ​

ts
assertIsAuthenticated(wsKey: WsKey): Promise<unknown>;

Promise-driven method to assert that a ws has been successfully authenticated (will await until auth is confirmed)

Parameters ​

ParameterType
wsKeyWsKey

Returns ​

Promise<unknown>

Inherited from ​

BaseWebsocketClient.assertIsAuthenticated


assertIsConnected() ​

ts
assertIsConnected(wsKey: WsKey): Promise<unknown>;

Promise-driven method to assert that a ws has successfully connected (will await until connection is open)

Parameters ​

ParameterType
wsKeyWsKey

Returns ​

Promise<unknown>

Inherited from ​

BaseWebsocketClient.assertIsConnected


close() ​

ts
close(wsKey: WsKey, force?: boolean): void;

Parameters ​

ParameterType
wsKeyWsKey
force?boolean

Returns ​

void

Inherited from ​

BaseWebsocketClient.close


closeAll() ​

ts
closeAll(force?: boolean): void;

Parameters ​

ParameterType
force?boolean

Returns ​

void

See ​

Shut down cleanly

Inherited from ​

BaseWebsocketClient.closeAll


connect() ​

ts
connect(
   wsKey: WsKey, 
   customUrl?: string, 
   throwOnError?: boolean
): Promise<WSConnectedResult | undefined>;

Request connection to a specific websocket, instead of waiting for automatic connection.

Parameters ​

ParameterType
wsKeyWsKey
customUrl?string
throwOnError?boolean

Returns ​

Promise<WSConnectedResult | undefined>

Inherited from ​

BaseWebsocketClient.connect


connectAll() ​

ts
connectAll(): Promise<WSConnectedResult | undefined>[];

Request connection of all dependent (public & private) websockets, instead of waiting for automatic connection by SDK.

Returns ​

Promise<WSConnectedResult | undefined>[]

Overrides ​

BaseWebsocketClient.connectAll


connectPrivate() ​

ts
connectPrivate(): Promise<WSConnectedResult | undefined>;

Returns ​

Promise<WSConnectedResult | undefined>


connectPublic() ​

ts
connectPublic(): Promise<WSConnectedResult | undefined>[];

Returns ​

Promise<WSConnectedResult | undefined>[]


connectWSAPI() ​

ts
connectWSAPI(): Promise<unknown>;

Ensures the WS API connection is active and ready.

You do not need to call this, but if you call this before making any WS API requests, it can accelerate the first request (by preparing the connection in advance).

Returns ​

Promise<unknown>


emit() ​

ts
emit<U extends keyof WSClientEventMap<TWSKey>>(event: U, ...args: Parameters<WSClientEventMap<WsKey>[U]>): boolean;

Type Parameters ​

Type Parameter
U extends keyof WSClientEventMap<TWSKey>

Parameters ​

ParameterType
eventU
...argsParameters<WSClientEventMap<WsKey>[U]>

Returns ​

boolean

Inherited from ​

BaseWebsocketClient.emit


getTimeOffsetMs() ​

ts
getTimeOffsetMs(): number;

Returns ​

number

Inherited from ​

BaseWebsocketClient.getTimeOffsetMs


getWsStore() ​

ts
getWsStore(): WsStore<WsKey, WsTopicRequest<string, unknown>>;

Get the WsStore that tracks websockets & topics

Returns ​

WsStore<WsKey, WsTopicRequest<string, unknown>>

Inherited from ​

BaseWebsocketClient.getWsStore


isConnected() ​

ts
isConnected(wsKey: WsKey): boolean;

Parameters ​

ParameterType
wsKeyWsKey

Returns ​

boolean

Inherited from ​

BaseWebsocketClient.isConnected


on() ​

ts
on<U extends keyof WSClientEventMap<TWSKey>>(event: U, listener: WSClientEventMap<WsKey>[U]): this;

Type Parameters ​

Type Parameter
U extends keyof WSClientEventMap<TWSKey>

Parameters ​

ParameterType
eventU
listenerWSClientEventMap<WsKey>[U]

Returns ​

this

Inherited from ​

BaseWebsocketClient.on


sendWSAPIRequest() ​

Call Signature ​

ts
sendWSAPIRequest<TWSKey extends "v5PrivateTrade", TWSOperation extends WSAPIOperation, TWSParams extends Exact<WsAPITopicRequestParamMap[TWSOperation]>>(
   wsKey: TWSKey, 
   operation: TWSOperation, 
   params?: TWSParams extends void ? undefined : TWSParams, 
   requestFlags?: WSAPIRequestFlags
): Promise<WsAPIOperationResponseMap[TWSOperation]>;

Send a Websocket API command/request on a connection. Returns a promise that resolves on reply.

WS API Documentation for list of operations and parameters: https://bybit-exchange.github.io/docs/v5/websocket/trade/guideline

Returned promise is rejected if:

  • an exception is detected in the reply, OR
  • the connection disconnects for any reason (even if automatic reconnect will happen).

Authentication is automatic. If you didn't request authentication yourself, there might be a small delay after your first request, while the SDK automatically authenticates.

Type Parameters ​
Type Parameter
TWSKey extends "v5PrivateTrade"
TWSOperation extends WSAPIOperation
TWSParams extends Exact<WsAPITopicRequestParamMap[TWSOperation]>
Parameters ​
ParameterTypeDescription
wsKeyTWSKeyThe connection this event is for. Currently only "v5PrivateTrade" is supported for Bybit, since that is the dedicated WS API connection.
operationTWSOperationThe command being sent, e.g. "order.create" to submit a new order.
params?TWSParams extends void ? undefined : TWSParamsAny request parameters for the command. E.g. OrderParamsV5 to submit a new order. Only send parameters for the request body. Everything else is automatically handled.
requestFlags?WSAPIRequestFlags-
Returns ​

Promise<WsAPIOperationResponseMap[TWSOperation]>

Promise - tries to resolve with async WS API response. Rejects if disconnected or exception is seen in async WS API response

Overrides ​

BaseWebsocketClient.sendWSAPIRequest

Call Signature ​

ts
sendWSAPIRequest<TWSOperation extends WSAPIOperation = "order.create">(
   wsKey: "v5PrivateTrade", 
   operation: TWSOperation, 
   params: WsAPITopicRequestParamMap[TWSOperation], 
   requestFlags?: WSAPIRequestFlags
): Promise<WsAPIOperationResponseMap[TWSOperation]>;

Send a Websocket API command/request on a connection. Returns a promise that resolves on reply.

WS API Documentation for list of operations and parameters: https://bybit-exchange.github.io/docs/v5/websocket/trade/guideline

Returned promise is rejected if:

  • an exception is detected in the reply, OR
  • the connection disconnects for any reason (even if automatic reconnect will happen).

Authentication is automatic. If you didn't request authentication yourself, there might be a small delay after your first request, while the SDK automatically authenticates.

Type Parameters ​
Type ParameterDefault type
TWSOperation extends WSAPIOperation"order.create"
Parameters ​
ParameterTypeDescription
wsKey"v5PrivateTrade"The connection this event is for. Currently only "v5PrivateTrade" is supported for Bybit, since that is the dedicated WS API connection.
operationTWSOperationThe command being sent, e.g. "order.create" to submit a new order.
paramsWsAPITopicRequestParamMap[TWSOperation]Any request parameters for the command. E.g. OrderParamsV5 to submit a new order. Only send parameters for the request body. Everything else is automatically handled.
requestFlags?WSAPIRequestFlags-
Returns ​

Promise<WsAPIOperationResponseMap[TWSOperation]>

Promise - tries to resolve with async WS API response. Rejects if disconnected or exception is seen in async WS API response

Overrides ​

BaseWebsocketClient.sendWSAPIRequest

Call Signature ​

ts
sendWSAPIRequest<TWSOperation extends WSAPIOperation = "order.amend">(
   wsKey: "v5PrivateTrade", 
   operation: TWSOperation, 
   params: WsAPITopicRequestParamMap[TWSOperation], 
   requestFlags?: WSAPIRequestFlags
): Promise<WsAPIOperationResponseMap[TWSOperation]>;

Send a Websocket API command/request on a connection. Returns a promise that resolves on reply.

WS API Documentation for list of operations and parameters: https://bybit-exchange.github.io/docs/v5/websocket/trade/guideline

Returned promise is rejected if:

  • an exception is detected in the reply, OR
  • the connection disconnects for any reason (even if automatic reconnect will happen).

Authentication is automatic. If you didn't request authentication yourself, there might be a small delay after your first request, while the SDK automatically authenticates.

Type Parameters ​
Type ParameterDefault type
TWSOperation extends WSAPIOperation"order.amend"
Parameters ​
ParameterTypeDescription
wsKey"v5PrivateTrade"The connection this event is for. Currently only "v5PrivateTrade" is supported for Bybit, since that is the dedicated WS API connection.
operationTWSOperationThe command being sent, e.g. "order.create" to submit a new order.
paramsWsAPITopicRequestParamMap[TWSOperation]Any request parameters for the command. E.g. OrderParamsV5 to submit a new order. Only send parameters for the request body. Everything else is automatically handled.
requestFlags?WSAPIRequestFlags-
Returns ​

Promise<WsAPIOperationResponseMap[TWSOperation]>

Promise - tries to resolve with async WS API response. Rejects if disconnected or exception is seen in async WS API response

Overrides ​

BaseWebsocketClient.sendWSAPIRequest

Call Signature ​

ts
sendWSAPIRequest<TWSOperation extends WSAPIOperation = "order.cancel">(
   wsKey: "v5PrivateTrade", 
   operation: TWSOperation, 
   params: WsAPITopicRequestParamMap[TWSOperation], 
   requestFlags?: WSAPIRequestFlags
): Promise<WsAPIOperationResponseMap[TWSOperation]>;

Send a Websocket API command/request on a connection. Returns a promise that resolves on reply.

WS API Documentation for list of operations and parameters: https://bybit-exchange.github.io/docs/v5/websocket/trade/guideline

Returned promise is rejected if:

  • an exception is detected in the reply, OR
  • the connection disconnects for any reason (even if automatic reconnect will happen).

Authentication is automatic. If you didn't request authentication yourself, there might be a small delay after your first request, while the SDK automatically authenticates.

Type Parameters ​
Type ParameterDefault type
TWSOperation extends WSAPIOperation"order.cancel"
Parameters ​
ParameterTypeDescription
wsKey"v5PrivateTrade"The connection this event is for. Currently only "v5PrivateTrade" is supported for Bybit, since that is the dedicated WS API connection.
operationTWSOperationThe command being sent, e.g. "order.create" to submit a new order.
paramsWsAPITopicRequestParamMap[TWSOperation]Any request parameters for the command. E.g. OrderParamsV5 to submit a new order. Only send parameters for the request body. Everything else is automatically handled.
requestFlags?WSAPIRequestFlags-
Returns ​

Promise<WsAPIOperationResponseMap[TWSOperation]>

Promise - tries to resolve with async WS API response. Rejects if disconnected or exception is seen in async WS API response

Overrides ​

BaseWebsocketClient.sendWSAPIRequest


setTimeOffsetMs() ​

ts
setTimeOffsetMs(newOffset: number): void;

Parameters ​

ParameterType
newOffsetnumber

Returns ​

void

Inherited from ​

BaseWebsocketClient.setTimeOffsetMs


subscribe() ​

ts
subscribe(requests: 
  | string
  | WsTopicRequest<string, unknown>
  | (
  | string
  | WsTopicRequest<string, unknown>)[], requestedWsKey?: WsKey): void;

Note: subscribeV5() might be simpler to use. The end result is the same.

Request subscription to one or more topics. Pass topics as either an array of strings, or array of objects (if the topic has parameters).

Objects should be formatted as {topic: string, params: object, category: WSCategoryV5}.

  • Subscriptions are automatically routed to the correct websocket connection.
  • Authentication/connection is automatic.
  • Resubscribe after network issues is automatic.

Call unsubscribe(topics) to remove topics

Parameters ​

ParameterType
requests| string | WsTopicRequest<string, unknown> | ( | string | WsTopicRequest<string, unknown>)[]
requestedWsKey?WsKey

Returns ​

void


subscribeV5() ​

ts
subscribeV5(
   wsTopics: string | string[], 
   category: WSCategoryV5, 
   isPrivateTopic?: boolean
): Promise<unknown>[];

Subscribe to V5 topics & track/persist them.

Parameters ​

ParameterTypeDescription
wsTopicsstring | string[]topic or list of topics
categoryWSCategoryV5the API category this topic is for (e.g. "linear", or "event" for Event Contract public topics). The value is only important when connecting to public topics and will be ignored for private topics.
isPrivateTopic?booleanoptional - the library will try to detect private topics, you can use this to mark a topic as private (if the topic isn't recognised yet)

Returns ​

Promise<unknown>[]

Example ​

ts
import { WebsocketClient } from 'bybit-api';

const ws = new WebsocketClient({});
let stopped = false;
let timer: ReturnType<typeof setTimeout> | undefined;
function stop() {
  if (stopped) return;
  stopped = true;
  clearTimeout(timer);
  ws.closeAll();
}
process.once('SIGINT', stop);
process.once('SIGTERM', stop);
ws.on('update', (message) => console.log(message));
ws.on('exception', () => {
  console.error('WebSocket exception. Check the topic, environment and connection.');
});
async function main() {
  await Promise.all(ws.subscribeV5('tickers.BTCUSDT', 'spot'));
  if (!stopped) timer = setTimeout(stop, 30000);
}
main().catch(() => {
  console.error('Subscription failed.');
  process.exitCode = 1;
  stop();
});

See ​

Subscribe to market data


tryWsSend() ​

ts
tryWsSend(
   wsKey: WsKey, 
   wsMessage: string, 
   throwExceptions?: boolean
): void;

Try sending a string event on a WS connection (identified by the WS Key)

Parameters ​

ParameterType
wsKeyWsKey
wsMessagestring
throwExceptions?boolean

Returns ​

void

Inherited from ​

BaseWebsocketClient.tryWsSend


unsubscribe() ​

ts
unsubscribe(requests: 
  | string
  | WsTopicRequest<string, unknown>
  | (
  | string
  | WsTopicRequest<string, unknown>)[], wsKey?: WsKey): void;

Note: unsubscribe() might be simpler to use. The end result is the same. Unsubscribe from one or more topics. Similar to subscribe() but in reverse.

  • Requests are automatically routed to the correct websocket connection.
  • These topics will be removed from the topic cache, so they won't be subscribed to again.

Parameters ​

ParameterType
requests| string | WsTopicRequest<string, unknown> | ( | string | WsTopicRequest<string, unknown>)[]
wsKey?WsKey

Returns ​

void


unsubscribeV5() ​

ts
unsubscribeV5(
   wsTopics: string | string[], 
   category: WSCategoryV5, 
   isPrivateTopic?: boolean
): Promise<unknown>[];

Unsubscribe from V5 topics & remove them from memory. They won't be re-subscribed to if the connection reconnects.

Parameters ​

ParameterTypeDescription
wsTopicsstring | string[]topic or list of topics
categoryWSCategoryV5the API category this topic is for (e.g. "linear", or "event" for Event Contract public topics). The value is only important when connecting to public topics and will be ignored for private topics.
isPrivateTopic?booleanoptional - the library will try to detect private topics, you can use this to mark a topic as private (if the topic isn't recognised yet)

Returns ​

Promise<unknown>[]

Built by Siebly. Open source SDKs for exchange APIs.