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.

WebsocketAPIClient wraps the Binance WebSocket API (WS API) with a promise-based interface, routing each call over a persistent WebSocket connection instead of REST. This reduces per-request latency compared to HTTP, especially for order placement and cancellation. Every method returns a typed Promise<WSAPIResponse<T>> that resolves when the exchange replies over the WebSocket. The client handles authentication, connection management, and optional automatic reconnection internally.
The WebSocket API is distinct from WebSocket market data streams. It is used for placing orders, querying account data, and market snapshots — not for subscribing to live event streams. For live streams, use WebsocketClient instead.

Constructor

import { WebsocketAPIClient } from 'binance';

const wsApiClient = new WebsocketAPIClient({
  api_key: 'YOUR_API_KEY',
  api_secret: 'YOUR_API_SECRET',
});
options
WSClientConfigurableOptions & Partial<WSAPIClientConfigurableOptions>
Configuration merging the standard WSClientConfigurableOptions (shared with WebsocketClient) with the following WS-API-specific fields:
OptionTypeDefaultDescription
resubscribeUserDataStreamAfterReconnectbooleantrueAutomatically resubscribe to user data stream after reconnect.
resubscribeUserDataStreamDelaySecondsnumber2Delay in seconds before resubscribing after reconnect.
attachEventListenersbooleantrueLog high-level connection lifecycle events to console.
muteLatencyWarningbooleanfalseSuppress the HMAC/RSA latency warning. Set true if using Ed25519 keys or if you acknowledge the tradeoff.
keepMarginListenTokenRefreshedbooleantrueProactively refresh the margin listen token before expiry.
logger
DefaultLogger
Optional custom logger. Defaults to the built-in DefaultLogger.
For the lowest latency, use Ed25519 signing keys. HMAC and RSA keys require per-request signing which adds overhead. The SDK will warn you if it detects HMAC/RSA keys unless muteLatencyWarning: true is set.

Utility Methods

MethodReturnsDescription
getWSClient()WebsocketClientReturns the underlying WebsocketClient instance. Use this to attach event listeners (.on('formattedMessage', ...)) or access lower-level connection controls.
setTimeOffsetMs(newOffset)voidSet the time offset (in milliseconds) applied to signed requests. Useful when the local clock differs from the Binance server clock.
disconnectAll()Promise<void>Gracefully close all active WebSocket API connections.

SPOT — General

MethodRequest TypeResponse TypeDescription
testSpotConnectivity(wsKey?)WSAPIResponse<object>Test connectivity to the Spot WebSocket API endpoint.
getSpotServerTime(wsKey?)WSAPIResponse<WSAPIServerTime>Get the current Binance server time.
getSpotExchangeInfo(params?, wsKey?)WSAPIExchangeInfoRequestWSAPIResponse<ExchangeInfo>Query exchange trading rules, rate limits, and symbol information.
getSpotSessionStatus(wsKey?)WSAPIResponse<WSAPISessionStatus>Query the authentication status of the current WebSocket session.

SPOT — Market Data

MethodRequest TypeResponse TypeDescription
getSpotOrderBook(params, wsKey?)WSAPIOrderBookRequestWSAPIResponse<WSAPIOrderBook>Retrieve the current order book snapshot for a symbol.
getSpotRecentTrades(params, wsKey?)WSAPITradesRecentRequestWSAPIResponse<WSAPITrade[]>Get the most recent trades for a symbol.
getSpotHistoricalTrades(params, wsKey?)WSAPITradesHistoricalRequestWSAPIResponse<WSAPITrade[]>Get older trades for a symbol starting from a given trade ID.
getSpotHistoricalBlockTrades(params, wsKey?)WSAPIBlockTradesHistoricalRequestWSAPIResponse<WSAPIBlockTrade[]>Get historical block trades.
getSpotAggregateTrades(params, wsKey?)WSAPITradesAggregateRequestWSAPIResponse<WSAPIAggregateTrade[]>Get aggregate trades compressed into single records per price level.
getSpotKlines(params, wsKey?)WSAPIKlinesRequestWSAPIResponse<WSAPIKline[]>Get candlestick (kline) data for a symbol and interval.
getSpotUIKlines(params, wsKey?)WSAPIKlinesRequestWSAPIResponse<WSAPIKline[]>Get UI-optimized kline data (same shape as getSpotKlines).
getSpotAveragePrice(params, wsKey?)WSAPIAvgPriceRequestWSAPIResponse<WSAPIAvgPrice>Get the current average price for a symbol.
getSpotExecutionRules(params?, wsKey?)WSAPIExecutionRulesRequestWSAPIResponse<SpotExecutionRulesResponse>Query execution rules such as PRICE_RANGE for symbols.
getSpotReferencePrice(params, wsKey?)WSAPIReferencePriceRequestWSAPIResponse<SpotReferencePriceResult>Get the reference price for a symbol.
getSpotReferencePriceCalculation(params, wsKey?)WSAPIReferencePriceCalculationRequestWSAPIResponse<SpotReferencePriceCalculationResponse>Get the method used to calculate the reference price for a symbol.
getSpot24hrTicker(params?, wsKey?)WSAPITicker24hrRequestWSAPIResponse<WSAPIFullTicker | WSAPIMiniTicker | WSAPIFullTicker[] | WSAPIMiniTicker[]>Get 24-hour rolling window price change statistics.
getSpotTradingDayTicker(params, wsKey?)WSAPITickerTradingDayRequestWSAPIResponse<WSAPIFullTicker | WSAPIMiniTicker | ...[]>Get price change statistics for a trading day.
getSpotTicker(params, wsKey?)WSAPITickerRequestWSAPIResponse<WSAPIFullTicker | WSAPIMiniTicker | ...[]>Get rolling window price change statistics with a custom window.
getSpotSymbolPriceTicker(params?, wsKey?)WSAPITickerPriceRequestWSAPIResponse<WSAPIPriceTicker | WSAPIPriceTicker[]>Get the latest market price for a symbol or all symbols.
getSpotSymbolOrderBookTicker(params?, wsKey?)WSAPITickerBookRequestWSAPIResponse<WSAPIBookTicker | WSAPIBookTicker[]>Get the current best bid/ask price and quantity.

SPOT — Order Management

All trading methods require api_key and api_secret to be set. Authentication is handled automatically by the client.
MethodRequest TypeResponse TypeDescription
submitNewSpotOrder(params, wsKey?)WSAPINewSpotOrderRequestWSAPIResponse<WSAPISpotOrderResponse>Place a new spot order.
testSpotOrder(params, wsKey?)WSAPIOrderTestRequestWSAPIResponse<WSAPIOrderTestResponse | WSAPIOrderTestWithCommission>Validate order parameters and signature without sending to the matching engine.
getSpotOrderStatus(params, wsKey?)WSAPIOrderStatusRequestWSAPIResponse<WSAPIOrder>Check the execution status of an order.
cancelSpotOrder(params, wsKey?)WSAPIOrderCancelRequestWSAPIResponse<WSAPIOrderCancel>Cancel an active order.
cancelReplaceSpotOrder(params, wsKey?)WSAPIOrderCancelReplaceRequestWSAPIResponse<WSAPIOrderCancelReplaceResponse>Cancel an existing order and immediately place a new one atomically.
amendSpotOrderKeepPriority(params, wsKey?)WSAPIOrderAmendKeepPriorityRequestWSAPIResponse<SpotAmendKeepPriorityResult>Reduce the quantity of an open order while preserving queue priority.
getSpotOpenOrders(params, wsKey?)WSAPIOpenOrdersStatusRequestWSAPIResponse<WSAPIOrder[]>Query all open orders for a symbol.
cancelAllSpotOpenOrders(params, wsKey?)WSAPIOpenOrdersCancelAllRequestWSAPIResponse<(WSAPIOrderCancel | WSAPIOrderListCancelResponse)[]>Cancel all open orders on a symbol, including order lists.

SPOT — Order Lists

MethodRequest TypeDescription
placeSpotOrderList(params, wsKey?)WSAPIOrderListPlaceRequestPlace a legacy order list (deprecated; prefer placeSpotOCOOrderList).
placeSpotOCOOrderList(params, wsKey?)WSAPIOrderListPlaceOCORequestPlace an OCO (One-Cancels-the-Other) order list.
placeSpotOTOOrderList(params, wsKey?)WSAPIOrderListPlaceOTORequestPlace an OTO (One-Triggers-the-Other) order list.
placeSpotOTOCOOrderList(params, wsKey?)WSAPIOrderListPlaceOTOCORequestPlace an OTOCO (One-Triggers-One-Cancels-the-Other) order list.
placeSpotOPOOrderList(params, wsKey?)WSAPIOrderListPlaceOPORequestPlace an OPO (One-Pays-the-Other) order list.
placeSpotOPOCOOrderList(params, wsKey?)WSAPIOrderListPlaceOPOCORequestPlace an OPOCO (One-Pays-One-Cancels-the-Other) order list.
getSpotOrderListStatus(params, wsKey?)WSAPIOrderListStatusRequestQuery the execution status of an order list.
cancelSpotOrderList(params, wsKey?)WSAPIOrderListCancelRequestCancel an active order list.
getSpotOpenOrderLists(params, wsKey?)WSAPIRecvWindowTimestampQuery all open order lists.

SPOT — SOR Orders

MethodDescription
placeSpotSOROrder(params, wsKey?)Place a new order using Smart Order Routing (SOR). Supports LIMIT and MARKET only.
testSpotSOROrder(params, wsKey?)Test SOR order placement without submitting to the matching engine.

SPOT — Account

MethodRequest TypeResponse TypeDescription
getSpotAccountInformation(params, wsKey?)WSAPIAccountInformationRequestWSAPIResponse<WSAPIAccountInformation>Query account details including balances. Weight: 20.
getSpotOrderRateLimits(params, wsKey?)WSAPIRecvWindowTimestampWSAPIResponse<WSAPIRateLimit[]>Query current unfilled order count across all rate limit intervals. Weight: 40.
getSpotAllOrders(params, wsKey?)WSAPIAllOrdersRequestWSAPIResponse<WSAPIOrder[]>Query all orders (active, cancelled, or filled) filtered by time range. Weight: 20.
getSpotAllOrderLists(params, wsKey?)WSAPIAllOrderListsRequestWSAPIResponse<WSAPIOrderListStatusResponse[]>Query all order lists filtered by time range. Weight: 20.
getSpotMyTrades(params, wsKey?)WSAPIMyTradesRequestWSAPIResponse<WSAPITrade[]>Query your trades filtered by time range. Weight: 20.
getSpotPreventedMatches(params, wsKey?)WSAPIMyPreventedMatchesRequestWSAPIResponse<WSAPIPreventedMatch[]>List orders expired due to self-trade prevention (STP).
getSpotAllocations(params, wsKey?)WSAPIMyAllocationsRequestWSAPIResponse<WSAPIAllocation[]>Retrieve allocations resulting from SOR order placement.
getSpotAccountCommission(params, wsKey?)WSAPIAccountCommissionWSAPIRequestWSAPIResponse<WSAPIAccountCommission>Get current account commission rates. Weight: 20.

FUTURES — Market Data

MethodRequest TypeResponse TypeDescription
getFuturesOrderBook(params)WSAPIFuturesOrderBookRequestWSAPIResponse<WSAPIFuturesOrderBook>Get the current order book for a USD-M Futures symbol.
getFuturesSymbolPriceTicker(params?)WSAPIFuturesTickerPriceRequestWSAPIResponse<WSAPIFuturesPriceTicker | WSAPIFuturesPriceTicker[]>Get the latest price for a futures symbol or all symbols.
getFuturesSymbolOrderBookTicker(params?)WSAPIFuturesTickerBookRequestWSAPIResponse<WSAPIFuturesBookTicker | WSAPIFuturesBookTicker[]>Get the best bid/ask for a futures symbol or all symbols.

FUTURES — Order Management

These methods accept a market parameter ('usdm' or 'coinm') to target the correct futures product group.
MethodParametersDescription
submitNewFuturesOrder(market, params)market: 'usdm' | 'coinm', WSAPINewFuturesOrderRequestSubmit a new futures order for USD-M or COIN-M.
modifyFuturesOrder(market, params)market: 'usdm' | 'coinm', WSAPIFuturesOrderModifyRequestModify an existing futures order.
cancelFuturesOrder(market, params)market: 'usdm' | 'coinm', WSAPIFuturesOrderCancelRequestCancel a futures order.
getFuturesOrderStatus(market, params)market: 'usdm' | 'coinm', WSAPIFuturesOrderStatusRequestQuery futures order status.
getFuturesPosition(market, params)market: 'usdm' | 'coinm', WSAPIFuturesPositionRequestGet current position information.
getFuturesPositionV2(params)WSAPIFuturesPositionV2RequestGet current position information (V2, USD-M only).
submitNewFuturesAlgoOrder(params)WSAPINewFuturesAlgoOrderRequestSubmit a new USD-M Futures algo order (TWAP/VP).
cancelFuturesAlgoOrder(params)WSAPIFuturesAlgoOrderCancelRequestCancel an active USD-M Futures algo order.

FUTURES — Account

MethodParametersDescription
getFuturesAccountBalanceV2(params)WSAPIRecvWindowTimestampGet USD-M Futures account balance information (V2).
getFuturesAccountBalance(market, params)market: 'usdm' | 'coinm', WSAPIRecvWindowTimestampGet account balance for USD-M or COIN-M Futures.
getFuturesAccountStatusV2(params)WSAPIRecvWindowTimestampGet detailed USD-M Futures account information (V2).
getFuturesAccountStatus(market, params)market: 'usdm' | 'coinm', WSAPIRecvWindowTimestampGet detailed account information for USD-M or COIN-M Futures.

User Data Stream

The WebsocketAPIClient provides a higher-level method to manage user data subscriptions over the WS API connection (no traditional listen-key polling required for Spot).
MethodParametersDescription
subscribeUserDataStream(wsKey)wsKey: WSAPIWsKeySubscribe to the user data stream on the given WS API connection. Automatically resubscribes after reconnect.
unsubscribeUserDataStream(wsKey)wsKey: WSAPIWsKeyUnsubscribe from the user data stream and cancel automatic resubscription.
startUserDataStreamForKey(params, wsKey?){ apiKey: string }Start a user data stream using the legacy listen-key workflow.
pingUserDataStreamForKey(params, wsKey?)WSAPIUserDataListenKeyRequestPing an active listen key to prevent expiry.
stopUserDataStreamForKey(params, wsKey?)WSAPIUserDataListenKeyRequestStop a listen-key user data stream.

Code Example

import { WebsocketAPIClient } from 'binance';

const wsApiClient = new WebsocketAPIClient({
  api_key: 'YOUR_API_KEY',
  api_secret: 'YOUR_API_SECRET',
});

// Listen to the underlying WebSocket client events
wsApiClient.getWSClient().on('exception', (err) => {
  console.error('WS API exception:', err);
});

async function main() {
  // Fetch order book snapshot
  const orderBook = await wsApiClient.getSpotOrderBook({ symbol: 'BTCUSDT', limit: 10 });
  console.log('Order book asks:', orderBook.result.asks.slice(0, 3));

  // Place a spot market order
  const order = await wsApiClient.submitNewSpotOrder({
    symbol: 'BTCUSDT',
    side: 'BUY',
    type: 'MARKET',
    quoteOrderQty: 20,
    timestamp: Date.now(),
  });
  console.log('Order placed:', order.result.orderId);

  // Query account information
  const account = await wsApiClient.getSpotAccountInformation({
    timestamp: Date.now(),
  });
  console.log(
    'BTC balance:',
    account.result.balances.find((b) => b.asset === 'BTC'),
  );

  // Subscribe to user data stream for live order updates
  await wsApiClient.subscribeUserDataStream('mainWSAPI');

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

main();

Build docs developers (and LLMs) love