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
BaseWebsocketClient<WsKey,WsRequestOperationBinance<WsTopic>>
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, WsRequestOperationBinance<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
closeUserDataStream()
closeUserDataStream(
wsKey: WsKey,
wsMarket: WsMarket,
symbol?: string
): Promise<void>;Close an active, dedicated, user data stream connection.
Parameters
| Parameter | Type | Description |
|---|---|---|
wsKey | WsKey | the 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. |
wsMarket | WsMarket | the 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()
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 & 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()
connectPrivate(): Promise<WebSocket | undefined>;This function serves no purpose in the Binance SDK
Returns
Promise<WebSocket | undefined>
connectPublic()
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()
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
| Parameter | Type |
|---|---|
wsKey | WSAPIWsKey |
skipAuth? | boolean |
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
fetchMarginListenToken()
fetchMarginListenToken(params?: object): Promise<{
expirationTime: number;
token: string;
}>;Parameters
| Parameter | Type |
|---|---|
params? | { isIsolated?: boolean; symbol?: string; validity?: number; } |
params.isIsolated? | boolean |
params.symbol? | string |
params.validity? | number |
Returns
Promise<{ expirationTime: number; token: string; }>
getCachedMidFlightRequest()
getCachedMidFlightRequest(wsKey: WsKey, requestKey: string):
| WsRequestOperationBinance<string, any>
| undefined;Parameters
| Parameter | Type |
|---|---|
wsKey | WsKey |
requestKey | string |
Returns
| WsRequestOperationBinance<string, any> | undefined
Inherited from
BaseWebsocketClient.getCachedMidFlightRequest
getSignKeyType()
getSignKeyType(): SignKeyType | undefined;Returns
SignKeyType | undefined
Inherited from
BaseWebsocketClient.getSignKeyType
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
getWsUrl()
getWsUrl(wsKey: WsKey, connectionType?: "public" | "market" | "private"): Promise<string>;Parameters
| Parameter | Type | Default value |
|---|---|---|
wsKey | WsKey | undefined |
connectionType? | "public" | "market" | "private" | 'market' |
Returns
Promise<string>
The WS URL to connect to for this WS key
Overrides
BaseWebsocketClient.getWsUrl
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
removeCachedMidFlightRequest()
removeCachedMidFlightRequest(wsKey: WsKey, requestKey: string): void;Parameters
| Parameter | Type |
|---|---|
wsKey | WsKey |
requestKey | string |
Returns
void
Inherited from
BaseWebsocketClient.removeCachedMidFlightRequest
sendWSAPIRequest()
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:
- Spot: https://developers.binance.com/docs/binance-spot-api-docs/websocket-api/general-api-information
- USDM Futures: https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-api-general-info
- COINM Futures: https://developers.binance.com/docs/derivatives/coin-margined-futures/websocket-api-general-info
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 Parameter | Default 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 unknown | WsAPIOperationResponseMap[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<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()
setAuthEveryRequest(enabled: boolean): this;Parameters
| Parameter | Type |
|---|---|
enabled | boolean |
Returns
this
Inherited from
BaseWebsocketClient.setAuthEveryRequest
setAuthOnConnect()
setAuthOnConnect(enabled: boolean): this;Parameters
| Parameter | Type |
|---|---|
enabled | boolean |
Returns
this
Inherited from
BaseWebsocketClient.setAuthOnConnect
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>)[], 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
| Parameter | Type |
|---|---|
requests | | string | WsTopicRequest<string, unknown> | ( | string | WsTopicRequest<string, unknown>)[] |
wsKey | WsKey |
Returns
Promise<unknown>
subscribeAggregateTrades()
subscribeAggregateTrades(
symbol: string,
market: "spot" | "usdm" | "coinm",
wsKeyOverride?: WsKey
): Promise<unknown>;Subscribe to aggregate trades for a symbol in a market category
Parameters
| Parameter | Type |
|---|---|
symbol | string |
market | "spot" | "usdm" | "coinm" |
wsKeyOverride? | WsKey |
Returns
Promise<unknown>
subscribeAll24hrTickers()
subscribeAll24hrTickers(market: "spot" | "usdm" | "coinm", wsKeyOverride?: WsKey): Promise<unknown>;Subscribe to 24hr ticker in any market.
Parameters
| Parameter | Type |
|---|---|
market | "spot" | "usdm" | "coinm" |
wsKeyOverride? | WsKey |
Returns
Promise<unknown>
subscribeAllBookTickers()
subscribeAllBookTickers(market: "usdm" | "coinm", wsKeyOverride?: WsKey): Promise<unknown>;Subscribe to best bid/ask for all symbols in spot markets.
Parameters
| Parameter | Type |
|---|---|
market | "usdm" | "coinm" |
wsKeyOverride? | WsKey |
Returns
Promise<unknown>
subscribeAllLiquidationOrders()
subscribeAllLiquidationOrders(market: "usdm" | "coinm", wsKeyOverride?: WsKey): Promise<unknown>;Subscribe to best bid/ask for all symbols in spot markets.
Parameters
| Parameter | Type |
|---|---|
market | "usdm" | "coinm" |
wsKeyOverride? | WsKey |
Returns
Promise<unknown>
subscribeAllMarketMarkPrice()
subscribeAllMarketMarkPrice(
market: "usdm" | "coinm",
updateSpeedMs?: 1000 | 3000,
wsKeyOverride?: WsKey
): Promise<unknown>;Subscribe to mark price for all symbols in a market category
Parameters
| Parameter | Type | Default value |
|---|---|---|
market | "usdm" | "coinm" | undefined |
updateSpeedMs? | 1000 | 3000 | 3000 |
wsKeyOverride? | WsKey | undefined |
Returns
Promise<unknown>
subscribeAllMini24hrTickers()
subscribeAllMini24hrTickers(market: "spot" | "usdm" | "coinm", wsKeyOverride?: WsKey): Promise<unknown>;Subscribe to mini 24hr mini ticker in market category.
Parameters
| Parameter | Type |
|---|---|
market | "spot" | "usdm" | "coinm" |
wsKeyOverride? | WsKey |
Returns
Promise<unknown>
subscribeAllRollingWindowTickers()
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
| Parameter | Type |
|---|---|
market | "spot" |
windowSize | "1h" | "4h" | "1d" |
wsKeyOverride? | WsKey |
Returns
Promise<unknown>
subscribeAlpha()
subscribeAlpha(topics: string | string[]): Promise<unknown>;Subscribe to Alpha Trading WebSocket Market Data streams. Base URL: wss://nbstream.binance.com/w3w/wsa/stream
Parameters
| Parameter | Type |
|---|---|
topics | string | string[] |
Returns
Promise<unknown>
subscribeAlphaAggTrade()
subscribeAlphaAggTrade(symbol: string): Promise<unknown>;Subscribe to Alpha aggregate trades for a symbol
Parameters
| Parameter | Type | Description |
|---|---|---|
symbol | string | e.g. ALPHA_474USDT |
Returns
Promise<unknown>
subscribeAlphaAllTokensTicker24()
subscribeAlphaAllTokensTicker24(): Promise<unknown>;Subscribe to Alpha all tokens 24h ticker (came@allTokens@ticker24)
Returns
Promise<unknown>
subscribeAlphaFulldepth()
subscribeAlphaFulldepth(symbol: string, intervalMs?: 0 | 100 | 500): Promise<unknown>;Subscribe to Alpha full depth for a symbol
Parameters
| Parameter | Type | Default value | Description |
|---|---|---|---|
symbol | string | undefined | e.g. ALPHA_474USDT |
intervalMs? | 0 | 100 | 500 | 500 | 0, 100, or 500 |
Returns
Promise<unknown>
subscribeAlphaKline()
subscribeAlphaKline(
contractAddress: string,
chainId: string,
interval: "1s" | "1m" | "5m" | "15m" | "1h" | "4h" | "1d"
): Promise<unknown>;Subscribe to Alpha klines for a contract
Parameters
| Parameter | Type | Description |
|---|---|---|
contractAddress | string | Contract address |
chainId | string | Chain 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()
subscribeBlockTrades(symbol: string, wsKeyOverride?: WsKey): Promise<unknown>;Subscribe to block trades for a symbol in spot markets.
Parameters
| Parameter | Type |
|---|---|
symbol | string |
wsKeyOverride? | WsKey |
Returns
Promise<unknown>
subscribeCoinFuturesUserDataStream()
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
| Parameter | Type | Default value |
|---|---|---|
wsKey? | WsKey | 'coinm' |
forceNewConnection? | boolean | undefined |
miscState? | MiscUserDataConnectionState | undefined |
Returns
Promise<WSConnectedResult | undefined>
subscribeCoinIndexPrice()
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
| Parameter | Type | Default value |
|---|---|---|
symbol | string | undefined |
_updateSpeedMs? | 1000 | 3000 | 3000 |
wsKeyOverride? | WsKey | undefined |
Returns
Promise<unknown>
subscribeContinuousContractKlines()
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
| Parameter | Type |
|---|---|
symbol | string |
contractType | "perpetual" | "current_quarter" | "next_quarter" |
interval | KlineInterval |
market | "usdm" | "coinm" |
wsKeyOverride? | WsKey |
Returns
Promise<unknown>
subscribeContractInfoStream()
subscribeContractInfoStream(market: "usdm" | "coinm", wsKeyOverride?: WsKey): Promise<unknown>;Subscribe to best bid/ask for all symbols in spot markets.
Parameters
| Parameter | Type |
|---|---|
market | "usdm" | "coinm" |
wsKeyOverride? | WsKey |
Returns
Promise<unknown>
subscribeCrossMarginUserDataStream()
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
| Parameter | Type | Default value |
|---|---|---|
wsKey? | WsKey | 'main' |
forceNewConnection? | boolean | undefined |
miscState? | MiscUserDataConnectionState | undefined |
Returns
Promise<WSConnectedResult | undefined>
subscribeDiffBookDepth()
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
- Spot: https://binance-docs.github.io/apidocs/spot/en/#diff-depth-stream
- USDM Futures: https://binance-docs.github.io/apidocs/futures/en/#diff-book-depth-streams
Parameters
| Parameter | Type | Default value |
|---|---|---|
symbol | string | undefined |
updateMs? | 100 | 250 | 500 | 1000 | 100 |
market | "spot" | "usdm" | "coinm" | undefined |
wsKeyOverride? | WsKey | undefined |
Returns
Promise<unknown>
subscribeEndpoint()
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
| Parameter | Type |
|---|---|
endpoint | string |
market | "spot" | "usdm" | "coinm" |
Returns
Promise<unknown>
subscribeIndexKlines()
subscribeIndexKlines(
symbol: string,
interval: KlineInterval,
wsKeyOverride?: WsKey
): Promise<unknown>;Subscribe to index klines(candles) for a symbol in a coinm futures
Parameters
| Parameter | Type |
|---|---|
symbol | string |
interval | KlineInterval |
wsKeyOverride? | WsKey |
Returns
Promise<unknown>
subscribeIsolatedMarginUserDataStream()
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
| Parameter | Type | Default value |
|---|---|---|
symbol | string | undefined |
wsKey? | WsKey | 'main' |
forceNewConnection? | boolean | undefined |
miscState? | MiscUserDataConnectionState | undefined |
Returns
Promise<WSConnectedResult | undefined>
subscribeKlines()
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
| Parameter | Type |
|---|---|
symbol | string |
interval | KlineInterval |
market | "spot" | "usdm" | "coinm" |
wsKeyOverride? | WsKey |
Returns
Promise<unknown>
subscribeMarginRiskUserDataStream()
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
| Parameter | Type | Default value |
|---|---|---|
wsKey? | WsKey | 'main' |
forceNewConnection? | boolean | undefined |
miscState? | MiscUserDataConnectionState | undefined |
Returns
Promise<WSConnectedResult | undefined>
subscribeMarkPrice()
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
| Parameter | Type | Default value |
|---|---|---|
symbol | string | undefined |
market | "usdm" | "coinm" | undefined |
updateSpeedMs? | 1000 | 3000 | 3000 |
wsKeyOverride? | WsKey | undefined |
Returns
Promise<unknown>
subscribeMarkPriceKlines()
subscribeMarkPriceKlines(
symbol: string,
interval: KlineInterval,
wsKeyOverride?: WsKey
): Promise<unknown>;Subscribe to index klines(candles) for a symbol in a coinm futures
Parameters
| Parameter | Type |
|---|---|
symbol | string |
interval | KlineInterval |
wsKeyOverride? | WsKey |
Returns
Promise<unknown>
subscribePartialBookDepths()
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
| Parameter | Type |
|---|---|
symbol | string |
levels | 5 | 10 | 20 |
updateMs | 100 | 250 | 500 | 1000 |
market | "spot" | "usdm" | "coinm" |
wsKeyOverride? | WsKey |
Returns
Promise<unknown>
subscribePortfolioMarginUserDataStream()
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
| Parameter | Type | Default value |
|---|---|---|
wsKey? | WsKey | 'portfolioMarginUserData' |
forceNewConnection? | boolean | undefined |
miscState? | MiscUserDataConnectionState | undefined |
Returns
Promise<WSConnectedResult | undefined>
subscribeSpotAggregateTrades()
subscribeSpotAggregateTrades(symbol: string, wsKeyOverride?: WsKey): Promise<unknown>;Subscribe to aggregate trades for a symbol in spot markets.
Parameters
| Parameter | Type |
|---|---|
symbol | string |
wsKeyOverride? | WsKey |
Returns
Promise<unknown>
subscribeSpotAll24hrTickers()
subscribeSpotAll24hrTickers(wsKeyOverride?: WsKey): Promise<unknown>;Subscribe to 24hr ticker in spot markets.
Parameters
| Parameter | Type |
|---|---|
wsKeyOverride? | WsKey |
Returns
Promise<unknown>
subscribeSpotAllMini24hrTickers()
subscribeSpotAllMini24hrTickers(wsKeyOverride?: WsKey): Promise<unknown>;Subscribe to mini 24hr mini ticker in spot markets.
Parameters
| Parameter | Type |
|---|---|
wsKeyOverride? | WsKey |
Returns
Promise<unknown>
subscribeSpotBlockTrades()
subscribeSpotBlockTrades(symbol: string, wsKeyOverride?: WsKey): Promise<unknown>;Subscribe to block trades for a symbol in spot markets.
Parameters
| Parameter | Type |
|---|---|
symbol | string |
wsKeyOverride? | WsKey |
Returns
Promise<unknown>
subscribeSpotDiffBookDepth()
subscribeSpotDiffBookDepth(
symbol: string,
updateMs?: 100 | 1000,
wsKeyOverride?: WsKey
): Promise<unknown>;Subscribe to spot orderbook depth updates to locally manage an order book.
Parameters
| Parameter | Type | Default value |
|---|---|---|
symbol | string | undefined |
updateMs? | 100 | 1000 | 1000 |
wsKeyOverride? | WsKey | undefined |
Returns
Promise<unknown>
subscribeSpotKline()
subscribeSpotKline(
symbol: string,
interval: KlineInterval,
wsKeyOverride?: WsKey
): Promise<unknown>;Subscribe to candles for a symbol in spot markets.
Parameters
| Parameter | Type |
|---|---|
symbol | string |
interval | KlineInterval |
wsKeyOverride? | WsKey |
Returns
Promise<unknown>
subscribeSpotPartialBookDepth()
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
| Parameter | Type | Default value |
|---|---|---|
symbol | string | undefined |
levels | 5 | 10 | 20 | undefined |
updateMs? | 100 | 1000 | 1000 |
wsKeyOverride? | WsKey | undefined |
Returns
Promise<unknown>
subscribeSpotSymbol24hrTicker()
subscribeSpotSymbol24hrTicker(symbol: string, wsKeyOverride?: WsKey): Promise<unknown>;Subscribe to 24hr ticker for a symbol in spot markets.
Parameters
| Parameter | Type |
|---|---|
symbol | string |
wsKeyOverride? | WsKey |
Returns
Promise<unknown>
Example
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
subscribeSpotSymbolBookTicker()
subscribeSpotSymbolBookTicker(symbol: string, wsKeyOverride?: WsKey): Promise<unknown>;Subscribe to best bid/ask for symbol in spot markets.
Parameters
| Parameter | Type |
|---|---|
symbol | string |
wsKeyOverride? | WsKey |
Returns
Promise<unknown>
subscribeSpotSymbolMini24hrTicker()
subscribeSpotSymbolMini24hrTicker(symbol: string, wsKeyOverride?: WsKey): Promise<unknown>;Subscribe to mini 24hr ticker for a symbol in spot markets.
Parameters
| Parameter | Type |
|---|---|
symbol | string |
wsKeyOverride? | WsKey |
Returns
Promise<unknown>
subscribeSpotTrades()
subscribeSpotTrades(symbol: string, wsKeyOverride?: WsKey): Promise<unknown>;Subscribe to trades for a symbol in spot markets.
Parameters
| Parameter | Type |
|---|---|
symbol | string |
wsKeyOverride? | WsKey |
Returns
Promise<unknown>
subscribeSpotUserDataStream()
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
| Parameter | Type | Default value |
|---|---|---|
wsKey? | WsKey | 'main' |
forceNewConnection? | boolean | undefined |
miscState? | MiscUserDataConnectionState | undefined |
Returns
Promise<WSConnectedResult | undefined>
subscribeSpotUserDataStreamWithListenKey()
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
| Parameter | Type |
|---|---|
wsKey | WsKey |
listenKey | string |
forceNewConnection? | boolean |
miscState? | MiscUserDataConnectionState |
Returns
Promise<WSConnectedResult | undefined>
subscribeSymbol24hrTicker()
subscribeSymbol24hrTicker(
symbol: string,
market: "spot" | "usdm" | "coinm",
wsKeyOverride?: WsKey
): Promise<unknown>;Subscribe to 24hr ticker for a symbol in any market.
Parameters
| Parameter | Type |
|---|---|
symbol | string |
market | "spot" | "usdm" | "coinm" |
wsKeyOverride? | WsKey |
Returns
Promise<unknown>
subscribeSymbolBookTicker()
subscribeSymbolBookTicker(
symbol: string,
market: "spot" | "usdm" | "coinm",
wsKeyOverride?: WsKey
): Promise<unknown>;Subscribe to best bid/ask for symbol in spot markets.
Parameters
| Parameter | Type |
|---|---|
symbol | string |
market | "spot" | "usdm" | "coinm" |
wsKeyOverride? | WsKey |
Returns
Promise<unknown>
subscribeSymbolLiquidationOrders()
subscribeSymbolLiquidationOrders(
symbol: string,
market: "usdm" | "coinm",
wsKeyOverride?: WsKey
): Promise<unknown>;Subscribe to best bid/ask for symbol in spot markets.
Parameters
| Parameter | Type |
|---|---|
symbol | string |
market | "usdm" | "coinm" |
wsKeyOverride? | WsKey |
Returns
Promise<unknown>
subscribeSymbolMini24hrTicker()
subscribeSymbolMini24hrTicker(
symbol: string,
market: "spot" | "usdm" | "coinm",
wsKeyOverride?: WsKey
): Promise<unknown>;Subscribe to mini 24hr ticker for a symbol in market category.
Parameters
| Parameter | Type |
|---|---|
symbol | string |
market | "spot" | "usdm" | "coinm" |
wsKeyOverride? | WsKey |
Returns
Promise<unknown>
subscribeTrades()
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
| Parameter | Type |
|---|---|
symbol | string |
market | "spot" | "usdm" | "coinm" |
wsKeyOverride? | WsKey |
Returns
Promise<unknown>
subscribeUsdFuturesUserDataStream()
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
| Parameter | Type | Default value |
|---|---|---|
userWsKey? | WsKey | WS_KEY_MAP.usdmPrivate |
forceNewConnection? | boolean | undefined |
miscState? | MiscUserDataConnectionState | undefined |
Returns
Promise<WSConnectedResult | undefined>
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): 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
| Parameter | Type |
|---|---|
requests | | string | WsTopicRequest<string, unknown> | ( | string | WsTopicRequest<string, unknown>)[] |
wsKey | WsKey |
Returns
Promise<unknown[]>
unsubscribeCoinFuturesUserDataStream()
unsubscribeCoinFuturesUserDataStream(wsKey?: WsKey): Promise<void>;Parameters
| Parameter | Type | Default value |
|---|---|---|
wsKey? | WsKey | 'coinm' |
Returns
Promise<void>
unsubscribeCrossMarginUserDataStream()
unsubscribeCrossMarginUserDataStream(wsKey?: WsKey): Promise<void>;Parameters
| Parameter | Type | Default value |
|---|---|---|
wsKey? | WsKey | 'main' |
Returns
Promise<void>
unsubscribeIsolatedMarginUserDataStream()
unsubscribeIsolatedMarginUserDataStream(symbol: string, wsKey?: WsKey): Promise<void>;Parameters
| Parameter | Type | Default value |
|---|---|---|
symbol | string | undefined |
wsKey? | WsKey | 'main' |
Returns
Promise<void>
unsubscribeMarginRiskUserDataStream()
unsubscribeMarginRiskUserDataStream(wsKey?: WsKey): Promise<void>;Parameters
| Parameter | Type | Default value |
|---|---|---|
wsKey? | WsKey | 'main' |
Returns
Promise<void>
unsubscribePortfolioMarginUserDataStream()
unsubscribePortfolioMarginUserDataStream(wsKey?: WsKey): Promise<void>;Parameters
| Parameter | Type | Default value |
|---|---|---|
wsKey? | WsKey | 'portfolioMarginUserData' |
Returns
Promise<void>
unsubscribeSpotUserDataStream()
unsubscribeSpotUserDataStream(wsKey?: WsKey): Promise<void>;Parameters
| Parameter | Type | Default value |
|---|---|---|
wsKey? | WsKey | 'main' |
Returns
Promise<void>
unsubscribeUsdFuturesUserDataStream()
unsubscribeUsdFuturesUserDataStream(wsKey?: WsKey): Promise<void>;Parameters
| Parameter | Type | Default value |
|---|---|---|
wsKey? | WsKey | WS_KEY_MAP.usdmPrivate |
Returns
Promise<void>