A Binance USD-M futures bot usually places orders over REST and learns what happened from the user data stream: fills, cancels, and balance and position changes. If that stream stops and nothing notices, orders still go out, but the bot never hears about them. Its view of open orders and positions goes stale while it keeps trading.
The binance SDK (3.6.13) reconnects the stream. Pause new orders while the stream is down and reconcile open orders and positions over REST before resuming.
Reported listenKey failure
nautilus_trader issue #5755, opened on 23 November 2026, describes this failure on Binance USD-M futures (demo environment, HMAC keys, REST listenKey mode). According to the report:
- When the user data socket reconnected, the adapter closed the new socket and requested a fresh listenKey with a single REST call.
- That call failed, because REST was still unreachable at that moment. The adapter marked recovery as failed and disconnected.
- Nothing retried after that, no error event was raised, and the execution client still reported itself as connected. Orders could still be submitted over REST, but no order or account updates arrived.
The report concerns one demo incident. The proposed mitigations include capped backoff, obtaining a replacement key before closing the old stream, and reporting a terminal failure.
This is not a criticism of that project. Any client that treats the listenKey refresh as a one-shot step can end up here, and the lesson applies to any stack: a user data stream can be down while everything else looks healthy.
What the SDK handles for you
With the binance SDK, WebsocketClient.subscribeUsdFuturesUserDataStream() creates the listenKey over REST, opens the stream, and manages the key for as long as you are subscribed:
- Keepalive. The SDK sends listenKey keepalives on a timer. A failed keepalive is retried after 15 seconds. After 3 failures in a row, or if Binance says the key no longer exists, the SDK closes the stream and starts a fresh one with a new listenKey.
- Respawn after a drop. When the user data socket closes unexpectedly, the SDK emits
reconnecting, requests a new listenKey and reconnects. If that attempt fails, for example because REST is unreachable, it emitsexceptionand tries again 2 seconds later, until it succeeds. - Expiry. A
listenKeyExpiredevent triggers the same respawn. - Dead sockets. The client sends pings and expects pongs, so a connection that silently stops responding is closed and reconnected.
So the transport recovers by itself. What the SDK cannot know is what your strategy did, or missed, while the stream was down. Events from the gap are not something to rely on getting later. That part is yours.
The events to watch
These are the lifecycle events on WebsocketClient. Use exception for errors; there is no error event to listen to.
ws.on('open', ({ wsKey }) => console.log('open', wsKey));
ws.on('reconnecting', ({ wsKey }) => console.log('reconnecting', wsKey));
ws.on('reconnected', ({ wsKey }) => console.log('reconnected', wsKey));
ws.on('close', ({ wsKey }) => console.log('close', wsKey));
ws.on('exception', (data) => console.error('exception', data));
| Event | When it fires for the user data stream |
|---|---|
open |
A fresh connection opened, including the first subscribe |
reconnecting |
The socket closed unexpectedly and the SDK is about to respawn it |
reconnected |
The respawned stream (new listenKey) is connected again |
close |
The connection was closed on purpose, for example after repeated keepalive failures before a respawn, or when you unsubscribe |
exception |
Something failed, such as the listenKey REST call or a respawn attempt |
The wsKey on these events names the connection. For the USD-M user data stream it starts with usdm_userData and includes the listenKey, so match it with startsWith(). On testnet the prefix is usdmTestnet_userData.
Fail closed, then resync
The rule is simple: trading is off unless the stream is connected and a REST resync has finished since it connected. Any drop turns trading off again.
import {
isWsFormattedFuturesUserDataTradeUpdateEvent,
NewFuturesOrderParams,
USDMClient,
WebsocketClient,
} from 'binance';
const api_key = process.env.BINANCE_API_KEY;
const api_secret = process.env.BINANCE_API_SECRET;
const rest = new USDMClient({ api_key, api_secret });
const ws = new WebsocketClient({ api_key, api_secret, beautify: true });
// The SDK names the USD-M user data connection "usdm_userData_..."
// (the listen key is part of the name). Testnet uses "usdmTestnet_userData_...".
function isUsdmUserData(wsKey: string): boolean {
return wsKey.startsWith('usdm_userData');
}
let streamUp = false;
let everConnected = false;
let tradingEnabled = false;
let resyncRun = 0;
function pauseTrading(reason: string) {
streamUp = false;
tradingEnabled = false;
resyncRun++; // any resync still in flight is now stale
console.warn('Trading paused:', reason);
}
async function resync(reason: string) {
const run = ++resyncRun;
tradingEnabled = false;
try {
const [openOrders, openAlgoOrders, positions] = await Promise.all([
rest.getAllOpenOrders(),
rest.getOpenAlgoOrders(),
rest.getPositionsV3(),
]);
// The stream dropped again, or a newer resync started, while we waited.
if (run !== resyncRun || !streamUp) return;
// Replace your local state with what Binance reports now.
console.log('Resynced after', reason, {
openOrders: openOrders.length,
openAlgoOrders: openAlgoOrders.length,
openPositions: positions.filter((p) => Number(p.positionAmt) !== 0)
.length,
});
tradingEnabled = true;
} catch (e) {
console.error('Resync failed, trading stays paused', e);
setTimeout(() => {
if (run === resyncRun && streamUp) void resync('retry');
}, 2000);
}
}
ws.on('open', ({ wsKey }) => {
if (!isUsdmUserData(wsKey)) return;
streamUp = true;
everConnected = true;
void resync('open');
});
ws.on('reconnected', ({ wsKey }) => {
if (!isUsdmUserData(wsKey)) return;
streamUp = true;
void resync('reconnected');
});
ws.on('reconnecting', ({ wsKey }) => {
if (isUsdmUserData(wsKey)) pauseTrading('user data stream reconnecting');
});
ws.on('close', ({ wsKey }) => {
if (isUsdmUserData(wsKey)) pauseTrading('user data stream closed');
});
ws.on('exception', (data) => {
console.error('ws exception', data);
// A failed FIRST subscribe attempt is not retried by the SDK. Respawns
// after a reconnect carry isReconnecting: true and are retried for you.
const firstAttemptFailed =
data?.functionRef === 'subscribeUsdFuturesUserDataStream()' &&
!data.isReconnecting &&
!everConnected;
if (firstAttemptFailed) {
setTimeout(() => void ws.subscribeUsdFuturesUserDataStream(), 1000);
}
});
ws.on('formattedUserDataMessage', (data) => {
if (isWsFormattedFuturesUserDataTradeUpdateEvent(data)) {
const { symbol, clientOrderId, orderStatus } = data.order;
console.log('order update', symbol, clientOrderId, orderStatus);
}
});
// Every order goes through this check.
export async function placeOrder(params: NewFuturesOrderParams) {
if (!tradingEnabled) {
throw new Error('Trading paused: user data stream not confirmed');
}
return rest.submitNewOrder(params);
}
void ws.subscribeUsdFuturesUserDataStream();
How it works
tradingEnabledstarts asfalse. Only a finished resync sets it totrue.reconnectingandcloseon the user data key turn trading off straight away.openandreconnectedstart a resync. It reads open orders withgetAllOpenOrders(), open conditional (algo) orders withgetOpenAlgoOrders(), and positions withgetPositionsV3(). Replace your local state with those results. Do not merge them into the old state.resyncRunis a counter that makes stale work harmless. If the stream drops while a resync is waiting on REST, the counter moves on, and the old resync returns without enabling trading.- If the resync itself fails, trading stays off and the resync is retried while the stream is still up.
placeOrder()refuses to send anything while trading is paused. Route every order through it, including cancels and replaces if your strategy depends on knowing their result.
The first connection is different
The automatic respawn covers drops after the stream has connected once. If the very first subscribeUsdFuturesUserDataStream() call fails, for example because the listenKey request fails at startup, the SDK emits exception and does not retry by itself. The exception handler above retries in that case only. Respawn attempts carry isReconnecting: true and are left to the SDK. The SDK repository has a fuller version of this pattern in ws-userdata-connection-safety.ts.
Diagnose listenKey failures
| Symptom | Likely cause | Fix |
|---|---|---|
| Orders fill on Binance, but the bot never sees the fill | The user data stream is down, or came back without a resync | Pause on reconnecting and close. Resync open orders and positions on open and reconnected before trading |
| Bot thinks an order is still open after a reconnect | A cancel or fill happened during the gap | Replace local orders with getAllOpenOrders() and getOpenAlgoOrders() after every reconnect |
| Position size in the bot differs from the exchange | Missed ACCOUNT_UPDATE or ORDER_TRADE_UPDATE events |
Replace local positions with getPositionsV3() after every reconnect |
No user data at all after startup, and an exception in the logs |
The first subscribe failed, which is not retried automatically | Retry the first subscribeUsdFuturesUserDataStream() from your exception handler |
- Treat “connected” and “safe to trade” as two different states.
- Start with trading off, and only turn it on after a resync.
- Drop the result of any resync that finishes after the stream went down again.
- Log every
reconnecting,reconnectedandexceptionevent, so a pause is visible.
Further reading
- Binance JavaScript SDK: install, clients and examples
- Binance API JavaScript tutorial: REST and WebSocket clients in more detail
- binance SDK docs
- Binance API docs: USD-M futures user data streams
- Related: Binance user data stream 410 Gone and listenKey and WebSocket reliability and account state
- REST API vs WebSockets vs WebSocket API: which one to use for orders, account state and market data
