KuCoin JavaScript SDK example: ws-public-spot-pro-v2.ts

KuCoin websocket public spot pro V2 JavaScript example for the Siebly KuCoin SDK, covering exchange REST API and WebSocket integration, setup, and production SDK docs.

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

examples/Kucoin/WebSockets/ws-public-spot-pro-v2.ts

What this example covers

  • KuCoin WebSocket stream JavaScript example.
  • Uses the Siebly KuCoin SDK package kucoin-api instead of hand-written WebSocket plumbing.
  • Source path: Kucoin/WebSockets/ws-public-spot-pro-v2.ts.
  • Imports SDK symbols including WebsocketClient, WS_KEY_MAP.
  • Calls SDK methods such as on(), connect(), 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.
/* eslint-disable no-unused-vars */import { WebsocketClient, WS_KEY_MAP, WsTopicRequest } from 'kucoin-api'; async function start() {  // Optional: fully customise the logging experience by injecting a custom logger  // const logger: typeof DefaultLogger = {  //   ...DefaultLogger,  //   trace: (...params) => {  //     if (  //       [  //         'Sending ping',  //         'Sending upstream ws message: ',  //         'Received pong',  //       ].includes(params[0])  //     ) {  //       return;  //     }  //     console.log('trace', params);  //   },  // };   // const client = new WebsocketClient({}, logger);  const client = new WebsocketClient();   client.on('open', (data) => {    console.log('open: ', data?.wsKey);  });   // Data received  client.on('update', (data) => {    console.info('data received: ', JSON.stringify(data));  });   // Something happened, attempting to reconnect  client.on('reconnect', (data) => {    console.log('reconnect: ', data);  });   // Reconnect successful  client.on('reconnected', (data) => {    console.log('reconnected: ', data);  });   // Connection closed. If unexpected, expect reconnect -> reconnected.  client.on('close', (data) => {    console.error('close: ', data);  });   // Reply to a request, e.g. "subscribe"/"unsubscribe"/"authenticate"  client.on('response', (data) => {    console.info('response: ', data);    // throw new Error('res?');  });   client.on('exception', (data) => {    console.error('exception: ', {      msg: data.msg,      errno: data.errno,      code: data.code,      syscall: data.syscall,      hostname: data.hostname,    });  });   /**   * The following example demonstrates the ways to consume data from the V2 (Pro) WebSockets. For the V1 examples, ws-private-spot-v1.ts   */  try {    // Optional: await a connection to be ready before subscribing (this is not necessary)    // await client.connect(WS_KEY_MAP.spotPublicProV2);     /**     * Structure your requests into the following format. The below example will be sent as per the example in the docs. The parameters are automatically merged into the request. Just follow the example below:     * {     *    "id": "1545910660739", // automatically generated by SDK     *    "action": "SUBSCRIBE", // automatically added by SDK     *    "channel":"kline",     *    "tradeType": "SPOT",       // SPOT / FUTURES     *    "symbol": "BTC-USDT",     *    "interval": "1min"     * }     *     * https://www.kucoin.com/docs-new/3470223w0     */    const klineRequest: WsTopicRequest = {      topic: 'kline',      /**       * Anything in the payload will be merged into the subscribe "request", allowing you to send misc parameters supported by the exchange.       * For more info on parameters, see: https://www.kucoin.com/docs-new/websocket-api/base-info/introduction-uta#5-subscribe       */      payload: {        // this needs to match the WsKey below.        // tradeType: SPOT ==> spotPublicProV2        // tradeType: FUTURES ==> futuresPublicProV2        tradeType: 'SPOT',        symbol: 'BTC-USDT',        interval: '1min',      },    };    client.subscribe(klineRequest, WS_KEY_MAP.spotPublicProV2);     /**     * Or, send an array of structured objects with parameters, if you wanted to send multiple in one request     *     */    client.subscribe(      [        // BTCUSDT tickers for spot market        // https://www.kucoin.com/docs-new/3470222w0        {          topic: 'ticker',          payload: {            tradeType: 'SPOT',            symbol: 'BTC-USDT',          },        },        // BTCUSDT orderbook updates for spot market        // https://www.kucoin.com/docs-new/3470221w0        {          topic: 'obu',          payload: {            tradeType: 'SPOT',            symbol: 'BTC-USDT',            depth: '5', // 1 / 5 / 50 / increment            rpiFilter: 0, // 0:Only NoneRPI orders [Default]  1(Only Support Futures):NoneRPI+ RPI Orders. When rpiFilter=1, "depth" only supports 5/50.          },        },        // BTCUSDT trades for spot market        // https://www.kucoin.com/docs-new/3470224w0        {          topic: 'trade',          payload: {            tradeType: 'SPOT',            symbol: 'BTC-USDT',          },        },      ],      WS_KEY_MAP.spotPublicProV2,    );  } catch (e) {    console.error('Subscribe V2 exception: ', e);  }} start(); 

Subscribe on Substack

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