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 WebsocketAPIClient wraps KuCoin’s WebSocket API for order management, giving you REST-like method calls that are transmitted over a persistent WebSocket connection instead of HTTP. This dramatically reduces round-trip latency compared to traditional REST endpoints, making it ideal for high-frequency spot and margin order workflows. All methods return typed Promises and handle connection management, authentication, and reconnection automatically.

Initialization

Instantiate the client with your API credentials. The underlying WebSocket connection is established on first use.
import { WebsocketAPIClient } from 'kucoin-api';

const client = new WebsocketAPIClient({
  apiKey: 'your-api-key',
  apiSecret: 'your-api-secret',
  apiPassphrase: 'your-api-passphrase',

  // Optional: disable built-in console event listeners if you want
  // to attach your own via client.getWSClient().on(...)
  // attachEventListeners: false,
});
To connect to the testnet, pass testnet: true in the constructor options rather than using a custom wsKey.
The attachEventListeners option (default true) automatically logs connection lifecycle events — open, reconnect, reconnected, authenticated, and exception — to the console. Disable it and call client.getWSClient().on(...) to attach your own handlers.

The wsKey Parameter

Every method accepts an optional wsKey parameter of type WSAPIWsKey. This lets you specify which underlying WebSocket connection should carry the request. Valid values are:
  • WS_KEY_MAP.wsApiSpotV1 — default for all spot and margin methods
  • WS_KEY_MAP.wsApiFuturesV1 — default for futures methods
You only need to supply a wsKey if you want to route a request over an alternative supported connection (for example, a secondary domain). Omit it in normal usage.
import { WS_KEY_MAP } from 'kucoin-api';

// Explicit wsKey (usually not required)
const response = await client.submitNewSpotOrder(params, WS_KEY_MAP.wsApiSpotV1);

Spot Order Methods

submitNewSpotOrder

Submit a new High-Frequency (HF) spot limit or market order.
submitNewSpotOrder(
  params: SubmitHFOrderRequest,
  wsKey?: WSAPIWsKey,
): Promise<WSAPIResponse<WSAPIOrderResponse>>
type
'limit' | 'market'
required
Order type. 'limit' requires price; 'market' requires either size or funds.
symbol
string
required
Trading pair, e.g. 'BTC-USDT'.
side
'buy' | 'sell'
required
Order side.
clientOid
string
Unique client-generated order ID (UUID recommended). Used for deduplication.
price
string
Required for limit orders. Order price as a string.
size
string
Order quantity in base currency. Required for limit orders; optional for market orders if funds is provided.
funds
string
Quote currency amount to spend (market buy) or receive (market sell). Used instead of size for market orders.
timeInForce
'GTC' | 'GTT' | 'IOC' | 'FOK'
Time-in-force policy. Defaults to 'GTC' (Good Till Cancelled).
cancelAfter
number
Seconds until the order is cancelled (requires timeInForce: 'GTT').
postOnly
boolean
If true, the order will only be added to the order book, never matched immediately.
hidden
boolean
If true, the order is not visible in the order book.
iceberg
boolean
If true, only visibleSize of the order is shown in the order book.
visibleSize
string
Maximum visible quantity for iceberg orders.
stp
'DC' | 'CO' | 'CN' | 'CB'
Self-Trade Prevention strategy.
tags
string
Order tag (max 20 characters).
remark
string
Order remark (max 20 characters).
clientTimestamp
number
Client-side timestamp (milliseconds). Required when iceberg is specified.
allowMaxTimeWindow
number
Maximum milliseconds the order is valid after clientTimestamp. Orders received after clientTimestamp + allowMaxTimeWindow are rejected.
orderId
string
Server-assigned order ID.
clientOid
string
The client order ID provided in the request.
import { WebsocketAPIClient } from 'kucoin-api';

const client = new WebsocketAPIClient({
  apiKey: 'your-api-key',
  apiSecret: 'your-api-secret',
  apiPassphrase: 'your-api-passphrase',
});

// Submit a limit buy order
const response = await client.submitNewSpotOrder({
  side: 'buy',
  symbol: 'BTC-USDT',
  type: 'limit',
  price: '20000',
  size: '0.0001',
});

console.log('Order ID:', response.data.orderId);
console.log('Client OID:', response.data.clientOid);

submitSyncSpotOrder

Submit a spot order and receive full fill details in the response (synchronous mode). Unlike submitNewSpotOrder, this waits for matching to complete and returns order status, fill size, remaining size, and match time.
submitSyncSpotOrder(
  params: SubmitHFOrderRequest,
  wsKey?: WSAPIWsKey,
): Promise<WSAPIResponse<SubmitHFOrderSyncResponse>>
orderId
string
Server-assigned order ID.
clientOid
string
Client order ID.
orderTime
number
Time the order was placed (milliseconds).
originSize
string
Original order quantity.
dealSize
string
Filled quantity.
remainSize
string
Remaining unfilled quantity.
canceledSize
string
Cumulative cancelled quantity.
status
string
'open' — order is active; 'done' — order is completed.
matchTime
number
Time of last match (milliseconds).
const syncResponse = await client.submitSyncSpotOrder({
  side: 'buy',
  symbol: 'BTC-USDT',
  type: 'limit',
  price: '20000',
  size: '0.01',
});

console.log('Status:', syncResponse.data.status);
console.log('Filled:', syncResponse.data.dealSize);

modifySpotOrder

Modify the price or size of an existing open spot order. Either orderId or clientOid must be provided.
modifySpotOrder(
  params: ModifyHFOrderRequest,
  wsKey?: WSAPIWsKey,
): Promise<WSAPIResponse<{ newOrderId: string; clientOid: string }>>
symbol
string
required
Trading pair of the order to modify, e.g. 'BTC-USDT'.
orderId
string
Server order ID of the order to modify. Either orderId or clientOid is required.
clientOid
string
Client order ID of the order to modify.
newPrice
string
New limit price for the order.
newSize
string
New quantity for the order.
const modifyResponse = await client.modifySpotOrder({
  symbol: 'BTC-USDT',
  orderId: '68cc3476693c1c00072ef1d9',
  newPrice: '19500',
});

console.log('New order ID:', modifyResponse.data.newOrderId);

cancelSpotOrder

Cancel an open spot order by order ID or client order ID.
cancelSpotOrder(
  params: WSAPICancelOrderRequest,
  wsKey?: WSAPIWsKey,
): Promise<WSAPIResponse<WSAPIOrderResponse>>
symbol
string
required
Trading pair of the order to cancel, e.g. 'BTC-USDT'.
orderId
string
Server order ID. Provide either orderId or clientOid.
clientOid
string
Client order ID. Provide either orderId or clientOid.
const cancelResponse = await client.cancelSpotOrder({
  symbol: 'BTC-USDT',
  orderId: '68cc34c6693c1c0007301929',
});

console.log('Cancelled order ID:', cancelResponse.data.orderId);

cancelSyncSpotOrder

Cancel a spot order and receive full order status details in the response (synchronous mode).
cancelSyncSpotOrder(
  params: WSAPICancelOrderRequest,
  wsKey?: WSAPIWsKey,
): Promise<WSAPIResponse<SyncCancelHFOrderResponse>>
orderId
string
Server order ID.
clientOid
string
Client order ID.
originSize
string
Original order quantity.
dealSize
string
Filled quantity at time of cancellation.
remainSize
string
Remaining unfilled quantity.
canceledSize
string
Cumulative cancelled quantity.
status
string
'open' or 'done'.
const syncCancel = await client.cancelSyncSpotOrder({
  symbol: 'BTC-USDT',
  orderId: '68cc3530b9870a0007670294',
});

console.log('Remaining size:', syncCancel.data.remainSize);
console.log('Deal size:', syncCancel.data.dealSize);

Margin Order Methods

submitMarginOrder

Submit a new High-Frequency margin order (cross or isolated margin).
submitMarginOrder(
  params: SubmitHFMarginOrderRequest,
  wsKey?: WSAPIWsKey,
): Promise<WSAPIResponse<MarginSubmitOrderV3Response>>
clientOid
string
required
Unique client-generated order ID.
side
'buy' | 'sell'
required
Order side.
symbol
string
required
Trading pair, e.g. 'BTC-USDT'.
type
'limit' | 'market'
Order type. Defaults to 'limit'.
isIsolated
boolean
false for cross margin (default), true for isolated margin.
autoBorrow
boolean
If true, automatically borrows funds if the account balance is insufficient.
autoRepay
boolean
If true, automatically repays the loan when the order is filled.
price
string
Required for limit orders.
size
string
Order quantity in base currency.
funds
string
Quote currency amount (used instead of size for market orders).
timeInForce
'GTC' | 'GTT' | 'IOC' | 'FOK'
Time-in-force policy.
stp
'CN' | 'CO' | 'CB' | 'DC'
Self-Trade Prevention strategy.
orderId
string
Server-assigned order ID.
clientOid
string
Client order ID.
borrowSize
string
Amount borrowed to fill the order (if autoBorrow was enabled).
loanApplyId
string
Loan application ID for the auto-borrow operation.
const marginOrder = await client.submitMarginOrder({
  clientOid: 'margin-' + Date.now(),
  side: 'buy',
  symbol: 'BTC-USDT',
  type: 'limit',
  price: '19000',
  size: '0.0001',
  isIsolated: false,   // cross margin
  autoBorrow: true,
  autoRepay: true,
});

console.log('Margin order ID:', marginOrder.data.orderId);
console.log('Borrowed:', marginOrder.data.borrowSize);

cancelMarginOrder

Cancel an open margin order by order ID or client order ID.
cancelMarginOrder(
  params: WSAPICancelOrderRequest,
  wsKey?: WSAPIWsKey,
): Promise<WSAPIResponse<WSAPIOrderResponse>>
Accepts the same WSAPICancelOrderRequest shape as cancelSpotOrder — provide symbol plus either orderId or clientOid.
const cancelMargin = await client.cancelMarginOrder({
  symbol: 'BTC-USDT',
  orderId: 'your-margin-order-id',
});

console.log('Cancelled:', cancelMargin.data.orderId);

Common Response Envelope

All methods return a WSAPIResponse<T> wrapper:
id
string
Auto-generated request correlation ID.
op
string
The WS API operation that was executed (e.g. 'spot.order').
code
string
'200000' on success; an error code string on failure.
msg
string
Human-readable error message (only present on failure).
data
T
The method-specific response payload.
inTime
number
Gateway request receipt time (milliseconds).
outTime
number
Gateway response dispatch time (milliseconds).
rateLimit
object
Optional rate-limit metadata: { limit, reset, remaining }.
wsKey
string
The WebSocket key used for this request.
isWSAPIResponse
boolean
Always true for WS API responses, used internally to differentiate from streaming updates.
Use the inTime and outTime fields to measure gateway latency for your orders. The difference outTime - inTime reflects the time the KuCoin gateway spent processing your request.

Method Summary

MethodWS OperationRequest TypeResponse Data
submitNewSpotOrderspot.orderSubmitHFOrderRequestWSAPIOrderResponse
submitSyncSpotOrderspot.sync_orderSubmitHFOrderRequestSubmitHFOrderSyncResponse
modifySpotOrderspot.modifyModifyHFOrderRequest{ newOrderId, clientOid }
cancelSpotOrderspot.cancelWSAPICancelOrderRequestWSAPIOrderResponse
cancelSyncSpotOrderspot.sync_cancelWSAPICancelOrderRequestSyncCancelHFOrderResponse
submitMarginOrdermargin.orderSubmitHFMarginOrderRequestMarginSubmitOrderV3Response
cancelMarginOrdermargin.cancelWSAPICancelOrderRequestWSAPIOrderResponse

Build docs developers (and LLMs) love