Skip to content

Class: WebsocketClient ​

Multiplex Node.js, JavaScript & TypeScript Websocket Client for all of Binance's available WebSockets.

When possible, it will subscribe to all requested topics on a single websocket connection. A list of all available streams can be seen in the WS_KEY_URL_MAP found in util/websockets/websocket-util.ts.

Connectivity is automatically maintained. If disconnected, the WebsocketClient will automatically clean out the old dead connection, respawn a fresh one and resubscribe to all the requested topics.

If any connection is reconnected, the WS client will:

  • Emit the "reconnecting" event when the process begins.
  • Emit the "reconnected" event, when the process has completed. When this event arrives, it is often a good time to execute any synchorisation workflow (e.g. via the REST API) if any information was missed while disconnected.

User data streams will use a dedicated connection per stream for increased resilience.

Extends ​

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, WsRequestOperationBinance<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


closeUserDataStream() ​

ts
closeUserDataStream(
   wsKey: WsKey, 
   wsMarket: WsMarket, 
   symbol?: string
): Promise<void>;

Close an active, dedicated, user data stream connection.

Parameters ​

ParameterTypeDescription
wsKeyWsKeythe connection key used to open the connection (excluding any automatic parameters such as the listen key). E.g. 'main' for spot/margin, 'usdm' for futures.
wsMarketWsMarketthe product group, recommended if you're subscribed to both spot and margin (since they're on the same wsKey (main)).
symbol?string-

Returns ​

Promise<void>


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 & WS API) websockets in prod, instead of waiting for automatic connection by SDK.

For the Binance SDK, this will only open public connections (without auth), but is almost definitely overkill if you're only working with one product group.

Returns ​

Promise<WSConnectedResult | undefined>[]

Overrides ​

BaseWebsocketClient.connectAll


connectPrivate() ​

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

This function serves no purpose in the Binance SDK

Returns ​

Promise<WebSocket | undefined>


connectPublic() ​

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

Request connection to all public websockets in prod (spot, margin, futures, options). Overkill if you're only working with one product group.

Returns ​

Promise<WSConnectedResult | undefined>[]


connectWSAPI() ​

ts
connectWSAPI(wsKey: WSAPIWsKey, skipAuth?: boolean): 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).

Parameters ​

ParameterType
wsKeyWSAPIWsKey
skipAuth?boolean

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


fetchMarginListenToken() ​

ts
fetchMarginListenToken(params?: object): Promise<{
  expirationTime: number;
  token: string;
}>;

Parameters ​

ParameterType
params?{ isIsolated?: boolean; symbol?: string; validity?: number; }
params.isIsolated?boolean
params.symbol?string
params.validity?number

Returns ​

Promise<{ expirationTime: number; token: string; }>


getCachedMidFlightRequest() ​

ts
getCachedMidFlightRequest(wsKey: WsKey, requestKey: string): 
  | WsRequestOperationBinance<string, any>
  | undefined;

Parameters ​

ParameterType
wsKeyWsKey
requestKeystring

Returns ​

| WsRequestOperationBinance<string, any> | undefined

Inherited from ​

BaseWebsocketClient.getCachedMidFlightRequest


getSignKeyType() ​

ts
getSignKeyType(): SignKeyType | undefined;

Returns ​

SignKeyType | undefined

Inherited from ​

BaseWebsocketClient.getSignKeyType


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


getWsUrl() ​

ts
getWsUrl(wsKey: WsKey, connectionType?: "public" | "market" | "private"): Promise<string>;

Parameters ​

ParameterTypeDefault value
wsKeyWsKeyundefined
connectionType?"public" | "market" | "private"'market'

Returns ​

Promise<string>

The WS URL to connect to for this WS key

Overrides ​

BaseWebsocketClient.getWsUrl


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


removeCachedMidFlightRequest() ​

ts
removeCachedMidFlightRequest(wsKey: WsKey, requestKey: string): void;

Parameters ​

ParameterType
wsKeyWsKey
requestKeystring

Returns ​

void

Inherited from ​

BaseWebsocketClient.removeCachedMidFlightRequest


sendWSAPIRequest() ​

ts
sendWSAPIRequest<TWSKey extends keyof WsAPIWsKeyTopicMap, TWSOperation extends 
  | "ticker"
  | "depth"
  | "ping"
  | WsOperation
  | "session.logon"
  | "session.status"
  | "session.logout"
  | "time"
  | "exchangeInfo"
  | "trades.recent"
  | "trades.historical"
  | "blockTrades.historical"
  | "trades.aggregate"
  | "klines"
  | "uiKlines"
  | "avgPrice"
  | "executionRules"
  | "referencePrice"
  | "referencePrice.calculation"
  | "ticker.24hr"
  | "ticker.tradingDay"
  | "ticker.price"
  | "ticker.book"
  | "account.status"
  | "account.commission"
  | "account.rateLimits.orders"
  | "allOrders"
  | "allOrderLists"
  | "myTrades"
  | "myPreventedMatches"
  | "myAllocations"
  | "v2/account.balance"
  | "account.balance"
  | "v2/account.status"
  | "account.position"
  | "v2/account.position"
  | "order.place"
  | "order.test"
  | "order.status"
  | "order.cancel"
  | "order.cancelReplace"
  | "order.amend.keepPriority"
  | "order.modify"
  | "openOrders.status"
  | "openOrders.cancelAll"
  | "algoOrder.place"
  | "algoOrder.cancel"
  | "orderList.place"
  | "orderList.place.oco"
  | "orderList.place.oto"
  | "orderList.place.otoco"
  | "orderList.place.opo"
  | "orderList.place.opoco"
  | "orderList.status"
  | "orderList.cancel"
  | "openOrderLists.status"
  | "sor.order.place"
  | "sor.order.test"
  | "userDataStream.start"
  | "userDataStream.ping"
  | "userDataStream.stop"
  | "userDataStream.subscribe"
  | "userDataStream.subscribe.signature"
  | "userDataStream.unsubscribe"
  | "userDataStream.subscribe.listenToken", TWSParams extends { [K in string | number | symbol]: WsAPITopicRequestParamMap<TWSKey>[TWSOperation][K] }, TWSAPIResponse extends unknown = WsAPIOperationResponseMap[TWSOperation]>(
   wsKey: TWSKey, 
   operation: TWSOperation, 
   params?: TWSParams extends void ? undefined : TWSParams, 
   requestFlags?: WSAPIRequestFlags
): Promise<TWSAPIResponse>;

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:

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.

Misc options:

  • signRequest: boolean - if included, this request will automatically be signed with the available credentials.

Type Parameters ​

Type ParameterDefault type
TWSKey extends keyof WsAPIWsKeyTopicMap-
TWSOperation extends | "ticker" | "depth" | "ping" | WsOperation | "session.logon" | "session.status" | "session.logout" | "time" | "exchangeInfo" | "trades.recent" | "trades.historical" | "blockTrades.historical" | "trades.aggregate" | "klines" | "uiKlines" | "avgPrice" | "executionRules" | "referencePrice" | "referencePrice.calculation" | "ticker.24hr" | "ticker.tradingDay" | "ticker.price" | "ticker.book" | "account.status" | "account.commission" | "account.rateLimits.orders" | "allOrders" | "allOrderLists" | "myTrades" | "myPreventedMatches" | "myAllocations" | "v2/account.balance" | "account.balance" | "v2/account.status" | "account.position" | "v2/account.position" | "order.place" | "order.test" | "order.status" | "order.cancel" | "order.cancelReplace" | "order.amend.keepPriority" | "order.modify" | "openOrders.status" | "openOrders.cancelAll" | "algoOrder.place" | "algoOrder.cancel" | "orderList.place" | "orderList.place.oco" | "orderList.place.oto" | "orderList.place.otoco" | "orderList.place.opo" | "orderList.place.opoco" | "orderList.status" | "orderList.cancel" | "openOrderLists.status" | "sor.order.place" | "sor.order.test" | "userDataStream.start" | "userDataStream.ping" | "userDataStream.stop" | "userDataStream.subscribe" | "userDataStream.subscribe.signature" | "userDataStream.unsubscribe" | "userDataStream.subscribe.listenToken"-
TWSParams extends { [K in string | number | symbol]: WsAPITopicRequestParamMap<TWSKey>[TWSOperation][K] }-
TWSAPIResponse extends unknownWsAPIOperationResponseMap[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<TWSAPIResponse>

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

Overrides ​

BaseWebsocketClient.sendWSAPIRequest


setAuthEveryRequest() ​

ts
setAuthEveryRequest(enabled: boolean): this;

Parameters ​

ParameterType
enabledboolean

Returns ​

this

Inherited from ​

BaseWebsocketClient.setAuthEveryRequest


setAuthOnConnect() ​

ts
setAuthOnConnect(enabled: boolean): this;

Parameters ​

ParameterType
enabledboolean

Returns ​

this

Inherited from ​

BaseWebsocketClient.setAuthOnConnect


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>)[], wsKey: WsKey): Promise<unknown>;

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: CategoryV5}.

  • 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>)[]
wsKeyWsKey

Returns ​

Promise<unknown>


subscribeAggregateTrades() ​

ts
subscribeAggregateTrades(
   symbol: string, 
   market: "spot" | "usdm" | "coinm", 
   wsKeyOverride?: WsKey
): Promise<unknown>;

Subscribe to aggregate trades for a symbol in a market category

Parameters ​

ParameterType
symbolstring
market"spot" | "usdm" | "coinm"
wsKeyOverride?WsKey

Returns ​

Promise<unknown>


subscribeAll24hrTickers() ​

ts
subscribeAll24hrTickers(market: "spot" | "usdm" | "coinm", wsKeyOverride?: WsKey): Promise<unknown>;

Subscribe to 24hr ticker in any market.

Parameters ​

ParameterType
market"spot" | "usdm" | "coinm"
wsKeyOverride?WsKey

Returns ​

Promise<unknown>


subscribeAllBookTickers() ​

ts
subscribeAllBookTickers(market: "usdm" | "coinm", wsKeyOverride?: WsKey): Promise<unknown>;

Subscribe to best bid/ask for all symbols in spot markets.

Parameters ​

ParameterType
market"usdm" | "coinm"
wsKeyOverride?WsKey

Returns ​

Promise<unknown>


subscribeAllLiquidationOrders() ​

ts
subscribeAllLiquidationOrders(market: "usdm" | "coinm", wsKeyOverride?: WsKey): Promise<unknown>;

Subscribe to best bid/ask for all symbols in spot markets.

Parameters ​

ParameterType
market"usdm" | "coinm"
wsKeyOverride?WsKey

Returns ​

Promise<unknown>


subscribeAllMarketMarkPrice() ​

ts
subscribeAllMarketMarkPrice(
   market: "usdm" | "coinm", 
   updateSpeedMs?: 1000 | 3000, 
   wsKeyOverride?: WsKey
): Promise<unknown>;

Subscribe to mark price for all symbols in a market category

Parameters ​

ParameterTypeDefault value
market"usdm" | "coinm"undefined
updateSpeedMs?1000 | 30003000
wsKeyOverride?WsKeyundefined

Returns ​

Promise<unknown>


subscribeAllMini24hrTickers() ​

ts
subscribeAllMini24hrTickers(market: "spot" | "usdm" | "coinm", wsKeyOverride?: WsKey): Promise<unknown>;

Subscribe to mini 24hr mini ticker in market category.

Parameters ​

ParameterType
market"spot" | "usdm" | "coinm"
wsKeyOverride?WsKey

Returns ​

Promise<unknown>


subscribeAllRollingWindowTickers() ​

ts
subscribeAllRollingWindowTickers(
   market: "spot", 
   windowSize: "1h" | "4h" | "1d", 
   wsKeyOverride?: WsKey
): Promise<unknown>;

Subscribe to rolling window ticker statistics for all market symbols, computed over multiple windows. Note that only tickers that have changed will be present in the array.

Notes:

  • Supported window sizes: 1h,4h,1d.
  • Supported markets: spot

Parameters ​

ParameterType
market"spot"
windowSize"1h" | "4h" | "1d"
wsKeyOverride?WsKey

Returns ​

Promise<unknown>


subscribeAlpha() ​

ts
subscribeAlpha(topics: string | string[]): Promise<unknown>;

Subscribe to Alpha Trading WebSocket Market Data streams. Base URL: wss://nbstream.binance.com/w3w/wsa/stream

Parameters ​

ParameterType
topicsstring | string[]

Returns ​

Promise<unknown>


subscribeAlphaAggTrade() ​

ts
subscribeAlphaAggTrade(symbol: string): Promise<unknown>;

Subscribe to Alpha aggregate trades for a symbol

Parameters ​

ParameterTypeDescription
symbolstringe.g. ALPHA_474USDT

Returns ​

Promise<unknown>


subscribeAlphaAllTokensTicker24() ​

ts
subscribeAlphaAllTokensTicker24(): Promise<unknown>;

Subscribe to Alpha all tokens 24h ticker (came@allTokens@ticker24)

Returns ​

Promise<unknown>


subscribeAlphaFulldepth() ​

ts
subscribeAlphaFulldepth(symbol: string, intervalMs?: 0 | 100 | 500): Promise<unknown>;

Subscribe to Alpha full depth for a symbol

Parameters ​

ParameterTypeDefault valueDescription
symbolstringundefinede.g. ALPHA_474USDT
intervalMs?0 | 100 | 5005000, 100, or 500

Returns ​

Promise<unknown>


subscribeAlphaKline() ​

ts
subscribeAlphaKline(
   contractAddress: string, 
   chainId: string, 
   interval: "1s" | "1m" | "5m" | "15m" | "1h" | "4h" | "1d"
): Promise<unknown>;

Subscribe to Alpha klines for a contract

Parameters ​

ParameterTypeDescription
contractAddressstringContract address
chainIdstringChain ID (e.g. CT_501, 56)
interval"1s" | "1m" | "5m" | "15m" | "1h" | "4h" | "1d"1s, 1m, 5m, 15m, 1h, 4h, 1d

Returns ​

Promise<unknown>


subscribeBlockTrades() ​

ts
subscribeBlockTrades(symbol: string, wsKeyOverride?: WsKey): Promise<unknown>;

Subscribe to block trades for a symbol in spot markets.

Parameters ​

ParameterType
symbolstring
wsKeyOverride?WsKey

Returns ​

Promise<unknown>


subscribeCoinFuturesUserDataStream() ​

ts
subscribeCoinFuturesUserDataStream(
   wsKey?: WsKey, 
   forceNewConnection?: boolean, 
   miscState?: MiscUserDataConnectionState
): Promise<WSConnectedResult | undefined>;

Subscribe to COIN-M Futures user data stream - listen key is automatically generated. Calling multiple times only opens one connection.

Note: the wsKey parameter is optional, but can be used to connect to other environments for this product group.

Parameters ​

ParameterTypeDefault value
wsKey?WsKey'coinm'
forceNewConnection?booleanundefined
miscState?MiscUserDataConnectionStateundefined

Returns ​

Promise<WSConnectedResult | undefined>


subscribeCoinIndexPrice() ​

ts
subscribeCoinIndexPrice(
   symbol: string, 
   _updateSpeedMs?: 1000 | 3000, 
   wsKeyOverride?: WsKey
): Promise<unknown>;

Subscribe to coin index for a symbol in COINM Futures markets _updateSpeedMs is ignored (<pair>@indexPrice@1s was removed). Drop this arg in the next major.

Parameters ​

ParameterTypeDefault value
symbolstringundefined
_updateSpeedMs?1000 | 30003000
wsKeyOverride?WsKeyundefined

Returns ​

Promise<unknown>


subscribeContinuousContractKlines() ​

ts
subscribeContinuousContractKlines(
   symbol: string, 
   contractType: "perpetual" | "current_quarter" | "next_quarter", 
   interval: KlineInterval, 
   market: "usdm" | "coinm", 
   wsKeyOverride?: WsKey
): Promise<unknown>;

Subscribe to continuous contract klines(candles) for a symbol futures

Parameters ​

ParameterType
symbolstring
contractType"perpetual" | "current_quarter" | "next_quarter"
intervalKlineInterval
market"usdm" | "coinm"
wsKeyOverride?WsKey

Returns ​

Promise<unknown>


subscribeContractInfoStream() ​

ts
subscribeContractInfoStream(market: "usdm" | "coinm", wsKeyOverride?: WsKey): Promise<unknown>;

Subscribe to best bid/ask for all symbols in spot markets.

Parameters ​

ParameterType
market"usdm" | "coinm"
wsKeyOverride?WsKey

Returns ​

Promise<unknown>


subscribeCrossMarginUserDataStream() ​

ts
subscribeCrossMarginUserDataStream(
   wsKey?: WsKey, 
   forceNewConnection?: boolean, 
   miscState?: MiscUserDataConnectionState
): Promise<WSConnectedResult | undefined>;

Subscribe to margin user data stream - listen key is automatically generated. Calling multiple times only opens one connection.

Note: the wsKey parameter is optional, but can be used to connect to other environments for this product group (e.g. port 9443 (main) vs 443 (main2))

Parameters ​

ParameterTypeDefault value
wsKey?WsKey'main'
forceNewConnection?booleanundefined
miscState?MiscUserDataConnectionStateundefined

Returns ​

Promise<WSConnectedResult | undefined>


subscribeDiffBookDepth() ​

ts
subscribeDiffBookDepth(
   symbol: string, 
   updateMs?: 100 | 250 | 500 | 1000, 
   market: "spot" | "usdm" | "coinm", 
   wsKeyOverride?: WsKey
): Promise<unknown>;

Subscribe to orderbook depth updates to locally manage an order book.

Note that the updatems parameter depends on which market you're trading

Parameters ​

ParameterTypeDefault value
symbolstringundefined
updateMs?100 | 250 | 500 | 1000100
market"spot" | "usdm" | "coinm"undefined
wsKeyOverride?WsKeyundefined

Returns ​

Promise<unknown>


subscribeEndpoint() ​

ts
subscribeEndpoint(endpoint: string, market: "spot" | "usdm" | "coinm"): Promise<unknown>;

Advanced: Subscribe to a universal market websocket stream

This is NOT recommended unless you're very confident with what you're doing.

Parameters ​

ParameterType
endpointstring
market"spot" | "usdm" | "coinm"

Returns ​

Promise<unknown>


subscribeIndexKlines() ​

ts
subscribeIndexKlines(
   symbol: string, 
   interval: KlineInterval, 
   wsKeyOverride?: WsKey
): Promise<unknown>;

Subscribe to index klines(candles) for a symbol in a coinm futures

Parameters ​

ParameterType
symbolstring
intervalKlineInterval
wsKeyOverride?WsKey

Returns ​

Promise<unknown>


subscribeIsolatedMarginUserDataStream() ​

ts
subscribeIsolatedMarginUserDataStream(
   symbol: string, 
   wsKey?: WsKey, 
   forceNewConnection?: boolean, 
   miscState?: MiscUserDataConnectionState
): Promise<WSConnectedResult | undefined>;

Subscribe to isolated margin user data stream - listen key is automatically generated. Calling multiple times only opens one connection.

Note: the wsKey parameter is optional, but can be used to connect to other environments for this product group (e.g. port 9443 (main) vs 443 (main2))

Parameters ​

ParameterTypeDefault value
symbolstringundefined
wsKey?WsKey'main'
forceNewConnection?booleanundefined
miscState?MiscUserDataConnectionStateundefined

Returns ​

Promise<WSConnectedResult | undefined>


subscribeKlines() ​

ts
subscribeKlines(
   symbol: string, 
   interval: KlineInterval, 
   market: "spot" | "usdm" | "coinm", 
   wsKeyOverride?: WsKey
): Promise<unknown>;

Subscribe to klines(candles) for a symbol in a market category

Parameters ​

ParameterType
symbolstring
intervalKlineInterval
market"spot" | "usdm" | "coinm"
wsKeyOverride?WsKey

Returns ​

Promise<unknown>


subscribeMarginRiskUserDataStream() ​

ts
subscribeMarginRiskUserDataStream(
   wsKey?: WsKey, 
   forceNewConnection?: boolean, 
   miscState?: MiscUserDataConnectionState
): Promise<WSConnectedResult | undefined>;

Subscribe to margin risk user data stream - listen key is automatically generated. Calling multiple times only opens one connection.

Note: the wsKey parameter is optional, but can be used to connect to other environments for this product group (e.g. port 9443 (main) vs 443 (main2))

Parameters ​

ParameterTypeDefault value
wsKey?WsKey'main'
forceNewConnection?booleanundefined
miscState?MiscUserDataConnectionStateundefined

Returns ​

Promise<WSConnectedResult | undefined>


subscribeMarkPrice() ​

ts
subscribeMarkPrice(
   symbol: string, 
   market: "usdm" | "coinm", 
   updateSpeedMs?: 1000 | 3000, 
   wsKeyOverride?: WsKey
): Promise<unknown>;

Subscribe to mark price for a symbol in a market category

Parameters ​

ParameterTypeDefault value
symbolstringundefined
market"usdm" | "coinm"undefined
updateSpeedMs?1000 | 30003000
wsKeyOverride?WsKeyundefined

Returns ​

Promise<unknown>


subscribeMarkPriceKlines() ​

ts
subscribeMarkPriceKlines(
   symbol: string, 
   interval: KlineInterval, 
   wsKeyOverride?: WsKey
): Promise<unknown>;

Subscribe to index klines(candles) for a symbol in a coinm futures

Parameters ​

ParameterType
symbolstring
intervalKlineInterval
wsKeyOverride?WsKey

Returns ​

Promise<unknown>


subscribePartialBookDepths() ​

ts
subscribePartialBookDepths(
   symbol: string, 
   levels: 5 | 10 | 20, 
   updateMs: 100 | 250 | 500 | 1000, 
   market: "spot" | "usdm" | "coinm", 
   wsKeyOverride?: WsKey
): Promise<unknown>;

Subscribe to partial book depths (snapshots).

Note:

  • spot only supports 1000ms or 100ms for updateMs
  • futures only support 100, 250 or 500ms for updateMs

Parameters ​

ParameterType
symbolstring
levels5 | 10 | 20
updateMs100 | 250 | 500 | 1000
market"spot" | "usdm" | "coinm"
wsKeyOverride?WsKey

Returns ​

Promise<unknown>


subscribePortfolioMarginUserDataStream() ​

ts
subscribePortfolioMarginUserDataStream(
   wsKey?: WsKey, 
   forceNewConnection?: boolean, 
   miscState?: MiscUserDataConnectionState
): Promise<WSConnectedResult | undefined>;

Subscribe to Portfolio Margin user data stream - listen key is automatically generated. Calling multiple times only opens one connection.

Note: the wsKey parameter is optional, but can be used to connect to other environments for this product group.

Parameters ​

ParameterTypeDefault value
wsKey?WsKey'portfolioMarginUserData'
forceNewConnection?booleanundefined
miscState?MiscUserDataConnectionStateundefined

Returns ​

Promise<WSConnectedResult | undefined>


subscribeSpotAggregateTrades() ​

ts
subscribeSpotAggregateTrades(symbol: string, wsKeyOverride?: WsKey): Promise<unknown>;

Subscribe to aggregate trades for a symbol in spot markets.

Parameters ​

ParameterType
symbolstring
wsKeyOverride?WsKey

Returns ​

Promise<unknown>


subscribeSpotAll24hrTickers() ​

ts
subscribeSpotAll24hrTickers(wsKeyOverride?: WsKey): Promise<unknown>;

Subscribe to 24hr ticker in spot markets.

Parameters ​

ParameterType
wsKeyOverride?WsKey

Returns ​

Promise<unknown>


subscribeSpotAllMini24hrTickers() ​

ts
subscribeSpotAllMini24hrTickers(wsKeyOverride?: WsKey): Promise<unknown>;

Subscribe to mini 24hr mini ticker in spot markets.

Parameters ​

ParameterType
wsKeyOverride?WsKey

Returns ​

Promise<unknown>


subscribeSpotBlockTrades() ​

ts
subscribeSpotBlockTrades(symbol: string, wsKeyOverride?: WsKey): Promise<unknown>;

Subscribe to block trades for a symbol in spot markets.

Parameters ​

ParameterType
symbolstring
wsKeyOverride?WsKey

Returns ​

Promise<unknown>


subscribeSpotDiffBookDepth() ​

ts
subscribeSpotDiffBookDepth(
   symbol: string, 
   updateMs?: 100 | 1000, 
   wsKeyOverride?: WsKey
): Promise<unknown>;

Subscribe to spot orderbook depth updates to locally manage an order book.

Parameters ​

ParameterTypeDefault value
symbolstringundefined
updateMs?100 | 10001000
wsKeyOverride?WsKeyundefined

Returns ​

Promise<unknown>


subscribeSpotKline() ​

ts
subscribeSpotKline(
   symbol: string, 
   interval: KlineInterval, 
   wsKeyOverride?: WsKey
): Promise<unknown>;

Subscribe to candles for a symbol in spot markets.

Parameters ​

ParameterType
symbolstring
intervalKlineInterval
wsKeyOverride?WsKey

Returns ​

Promise<unknown>


subscribeSpotPartialBookDepth() ​

ts
subscribeSpotPartialBookDepth(
   symbol: string, 
   levels: 5 | 10 | 20, 
   updateMs?: 100 | 1000, 
   wsKeyOverride?: WsKey
): Promise<unknown>;

Subscribe to top bid/ask levels for symbol in spot markets.

Parameters ​

ParameterTypeDefault value
symbolstringundefined
levels5 | 10 | 20undefined
updateMs?100 | 10001000
wsKeyOverride?WsKeyundefined

Returns ​

Promise<unknown>


subscribeSpotSymbol24hrTicker() ​

ts
subscribeSpotSymbol24hrTicker(symbol: string, wsKeyOverride?: WsKey): Promise<unknown>;

Subscribe to 24hr ticker for a symbol in spot markets.

Parameters ​

ParameterType
symbolstring
wsKeyOverride?WsKey

Returns ​

Promise<unknown>

Example ​

ts
import { WebsocketClient } from 'binance';

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('message', (message) => console.log(message));
ws.on('exception', () => {
  console.error('WebSocket exception. Check the topic, environment and connection.');
});
async function main() {
  await ws.subscribeSpotSymbol24hrTicker('btcusdt');
  if (!stopped) timer = setTimeout(stop, 30000);
}
main().catch(() => {
  console.error('Subscription failed.');
  process.exitCode = 1;
  stop();
});

See ​

Subscribe to market data


subscribeSpotSymbolBookTicker() ​

ts
subscribeSpotSymbolBookTicker(symbol: string, wsKeyOverride?: WsKey): Promise<unknown>;

Subscribe to best bid/ask for symbol in spot markets.

Parameters ​

ParameterType
symbolstring
wsKeyOverride?WsKey

Returns ​

Promise<unknown>


subscribeSpotSymbolMini24hrTicker() ​

ts
subscribeSpotSymbolMini24hrTicker(symbol: string, wsKeyOverride?: WsKey): Promise<unknown>;

Subscribe to mini 24hr ticker for a symbol in spot markets.

Parameters ​

ParameterType
symbolstring
wsKeyOverride?WsKey

Returns ​

Promise<unknown>


subscribeSpotTrades() ​

ts
subscribeSpotTrades(symbol: string, wsKeyOverride?: WsKey): Promise<unknown>;

Subscribe to trades for a symbol in spot markets.

Parameters ​

ParameterType
symbolstring
wsKeyOverride?WsKey

Returns ​

Promise<unknown>


subscribeSpotUserDataStream() ​

ts
subscribeSpotUserDataStream(
   wsKey?: WsKey, 
   forceNewConnection?: boolean, 
   miscState?: MiscUserDataConnectionState
): Promise<WSConnectedResult | undefined>;

Subscribe to spot user data stream - listen key is automatically generated. Calling multiple times only opens one connection.

Note: the wsKey parameter is optional, but can be used to connect to other environments for this product group (e.g. port 9443 (main) vs 443 (main2))

Parameters ​

ParameterTypeDefault value
wsKey?WsKey'main'
forceNewConnection?booleanundefined
miscState?MiscUserDataConnectionStateundefined

Returns ​

Promise<WSConnectedResult | undefined>


subscribeSpotUserDataStreamWithListenKey() ​

ts
subscribeSpotUserDataStreamWithListenKey(
   wsKey: WsKey, 
   listenKey: string, 
   forceNewConnection?: boolean, 
   miscState?: MiscUserDataConnectionState
): Promise<WSConnectedResult | undefined>;

Subscribe to a spot user data stream. Use REST client to generate and persist listen key. Supports spot, margin & isolated margin listen keys.

Parameters ​

ParameterType
wsKeyWsKey
listenKeystring
forceNewConnection?boolean
miscState?MiscUserDataConnectionState

Returns ​

Promise<WSConnectedResult | undefined>


subscribeSymbol24hrTicker() ​

ts
subscribeSymbol24hrTicker(
   symbol: string, 
   market: "spot" | "usdm" | "coinm", 
   wsKeyOverride?: WsKey
): Promise<unknown>;

Subscribe to 24hr ticker for a symbol in any market.

Parameters ​

ParameterType
symbolstring
market"spot" | "usdm" | "coinm"
wsKeyOverride?WsKey

Returns ​

Promise<unknown>


subscribeSymbolBookTicker() ​

ts
subscribeSymbolBookTicker(
   symbol: string, 
   market: "spot" | "usdm" | "coinm", 
   wsKeyOverride?: WsKey
): Promise<unknown>;

Subscribe to best bid/ask for symbol in spot markets.

Parameters ​

ParameterType
symbolstring
market"spot" | "usdm" | "coinm"
wsKeyOverride?WsKey

Returns ​

Promise<unknown>


subscribeSymbolLiquidationOrders() ​

ts
subscribeSymbolLiquidationOrders(
   symbol: string, 
   market: "usdm" | "coinm", 
   wsKeyOverride?: WsKey
): Promise<unknown>;

Subscribe to best bid/ask for symbol in spot markets.

Parameters ​

ParameterType
symbolstring
market"usdm" | "coinm"
wsKeyOverride?WsKey

Returns ​

Promise<unknown>


subscribeSymbolMini24hrTicker() ​

ts
subscribeSymbolMini24hrTicker(
   symbol: string, 
   market: "spot" | "usdm" | "coinm", 
   wsKeyOverride?: WsKey
): Promise<unknown>;

Subscribe to mini 24hr ticker for a symbol in market category.

Parameters ​

ParameterType
symbolstring
market"spot" | "usdm" | "coinm"
wsKeyOverride?WsKey

Returns ​

Promise<unknown>


subscribeTrades() ​

ts
subscribeTrades(
   symbol: string, 
   market: "spot" | "usdm" | "coinm", 
   wsKeyOverride?: WsKey
): Promise<unknown>;

Subscribe to trades for a symbol in a market category IMPORTANT: This topic for usdm and coinm is not listed in the api docs and might stop working without warning

Parameters ​

ParameterType
symbolstring
market"spot" | "usdm" | "coinm"
wsKeyOverride?WsKey

Returns ​

Promise<unknown>


subscribeUsdFuturesUserDataStream() ​

ts
subscribeUsdFuturesUserDataStream(
   userWsKey?: WsKey, 
   forceNewConnection?: boolean, 
   miscState?: MiscUserDataConnectionState
): Promise<WSConnectedResult | undefined>;

Subscribe to USD-M Futures user data stream - listen key is automatically generated. Calling multiple times only opens one connection.

Note: the wsKey parameter is optional, but can be used to connect to other environments for this product group.

Parameters ​

ParameterTypeDefault value
userWsKey?WsKeyWS_KEY_MAP.usdmPrivate
forceNewConnection?booleanundefined
miscState?MiscUserDataConnectionStateundefined

Returns ​

Promise<WSConnectedResult | undefined>


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): Promise<unknown[]>;

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>)[]
wsKeyWsKey

Returns ​

Promise<unknown[]>


unsubscribeCoinFuturesUserDataStream() ​

ts
unsubscribeCoinFuturesUserDataStream(wsKey?: WsKey): Promise<void>;

Parameters ​

ParameterTypeDefault value
wsKey?WsKey'coinm'

Returns ​

Promise<void>


unsubscribeCrossMarginUserDataStream() ​

ts
unsubscribeCrossMarginUserDataStream(wsKey?: WsKey): Promise<void>;

Parameters ​

ParameterTypeDefault value
wsKey?WsKey'main'

Returns ​

Promise<void>


unsubscribeIsolatedMarginUserDataStream() ​

ts
unsubscribeIsolatedMarginUserDataStream(symbol: string, wsKey?: WsKey): Promise<void>;

Parameters ​

ParameterTypeDefault value
symbolstringundefined
wsKey?WsKey'main'

Returns ​

Promise<void>


unsubscribeMarginRiskUserDataStream() ​

ts
unsubscribeMarginRiskUserDataStream(wsKey?: WsKey): Promise<void>;

Parameters ​

ParameterTypeDefault value
wsKey?WsKey'main'

Returns ​

Promise<void>


unsubscribePortfolioMarginUserDataStream() ​

ts
unsubscribePortfolioMarginUserDataStream(wsKey?: WsKey): Promise<void>;

Parameters ​

ParameterTypeDefault value
wsKey?WsKey'portfolioMarginUserData'

Returns ​

Promise<void>


unsubscribeSpotUserDataStream() ​

ts
unsubscribeSpotUserDataStream(wsKey?: WsKey): Promise<void>;

Parameters ​

ParameterTypeDefault value
wsKey?WsKey'main'

Returns ​

Promise<void>


unsubscribeUsdFuturesUserDataStream() ​

ts
unsubscribeUsdFuturesUserDataStream(wsKey?: WsKey): Promise<void>;

Parameters ​

ParameterTypeDefault value
wsKey?WsKeyWS_KEY_MAP.usdmPrivate

Returns ​

Promise<void>

Built by Siebly. Open source SDKs for exchange APIs.