OKX JavaScript SDK example: ws-public.ts

OKX websocket public JavaScript example. Read the source code, review its SDK calls, and browse related exchange integration examples.

This example uses okx-api, the JavaScript and TypeScript SDK for OKX. Install it with npm install okx-api.

We use environment variables in our examples for API keys. It is your responsibility to manage and secure your keys appropriately.

examples/OKX/Websocket/ws-public.ts

What this example covers

  • OKX WebSocket stream JavaScript example.
  • Uses the Siebly OKX SDK package okx-api instead of hand-written WebSocket plumbing.
  • Source path: OKX/Websocket/ws-public.ts.
  • Imports SDK symbols including DefaultLogger, WebsocketClient.
  • Calls SDK methods such as on(), subscribe().

How to use this example

  • Start here for the specific request or stream pattern, then check the matching SDK guide for install, credentials, and operational notes.
  • For WebSocket examples, keep reconnect, resubscribe, heartbeat, and event-handler behavior explicit in your service.
  • Open the repository source when you need the latest committed version: GitHub source file.
import { DefaultLogger, WebsocketClient } from 'okx-api'; // Optional: Inject a custom logger.// This example overrides the default logger to also log "trace" (super verbose) messages, which are disabled by defaultconst logger = {  ...DefaultLogger,  // trace: (...params) => console.log('trace', ...params),}; const wsClient = new WebsocketClient(  {    // For Global users (www.okx.com), you don't need to set the market.    // It will use global by default.    // Not needed: market: 'GLOBAL',    // For EEA users (my.okx.com), set market to "EEA":    // market: 'EEA',    // For US users (app.okx.com), set market to "US":    // market: 'US',  },  logger, // Optional: inject the custom logger here); // Raw data will arrive on the 'update' eventwsClient.on('update', (data) => {  // console.log(  //   new Date(),  //   'ws update (raw data received)',  //   JSON.stringify(data, null, 2),  // );  // console.log('ws update (raw data received)', JSON.stringify(data, null, 2));  console.log(    new Date(),    'ws update (raw data received)',    JSON.stringify(data),  );}); wsClient.on('open', (data) => {  console.log('ws connection opened open:', data.wsKey);}); // Replies (e.g. authenticating or subscribing to channels) will arrive on the 'response' eventwsClient.on('response', (data) => {  console.log('ws response received: ', JSON.stringify(data, null, 2));}); wsClient.on('reconnect', ({ wsKey }) => {  console.log('ws automatically reconnecting.... ', wsKey);});wsClient.on('reconnected', (data) => {  console.log('ws has reconnected ', data?.wsKey);});wsClient.on('exception', (data) => {  console.error('ws exception: ', data);}); // Send one topic at a timewsClient.subscribe({  channel: 'instruments',  instType: 'FUTURES',}); // Or an array of requestswsClient.subscribe([  {    channel: 'instruments',    instType: 'SPOT',  },  {    channel: 'tickers',    instId: 'LTC-BTC',  },]); /** * * Examples for each channel: https://www.okx.com/docs-v5/en/#websocket-api-public-channel * */ // Instruments channelwsClient.subscribe({  channel: 'instruments',  instType: 'SPOT',}); // Tickers channelwsClient.subscribe({  channel: 'tickers',  instId: 'BTC-USDT',}); // Open interest channelwsClient.subscribe({  channel: 'open-interest',  instId: 'BTC-USD-SWAP',}); // Candlesticks channelwsClient.subscribe({  channel: 'candle1m',  instId: 'BTC-USDT',}); // Trades channelwsClient.subscribe({  channel: 'trades',  instId: 'BTC-USDT',}); // Estimated delivery/exercise price channelwsClient.subscribe({  channel: 'estimated-price',  instType: 'FUTURES',  instFamily: 'BTC-USD',}); // Mark price channelwsClient.subscribe({  channel: 'mark-price',  instId: 'BTC-USDT',}); // Mark price candlesticks channelwsClient.subscribe({  channel: 'mark-price-candle1m',  instId: 'BTC-USDT',}); // Price limit channelwsClient.subscribe({  channel: 'price-limit',  instId: 'BTC-USDT-SWAP',}); // Order book channelwsClient.subscribe({  channel: 'books',  instId: 'BTC-USDT',}); // OPTION summary channelwsClient.subscribe({  channel: 'opt-summary',  instFamily: 'BTC-USD',}); // Funding rate channelwsClient.subscribe({  channel: 'funding-rate',  instId: 'BTC-USD-SWAP',}); // Index candlesticks channelwsClient.subscribe({  channel: 'index-candle1m',  instId: 'BTC-USD',}); // Index tickers channelwsClient.subscribe({  channel: 'index-tickers',  instId: 'BTC-USDT',}); // Status channelwsClient.subscribe({  channel: 'status',}); // Liquidation orders channelwsClient.subscribe({  channel: 'liquidation-orders',  instType: 'FUTURES',}); wsClient.subscribe({  channel: 'liquidation-orders',  instType: 'SWAP',}); 

Subscribe on Substack

Complete the Substack form below to join our newsletter. Substack handles all subscriber data directly.