Skip to main content

Documentation Index

Fetch the complete documentation index at: https://mintlify.com/tiagosiebler/kucoin-api/llms.txt

Use this file to discover all available pages before exploring further.

The KuCoin WebSocket API lets you send trading commands — place orders, modify them, cancel them — over a persistent WebSocket connection instead of making individual HTTP REST requests. This reduces round-trip latency and is ideal for high-frequency or latency-sensitive strategies. The SDK provides two ways to use it: the high-level WebsocketAPIClient wrapper that feels like a REST client, and the lower-level sendWSAPIRequest() method on WebsocketClient for full control.

WebsocketAPIClient — REST-Like Wrapper

WebsocketAPIClient wraps the raw WebSocket API in typed, promise-returning methods. Each method connects and authenticates automatically on first call, then returns a promise that resolves with the exchange’s response.
The WS API uses two separate WsKey connections internally: wsApiSpotV1 for spot and margin operations, and wsApiFuturesV1 for futures operations. WebsocketAPIClient routes each method to the correct connection automatically.

Initialization

import { WebsocketAPIClient, DefaultLogger } from 'kucoin-api';

const wsClient = new WebsocketAPIClient(
  {
    apiKey: process.env.API_KEY || 'keyHere',
    apiSecret: process.env.API_SECRET || 'secretHere',
    apiPassphrase: process.env.API_PASSPHRASE || 'apiPassPhraseHere',

    // Set to false to attach your own event handlers (see below)
    // attachEventListeners: false,
  },
  // Optional: pass a custom logger
  { ...DefaultLogger },
);
The attachEventListeners option (default: true) automatically logs connection lifecycle events (open, reconnect, reconnected, authenticated, exception) to the console. Disable it if you want to register your own handlers via wsClient.getWSClient().on(...).

Available Methods

All methods return a typed Promise<WSAPIResponse<...>> and accept an optional wsKey override for advanced routing.

submitNewSpotOrder

Submit a new spot HF order.
const spotOrderResponse = await wsClient.submitNewSpotOrder({
  side: 'buy',
  symbol: 'BTC-USDT',
  type: 'limit',
  price: '20000',
  size: '0.0001',
});
console.log('Spot order response:', spotOrderResponse);

submitSyncSpotOrder

Submit a spot order and receive a synchronous, fully-filled response including final order state.
const syncSpotOrderResponse = await wsClient.submitSyncSpotOrder({
  side: 'buy',
  symbol: 'BTC-USDT',
  type: 'limit',
  price: '1000',
  size: '0.01',
});
console.log('Sync spot order response:', syncSpotOrderResponse);

modifySpotOrder

Modify the price or size of an existing open spot order.
const modifyResponse = await wsClient.modifySpotOrder({
  symbol: 'BTC-USDT',
  orderId: 'your-order-id-here',
  newPrice: '2000',
});
console.log('Modify spot order response:', modifyResponse);

cancelSpotOrder

Cancel an open spot order by orderId or clientOid.
const cancelSpotResponse = await wsClient.cancelSpotOrder({
  symbol: 'BTC-USDT',
  orderId: 'your-order-id-here',
});
console.log('Cancel spot order response:', cancelSpotResponse);

cancelSyncSpotOrder

Cancel a spot order and receive a synchronous response with confirmation.
const cancelSyncResponse = await wsClient.cancelSyncSpotOrder({
  symbol: 'BTC-USDT',
  orderId: 'your-order-id-here',
});
console.log('Cancel sync spot order response:', cancelSyncResponse);

submitMarginOrder

Submit a margin order (cross or isolated).
const marginOrderResponse = await wsClient.submitMarginOrder({
  clientOid: 'margin-test-' + Date.now(),
  side: 'buy',
  symbol: 'BTC-USDT',
  type: 'limit',
  price: '19000',
  size: '0.0001',
  isIsolated: false, // false = cross margin, true = isolated
});
console.log('Margin order response:', marginOrderResponse);

cancelMarginOrder

Cancel an open margin order.
const cancelMarginResponse = await wsClient.cancelMarginOrder({
  symbol: 'BTC-USDT',
  orderId: 'your-margin-order-id-here',
});
console.log('Cancel margin order response:', cancelMarginResponse);

submitFuturesOrder

Submit a new futures order.
const futuresOrderResponse = await wsClient.submitFuturesOrder({
  clientOid: 'futures-test-' + Date.now(),
  side: 'buy',
  symbol: 'XBTUSDTM',
  marginMode: 'CROSS',
  type: 'limit',
  price: '1000',
  qty: '0.01',
  leverage: 10,
  positionSide: 'LONG', // required for hedge/two-way position mode
});
console.log('Futures order response:', futuresOrderResponse);

cancelFuturesOrder

Cancel an open futures order.
const cancelFuturesResponse = await wsClient.cancelFuturesOrder({
  symbol: 'XBTUSDTM',
  orderId: 'your-futures-order-id-here',
});
console.log('Cancel futures order response:', cancelFuturesResponse);

submitMultipleFuturesOrders

Submit a batch of futures orders in a single WebSocket message.
const multiFuturesResponse = await wsClient.submitMultipleFuturesOrders([
  {
    clientOid: 'futures-test-1-' + Date.now(),
    side: 'buy',
    symbol: 'XBTUSDTM',
    marginMode: 'CROSS',
    type: 'limit',
    price: '1000',
    qty: '0.01',
    leverage: 10,
    positionSide: 'LONG',
  },
  {
    clientOid: 'futures-test-2-' + Date.now(),
    side: 'buy',
    symbol: 'XBTUSDTM',
    marginMode: 'CROSS',
    type: 'limit',
    price: '1010',
    qty: '0.01',
    leverage: 10,
    positionSide: 'LONG',
  },
]);
console.log('Multiple futures orders response:', multiFuturesResponse);

cancelMultipleFuturesOrders

Cancel multiple futures orders in a single request.
const cancelMultiFuturesResponse = await wsClient.cancelMultipleFuturesOrders({
  orderIdsList: ['order-id-1', 'order-id-2'],
});
console.log('Cancel multiple futures orders response:', cancelMultiFuturesResponse);

Full Example: All Operations

The following is a condensed version of the complete ws-api-client.ts example, showing how to call every available method in sequence:
import { DefaultLogger, WebsocketAPIClient } from 'kucoin-api';

async function main() {
  const wsClient = new WebsocketAPIClient(
    {
      apiKey: process.env.API_KEY || 'keyHere',
      apiSecret: process.env.API_SECRET || 'secretHere',
      apiPassphrase: process.env.API_PASSPHRASE || 'apiPassPhraseHere',
    },
    { ...DefaultLogger },
  );

  // Spot operations
  try {
    const spotRes = await wsClient.submitNewSpotOrder({
      side: 'buy', symbol: 'BTC-USDT', type: 'limit',
      price: '20000', size: '0.0001',
    });
    console.log('Spot order:', spotRes);
  } catch (e) { console.log('Spot order error:', e); }

  // Futures operations
  try {
    const futuresRes = await wsClient.submitFuturesOrder({
      clientOid: 'futures-test-' + Date.now(),
      side: 'buy', symbol: 'XBTUSDTM',
      marginMode: 'CROSS', type: 'limit',
      price: '1000', qty: '0.01',
      leverage: 10, positionSide: 'LONG',
    });
    console.log('Futures order:', futuresRes);
  } catch (e) { console.log('Futures order error:', e); }

  process.exit(1);
}

main();

Raw sendWSAPIRequest() on WebsocketClient

For advanced use cases or when you need full control over the request, call sendWSAPIRequest() directly on a WebsocketClient instance. This is the exact method that WebsocketAPIClient uses internally.
import { DefaultLogger, WebsocketClient, WS_KEY_MAP } from 'kucoin-api';

const client = new WebsocketClient(
  {
    apiKey: process.env.API_KEY || 'keyHere',
    apiSecret: process.env.API_SECRET || 'secretHere',
    apiPassphrase: process.env.API_PASSPHRASE || 'apiPassPhraseHere',
  },
);

client.on('open', (data) => console.log('open: ', data?.wsKey));
client.on('update', (data) => console.info('data received: ', JSON.stringify(data)));
client.on('reconnect', (data) => console.log('reconnect: ', data));
client.on('reconnected', (data) => console.log('reconnected: ', data));
client.on('close', (data) => console.error('close: ', data));
client.on('exception', (data) => console.error('exception: ', data));

try {
  const res = await client.sendWSAPIRequest(
    WS_KEY_MAP.wsApiSpotV1,
    'spot.order',
    {
      side: 'buy',
      symbol: 'BTC-USDT',
      type: 'limit',
      price: '20000',
      size: '0.0001',
    },
  );
  console.log('ws api res: ', res);
} catch (e) {
  console.error('ws api exception: ', e);
}

Event-Driven vs Promise-Driven Patterns


Attaching Custom Event Listeners

By default, WebsocketAPIClient attaches console-logging listeners for lifecycle events. To use your own handlers, set attachEventListeners: false and register handlers directly on the embedded WebsocketClient:
const wsClient = new WebsocketAPIClient({
  apiKey: process.env.API_KEY || 'keyHere',
  apiSecret: process.env.API_SECRET || 'secretHere',
  apiPassphrase: process.env.API_PASSPHRASE || 'apiPassPhraseHere',
  attachEventListeners: false,
});

wsClient.getWSClient()
  .on('open', (data) => {
    console.log(new Date(), 'ws connected', data.wsKey);
  })
  .on('reconnect', ({ wsKey }) => {
    console.log(new Date(), 'ws automatically reconnecting....', wsKey);
  })
  .on('reconnected', (data) => {
    console.log(new Date(), 'ws has reconnected', data?.wsKey);
  })
  .on('authenticated', (data) => {
    console.info(new Date(), 'ws has authenticated', data?.wsKey);
  })
  .on('exception', (data) => {
    console.error(new Date(), 'ws exception:', JSON.stringify(data));
  });

Build docs developers (and LLMs) love