Skip to main content
The WebsocketClient class provides an event-driven interface for subscribing to OKX WebSocket channels. It handles connection management, authentication, heartbeats, and automatic reconnection so you can focus on processing incoming data.

Installation

npm install okx-api

Basic usage

import { WebsocketClient } from 'okx-api';

const wsClient = new WebsocketClient({
  // market defaults to 'prod' (www.okx.com)
  // Add accounts array for private channels
});

// Listen for incoming channel data
wsClient.on('update', (data) => {
  console.log('received:', JSON.stringify(data));
});

// Subscribe to a public channel
wsClient.subscribe({
  channel: 'tickers',
  instId: 'BTC-USDT',
});

Constructor options

Pass a WSClientConfigurableOptions object as the first argument to the constructor.
OptionTypeDefaultDescription
accountsAPICredentials[]One or more API credentials. Required for private channels.
market'prod' | 'EEA' | 'US''prod'Selects the regional endpoint. 'prod' connects to www.okx.com, 'EEA' to my.okx.com, and 'US' to app.okx.com.
demoTradingbooleanfalseUse OKX demo trading endpoints.
pingIntervalnumberMilliseconds between heartbeat pings.
pongTimeoutnumberMilliseconds to wait for a pong before treating the connection as dead.
reconnectTimeoutnumberMilliseconds to wait before respawning a dropped connection.
disableHeartbeatbooleanfalseDisable the ping/pong heartbeat. Not recommended.
customSignMessageFn(message: string, secret: string) => Promise<string>Override the default HMAC signing implementation, e.g. to use Node’s createHmac.
wsOptionsobjectRaw options forwarded to the underlying WebSocket constructor (agent, protocols, etc.).
wsUrlstringOverride the WebSocket URL entirely.
import { DefaultLogger, WebsocketClient } from 'okx-api';

const wsClient = new WebsocketClient(
  {
    market: 'prod',
    demoTrading: false,
    pingInterval: 10000,
    pongTimeout: 5000,
    reconnectTimeout: 2500,
    accounts: [
      {
        apiKey: process.env.API_KEY!,
        apiSecret: process.env.API_SECRET!,
        apiPass: process.env.API_PASSPHRASE!,
      },
    ],
  },
  DefaultLogger, // optional custom logger
);

Subscribe and unsubscribe

Call subscribe() with a single channel arg object or an array of them. The client automatically opens the appropriate WebSocket connection if one does not exist yet, and resubscribes after any reconnection.
// Single subscription
wsClient.subscribe({
  channel: 'tickers',
  instId: 'BTC-USDT',
});

// Multiple subscriptions in one call
wsClient.subscribe([
  { channel: 'tickers', instId: 'BTC-USDT' },
  { channel: 'trades', instId: 'ETH-USDT' },
]);

// Unsubscribe
wsClient.unsubscribe({
  channel: 'tickers',
  instId: 'BTC-USDT',
});
Topics are persisted in memory. If the connection drops and reconnects, all active subscriptions are automatically resubscribed. Calling unsubscribe() removes a topic from that list so it is not resubscribed.

Event-driven architecture

All incoming data and lifecycle events are surfaced through Node.js EventEmitter events. Attach listeners with .on() before subscribing.
wsClient.on('update', (data) => { /* channel data */ });
wsClient.on('response', (data) => { /* subscribe/auth confirmations */ });
wsClient.on('open', (data) => { /* connection opened */ });
wsClient.on('reconnect', (data) => { /* reconnecting */ });
wsClient.on('reconnected', (data) => { /* reconnection succeeded */ });
wsClient.on('exception', (data) => { /* errors */ });

Connections

The client manages separate WebSocket connections per endpoint type (public, private, business). You can eagerly open connections before subscribing, or let the library open them on demand.
// Open all connections upfront
wsClient.connectAll();

// Or open specific connections
wsClient.connectPublic();
wsClient.connectPrivate();

Legacy WebSocket client

The SDK also exports WebsocketClientLegacy, which is a previous implementation retained for backwards compatibility. New integrations should use WebsocketClient instead.
import { WebsocketClientLegacy } from 'okx-api';

Learn more

Public Channels

Subscribe to instruments, tickers, order books, trades, and candles without authentication.

Private Channels

Subscribe to account, positions, orders, and fills with API credentials.

Event Handling

Full reference for all emitted events and their TypeScript types.

Reconnection

How the client detects dropped connections and restores subscriptions automatically.

Build docs developers (and LLMs) love