Class: WebsocketClient
Extends
Constructors
Constructor
new WebsocketClient(options?: WSClientConfigurableOptions, logger?: object): WebsocketClient;Parameters
| Parameter | Type | Description |
|---|---|---|
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) => void | Ping/pong events and other raw messages that might be noisy. Enable this while troubleshooting. |
Returns
WebsocketClient
Overrides
BaseWebsocketClient<WsKey, WsRequestOperationBybit<WsTopic>>.constructor
Properties
logger
logger: object;error
error: (...params: any) => void;Parameters
| Parameter | Type |
|---|---|
...params | any |
Returns
void
info
info: (...params: any) => void;Parameters
| Parameter | Type |
|---|---|
...params | any |
Returns
void
trace
trace: (..._params: any) => void;Ping/pong events and other raw messages that might be noisy. Enable this while troubleshooting.
Parameters
| Parameter | Type |
|---|---|
..._params | any |
Returns
void
Inherited from
BaseWebsocketClient.logger
Methods
assertIsAuthenticated()
assertIsAuthenticated(wsKey: WsKey): Promise<unknown>;Promise-driven method to assert that a ws has been successfully authenticated (will await until auth is confirmed)
Parameters
| Parameter | Type |
|---|---|
wsKey | WsKey |
Returns
Promise<unknown>
Inherited from
BaseWebsocketClient.assertIsAuthenticated
assertIsConnected()
assertIsConnected(wsKey: WsKey): Promise<unknown>;Promise-driven method to assert that a ws has successfully connected (will await until connection is open)
Parameters
| Parameter | Type |
|---|---|
wsKey | WsKey |
Returns
Promise<unknown>
Inherited from
BaseWebsocketClient.assertIsConnected
close()
close(wsKey: WsKey, force?: boolean): void;Parameters
| Parameter | Type |
|---|---|
wsKey | WsKey |
force? | boolean |
Returns
void
Inherited from
BaseWebsocketClient.close
closeAll()
closeAll(force?: boolean): void;Parameters
| Parameter | Type |
|---|---|
force? | boolean |
Returns
void
See
Inherited from
BaseWebsocketClient.closeAll
connect()
connect(
wsKey: WsKey,
customUrl?: string,
throwOnError?: boolean
): Promise<WSConnectedResult | undefined>;Request connection to a specific websocket, instead of waiting for automatic connection.
Parameters
| Parameter | Type |
|---|---|
wsKey | WsKey |
customUrl? | string |
throwOnError? | boolean |
Returns
Promise<WSConnectedResult | undefined>
Inherited from
BaseWebsocketClient.connect
connectAll()
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()
connectPrivate(): Promise<WSConnectedResult | undefined>;Returns
Promise<WSConnectedResult | undefined>
connectPublic()
connectPublic(): Promise<WSConnectedResult | undefined>[];Returns
Promise<WSConnectedResult | undefined>[]
connectWSAPI()
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()
emit<U extends keyof WSClientEventMap<TWSKey>>(event: U, ...args: Parameters<WSClientEventMap<WsKey>[U]>): boolean;Type Parameters
| Type Parameter |
|---|
U extends keyof WSClientEventMap<TWSKey> |
Parameters
| Parameter | Type |
|---|---|
event | U |
...args | Parameters<WSClientEventMap<WsKey>[U]> |
Returns
boolean
Inherited from
BaseWebsocketClient.emit
getTimeOffsetMs()
getTimeOffsetMs(): number;Returns
number
Inherited from
BaseWebsocketClient.getTimeOffsetMs
getWsStore()
getWsStore(): WsStore<WsKey, WsTopicRequest<string, unknown>>;Get the WsStore that tracks websockets & topics
Returns
WsStore<WsKey, WsTopicRequest<string, unknown>>
Inherited from
BaseWebsocketClient.getWsStore
isConnected()
isConnected(wsKey: WsKey): boolean;Parameters
| Parameter | Type |
|---|---|
wsKey | WsKey |
Returns
boolean
Inherited from
BaseWebsocketClient.isConnected
on()
on<U extends keyof WSClientEventMap<TWSKey>>(event: U, listener: WSClientEventMap<WsKey>[U]): this;Type Parameters
| Type Parameter |
|---|
U extends keyof WSClientEventMap<TWSKey> |
Parameters
| Parameter | Type |
|---|---|
event | U |
listener | WSClientEventMap<WsKey>[U] |
Returns
this
Inherited from
BaseWebsocketClient.on
sendWSAPIRequest()
Call Signature
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
| Parameter | Type | Description |
|---|---|---|
wsKey | TWSKey | The connection this event is for. Currently only "v5PrivateTrade" is supported for Bybit, since that is the dedicated WS API connection. |
operation | TWSOperation | The command being sent, e.g. "order.create" to submit a new order. |
params? | TWSParams extends void ? undefined : TWSParams | 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
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 Parameter | Default type |
|---|---|
TWSOperation extends WSAPIOperation | "order.create" |
Parameters
| Parameter | Type | Description |
|---|---|---|
wsKey | "v5PrivateTrade" | The connection this event is for. Currently only "v5PrivateTrade" is supported for Bybit, since that is the dedicated WS API connection. |
operation | TWSOperation | The command being sent, e.g. "order.create" to submit a new order. |
params | WsAPITopicRequestParamMap[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
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 Parameter | Default type |
|---|---|
TWSOperation extends WSAPIOperation | "order.amend" |
Parameters
| Parameter | Type | Description |
|---|---|---|
wsKey | "v5PrivateTrade" | The connection this event is for. Currently only "v5PrivateTrade" is supported for Bybit, since that is the dedicated WS API connection. |
operation | TWSOperation | The command being sent, e.g. "order.create" to submit a new order. |
params | WsAPITopicRequestParamMap[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
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 Parameter | Default type |
|---|---|
TWSOperation extends WSAPIOperation | "order.cancel" |
Parameters
| Parameter | Type | Description |
|---|---|---|
wsKey | "v5PrivateTrade" | The connection this event is for. Currently only "v5PrivateTrade" is supported for Bybit, since that is the dedicated WS API connection. |
operation | TWSOperation | The command being sent, e.g. "order.create" to submit a new order. |
params | WsAPITopicRequestParamMap[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()
setTimeOffsetMs(newOffset: number): void;Parameters
| Parameter | Type |
|---|---|
newOffset | number |
Returns
void
Inherited from
BaseWebsocketClient.setTimeOffsetMs
subscribe()
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
| Parameter | Type |
|---|---|
requests | | string | WsTopicRequest<string, unknown> | ( | string | WsTopicRequest<string, unknown>)[] |
requestedWsKey? | WsKey |
Returns
void
subscribeV5()
subscribeV5(
wsTopics: string | string[],
category: WSCategoryV5,
isPrivateTopic?: boolean
): Promise<unknown>[];Subscribe to V5 topics & track/persist them.
Parameters
| Parameter | Type | Description |
|---|---|---|
wsTopics | string | string[] | topic or list of topics |
category | WSCategoryV5 | the 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? | boolean | optional - 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
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
tryWsSend()
tryWsSend(
wsKey: WsKey,
wsMessage: string,
throwExceptions?: boolean
): void;Try sending a string event on a WS connection (identified by the WS Key)
Parameters
| Parameter | Type |
|---|---|
wsKey | WsKey |
wsMessage | string |
throwExceptions? | boolean |
Returns
void
Inherited from
BaseWebsocketClient.tryWsSend
unsubscribe()
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
| Parameter | Type |
|---|---|
requests | | string | WsTopicRequest<string, unknown> | ( | string | WsTopicRequest<string, unknown>)[] |
wsKey? | WsKey |
Returns
void
unsubscribeV5()
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
| Parameter | Type | Description |
|---|---|---|
wsTopics | string | string[] | topic or list of topics |
category | WSCategoryV5 | the 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? | boolean | optional - 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>[]