
Security News
AI Agent Lands PRs in Major OSS Projects, Targets Maintainers via Cold Outreach
An AI agent is merging PRs into major OSS projects and cold-emailing maintainers to drum up more work.
kucoin-api
Advanced tools
Complete & robust Node.js SDK for Kucoin's REST APIs and WebSockets, with TypeScript & strong end to end tests.
[!TIP] Upcoming change: As part of the Siebly.io brand, this SDK will soon be hosted under the Siebly.io GitHub organisation. The migration is seamless and requires no user changes.
Updated & performant JavaScript & Node.js SDK for the KuCoin REST APIs and WebSockets:
reconnected event when dropped connection is restored.sendWSAPIRequest() method, or;npm install --save kucoin-api
Refer to the examples folder for implementation demos.
Check out our JavaScript/TypeScript/Node.js SDKs & Projects:
Most methods accept JS objects. These can be populated using parameters specified by KuCoin's API documentation, or check the type definition in each class within this repository.
This project uses typescript. Resources are stored in 2 key structures:
Create API credentials on KuCoin's website:
The SDK provides dedicated REST clients for different trading products:
To use KuCoin's Spot and Margin APIs, import (or require) the SpotClient:
const { SpotClient, FuturesClient } = require('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));
const spotSellResult = await client.submitHFOrder({
clientOid: client.generateNewOrderID(),
side: 'sell',
type: 'market',
symbol: 'BTC-USDT',
size: '0.00001',
});
console.log('spotSellResult ', JSON.stringify(spotSellResult, null, 2));
} catch (e) {
console.error(`Req error: `, e);
}
See SpotClient for further information, or the examples for lots of usage examples.
Use the FuturesClient for futures trading operations. See FuturesClient for complete API coverage.
Use the BrokerClient for broker and sub-account management operations. See BrokerClient for complete API coverage.
The UnifiedAPIClient provides access to KuCoin's Unified API endpoints, which offer streamlined market data access across Spot, Futures, and Margin trading products. It doesn't serve a purpose of a UTA account(Unified trading account) - but it is a new generation of API endpoints generalised for all trading products.
All WebSocket functionality is supported via the unified WebsocketClient. This client handles both spot and futures WebSocket streams with automatic connection management and reconnection.
Key WebSocket features:
All websockets are accessible via the shared WebsocketClient. As before, API credentials are optional unless the user data stream is required.
For public market data, API credentials are not required:
All available WebSockets can be used via a shared WebsocketClient. The WebSocket client will automatically open/track/manage connections as needed. Each unique connection (one per server URL) is tracked using a WsKey (each WsKey is a string - see WS_KEY_MAP for a list of supported values).
Any subscribe/unsubscribe events will need to include a WsKey, so the WebSocket client understands which connection the event should be routed to. See examples below or in the examples folder on GitHub.
Data events are emitted from the WebsocketClient via the update event, see example below:
const { WebsocketClient } = require('kucoin-api');
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 reconenct
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,
});
});
try {
// Optional: await a connection to be ready before subscribing (this is not necessary)
// await client.connect('futuresPublicV1');
/**
* Examples for public futures websocket topics (that don't require authentication).
*
* These should all subscribe via the "futuresPublicV1" wsKey. For detailed usage, refer to the ws-private-spot-v1.ts & ws-public-futures-v1.ts examples.
*/
client.subscribe(
[
'/contractMarket/tickerV2:XBTUSDM',
'/contractMarket/ticker:XBTUSDM',
'/contractMarket/level2:XBTUSDM',
'/contractMarket/execution:XBTUSDM',
'/contractMarket/level2Depth5:XBTUSDM',
'/contractMarket/level2Depth50:XBTUSDM',
'/contractMarket/limitCandle:XBTUSDTM_1hour',
'/contract/instrument:XBTUSDM',
'/contract/announcement',
'/contractMarket/snapshot:XBTUSDM',
],
'futuresPublicV1',
);
/**
* The V2 (Pro) WebSockets are also supported, accessible via the corresponding V2 WsKeys. Below is a demonstration for the V2 public futures topics with the WsKey "futuresPublicProV2":
*/
client.subscribe(
[
// BTCUSDT tickers for FUTURES market
// https://www.kucoin.com/docs-new/3470222w0
{
topic: 'ticker',
payload: {
tradeType: 'FUTURES',
symbol: 'XBTUSDTM',
},
},
// BTCUSDT orderbook updates for FUTURES market
// https://www.kucoin.com/docs-new/3470221w0
{
topic: 'obu',
payload: {
tradeType: 'FUTURES',
symbol: 'XBTUSDTM',
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: 'FUTURES',
symbol: 'XBTUSDTM',
},
},
],
'futuresPublicProV2',
);
} catch (e) {
console.error(`Subscribe exception: `, e);
}
For private account data streams, API credentials are required. The WebsocketClient will automatically handle authentication when you provide API credentials.
See WebsocketClient for further information and make sure to check the examples/WebSockets/ folder for much more detail, especially ws-private-spot-v1.ts and ws-private-pro-v2.ts, which explain in a lot of detail.
KuCoin also support sending requests (commands) over an active WebSocket connection. This is called the WebSocket API. There are two key ways of interacting with the WebSocket API. The existing WebsocketClient allows raw event routing via the awaitable sendWSAPIRequest() method, or for a much simpler & convenient interface, use the promise-driven API. The surface feels like a REST API, but routing is automatically routed via a dedicated WebSocket connection.
The WebSocket API is available in the WebsocketClient via the sendWSAPIRequest(wsKey, command, commandParameters) method.
Each call to this method is wrapped in a promise, which you can async await for a response, or handle it in a raw event-driven design.
The WebSocket API is also available in a promise-wrapped REST-like format. Either, as above, await any calls to sendWSAPIRequest(...), or directly use the convenient WebsocketAPIClient. This class is very similar to existing REST API classes (such as the MainClient or USDMClient).
It provides one function per endpoint, feels like a REST API and will automatically route your request via an automatically persisted, authenticated and health-checked WebSocket API connection.
Below is an example showing how easy it is to use the WebSocket API without any concern for the complexity of managing WebSockets. For more detailed demonstration, take a look at the examples/WebSockets/WS-API/ws-api-client.ts example:
import { DefaultLogger, WebsocketAPIClient } from 'kucoin-api';
// or, if you prefer `require()`:
// const { DefaultLogger, WebsocketAPIClient } = require('kucoin-api');
const customLogger = {
...DefaultLogger,
// For a more detailed view of the WebsocketClient, enable the `trace` level by uncommenting the below line:
// trace: (...params) => console.log(new Date(), 'trace', ...params),
};
const account = {
key: process.env.API_KEY || 'keyHere',
secret: process.env.API_SECRET || 'secretHere',
passphrase: process.env.API_PASSPHRASE || 'apiPassPhraseHere', // This is NOT your account password
};
const wsClient = new WebsocketAPIClient(
{
apiKey: account.key,
apiSecret: account.secret,
apiPassphrase: account.passphrase,
// If you want your own event handlers instead of the default ones with logs, disable this setting and see the `attachEventHandlers` example below:
// attachEventListeners: false
},
// customLogger, // optional: uncomment this to inject a custom logger
);
// Make WebSocket API calls, very similar to a REST API:
wsClient
.submitNewSpotOrder({
side: 'buy',
symbol: 'BTC-USDT',
type: 'limit',
price: '150000',
size: '0.0001',
})
.then((syncSpotOrderResponse) => {
console.log('Sync spot order response:', syncSpotOrderResponse);
})
.catch((e) => {
console.log('Sync spot order error:', e);
});
wsClient
.submitFuturesOrder({
clientOid: 'futures-test-' + Date.now(),
side: 'buy',
symbol: 'XBTUSDTM',
marginMode: 'CROSS',
type: 'limit',
price: '1000',
qty: '0.01',
leverage: 10,
positionSide: 'LONG', // needed if trading two-way (hedge) position mode
})
.then((futuresOrderResponse) => {
console.log('Futures order response:', futuresOrderResponse);
})
.catch((e) => {
console.log('Futures order error:', e);
});
Below is an example for using this Node.js, TypeScript & JavaScript SDK for KuCoin's APIs, using an account registered on the KuCoin EU domain:
const client = new SpotClient({
apiKey: API_KEY,
apiSecret: API_SECRET,
apiPassphrase: API_PASSPHRASE,
// apiRegion: 'global', // KuCoin.com, the default behaviour. Or 'EU' or 'AU':
apiRegion: 'EU', // KuCoin EU,
// apiRegion: 'AU', // KuCoin AU
});
try {
const accountSummary = await client.getAccountSummary();
console.log('accountSummary ', JSON.stringify(accountSummary, null, 2));
} catch (e) {
console.error('Req error: ', e);
}
const wsClient = new WebsocketClient({
apiKey: account.key,
apiSecret: account.secret,
apiPassphrase: account.passphrase,
apiRegion: 'EU', // for KuCoin EU, or 'global' for KuCoin.com (default) or 'AU' for Australia
});
// ...
Pass a custom logger which supports the log methods trace, info and error, or override methods from the default logger as desired.
const { WebsocketClient, DefaultLogger } = require('kucoin-api');
// E.g. customise logging for only the trace level:
const logger = {
// Inherit existing logger methods, using an object spread
...DefaultLogger,
// Define a custom trace function to override only that function
trace: (...params) => {
if (
[
// Selectively prevent some traces from logging
'Sending ping',
'Received pong',
].includes(params[0])
) {
return;
}
console.log('trace', JSON.stringify(params, null, 2));
},
};
const ws = new WebsocketClient(
{
apiKey: 'apiKeyHere',
apiSecret: 'apiSecretHere',
apiPassphrase: 'apiPassPhraseHere',
},
logger,
);
Build a bundle using webpack:
npm installnpm run buildnpm run packThe bundle can be found in dist/. Altough usage should be largely consistent, smaller differences will exist. Documentation is still TODO.
This SDK includes a bundled llms.txt file in the root of the repository. If you're developing with LLMs, use the included llms.txt with your LLM - it will significantly improve the LLMs understanding of how to correctly use this SDK.
This file contains AI optimised structure of all the functions in this package, and their parameters for easier use with any learning models or artificial intelligence.
Have my projects helped you? Share the love, there are many ways you can show your thanks:
0xA3Bda8BecaB4DCdA539Dc16F9C54a592553Be06C Contributions are encouraged, I will review any incoming pull requests. See the issues tab for todo items.
FAQs
Complete & robust Node.js SDK for Kucoin's REST APIs and WebSockets, with TypeScript & strong end to end tests.
We found that kucoin-api demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 2 open source maintainers collaborating on the project.
Did you know?

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Security News
An AI agent is merging PRs into major OSS projects and cold-emailing maintainers to drum up more work.

Research
/Security News
Chrome extension CL Suite by @CLMasters neutralizes 2FA for Facebook and Meta Business accounts while exfiltrating Business Manager contact and analytics data.

Security News
After Matplotlib rejected an AI-written PR, the agent fired back with a blog post, igniting debate over AI contributions and maintainer burden.