Skip to content

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 'bybit-api';

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('update', (message) => console.log(message));
ws.on('exception', () => {
  console.error('WebSocket exception. Check the topic, environment and connection.');
});
async function main() {
  await Promise.all(ws.subscribeV5('tickers.BTCUSDT', 'spot'));
  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 update; response carries subscription replies.

Recover after a disconnect ​

The client reconnects and restores subscriptions. Use reconnect, 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.

Production usage · WebsocketClient reference

Built by Siebly. Open source SDKs for exchange APIs.