Skip to content

Subscribe to private account updates ​

Use WebsocketAPIClient to receive Spot account and order events through Binance's WebSocket API. This walkthrough uses production Spot; the client also supports Spot Testnet. Private account events are separate from public market-data subscriptions. Binance removed Spot's older listen-key REST and WebSocket API operations on 20 February 2026 at 07:00 UTC; use subscribeUserDataStream() for Spot. See the Spot API changelog.

Use these events to keep local order and balance state up to date after REST submissions. There is no need to query each order after placing or cancelling it when the required updates have arrived. See account state for startup and recovery.

To use Spot Testnet, set testnet: true and use Testnet credentials.

Connect to the account stream ​

Use Node.js 24 and install the SDK with npm install binance. Set the Spot credential variables from order management. Keep signing credentials on the server and out of browser bundles.

Save this as private-stream.ts:

ts
import { WebsocketAPIClient, WS_KEY_MAP } from 'binance';

async function main() {
  const api_key = process.env.BINANCE_API_KEY;
  const api_secret = process.env.BINANCE_API_SECRET;
  if (!api_key || !api_secret) {
    throw new Error('Set Spot credentials.');
  }
  const api = new WebsocketAPIClient({
    api_key,
    api_secret,
    beautify: false,
  });
  const ws = api.getWSClient();
  let stopped = false;
  const stop = () => {
    if (stopped) {
      return;
    }
    stopped = true;
    clearTimeout(timer);
    process.removeListener('SIGINT', stop);
    process.removeListener('SIGTERM', stop);
    void api.disconnectAll().catch((error) => {
      console.error('Disconnect failed:', error);
      process.exitCode = 1;
    });
  };
  // The 60-second limit includes connection and authentication.
  const timer = setTimeout(stop, 60000);
  process.once('SIGINT', stop);
  process.once('SIGTERM', stop);

  // Install listeners before subscribing so early events are not missed.
  ws.on('message', (message) => {
    if (stopped) {
      return;
    }
    if (Array.isArray(message)) {
      console.log('Private stream message:', message);
    } else if (message.e === 'executionReport') {
      console.log('Order update:', {
        symbol: message.s,
        orderId: message.i,
        executionType: message.x,
        status: message.X,
        lastExecutedQuantity: message.l,
        cumulativeExecutedQuantity: message.z,
      });
    } else if (
      message.e === 'outboundAccountPosition' ||
      message.e === 'balanceUpdate'
    ) {
      console.log('Account state changed:', message);
    } else if (message.e === 'eventStreamTerminated') {
      console.error('User data stream ended:', message);
    } else {
      console.log('Private stream message:', message);
    }
  });
  ws.on('exception', (error) => {
    console.error('Private stream exception:', error);
  });
  // The SDK owns reconnecting and restoring the user data subscription.
  ws.on('reconnecting', (event) => {
    console.log('WebSocket reconnecting:', event);
  });
  ws.on('reconnected', (event) => {
    console.log('WebSocket reconnected:', event);
    // If a gap leaves state unresolved, use a targeted REST recovery query.
    // Do not query after each order event or submission.
  });
  try {
    await api.subscribeUserDataStream(WS_KEY_MAP.mainWSAPI);
    if (stopped) {
      await api.disconnectAll();
    } else {
      console.log(
        'Spot user data subscribed. Waiting for account events.',
      );
    }
  } catch (error) {
    console.error('Private subscription failed:', error);
  }
}

main().catch((error) => {
  console.error(error);
  process.exitCode = 1;
});

Run it before placing an order in another terminal:

sh
node --env-file=.env private-stream.ts

WS_KEY_MAP.mainWSAPI selects the production Spot WebSocket API by default; the SDK maps it to Spot Testnet when testnet: true. The helper uses userDataStream.subscribe on an authenticated Ed25519 session, or a signed userDataStream.subscribe.signature request for HMAC/RSA credentials. This example accepts an HMAC API secret through the environment; see authentication for credential handling.

Listeners are registered before subscribing so early messages are not missed. Once subscribed, the script waits for account activity. A quiet account may produce no events during the 60-second window.

Read order events ​

The SDK unwraps the WebSocket API envelope before emitting message: inspect message.e, not message.event.e. With beautify: false, an executionReport includes:

  • s: symbol.
  • i: exchange order ID, which stays stable through cancellation.
  • x: execution type, such as NEW, TRADE or CANCELED.
  • X: current order status, such as NEW, PARTIALLY_FILLED or FILLED.
  • l: quantity executed in the latest fill.
  • z: cumulative executed quantity.

Match i to the BINANCE_ORDER_ID returned by the order example. The stream prints selected order fields, balance events and other received messages. Stream and subscription errors are logged with their error objects. Consult the user data stream payloads for the complete event definitions.

Optional: readable fields with the SDK beautifier ​

The SDK beautifier turns Binance's short field names into descriptive properties and converts known numeric strings to JavaScript numbers. For example, e, s, X and z become eventType, symbol, orderStatus and accumulatedQuantity.

In private-stream.ts, set beautify: true in the existing WebsocketAPIClient options. Add isWsFormattedSpotUserDataExecutionReport to the existing binance import, then replace the raw message listener with:

ts
ws.on('formattedMessage', (message) => {
  if (stopped) {
    return;
  }
  if (isWsFormattedSpotUserDataExecutionReport(message)) {
    console.log('Order update:', {
      symbol: message.symbol,
      orderId: message.orderId,
      status: message.orderStatus,
      filledQuantity: message.accumulatedQuantity,
    });
  } else {
    console.log('Account update:', message);
  }
});

Keep the existing subscription, error, reconnect and shutdown handling. Raw events still arrive on message; use those decimal strings when you need exact arithmetic rather than JavaScript floating-point numbers.

Disconnect and recover ​

The SDK reconnects automatically after a dropped connection and restores the user data subscription. The example logs reconnecting and reconnected without closing the client or setting a failure exit code. It keeps the SDK's default resubscribeUserDataStreamAfterReconnect behavior enabled; no manual resubscription loop is needed.

reconnected confirms the socket is open again. Authentication and resubscription may still be completing. For applications that depend on complete account state, reconcile orders, fills and balances through REST after a gap; a restored subscription does not replay missed updates. Subscription rejections and other errors are logged for diagnosis.

The 60-second timer and Ctrl+C/SIGTERM end this demonstration explicitly. Closing the stream does not cancel orders.

To stop just a user data subscription while keeping a connection, await unsubscribeUserDataStream(WS_KEY_MAP.mainWSAPI). To end all connections owned by this API client, call disconnectAll(). This example uses a dedicated client, so it closes all its connections. Remove application timers and signal listeners during shutdown.

Order management · WebSocket API client reference · Binance subscription methods

Built by Siebly. Open source SDKs for exchange APIs.