WebSocket subscriptions
WebsocketClient opens connections as needed, maintains heartbeats and resubscribes after reconnects.
Subscribe to ticker updates
Install okx-api and save this example as stream.ts. It subscribes to public BTC-USDT Spot ticker updates without credentials.
import { WebsocketClient } from 'okx-api';
const ws = new WebsocketClient();
ws.on('update', (message) => {
console.log('Market update:', message);
});
ws.on('response', (message) => {
console.log('Subscription response:', message);
});
ws.on('exception', (error) => {
console.error('WebSocket exception:', error);
});
ws.on('reconnect', () => {
console.log('Reconnecting; market data may be stale.');
});
ws.on('reconnected', () => {
console.log('Connection restored; wait for fresh market data.');
});
Promise.all(ws.subscribe({ channel: 'tickers', instId: 'BTC-USDT' })).catch((error) => {
console.error('Subscription failed:', error);
ws.closeAll();
process.exitCode = 1;
});
process.once('SIGINT', () => {
ws.closeAll();
});Run it on Node.js 24, or compile it with your TypeScript project:
node stream.tsThe example logs subscription responses and incoming market updates. Leave it running to receive new prices, then press Ctrl+C to close the connection.
Subscription acknowledgements and data
subscribe() returns an array of promises because channels can use different connections. Use Promise.all(ws.subscribe(...)), rather than awaiting the array itself. Observe response for subscription acknowledgements and exception for failures. An open socket does not prove a subscription succeeded.
The update event carries channel messages. Read arg.channel and instrument identifiers before dispatching the data to your handlers. A quiet private stream can be healthy when nothing changes.
Subscribe to multiple channels with an array. Use unsubscribe() with the same channel arguments when a view or strategy no longer needs them. Its returned promise array can also be awaited with Promise.all.
Connection recovery
The SDK restores subscriptions automatically; you do not need to subscribe again. Treat data as stale on reconnect and unexpected closure. The reconnected event signals an open socket, not fresh data. Wait for fresh updates before using cached market data. For incremental books, rebuild according to the channel documentation; for accounts, reconcile missed state.
Call closeAll() when shutting down to stop connections. This does not cancel orders.