Skip to main content

Documentation Index

Fetch the complete documentation index at: https://mintlify.com/tiagosiebler/binance/llms.txt

Use this file to discover all available pages before exploring further.

WebsocketClient is the primary class for subscribing to Binance WebSocket streams. It manages connection lifecycle, automatic reconnection, heartbeating, and event emission for all product groups — Spot, Margin, USD-M Futures, COIN-M Futures, European Options, Portfolio Margin, and testnet variants. Instantiate it once and subscribe to any number of topics across any supported market.

Constructor

options
WSClientConfigurableOptions
required
Configuration object for the WebSocket client. Common fields include api_key, api_secret, beautify, testnet, and reconnectTimeout. See Types Overview for the full interface.
logger
DefaultLogger
Optional custom logger. Defaults to the built-in DefaultLogger which writes to console.
import { WebsocketClient } from 'binance';

const wsClient = new WebsocketClient({
  api_key: 'YOUR_API_KEY',
  api_secret: 'YOUR_API_SECRET',
  beautify: true,
});
Set beautify: true to receive camelCase formatted events via the formattedMessage and formattedUserDataMessage events. Without it only the raw message event fires.

Core Subscription Methods

These are the lowest-level subscription primitives. All higher-level helpers ultimately delegate to these two methods.

subscribe(topics, wsKey)

Subscribe to one or more raw stream topics on a given WebSocket connection.
topics
string | string[]
required
A single topic string or array of topic strings. Topics use Binance’s stream naming convention, e.g. btcusdt@aggTrade or btcusdt@kline_1m.
wsKey
WsKey
required
The WebSocket connection key that identifies which product-group connection to use. See the WsKey reference table below.
// Subscribe to BTC/USDT 1-minute klines on the USD-M Futures connection
await wsClient.subscribe('btcusdt@kline_1m', 'usdm');

// Subscribe to multiple topics at once
await wsClient.subscribe(['btcusdt@aggTrade', 'ethusdt@aggTrade'], 'main');

unsubscribe(topics, wsKey)

Unsubscribe from one or more previously subscribed topics on a given connection.
topics
string | string[]
required
Topic string(s) to unsubscribe from. Must match the exact topic string used during subscribe.
wsKey
WsKey
required
The WebSocket connection key identifying the connection to unsubscribe from.
await wsClient.unsubscribe('btcusdt@kline_1m', 'usdm');

User Data Stream Methods

User data stream methods manage authenticated private streams for order updates, balance changes, and account events. They handle listen-key creation, renewal, and automatic reconnection internally.
All user data stream methods require api_key and api_secret to be set in the constructor options. The SDK fetches and manages listen keys automatically.

Spot User Data

MethodDescription
subscribeSpotUserDataStream(wsKey?)Fetch a Spot listen key and subscribe to the Spot user data stream. Defaults to wsKey: 'main'.
subscribeSpotUserDataStreamWithListenKey(listenKey, wsKey?)Subscribe to a Spot user data stream using a pre-fetched listen key.
unsubscribeSpotUserDataStream(wsKey?)Unsubscribe from the Spot user data stream and stop listen-key renewal. Defaults to wsKey: 'main'.

Cross Margin User Data

MethodDescription
subscribeCrossMarginUserDataStream()Fetch a Cross Margin listen key and subscribe to the Cross Margin user data stream.
unsubscribeCrossMarginUserDataStream()Unsubscribe from the Cross Margin user data stream.

Isolated Margin User Data

MethodDescription
subscribeIsolatedMarginUserDataStream(symbol)Fetch a per-symbol Isolated Margin listen key and subscribe to its user data stream. The symbol parameter (e.g. 'BTCUSDT') identifies which isolated margin account to stream.
unsubscribeIsolatedMarginUserDataStream(symbol)Unsubscribe from the Isolated Margin user data stream for the given symbol.

USD-M Futures User Data

MethodDescription
subscribeUsdFuturesUserDataStream()Fetch a USD-M Futures listen key and subscribe to the futures user data stream.
unsubscribeUsdFuturesUserDataStream()Unsubscribe from the USD-M Futures user data stream.

COIN-M Futures User Data

MethodDescription
subscribeCoinFuturesUserDataStream()Fetch a COIN-M Futures listen key and subscribe to the COIN-M user data stream.
unsubscribeCoinFuturesUserDataStream()Unsubscribe from the COIN-M Futures user data stream.

Margin Risk User Data

MethodDescription
subscribeMarginRiskUserDataStream()Fetch a Margin Risk listen key and subscribe to the Margin Risk user data stream (risk monitoring).
unsubscribeMarginRiskUserDataStream()Unsubscribe from the Margin Risk user data stream.

Portfolio Margin User Data

MethodDescription
subscribePortfolioMarginUserDataStream()Fetch a Portfolio Margin listen key and subscribe to the Portfolio Margin user data stream.
unsubscribePortfolioMarginUserDataStream()Unsubscribe from the Portfolio Margin user data stream.
// Subscribe to Spot user data stream
await wsClient.subscribeSpotUserDataStream();

// Subscribe to USD-M Futures user data stream
await wsClient.subscribeUsdFuturesUserDataStream();

// Handle user data events
wsClient.on('formattedUserDataMessage', (data) => {
  console.log('User data event:', data.eventType, data);
});

Legacy Topic Helpers

These convenience methods construct the correct raw topic string and call subscribe internally. They accept human-readable parameters instead of raw Binance stream names.
These helpers were added in earlier versions and remain fully supported. New code may prefer using subscribe() directly with explicit topic strings for more control.
MethodParametersDescription
subscribeAggregateTrades(symbol, market)symbol: string, market: WsMarketSubscribe to the compressed/aggregate trade stream for a symbol.
subscribeTrades(symbol, market)symbol: string, market: WsMarketSubscribe to the raw trade stream for a symbol.
subscribeKlines(symbol, interval, market)symbol: string, interval: KlineInterval, market: WsMarketSubscribe to candlestick (kline) updates.
subscribeContinuousContractKlines(symbol, contractType, interval, market)symbol: string, contractType: FuturesContractType, interval: KlineInterval, market: WsMarketSubscribe to continuous contract kline updates (futures only).
subscribeMarkPrice(symbol, market)symbol: string, market: WsMarketSubscribe to mark price updates for a symbol.
subscribeAllMarketMarkPrice(market)market: WsMarketSubscribe to mark price updates for all symbols on a market.
subscribeSymbol24hrTicker(symbol, market)symbol: string, market: WsMarketSubscribe to the 24-hour rolling window ticker for a symbol.
subscribeAllMini24hrTickers(market)market: WsMarketSubscribe to the all-symbol mini 24-hour ticker stream.
subscribeSymbolBookTicker(symbol, market)symbol: string, market: WsMarketSubscribe to the best bid/ask stream for a symbol.
subscribePartialBookDepths(symbol, levels, speed, market)symbol: string, levels: number, speed: number, market: WsMarketSubscribe to a partial order book snapshot at the given depth level.
subscribeDiffBookDepth(symbol, speed, market)symbol: string, speed: number, market: WsMarketSubscribe to the incremental diff book depth stream.
import { WebsocketClient } from 'binance';

const wsClient = new WebsocketClient({ beautify: true });

// Subscribe to BTC/USDT aggregate trades on USD-M Futures
wsClient.subscribeAggregateTrades('BTCUSDT', 'usdm');

// Subscribe to 1-minute klines on Spot
wsClient.subscribeKlines('ETHUSDT', '1m', 'spot');

// Subscribe to partial book depth (top 5 levels, 100ms updates)
wsClient.subscribePartialBookDepths('BTCUSDT', 5, 100, 'spot');

Events

WebsocketClient extends EventEmitter. Use .on(event, handler) to listen to events. All event handlers receive a payload that always includes the wsKey identifying which connection it originated from.
EventPayloadWhen Fired
open{ wsKey, event, wsUrl, ws }A new WebSocket connection is opened for the first time.
reconnected{ wsKey, event, wsUrl, ws }A previously dropped connection has been successfully restored.
reconnecting{ wsKey, event }A connection has dropped and a reconnection attempt is in progress.
close{ wsKey, event }A connection has been closed.
messageWsRawMessage & { wsKey }A raw (unprocessed) WebSocket message is received. Fires for every message regardless of beautify setting.
formattedMessageWsFormattedMessageA beautified, camelCase-formatted event message. Only fires when beautify: true is set in options.
formattedUserDataMessageWsUserDataEventsA formatted user data event. Only fires when beautify: true is set. Useful for narrowing with type guards.
responseany & { wsKey, isWSAPIResponse? }Confirmation response to a WebSocket subscribe/unsubscribe command or a WS API call.
exceptionany & { wsKey }An error or unhandled exception from the WebSocket client or an event handler.
import { WebsocketClient } from 'binance';
import {
  isWsFormattedKline,
  isWsFormattedMarkPriceUpdateEvent,
  isWsFormattedUserDataEvent,
} from 'binance';

const wsClient = new WebsocketClient({
  api_key: 'YOUR_API_KEY',
  api_secret: 'YOUR_API_SECRET',
  beautify: true,
});

wsClient.on('open', ({ wsKey, wsUrl }) => {
  console.log(`Connected [${wsKey}]: ${wsUrl}`);
});

wsClient.on('reconnecting', ({ wsKey }) => {
  console.warn(`Reconnecting [${wsKey}]...`);
});

wsClient.on('reconnected', ({ wsKey }) => {
  console.log(`Reconnected [${wsKey}]`);
});

wsClient.on('formattedMessage', (data) => {
  if (isWsFormattedKline(data)) {
    console.log(`Kline [${data.symbol}]:`, data.kline.close);
    return;
  }
  if (isWsFormattedMarkPriceUpdateEvent(data)) {
    console.log(`Mark price [${data.symbol}]:`, data.markPrice);
    return;
  }
});

wsClient.on('formattedUserDataMessage', (data) => {
  console.log('User data event:', data.eventType);
});

wsClient.on('exception', (err) => {
  console.error('WebSocket exception:', err);
});

// Subscribe to streams
wsClient.subscribeKlines('BTCUSDT', '1m', 'usdm');
wsClient.subscribeUsdFuturesUserDataStream();

WsKey Values

A WsKey is a string literal that identifies which underlying WebSocket connection to use. The SDK maintains one connection per WsKey and automatically routes topics to the correct connection.
WsKeyProduct GroupNotes
'main'Spot, Cross Margin, Isolated MarginPrimary Spot/Margin connection. Handles both public streams and user data.
'main2'Spot, Cross Margin, Isolated MarginAlternative Spot connection (same product group as main).
'main3'Spot, Cross MarginMarket data only — user data is not supported on this key.
'mainWSAPI'Spot WS APIWebSocket API connection for Spot/Margin order management.
'mainWSAPI2'Spot WS APIAlternative WebSocket API connection for Spot/Margin.
'mainWSAPITestnet'Spot WS API TestnetWebSocket API testnet connection for Spot/Margin.
'marginRiskUserData'Margin RiskMargin risk user data stream (risk monitoring).
'marginUserData'Margin User DataMargin user data stream via WS API listen-key mechanism.
'usdm'USD-M FuturesPrimary USD-M Futures connection. Auto-routes topics to split sub-keys.
'usdmPublic'USD-M FuturesHigh-frequency public data: book ticker and depth.
'usdmMarket'USD-M FuturesAll other USD-M market data streams.
'usdmPrivate'USD-M FuturesUSD-M user data stream only.
'usdmTestnet'USD-M Futures TestnetUSD-M Futures testnet connection.
'usdmTestnetPublic'USD-M Futures TestnetUSD-M Futures testnet high-frequency public data.
'usdmTestnetPrivate'USD-M Futures TestnetUSD-M Futures testnet user data stream.
'usdmTestnetMarket'USD-M Futures TestnetUSD-M Futures testnet other market data.
'usdmWSAPI'USD-M Futures WS APIWebSocket API connection for USD-M Futures order management.
'usdmWSAPITestnet'USD-M Futures WS API TestnetWebSocket API testnet for USD-M Futures.
'coinm'COIN-M FuturesPrimary COIN-M Futures connection.
'coinm2'COIN-M FuturesAlternative COIN-M Futures connection (requires listen key).
'coinmTestnet'COIN-M Futures TestnetCOIN-M Futures testnet connection.
'coinmWSAPI'COIN-M Futures WS APIWebSocket API connection for COIN-M Futures order management.
'coinmWSAPITestnet'COIN-M Futures WS API TestnetWebSocket API testnet for COIN-M Futures.
'eoptions'European OptionsBinance European Options market data and user data.
'portfolioMarginUserData'Portfolio MarginPortfolio Margin user data stream.
'portfolioMarginProUserData'Portfolio Margin ProPortfolio Margin Pro user data stream.
'mainTestnetPublic'Spot TestnetPublic Spot testnet streams. Set testnet: true or use this key directly.
'mainTestnetUserData'Spot TestnetSpot testnet user data.
'alpha'Alpha TradingBinance Alpha trading WebSocket market data.
When testnet: true is passed to the constructor, the SDK automatically maps standard WsKey values to their testnet equivalents. You don’t need to change your wsKey values — just set testnet: true.

Build docs developers (and LLMs) love