← All articles

Binance WebSocket API in Node.js and TypeScript: market streams, user data and requests

“Binance WebSocket” covers three different services, each with its own host and its own SDK client. This guide shows each one in Node.js and TypeScript with the Siebly Binance JavaScript SDK (the binance npm package): live market data streams, the user data stream for account and order events, and the WebSocket API for request and response calls. Every output below comes from Binance’s public streams or Spot Testnet.

Three Binance WebSocket services

What you want Binance service Host SDK client
Live trades, candles, tickers, order book updates WebSocket market streams stream.binance.com (Spot), fstream.binance.com (USD-M futures) WebsocketClient
Your own order, balance and position events User data stream Spot: the WebSocket API. Futures: the stream host with a listen key WebsocketAPIClient.subscribeUserDataStream() for Spot, WebsocketClient for futures
One request, one reply: server time, order book, account, orders WebSocket API ws-api.binance.com WebsocketAPIClient

Market streams push data, and the only requests they take are subscription changes. The WebSocket API answers requests and does not push market data. Install the SDK once for all three:

npm install binance

Stream Spot market data with WebsocketClient

Public streams need no API key. This script subscribes to BTCUSDT trades and one-minute candles, prints a few events and closes:

import {
  DefaultLogger,
  WebsocketClient,
  WS_KEY_MAP,
  isWsFormattedKline,
  isWsFormattedTrade,
} from 'binance';

// Keep the SDK's own error logs, silence its info logs.
const logger = { ...DefaultLogger, info: () => {} };

// Public market data needs no API key.
const ws = new WebsocketClient({ beautify: true }, logger);

ws.on('open', ({ wsKey, wsUrl }) => console.log('open', wsKey, wsUrl));
ws.on('response', (res) => console.log('response', JSON.stringify(res)));
ws.on('reconnecting', ({ wsKey }) => console.log('reconnecting', wsKey));
ws.on('reconnected', ({ wsKey }) => console.log('reconnected', wsKey));
ws.on('exception', (err) => console.error('exception', err));

let trades = 0;
let klines = 0;
let stopped = false;
ws.on('formattedMessage', (msg) => {
  if (stopped) return;
  if (isWsFormattedTrade(msg)) {
    if (trades < 3) console.log('trade', msg.symbol, msg.price, msg.quantity);
    trades += 1;
  } else if (isWsFormattedKline(msg)) {
    console.log('kline', msg.symbol, msg.kline.interval, 'close', msg.kline.close, 'final', msg.kline.final);
    klines += 1;
  }
  if (trades >= 3 && klines >= 1) {
    stopped = true;
    ws.closeAll();
  }
});

// Stream names are <symbol>@<stream>, with the symbol in lower case.
// main2 is stream.binance.com on port 443. main uses port 9443.
await ws.subscribe(['btcusdt@trade', 'btcusdt@kline_1m'], WS_KEY_MAP.main2);
node spot-streams.ts
open main2 wss://stream.binance.com:443/stream
response {"result":null,"id":1,"wsMarket":"spot","request":{"method":"SUBSCRIBE","params":["btcusdt@trade","btcusdt@kline_1m"],"id":1},"wsKey":"main2","isWSAPIResponse":true}
kline BTCUSDT 1m close 60982 final false
trade BTCUSDT 60982.01 0.004
trade BTCUSDT 60982.01 0.004
trade BTCUSDT 60982.01 0.002

What the output shows:

  • The response event is Binance’s reply to the SUBSCRIBE request: "result":null means the request was accepted. It does not mean data will arrive (see the next section).
  • beautify: true turns Binance’s one-letter fields into names and numbers: a trade’s p and q become price and quantity. The undecorated event, with prices as strings, is still emitted on message.
  • A candle event arrives on every update, not only when the minute closes. final is true only for the last update of a candle.

The SDK has three connection keys for Spot streams, all from Binance’s WebSocket streams documentation:

  • WS_KEY_MAP.main: wss://stream.binance.com:9443. The helper methods such as subscribeSpotTrades('BTCUSDT') use this one by default.
  • WS_KEY_MAP.main2: wss://stream.binance.com:443, the same service on port 443. If a firewall or network blocks outbound port 9443, use this key. Over a blocked port, main fails with Client network socket disconnected before secure TLS connection was established and keeps retrying.
  • WS_KEY_MAP.main3: wss://data-stream.binance.vision, which carries market data only, with no user data.

A subscription can succeed and still deliver nothing

Binance’s docs say all stream symbols are lower case. The helper methods lower-case the symbol for you, but a raw subscribe() sends the topic exactly as written. Binance accepts a wrong topic without complaint, so the only way to catch it is to watch for data. This script subscribes to one valid topic and two broken ones, then checks which have produced events after ten seconds:

import { DefaultLogger, WebsocketClient, WS_KEY_MAP } from 'binance';

const ws = new WebsocketClient({}, { ...DefaultLogger, info: () => {} });
const topics = ['btcusdt@aggTrade', 'BTCUSDT@aggTrade', 'btcusdt@aggtrades'];
const lastSeen = new Map<string, number>();

// Raw events from a combined stream carry the stream name they belong to.
ws.on('message', (msg) => {
  if (!Array.isArray(msg) && typeof msg.streamName === 'string') lastSeen.set(msg.streamName, Date.now());
});
ws.on('response', (res) => console.log('response', res.request?.params, 'result', res.result));

await ws.subscribe(topics, WS_KEY_MAP.main3);

setTimeout(() => {
  for (const topic of topics) {
    console.log(topic, lastSeen.has(topic) ? 'receiving data' : 'NO DATA after 10 s');
  }
  ws.closeAll();
}, 10_000);
response [ 'btcusdt@aggTrade', 'BTCUSDT@aggTrade', 'btcusdt@aggtrades' ] result null
btcusdt@aggTrade receiving data
BTCUSDT@aggTrade NO DATA after 10 s
btcusdt@aggtrades NO DATA after 10 s

All three topics went out in one SUBSCRIBE request and Binance answered result null. Only the lower-case, correctly spelt stream produced data. An upper-case symbol and a misspelt stream name produce no error, no data and no disconnect. In production, keep a last-seen time per stream and alert when a busy stream goes quiet. The same check catches a dead connection that has not noticed it is dead yet.

USD-M futures streams

Futures market streams use the same client with a different connection key. Binance now serves USD-M streams on two paths of fstream.binance.com: /public for book tickers and depth, and /market for the other market streams, as listed in Binance’s USD-M WebSocket market streams reference. With WS_KEY_MAP.usdm, the SDK sends each topic to the right path:

import { DefaultLogger, WebsocketClient, WS_KEY_MAP } from 'binance';

const logger = { ...DefaultLogger, info: () => {} };
const ws = new WebsocketClient({ beautify: true }, logger);

ws.on('open', ({ wsKey, wsUrl }) => console.log('open', wsKey, wsUrl));
ws.on('exception', (err) => console.error('exception', err));

const seen = new Set<string>();
ws.on('formattedMessage', (msg) => {
  if (Array.isArray(msg) || seen.has(msg.eventType)) return;
  seen.add(msg.eventType);
  console.log(msg.wsKey, JSON.stringify(msg).slice(0, 160));
  if (seen.size === 2) ws.closeAll();
});

// usdm is an alias: the SDK routes each topic to the USD-M connection it needs.
await ws.subscribe(['btcusdt@markPrice@1s', 'btcusdt@bookTicker'], WS_KEY_MAP.usdm);
open usdmPublic wss://fstream.binance.com/public/stream
open usdmMarket wss://fstream.binance.com/market/stream
usdmPublic {"eventType":"bookTicker","updateId":12297818941345,"symbol":"BTCUSDT","ps":"BTCUSDT","bidPrice":60968.1,"bidQty":6.091,"askPrice":60968.2,"askQty":3.981,"trans
usdmMarket {"eventType":"markPriceUpdate","eventTime":1796139273001,"symbol":"BTCUSDT","markPrice":60968.1,"markPriceMovingAverage":"60968.10000000","settlePriceEstimate":

One subscribe() call opened two connections, usdmPublic for the book ticker and usdmMarket for the mark price. Placing and managing futures orders is a separate subject, covered in the Binance Futures API guide.

What happens when the connection drops

Binance’s side of the connection, from the same streams documentation:

  • The server sends a ping frame every 20 seconds and disconnects a client that does not answer with a pong within a minute.
  • A connection to stream.binance.com is only valid for 24 hours, so expect a disconnect at least once a day.
  • A serverShutdown event warns that the server is about to close the connection.

The SDK’s side, in version 3.6.15: it answers Binance’s pings, sends its own ping every 10 seconds (pingInterval), treats a missing pong after 5 seconds (pongTimeout) as a dead connection, reconnects after 500 ms (reconnectTimeout), and subscribes again to every topic it had. This script kills the socket without a close handshake, the way a network failure would, and watches the client recover:

import { DefaultLogger, WebsocketClient, WS_KEY_MAP } from 'binance';

const logger = { ...DefaultLogger, info: () => {} };
const ws = new WebsocketClient({ beautify: true }, logger);
const wsKey = WS_KEY_MAP.main3; // data-stream.binance.vision: market data only

const t0 = Date.now();
const at = () => `${((Date.now() - t0) / 1000).toFixed(1)}s`;

let phase: 'before' | 'after' | 'done' = 'before';

ws.on('open', () => console.log(at(), 'open'));
ws.on('reconnecting', () => console.log(at(), 'reconnecting'));
ws.on('reconnected', () => console.log(at(), 'reconnected'));
ws.on('exception', (err) => console.error(at(), 'exception', err));

ws.on('formattedMessage', (msg) => {
  if (Array.isArray(msg) || msg.eventType !== 'bookTicker') return;
  if (phase === 'before') {
    console.log(at(), 'bookTicker', msg.symbol, 'update', msg.updateId);
    phase = 'after';
    // Simulate a dropped connection: kill the socket without a close handshake.
    ws.getWsStore().getWs(wsKey)?.terminate();
    console.log(at(), 'socket terminated');
  } else if (phase === 'after') {
    console.log(at(), 'bookTicker', msg.symbol, 'update', msg.updateId, '(resubscribed automatically)');
    phase = 'done';
    ws.closeAll();
  }
});

await ws.subscribe(['btcusdt@bookTicker'], wsKey);
1.8s open
2.2s bookTicker BTCUSDT update 104068434407
2.2s socket terminated
2.2s reconnecting
4.4s reconnected
4.9s bookTicker BTCUSDT update 104068438066 (resubscribed automatically)

The stream came back on its own in about 2.7 seconds with the same subscription. Look at the update IDs, though: 104068434407 before, 104068438066 after. Every book ticker update in between is gone. Reconnecting restores the stream, not the data you missed. For a book ticker that may not matter; for a local order book or trade history it does. Listen for reconnected and resynchronise from REST, as described in WebSocket reconnects and backfill.

Send requests over the Binance WebSocket API

WebsocketAPIClient wraps Binance’s WebSocket API in methods that return promises, so a request over the socket reads like a REST call. It opens and keeps the connection for you. Public requests need no key:

import { DefaultLogger, WebsocketAPIClient } from 'binance';

const logger = { ...DefaultLogger, info: () => {} };

// Public WebSocket API requests need no key. Each call returns a promise.
const api = new WebsocketAPIClient({ attachEventListeners: false }, logger);

try {
  const time = await api.getSpotServerTime();
  console.log('status', time.status, 'serverTime', time.result.serverTime);

  const book = await api.getSpotOrderBook({ symbol: 'BTCUSDT', limit: 5 });
  console.log('best bid', book.result.bids[0], 'best ask', book.result.asks[0]);

  const weight = book.rateLimits.find((l) => l.rateLimitType === 'REQUEST_WEIGHT');
  console.log('request weight used', weight?.count, 'of', weight?.limit, 'per minute');
} catch (err) {
  console.error('request failed', err);
} finally {
  await api.disconnectAll();
}
status 200 serverTime 1796139534249
best bid [ '60821.42000000', '1.06766000' ] best ask [ '60821.43000000', '4.66721000' ]
request weight used 8 of 6000 per minute

Every reply carries a rateLimits array, so you can see your weight without a separate call. Binance’s WebSocket API documentation states that connecting costs 2 weight, that weight is counted per IP address and shared by all connections from it, and that a WebSocket API connection is also only valid for 24 hours.

Authenticated requests and the Spot user data stream

Account requests and your own order events need an API key. With an Ed25519 key, the SDK logs the connection in once with session.logon and then sends requests unsigned. Binance supports session.logon only for Ed25519 keys, so with an HMAC or RSA key the SDK signs each request instead. Creating the key and choosing its type is covered in Binance API key for Node.js and TypeScript.

This script reads the account over the WebSocket API on Spot Testnet, then subscribes to the user data stream. It puts a deadline on every call and stops on an authentication error:

import { readFileSync } from 'node:fs';
import { DefaultLogger, WebsocketAPIClient, WS_KEY_MAP } from 'binance';

const api_key = process.env.BINANCE_API_KEY;
const keyPath = process.env.BINANCE_PRIVATE_KEY_PATH;
if (!api_key || !keyPath) throw new Error('Set BINANCE_API_KEY and BINANCE_PRIVATE_KEY_PATH');

// Give every WebSocket API call a deadline, and treat a missed one as unknown.
function withTimeout<T>(promise: Promise<T>, ms: number, label: string): Promise<T> {
  let timer: ReturnType<typeof setTimeout> | undefined;
  const deadline = new Promise<never>((_, reject) => {
    timer = setTimeout(() => reject(new Error(`${label}: no reply after ${ms} ms`)), ms);
  });
  return Promise.race([promise, deadline]).finally(() => clearTimeout(timer));
}

const logger = { ...DefaultLogger, info: () => {} };

// An Ed25519 private key PEM as api_secret: the SDK authenticates the
// connection once with session.logon instead of signing every request.
const api = new WebsocketAPIClient(
  {
    api_key,
    api_secret: readFileSync(keyPath, 'utf8'),
    testnet: true,
    attachEventListeners: false,
  },
  logger,
);

const ws = api.getWSClient();
ws.on('exception', (err) => {
  console.error('exception', JSON.stringify(err));
  // A rejected key will not fix itself on retry: stop instead of waiting.
  if (err?.status === 401) {
    process.exitCode = 1;
    void api.disconnectAll().finally(() => process.exit());
  }
});
// Account and order events arrive here once the user data stream is subscribed.
ws.on('message', (event) => console.log('user data', JSON.stringify(event)));

try {
  const account = await withTimeout(
    api.getSpotAccountInformation({ omitZeroBalances: true, timestamp: Date.now() }),
    10_000,
    'account.status',
  );
  console.log('canTrade', account.result.canTrade, 'balances', account.result.balances.length);

  await withTimeout(api.subscribeUserDataStream(WS_KEY_MAP.mainWSAPITestnet), 10_000, 'userDataStream.subscribe');
  console.log('user data stream subscribed');
} catch (err) {
  console.error((err as Error).message);
  await api.disconnectAll();
}

Run against Spot Testnet with a made-up API key and a throwaway Ed25519 key, Binance rejects the logon:

BINANCE_API_KEY=<random 64 characters> BINANCE_PRIVATE_KEY_PATH=./binance-ed25519-private.pem node ws-api-account.ts
exception {"id":1,"status":401,"error":{"code":-2015,"msg":"Invalid API-key, IP, or permissions for action."},"rateLimits":[{"rateLimitType":"REQUEST_WEIGHT","interval":"MINUTE","intervalNum":1,"limit":6000,"count":2}],"wsMarket":"spotTestnet","wsKey":"mainWSAPITestnet","isWSAPIResponse":true}

The rejection, -2015 Invalid API-key, IP, or permissions for action. with HTTP-style status 401, arrives on the exception event, and the script exits because a rejected key does not recover on retry. Always attach an exception listener, or authentication failures go unseen. The deadline in withTimeout() is ordinary practice for any request over a long-lived connection: a dropped socket or a slow server should end in an error you can handle, not a promise that waits forever. For an order request, a missed deadline means the outcome is unknown until your account events or a REST query settle it.

With a valid testnet key, the script goes on to print the account flags and subscribe, and order and balance events (executionReport, outboundAccountPosition, balanceUpdate) arrive on message. The SDK subscribes again after a reconnect unless you set resubscribeUserDataStreamAfterReconnect: false. Spot no longer uses listen keys for this: if you are moving older code, see Binance user data stream 410 Gone. USD-M futures still use a listen key through WebsocketClient.subscribeUsdFuturesUserDataStream(), and the futures user data stream guide covers resyncing it after a reconnect.

Binance WebSocket limits to design around

  • 5 incoming messages per second per stream connection, counting pings, pongs and subscribe requests. Subscribe in batches, as in the examples above, rather than one request per topic.
  • 1024 streams per connection.
  • 300 connection attempts every 5 minutes per IP.

These come from Binance’s WebSocket streams documentation. How they relate to REST request weight, 429 and 418 is covered in Binance API rate limits in Node.js.

Next steps

The binance package is one of the Siebly SDKs, which have over 4.8 million npm downloads across 10+ SDKs.

Versions: binance 3.6.15, Node.js 24.22.1, TypeScript 7.0.2.