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-api SDK surfaces errors from both the REST and WebSocket layers in distinct, predictable ways. REST errors are thrown as structured objects that include the HTTP status code, response body, and the original request context. WebSocket errors emit an exception event on the client so your application can react without crashing. Understanding both paths — and the options that control them — lets you write resilient trading applications from day one.

REST API Error Handling

How the SDK Throws Errors

By default, parseExceptions is true. When a request fails — whether due to a network issue, an HTTP 4xx/5xx response, or a KuCoin business-logic error (e.g. insufficient balance, invalid symbol) — the SDK throws a structured object with the following shape:
{
  code: number;        // HTTP status code (e.g. 400, 401, 429)
  message: string;     // HTTP status text (e.g. "Bad Request")
  body: object;        // Full response body from KuCoin, includes .code and .msg
  headers: object;     // Response headers
  requestOptions: object; // Copy of the RestClientOptions used (apiKey/apiSecret/apiPassphrase replaced with 'omittedFromError')
  requestParams: object;  // The method, endpoint, requestUrl, and params that were sent
}
KuCoin’s own error body always contains a code string and a msg string. For example:
{
  "code": "400100",
  "msg": "Order size below the minimum requirement."
}
KuCoin uses the HTTP 200 OK status for many business-logic errors. The SDK detects these by checking whether response.data.code is a string other than "200000" and throws accordingly — so a 200 response can still result in a thrown error.

Basic try/catch Pattern

Wrap every call in a try/catch block. This applies to both public and private endpoints:
import { SpotClient } from 'kucoin-api';

const client = new SpotClient({
  apiKey: 'apiKeyHere',
  apiSecret: 'apiSecretHere',
  apiPassphrase: 'apiPassPhraseHere',
});

try {
  const spotBuyResult = await client.submitHFOrder({
    clientOid: client.generateNewOrderID(),
    side: 'buy',
    type: 'market',
    symbol: 'BTC-USDT',
    size: '0.00001',
  });
  console.log('spotBuy ', JSON.stringify(spotBuyResult, null, 2));
} catch (e) {
  console.error('Req error: ', e);
}

Inspecting KuCoin Error Codes

When the error originates from a KuCoin business-logic rejection (HTTP 200 with a non-200000 code), the details are nested in e.body:
try {
  const result = await client.submitHFOrder({
    clientOid: client.generateNewOrderID(),
    side: 'buy',
    type: 'limit',
    symbol: 'BTC-USDT',
    price: '1',
    size: '0.00001',
  });
} catch (e: any) {
  if (e?.body?.code) {
    console.error('KuCoin error code:', e.body.code);
    console.error('KuCoin error message:', e.body.msg);
    // e.g. code: "400100", msg: "Order size below the minimum requirement."
  }

  if (e?.code === 429) {
    console.warn('Rate limited — backing off before retry');
  }
}

Disabling Exception Parsing

If you need the raw caught error instead (for custom error pipelines), set parseExceptions: false. The SDK will re-throw whatever was caught — either a network-level error or the raw response object — without wrapping it in the structured shape described above:
const client = new SpotClient({
  apiKey: 'apiKeyHere',
  apiSecret: 'apiSecretHere',
  apiPassphrase: 'apiPassPhraseHere',
  parseExceptions: false, // re-throw raw caught errors without wrapping
});

Strict Parameter Validation

By default, strictParamValidation is false, which means undefined values in a request object are silently stripped. Enable it to throw immediately if any request parameter is undefined — useful during development to catch typos and missing fields early:
const client = new SpotClient({
  apiKey: 'apiKeyHere',
  apiSecret: 'apiSecretHere',
  apiPassphrase: 'apiPassPhraseHere',
  strictParamValidation: true,
});

try {
  // This will throw because `price` is undefined on a limit order
  await client.submitHFOrder({
    clientOid: client.generateNewOrderID(),
    side: 'buy',
    type: 'limit',
    symbol: 'BTC-USDT',
    price: undefined as any,
    size: '0.001',
  });
} catch (e) {
  // Error: "Failed to sign API request due to undefined parameter"
  console.error(e);
}
Enable strictParamValidation in your development and staging environments to catch missing parameters before they reach production.

WebSocket Error Handling

The exception Event

The WebsocketClient emits an exception event when a connection-level error occurs (e.g. DNS failure, TCP reset, authentication error). Listen to it on the client instance:
import { WebsocketClient } from 'kucoin-api';

const client = new WebsocketClient({
  apiKey: 'apiKeyHere',
  apiSecret: 'apiSecretHere',
  apiPassphrase: 'apiPassPhraseHere',
});

client.on('exception', (data) => {
  console.error('exception: ', {
    msg: data.msg,
    errno: data.errno,
    code: data.code,
    syscall: data.syscall,
    hostname: data.hostname,
  });
});
If you do not listen to the exception event, unhandled WebSocket errors may crash your Node.js process. Always attach an exception handler before subscribing to any topics.

Full WebSocket Event Setup

A robust WebSocket setup handles all lifecycle events alongside exceptions:
import { WebsocketClient } from 'kucoin-api';

const client = new WebsocketClient({
  apiKey: 'apiKeyHere',
  apiSecret: 'apiSecretHere',
  apiPassphrase: '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);
});

// Connection closed. If unexpected, expect reconnect -> reconnected.
client.on('close', (data) => {
  console.error('close: ', data);
});

// Reply to a subscribe/unsubscribe/authenticate request
client.on('response', (data) => {
  console.info('response: ', data);
});

client.on('exception', (data) => {
  console.error('exception: ', {
    msg: data.msg,
    errno: data.errno,
    code: data.code,
    syscall: data.syscall,
    hostname: data.hostname,
  });
});

try {
  client.subscribe('/market/ticker:BTC-USDT,ETH-USDT', 'spotPublicV1');
} catch (e) {
  console.error('Subscribe exception: ', e);
}

Practical Patterns

KuCoin returns HTTP 429 when you exceed the rate limit for an endpoint. A simple exponential-backoff wrapper keeps your bot running without manual intervention:
async function withRetry<T>(
  fn: () => Promise<T>,
  retries = 3,
  delayMs = 1000,
): Promise<T> {
  for (let attempt = 1; attempt <= retries; attempt++) {
    try {
      return await fn();
    } catch (e: any) {
      const isRateLimit = e?.code === 429;
      if (isRateLimit && attempt < retries) {
        const wait = delayMs * Math.pow(2, attempt - 1);
        console.warn(`Rate limited. Retrying in ${wait}ms (attempt ${attempt})`);
        await new Promise((r) => setTimeout(r, wait));
      } else {
        throw e;
      }
    }
  }
  throw new Error('Exceeded retry limit');
}

// Usage
const ticker = await withRetry(() =>
  client.getTicker({ symbol: 'BTC-USDT' }),
);
KuCoin documents its error codes in the official API reference. Common ones you may encounter:
CodeMeaning
200000Success
400001Any header not found
400100Argument problem (e.g. below minimum)
400200Forbidden to place an order
401000Key expired
429000Too many requests
try {
  await client.submitHFOrder({ /* ... */ });
} catch (e: any) {
  switch (e?.body?.code) {
    case '400100':
      console.error('Order argument invalid:', e.body.msg);
      break;
    case '401000':
      console.error('API key expired — please rotate your credentials');
      break;
    case '429000':
      console.warn('Rate limit exceeded — slow down requests');
      break;
    default:
      console.error('Unexpected error:', e);
  }
}
Public endpoints don’t require credentials and rarely fail, but network issues and exchange outages can still cause exceptions:
import { SpotClient } from 'kucoin-api';

const client = new SpotClient();

try {
  const symbols = await client.getSymbols();
  console.log('symbols:', JSON.stringify(symbols, null, 2));

  const ticker = await client.getTicker({ symbol: 'BTC-USDT' });
  console.log('ticker:', JSON.stringify(ticker, null, 2));
} catch (e) {
  console.error('Req error: ', e);
}

Build docs developers (and LLMs) love