Simple Demo for Connecting to OKX WebSockets in JavaScript/Node.js

ยท

Introduction

WebSocket connections enable real-time data streaming between clients and servers, making them essential for financial applications like cryptocurrency trading. This guide demonstrates how to connect to OKX's WebSocket API using JavaScript and Node.js.

Prerequisites

Before starting, ensure you have:

Setting Up the Websocket Client

Here's the complete code to establish a WebSocket connection with OKX's API:

import { DefaultLogger, WebsocketClient } from 'okx-api';

// Optional: Inject a custom logger
const logger = {
  ...DefaultLogger,
  silly: (...params) => console.log('silly', ...params),
};

const wsClient = new WebsocketClient(
  {
    // market: 'prod' (default)
    // market: 'aws'
    // market: 'demo'
  },
  logger
);

Event Handlers

Configure these essential event listeners for your WebSocket client:

// Raw data handler
wsClient.on('update', (data) => {
  console.log(
    new Date(),
    'ws update (raw data received)',
    JSON.stringify(data)
  );
});

// Connection opened
wsClient.on('open', (data) => {
  console.log('ws connection opened:', data.wsKey);
});

// Response handler
wsClient.on('response', (data) => {
  console.log('ws response received: ', JSON.stringify(data, null, 2));
});

// Reconnection events
wsClient.on('reconnect', ({ wsKey }) => {
  console.log('ws automatically reconnecting... ', wsKey);
});

wsClient.on('reconnected', (data) => {
  console.log('ws has reconnected ', data?.wsKey);
});

// Error handler
wsClient.on('error', (data) => {
  console.error('ws exception: ', data);
});

Subscribing to Channels

To receive candlestick data for BTC-USDT:

wsClient.subscribe({
  channel: 'candle1m',
  instId: 'BTC-USDT',
});

Key Features of OKX WebSocket API

  1. Real-time Data: Get instant market updates
  2. Multiple Markets: Choose between production, demo, or AWS environments
  3. Customizable Logging: Adjust verbosity as needed
  4. Automatic Reconnection: Handles network interruptions gracefully

๐Ÿ‘‰ Explore OKX's full API documentation for more advanced features and endpoints.

Best Practices

FAQ

Q: What markets does OKX WebSocket API support?

A: The API supports production ('prod'), demo ('demo'), and AWS ('aws') environments.

Q: How do I handle disconnections?

A: The client automatically attempts reconnection. You can monitor this process through the 'reconnect' and 'reconnected' events.

Q: Can I subscribe to multiple instruments?

A: Yes, simply call the subscribe method for each instrument/channel combination you need.

Q: What's the difference between 'update' and 'response' events?

A: 'update' contains market data, while 'response' contains system messages like subscription confirmations.

Q: Is authentication required?

A: For public data streams no, but private endpoints require API keys.

๐Ÿ‘‰ Learn more about OKX WebSocket authentication

Conclusion

This implementation provides a solid foundation for building real-time cryptocurrency trading applications using OKX's WebSocket API. Remember to adapt the code to your specific requirements and error handling needs.