WebSocket subscriptions
Subscribe to BTCUSDT Spot ticker updates. This public stream requires no API key.
Subscribe to a ticker
Save this as stream.ts in a TypeScript project. It prints updates for 30 seconds and closes on completion, Ctrl+C or SIGTERM.
ts
import { WebsocketClient } from 'binance';
const ws = new WebsocketClient({});
let stopped = false;
let timer: ReturnType<typeof setTimeout> | undefined;
function stop() {
if (stopped) return;
stopped = true;
clearTimeout(timer);
ws.closeAll();
}
process.once('SIGINT', stop);
process.once('SIGTERM', stop);
ws.on('message', (message) => console.log(message));
ws.on('exception', () => {
console.error('WebSocket exception. Check the topic, environment and connection.');
});
async function main() {
await ws.subscribeSpotSymbol24hrTicker('btcusdt');
if (!stopped) timer = setTimeout(stop, 30000);
}
main().catch(() => {
console.error('Subscription failed.');
process.exitCode = 1;
stop();
});Subscription results and messages
Await the subscription promise and catch failures. Market data arrives on message; response carries subscription replies.
Recover after a disconnect
The client reconnects and restores subscriptions. Use reconnecting, reconnected and exception to track connection changes. See stream recovery for rebuilding application state after a gap.
Shut down
Call closeAll() to close this client's connections. Clear application timers and stop new work during shutdown.