This file is a merged representation of a subset of the codebase, containing files not matching ignore patterns, combined into a single document by Repomix.
The content has been processed where content has been compressed (code blocks are separated by ⋮---- delimiter).
================================================================
File Summary
================================================================
Purpose:
--------
This file contains a packed representation of a subset of the repository's contents that is considered the most important context.
It is designed to be easily consumable by AI systems for analysis, code review,
or other automated processes.
File Format:
------------
The content is organized as follows:
1. This summary section
2. Repository information
3. Directory structure
4. Repository files (if enabled)
5. Multiple file entries, each consisting of:
a. A separator line (================)
b. The file path (File: path/to/file)
c. Another separator line
d. The full contents of the file
e. A blank line
Usage Guidelines:
-----------------
- This file should be treated as read-only. Any changes should be made to the
original repository files, not this packed version.
- When processing this file, use the file path to distinguish
between different files in the repository.
- Be aware that this file may contain sensitive information. Handle it with
the same level of security as you would the original repository.
Notes:
------
- Some files may have been excluded based on .gitignore rules and Repomix's configuration
- Binary files are not included in this packed representation. Please refer to the Repository Structure section for a complete list of file paths, including binary files
- Files matching these patterns are excluded: .github/, examples/apidoc/, docs/images/, docs/endpointFunctionList.md, test/, src/util/
- Files matching patterns in .gitignore are excluded
- Files matching default ignore patterns are excluded
- Content has been compressed - code blocks are separated by ⋮---- delimiter
- Files are sorted by Git change count (files with more changes are at the bottom)
================================================================
Directory Structure
================================================================
examples/
auth/
authorizationHeader.ts
fasterHmacSign.ts
WebSockets/
subscriptions/
README.md
ws-futures-private.ts
ws-futures-public.ts
ws-spot-private.ts
ws-spot-public.ts
ws-api-client.ts
ws-api-raw-promises.ts
kucoin-FUTURES-examples-nodejs.md
kucoin-SPOT-examples-nodejs.md
rest-futures-orders-guide.ts
rest-futures-private-trade.ts
rest-futures-public.ts
rest-spot-private-trade.ts
rest-spot-public.ts
tsconfig.examples.json
src/
lib/
websocket/
logger.ts
websocket-util.ts
WsStore.ts
WsStore.types.ts
BaseRestClient.ts
BaseWSClient.ts
misc-util.ts
requestUtils.ts
webCryptoAPI.ts
types/
request/
broker.types.ts
futures.types.ts
spot-account.ts
spot-affiliate.ts
spot-convert.ts
spot-earn.ts
spot-funding.ts
spot-margin-trading.ts
spot-misc.ts
spot-trading.ts
uta-types.ts
response/
broker.types.ts
futures.types.ts
shared.types.ts
spot-account.ts
spot-affiliate.ts
spot-convert.ts
spot-earn.ts
spot-funding.ts
spot-margin-trading.ts
spot-misc.ts
spot-trading.ts
spot-vip.ts
uta-types.ts
ws.ts
websockets/
ws-api.ts
ws-events.ts
ws-general.ts
BrokerClient.ts
FuturesClient.ts
index.ts
SpotClient.ts
UnifiedAPIClient.ts
WebsocketAPIClient.ts
WebsocketClient.ts
.eslintrc.cjs
.gitignore
.nvmrc
.prettierrc
jest.config.ts
LICENSE.md
package.json
postBuild.sh
README.md
tea.yaml
tsconfig.cjs.json
tsconfig.esm.json
tsconfig.json
tsconfig.linting.json
================================================================
Files
================================================================
================
File: examples/kucoin-FUTURES-examples-nodejs.md
================
# **KuCoin FUTURES API Examples** - Node.js, JavaScript & Typescript SDK for Kucoin REST APIs & WebSockets
This document provides comprehensive examples for using the KuCoin FUTURES API with Node.js and JavaScript. It covers various functionalities including account management, fund transfers, trade execution, order management, and market data retrieval. The examples are designed to help developers quickly integrate KuCoin Futures API into their NodeJS, Javascript and Typscript applications.
If you are here, it means you will be great addition to our [Node.js Traders](https://t.me/nodetraders) community on Telegram where we discuss trading ideas, provide support regarding SDKs and share valuable resources!
- [KuCoin Documentation](https://docs.kucoin.com/futures/#introduction) - official Kucoin API docs
- [Node.js & JavaScript SDK for Kucoin](https://github.com/tiagosiebler/kucoin-api) - Github repo of our SDK
Current file contains only certain most used examples. If you can't find what you need, you can search through [FuturesClient.ts](https://github.com/tiagosiebler/kucoin-api/blob/master/src/FuturesClient.ts) - all of the endpoints and functions will be there! Otherwise, just ask in [Node.js Traders](https://t.me/nodetraders) Telegram group.
Do you need help with Spot? Check out [Spot Quickstart guide](https://github.com/tiagosiebler/kucoin-api/blob/master/examples/kucoin-SPOT-examples-nodejs.md)
**Table of contents:**
- [Installation](#installation)
- [Usage](#usage)
- [REST API](#rest-api)
- [Account and balance](#account-examples)
- [Subaccount API management](#subaccount-api-management)
- [Market Data](#market-data)
- [Symbol and exchange info](#symbol-and-exchange-info)
- [Order Book data](#order-book-data)
- [Public Trades and Index data](#public-trades-and-index-data)
- [Funding Fees](#funding-fees)
- [Kline/Candles](#klinecandles)
- [Transfer funds in and out of Futures Account](#transfer-funds-in-and-out-of-futures-account)
- [Trade Execution](#trade)
- [General info](#general-info)
- [Market short](#market-short)
- [Market long](#market-long)
- [Limit short](#limit-short)
- [Limit long](#limit-long)
- [Market close](#market-close)
- [Limit close](#limit-close)
- [Stop loss](#stop-loss)
- [Place multiple orders](#place-multiple-orders)
- [Cancel order](#cancel-order)
- [Cancel all orders for specific symbol](#cancel-all-orders-for-specific-symbol)
- [Trade/Order/Positions Management](#tradeorderpositions-management)
- [Fetching orders](#fetching-orders)
- [Fills](#fills)
- [Positions](#positions)
- [WebSocket](#websocket)
- [Community group](#community-group)
## Installation:
```js
// Install by npm
npm install kucoin-api
// Install by yarn
yarn add kucoin-api
```
## Usage
#### Create API credentials
- [Kucoin API Key Management](https://www.kucoin.com/account/api)
#### Import SDK to your project
```js
// require
const { FuturesClient } = require('kucoin-api');
// import
import { FuturesClient } from 'kucoin-api';
// initialise Futures Client
const futuresClient = new FuturesClient({
// insert your api key, secret and passphrase - use env vars, if not just fill the string values
apiKey: process.env.KUCOIN_API_KEY || 'insert-your-api-key',
apiSecret: process.env.KUCOIN_API_SECRET || 'insert-your-api-secret',
apiPassphrase:
process.env.KUCOIN_API_PASSPHRASE || 'insert-your-api-passphrase',
});
```
## REST API
### Account examples
#### Get Account Overview
```js
// Get Account Balance - XBT or USDT, default XBT
futuresClient.getBalance({ currency: 'XBT' });
// Get All Subaccount Accounts Balance
futuresClient.getSubBalances({ currency: 'XBT' });
```
#### Get Transaction History
```js
futuresClient.getTransactions({
type: 'RealisedPNL', // 'RealisedPNL' | 'Deposit' | 'Withdrawal' | 'Transferin' | 'TransferOut'
maxCount: 10,
currency: 'USDT',
});
```
### Subaccount API management
```js
// Get all subaccount APIs
futuresClient.getSubAPIs({
subName: 'my_sub_name',
});
// Create Futures APIs for Sub-Account
futuresClient.createSubAPI({
subName: 'my_sub_name',
passphrase: 'my_passphrase',
remark: 'my_remark',
});
// Modify Sub-Account Futures APIs
futuresClient.updateSubAPI({
subName: 'my_sub_name',
passphrase: 'my_passphrase',
apiKey: 'my_api_key',
});
// Delete Sub-Account Futures APIs
futuresClient.deleteSubAPI({
subName: 'my_sub_name',
passphrase: 'my_passphrase',
apiKey: 'my_api_key',
});
```
### Market Data
#### Symbol and exchange info
```js
// Get All Contract List
futuresClient.getSymbols();
// Get Order Info of the Contract
futuresClient.getSymbol({ symbol: 'XBTUSDTM' });
// Get Ticker
futuresClient.getTicker({ symbol: 'XBTUSDTM' });
```
#### Order Book data
```js
// Get Full Order Book - Level 2
futuresClient.getFullOrderBookLevel2({ symbol: 'XBTUSDTM' });
// Get Level2 depth20
futuresClient.getPartOrderBookLevel2Depth20({ symbol: 'XBTUSDTM' });
// Get Level2 depth100
futuresClient.getPartOrderBookLevel2Depth100({ symbol: 'XBTUSDTM' });
```
#### Public Trades and Index data
```js
// Get Public Trades
futuresClient.getMarketTrades({ symbol: 'XBTUSDTM' });
// Get Interest Rate List
futuresClient.getInterestRates({ symbol: '.XBTINT' });
// Get Index List
futuresClient.getIndex({ symbol: '.KXBT' });
// Get Current Mark Price
futuresClient.getMarkPrice({ symbol: 'XBTUSDM' });
// Get Premium Index
futuresClient.getPremiumIndex({ symbol: '.XBTUSDMPI' });
// Get 24hour futures transaction volume
futuresClient.get24HourTransactionVolume();
```
#### Funding Fees
```js
// Get Current Funding Rate
futuresClient.getFundingRate({ symbol: 'XBTUSDM' });
// Get Public Funding History
futuresClient.getFundingRates({
symbol: 'XBTUSDTM',
from: '1700310700000',
to: '1702310700000',
});
// Get Private Funding History
futuresClient.getFundingHistory({ symbol: 'ETHUSDTM' });
```
#### Kline/Candles
```js
futuresClient.getKlines({
symbol: 'XBTUSDTM',
granularity: 60,
from: new Date().getTime() - 24 * 60 * 60 * 1000, // 24 hours ago
to: new Date().getTime(),
});
```
### Transfer funds in and out of Futures Account
```js
// Transfer out of the Futures to main acc
futuresClient.submitTransferOut({
amount: 0.01,
currency: 'USDT',
recAccountType: 'MAIN',
});
// Transfer to Futures Account
futuresClient.submitTransferIn({
amount: 0.01,
currency: 'USDT',
payAccountType: 'MAIN',
});
// Get All Transfers
futuresClient.futureTransfers({
status: 'SUCCESS', // optional, 'PROCESSING' | 'SUCCESS' | 'FAILURE';
currency: 'USDT', // optional
startAt: 1723550000, // optional
endAt: 1723557472, // optional
currentPage: 1, // optional
pageSize: 100, // optional
});
```
---
### Trade
#### General info
Futures are contracts, not currencies. In the futures symbols list you will see a "multiplier" field for each of the symbols. Each contract is equal to Multiplier x Size.
For example click on this endpoint and get a symbol info for XRPUSDTM: https://api-futures.kucoin.com/api/v1/contracts/XRPUSDTM
In the object, find the "multiplier" value.
```js
// In your code, you can fetch it like this
const symbolInfo = await client.getSymbol({ symbol: 'XRPUSDTM' });
const multiplier = symbolInfo.data.multiplier;
```
E.g. if multiplier is 10(what you can see from the endpoint), that means each SIZE is 10 XRP. So if XRP is currently at $0.5, then each 1 contract (size 10) is going to cost $5.00
size = (Funds x leverage) / (price x multiplier)
```js
const XRPPriceExample = 0.5;
const leverage = 5;
const fundsToTradeUSDT = 100;
const costOfContract = XRPPriceExample * multiplier;
const size = (fundsToTradeUSDT * leverage) / costOfContract;
console.log(`Size: ${size}`);
```
The trade amount indicates the amount of contract to buy or sell, and contract uses the base currency(USD contracts e.g. XBTUSDM) or lot( USDT contracts e.g. XBTUSDTM) as the trading unit.
The trade amount must be no less than 1 lot for the contract and no larger than the maxOrderQty.
It should be a multiple number of the lot, or the system will report an error when you place the order.
E.g. 1 lot of XBTUSDTM is 0.001 Bitcoin, while 1 lot of XBTUSDM is 1 USD.
You can get info about any contract on the link: https://api-futures.kucoin.com/api/v1/contracts/****\_\_**** - just replace the empty space with the symbol of the contract.
Here are function examples using the Futures Create Order endpoint:
#### Market Short
```js
// A MARKET SHORT of 2 contracts of XBT using leverage of 5:
const marketShort = futureTransfers.submitOrder({
clientOid: '123456789',
leverage: '5',
side: 'sell',
size: 2,
symbol: 'XBTUSDTM',
timeInForce: 'GTC',
type: 'market',
});
```
#### Market Long
```js
// A MARKET LONG of 2 contracts of XBT using leverage of 5:
const marketLong = futureTransfers.submitOrder({
clientOid: '123456789',
leverage: '5',
side: 'buy',
size: 2,
symbol: 'XBTUSDTM',
timeInForce: 'GTC',
type: 'market',
});
```
#### Limit Short
```js
// A LIMIT SHORT of 2 contracts of XBT using leverage of 5:
const limitShort = futureTransfers.submitOrder({
clientOid: '123456789',
leverage: '5',
price: '70300.31',
side: 'sell',
size: 2,
symbol: 'XBTUSDTM',
timeInForce: 'GTC',
type: 'limit',
});
```
#### Limit Long
```js
// A LIMIT LONG of 2 contracts of XBT using leverage of 5:
const limitLong = futureTransfers.submitOrder({
clientOid: '123456789',
leverage: '5',
price: '40300.31',
side: 'buy',
size: 2,
symbol: 'XBTUSDTM',
timeInForce: 'GTC',
type: 'limit',
});
```
On any "close position" action, if you specify a SIZE=0 or leave off the SIZE parameter,
then it will close the whole position, regardless of the size.
If you specify a SIZE, it will close only the number of contracts you specify.
If closeOrder is set to TRUE,
the system will close the position and the position size will become 0.
Side, Size and Leverage fields can be left empty and the system will determine the side and size automatically.
#### Market close
```js
// A MARKET CLOSE POSITION example:
const marketClose = futureTransfers.submitOrder({
clientOid: '123456789',
closeOrder: true,
symbol: 'XBTUSDTM',
timeInForce: 'GTC',
type: 'market',
side: 'sell',
size: 0,
});
```
#### Limit close
```js
// A LIMIT CLOSE of a LONG example:
const limitCloseLong = futureTransfers.submitOrder({
clientOid: '123456789',
leverage: '5',
price: '70300.31',
closeOrder: true,
side: 'sell',
size: 2,
symbol: 'XBTUSDTM',
timeInForce: 'GTC',
type: 'limit',
});
// A LIMIT CLOSE of a SHORT example:
const limitCloseShort = futureTransfers.submitOrder({
clientOid: '123456789',
leverage: '5',
price: '40300.31',
closeOrder: true,
side: 'buy',
size: 2,
symbol: 'XBTUSDTM',
timeInForce: 'GTC',
type: 'limit',
});
```
#### Stop loss
```js
// A STOP LOSS example for a LONG position:
const stopLossLong = futureTransfers.submitOrder({
clientOid: '123456789',
closeOrder: true,
stop: 'down',
stopPrice: '40200.31',
stopPriceType: 'TP',
symbol: 'XBTUSDTM',
timeInForce: 'GTC',
type: 'market',
});
// A STOP LOSS example for a SHORT position:
const stopLossShort = futureTransfers.submitOrder({
clientOid: '123456789',
closeOrder: true,
stop: 'up',
stopPrice: '40200.31',
stopPriceType: 'TP',
symbol: 'XBTUSDTM',
timeInForce: 'GTC',
type: 'market',
});
```
##### Place Multiple Orders
```js
//request
const orders = [
{
clientOid: '5c52e11203aa677f33e491',
side: 'buy',
symbol: 'ETHUSDTM',
type: 'limit',
price: '2150',
leverage: '1',
size: 2,
},
{
clientOid: 'je12019ka012ja013099',
side: 'buy',
symbol: 'XBTUSDTM',
type: 'limit',
price: '32150',
leverage: '1',
size: 2,
},
];
futuresClient.submitMultipleOrders(orders);
```
#### Cancel Order
```js
futuresClient.cancelOrderById({ orderId: 'orderId' });
futuresClient.cancelOrderByClientOid({ clientOid: 'clientOid' });
```
#### Cancel all orders for specific symbol
```js
futuresClient.cancelAllOrders({ symbol: 'XBTUSDTM' });
futuresClient.cancelAllStopOrders({ symbol: 'XBTUSDTM' });
```
### Trade/Order/Positions Management
#### Fetching orders
```js
// Get open orders
futuresClient.getOrders({ status: 'active' });
// Get closed orders
futuresClient.getOrders({ status: 'done' });
// Get Untriggered Stop Orders
futuresClient.getStopOrders({ type: 'limit' });
// Get List of Orders Completed in 24h
futuresClient.getRecentOrders();
// Get Details of a Single Order by ClientOrderId
futuresClient.getOrderByClientOrderId({ clientOid: 'clientOid' });
// Or By OrderId
futuresClient.getOrderByOrderId({ orderId: 'orderId' });
```
#### Fills
```js
// Get Specific Fills
futuresClient.getFills({ type: 'market' });
// or search for all
futuresClient.getFills({});
// Recent Fills from last 24 hours
futuresClient.futuresRecentFills({ symbol: 'ETHUSDTM' });
// Or Search All
futuresClient.futuresRecentFills({});
// Active Order Value Calculation
futuresClient.getOpenOrderStatistics({ symbol: 'ETHUSDTM' });
```
#### Positions
```js
// Get Position Details
futuresClient.getPosition({ symbol: 'ETHUSDTM' });
// Get Position List
futuresClient.getPositions({ currency: 'USDT' });
// Or Search All
futuresClient.getPositions();
// Get History Positions
futuresClient.getHistoryPositions({ symbol: 'ETHUSDTM' });
```
## Websocket
For Websocket examples, please refer to these links:
- [Spot Public Websocket](https://github.com/tiagosiebler/kucoin-api/blob/master/examples/ws-spot-public.ts)
- [Spot Private Websocket](https://github.com/tiagosiebler/kucoin-api/blob/master/examples/ws-spot-private.ts)
- [Futures Public Websocket](https://github.com/tiagosiebler/kucoin-api/blob/master/examples/ws-futures-public.ts)
- [Futures Private Websocket](https://github.com/tiagosiebler/kucoin-api/blob/master/examples/ws-futures-private.ts)
## Community group
If you need help, something is wrong/missing or you have suggestions, please join our [Node.js Traders](https://t.me/nodetraders) community group on Telegram and let us know!
================
File: examples/kucoin-SPOT-examples-nodejs.md
================
# **KuCoin SPOT API Examples** - Node.js, JavaScript & Typescript SDK for Kucoin REST APIs & WebSockets
This document provides comprehensive examples for using the KuCoin SPOT API with Node.js and JavaScript. It covers various functionalities including account management, fund transfers, trade execution, order management, and market data retrieval. The examples are designed to help developers quickly integrate KuCoin Spot API into their NodeJS, Javascript and Typscript applications.
If you are here, it means you will be great addition to our [Node.js Traders](https://t.me/nodetraders) community on Telegram where we discuss trading ideas, provide support regarding SDKs and share valuable resources!
- [KuCoin Documentation](https://www.kucoin.com/docs/beginners/introduction) - official Kucoin API docs
- [Node.js & JavaScript SDK for Kucoin](https://github.com/tiagosiebler/kucoin-api) - Github repo of our SDK
Current file contains only certain most used examples. If you can't find what you need, you can search through [SpotClient.ts](https://github.com/tiagosiebler/kucoin-api/blob/master/src/SpotClient.ts) - all of the endpoints and functions will be there! Otherwise, just ask in [Node.js Traders](https://t.me/nodetraders) Telegram group.
Do you need help with Futures? Check out [Futures Quickstart guide](https://github.com/tiagosiebler/kucoin-api/blob/master/examples/kucoin-FUTURES-examples-nodejs.md)
**Table of contents:**
- [Installation](#installation)
- [Usage](#usage)
- [REST API](#rest-api)
- [Account and balance](#account-examples)
- [Account overview](#account-overview)
- [Transactions](#transactions)
- [Deposit and Withdrawal](#deposit-and-withdrawal)
- [Subaccount](#subaccount)
- [Subaccount management](#subaccount-management)
- [Subaccount API management](#subaccount-api-management)
- [Market Data](#market-data)
- [Symbol and exchange info](#symbol-and-exchange-info)
- [Order Book data](#order-book-data)
- [Kline/Candles](#klinecandles)
- [Trade Execution](#trade)
- [General info](#general-info)
- [Market short](#market-short)
- [Market long](#market-long)
- [Limit short](#limit-short)
- [Limit long](#limit-long)
- [Place multiple orders](#place-multiple-orders)
- [Trade/Order/Positions Management](#tradeorderpositions-management)
- [Fetching orders](#fetching-orders)
- [Cancel order](#cancel-order)
- [Cancel all orders for specific symbol](#cancel-all-orders-for-specific-symbol)
- [Fills](#fills)
- [Spot HF trade](#spot-hf-trade)
- [Margin trade](#margin-trade--margin-hf-trade)
- [WebSocket](#websocket)
- [Community group](#community-group)
## Installation:
```js
// Install by npm
npm install kucoin-api
// Install by yarn
yarn add kucoin-api
```
## Usage
#### Create API credentials
- [Kucoin API Key Management](https://www.kucoin.com/account/api)
#### Import SDK to your project
```js
// require
const { SpotClient } = require('kucoin-api');
// import
import { SpotClient } from 'kucoin-api';
// initialise Spot Client
const spotClient = new SpotClient({
// insert your api key, secret and passphrase - use env vars, if not just fill the string values
apiKey: process.env.KUCOIN_API_KEY || 'insert-your-api-key',
apiSecret: process.env.KUCOIN_API_SECRET || 'insert-your-api-secret',
apiPassphrase:
process.env.KUCOIN_API_PASSPHRASE || 'insert-your-api-passphrase',
});
```
## REST API
### Account examples
#### Account Overview
```js
// Get Account Summary
spotClient.getAccountSummary();
// Get all Account Balances
spotClient.getBalances();
// Get specific Account or Currency Balance
spotClient.getBalance({
currency: 'USDT',
type: 'main', // 'trade' | 'margin' | 'trade_hf'
});
// Example call to get account details by ID
spotClient.getAccountDetails({ accountId: '5bd6e9286d99522a52e458de' });
// Margin endpoints for balances
spotClient.getMarginBalances();
spotClient.getMarginBalance();
spotClient.getIsolatedMarginBalance();
```
#### Transactions
```js
// Example call to get account ledgers with specified parameters
spotClient.getTransactions({ currency: 'BTC', startAt: 1601395200000 });
// Example call to get high-frequency account ledgers with specified parameters
spotClient.getHFTransactions({
bizType: 'TRADE_EXCHANGE',
currency: 'YOP,DAI',
startAt: 1601395200000,
});
// Example call to get high-frequency margin account ledgers with specified parameters
spotClient.getHFMarginTransactions({
bizType: 'MARGIN_EXCHANGE',
currency: 'YOP,DAI',
startAt: 1601395200000,
});
```
#### Deposit and Withdrawal
```js
// Example call to create a deposit address
spotClient.createDepositAddress({
currency: 'BTC',
// Optional parameter
chain: 'BTC',
});
// Example call to get deposit addresses with specified parameters
spotClient.getDepositAddressesV2({
currency: 'BTC',
});
// Example call to get deposits
spotClient.getDeposits();
// Example call to get withdrawals with specified parameters
spotClient.getWithdrawals({
currency: 'BTC', // Optional parameter
});
// Example call to submit a withdrawal
spotClient.submitWithdraw({
currency: 'BTC',
address: '1A1zP1eP5QGefi2DMPTfTL5SLmv7DivfNa',
amount: 0.01,
// Optional parameters
memo: 'exampleMemo',
chain: 'BTC',
});
// Example call to cancel a withdrawal by ID
spotClient.cancelWithdrawal({
withdrawalId: '5bffb63303aa675e8bbe18f9',
});
```
### Subaccount
#### Subaccount Management
```js
// Get all subaccounts
spotClient.getSubAccountsV2({});
// Example call to create a sub-account
spotClient.createSubAccount({
// Fill in the required parameters for creating a sub-account
subName: 'exampleSubAccount',
password: 'examplePassword',
access: 'trade',
});
// Example call to get sub-account balance with specified parameters
spotClient.getSubAccountBalance({
subUserId: '5caefba7d9575a0688f83c45',
includeBaseAmount: false,
});
// Example call to get sub-account balances
spotClient.getSubAccountBalancesV2();
// Example call to get transferable funds
spotClient.getTransferable({
currency: 'BTC',
type: 'MAIN',
});
// Example call to submit a transfer from master to sub-account
spotClient.submitTransferMasterSub({
clientOid: client.generateNewOrderID(), // or use your custom UUID
amount: 0.01,
currency: 'USDT',
direction: 'OUT', // 'IN' for transfer to master, 'OUT' for transfer to sub
subUserId: 'enter_sub_user_id_here',
});
// Example call to submit an inner transfer within same account
spotClient.submitInnerTransfer({
clientOid: client.generateNewOrderID(), // or use your custom UUID
amount: 0.01,
currency: 'USDT',
from: 'main', // Source account type
to: 'trade', // Destination account type
});
```
#### Subaccount API management
```js
// Get all subaccount APIs
spotClient.getSubAPIs({
subName: 'my_sub_name',
});
// Create APIs for Sub-Account
spotClient.createSubAPI({
subName: 'my_sub_name',
passphrase: 'my_passphrase',
remark: 'my_remark',
});
// Modify Sub-Account APIs
spotClient.updateSubAPI({
subName: 'my_sub_name',
passphrase: 'my_passphrase',
apiKey: 'my_api_key',
});
// Delete Sub-Account APIs
spotClient.deleteSubAPI({
subName: 'my_sub_name',
passphrase: 'my_passphrase',
apiKey: 'my_api_key',
});
```
### Market Data
#### Symbol and exchange info
```js
// Get All Currencies List
spotClient.getCurrencies();
// Get info for a specific currency
spotClient.getCurrency({
currency: 'BTC',
});
// Get all Symbols
spotClient.getSymbols();
// Example call to get ticker information for a specific symbol
spotClient.getTicker({
symbol: 'BTC-USDT',
});
// All tickers
spotClient.getTickers();
// Get 24h stats for a specific symbol
spotClient.get24hrStats({
symbol: 'BTC-USDT',
});
```
#### Order Book data
```js
// get partial orderbook
spotClient.getOrderBookLevel20({ symbol: 'BTC-USDT' });
// get partial orderbook
spotClient.getOrderBookLevel100({ symbol: 'BTC-USDT' });
// get full orderbook
spotClient.getFullOrderBook({ symbol: 'BTC-USDT' });
```
#### Kline/Candles
```js
// Example call to get Klines (candlestick data) with specified parameters
spotClient.getKlines({
type: '1min',
symbol: 'BTC-USDT',
startAt: 1566703297,
endAt: 1566789757,
});
```
---
### Trade
#### General info
Please, read official [Kucoin API docs](https://www.kucoin.com/docs/rest/spot-trading/orders/place-order) to understand how to place orders, cancel orders, etc. and what is needed for each endpoint. These are just low-end examples to understand how to use it with SDK.
#### Market Short
```js
// Market short order
const marketShort = spotClient.submitOrder({
clientOid: client.generateNewOrderID(), // or use your custom UUID
side: 'sell',
symbol: 'ETH-BTC',
type: 'market',
size: '0.5', // Specify the quantity to sell
});
```
#### Market Long
```js
// Market long order
const marketLong = spotClient.submitOrder({
clientOid: client.generateNewOrderID(), // or use your custom UUID
side: 'buy',
symbol: 'ETH-BTC',
type: 'market',
size: '0.5', // Specify the quantity to buy
});
```
#### Limit Short
```js
// Limit short order
const limitShort = spotClient.submitOrder({
clientOid: client.generateNewOrderID(), // or use your custom UUID
side: 'sell',
symbol: 'ETH-BTC',
type: 'limit',
price: '0.03', // Specify the price to sell
size: '0.5', // Specify the quantity to sell
timeInForce: 'GTC', // Good Till Canceled
});
```
#### Limit Long
```js
// Limit long order
const limitLong = spotClient.submitOrder({
clientOid: client.generateNewOrderID(), // or use your custom UUID
side: 'buy',
symbol: 'ETH-BTC',
type: 'limit',
price: '0.03', // Specify the price to buy
size: '0.5', // Specify the quantity to buy
timeInForce: 'GTC', // Good Till Canceled
});
```
##### Place Multiple Orders
```js
//request
const multipleOrders = [
{
clientOid: '3d07008668054da6b3cb12e432c2b13a',
side: 'buy',
type: 'limit',
price: '0.01',
size: '0.01',
},
{
clientOid: '37245dbe6e134b5c97732bfb36cd4a9d',
side: 'buy',
type: 'limit',
price: '0.01',
size: '0.01',
},
];
spotClient.submitMultipleOrders({
symbol: 'KCS-USDT',
orderList: multipleOrders,
});
```
### Trade/Order/Positions Management
#### Fetching orders
```js
// Get open orders
spotClient.getOrders({ status: 'active' });
// Get closed orders
spotClient.getOrders({ status: 'done' });
// Get List of Orders Completed in 24h
spotClient.getRecentOrders();
// Get Details of a Single Order by ClientOrderId
spotClient.getOrderByClientOid({ clientOid: 'clientOid' });
// Or By OrderId
spotClient.getOrderByOrderId({ orderId: 'orderId' });
```
#### Cancel Order
```js
spotClient.cancelOrderById({ orderId: 'orderId' });
spotClient.cancelOrderByClientOid({ clientOid: 'clientOid' });
```
#### Cancel all orders for specific symbol
```js
//cancel all orders for symbol
spotClient.cancelAllOrders({ symbol: 'XBTUSDTM' });
// cancel all orders for all symbols
spotClient.cancelAllOrders();
```
#### Fills
```js
// Get Specific Fills
spotClient.getFills({ type: 'market' });
// or search for all
spotClient.getFills();
// Recent Fills from last 24 hours
spotClient.getRecentFills();
```
### Spot HF trade
All of the examples are 99% same as regular spot, but you can follow the [official HF Trade API documentation](https://www.kucoin.com/docs/rest/spot-trading/spot-hf-trade-pro-account/place-hf-order) and list of functions in [SpotClient.ts](https://github.com/tiagosiebler/kucoin-api/blob/master/src/SpotClient.ts) to find what you need!
### Margin trade & Margin HF trade
All of the examples are 99% same as regular spot, but you can follow the [official Margin Trade API documentation](https://www.kucoin.com/docs/rest/margin-trading/market-data) and list of functions in [SpotClient.ts](https://github.com/tiagosiebler/kucoin-api/blob/master/src/SpotClient.ts) to find what you need!
---
## Websocket
For Websocket examples, please refer to these links:
- [Spot Public Websocket](https://github.com/tiagosiebler/kucoin-api/blob/master/examples/ws-spot-public.ts)
- [Spot Private Websocket](https://github.com/tiagosiebler/kucoin-api/blob/master/examples/ws-spot-private.ts)
- [Futures Public Websocket](https://github.com/tiagosiebler/kucoin-api/blob/master/examples/ws-futures-public.ts)
- [Futures Private Websocket](https://github.com/tiagosiebler/kucoin-api/blob/master/examples/ws-futures-private.ts)
## Community group
If you need help, something is wrong/missing or you have suggestions, please join our [Node.js Traders](https://t.me/nodetraders) community group on Telegram and let us know!
================
File: examples/rest-futures-orders-guide.ts
================
import { FuturesClient } from '../src/index.ts';
// import { FuturesClient } from 'kucoin-api';
// normally you should install this module via npm: `npm install kucoin-api`
⋮----
async function start()
⋮----
/**
* =======
* Credits for this guide go to user: @DKTradingClient / Code Nerd from the Kucoin API Telegram group!
* =======
/**
* Futures are contracts, not currencies. In the futures symbols list you will see a "multiplier" field for each of the symbols.
* Each contract equals to Multiplier x Size
* For example: https://api-futures.kucoin.com/api/v1/contracts/XRPUSDTM - see the "multiplier" value.
* */
⋮----
/**
* E.g. if multiplier is 10(what you can see from the endpoint), that means each SIZE is 10 XRP. So if XRP is currently at $0.5,
* then each 1 contract (size 10) is going to cost $5.00
* size = (Funds x leverage) / (price x multiplier)
*/
⋮----
/**
* The trade amount indicates the amount of contract to buy or sell, and contract uses the base currency or lot as the trading unit.
* The trade amount must be no less than 1 lot for the contract and no larger than the maxOrderQty.
* It should be a multiple number of the lot, or the system will report an error when you place the order.
* E.g. 1 lot of XBTUSDTM is 0.001 Bitcoin, while 1 lot of XBTUSDM is 1 USD.
* or check the XRPUSDTM example above.
*
* Here are function examples using the Futures Create Order endpoint:
*/
⋮----
// A MARKET SHORT of 2 contracts of XBT using leverage of 5:
⋮----
// A MARKET LONG of 2 contracts of XBT using leverage of 5:
⋮----
// A LIMIT SHORT of 2 contracts of XBT using leverage of 5:
⋮----
// A LIMIT LONG of 2 contracts of XBT using leverage of 5:
⋮----
// On any "close position" action, if you specify a SIZE=0 or leave off the SIZE parameter,
// then it will close the whole position, regardless of the size.
// If you specify a SIZE, it will close only the number of contracts you specify.
⋮----
// If closeOrder is set to TRUE,
// the system will close the position and the position size will become 0.
// Side, Size and Leverage fields can be left empty and the system will determine the side and size automatically.
⋮----
// A MARKET CLOSE POSITION example:
⋮----
// A LIMIT CLOSE of a LONG example:
⋮----
// A LIMIT CLOSE of a SHORT example:
⋮----
// A STOP LOSS example for a LONG position:
⋮----
// A STOP LOSS example for a SHORT position:
================
File: examples/rest-futures-private-trade.ts
================
import { FuturesClient } from '../src/index.ts';
// import { FuturesClient } from 'kucoin-api';
// normally you should install this module via npm: `npm install kucoin-api`
⋮----
async function start()
⋮----
/**
* The trade amount indicates the amount of contract to buy or sell, and contract uses the base currency or lot as the trading unit.
* The trade amount must be no less than 1 lot for the contract and no larger than the maxOrderQty.
* It should be a multiple number of the lot, or the system will report an error when you place the order.
* E.g. 1 lot of XBTUSDTM is 0.001 Bitcoin, while 1 lot of XBTUSDM is 1 USD.
*/
⋮----
// Submit a futures entry order for 1 lot of XBTUSDTM (0.001 bitcoin)
================
File: examples/rest-futures-public.ts
================
import { FuturesClient } from '../src/index.ts';
// import { FuturesClient } from 'kucoin-api';
// normally you should install this module via npm: `npm install kucoin-api`
⋮----
async function start()
⋮----
// Fetch all symbols
⋮----
// Fetch ticker for a specific symbol
⋮----
// Fetch klines for a specific symbol
================
File: examples/rest-spot-private-trade.ts
================
import { SpotClient } from '../src/index.ts';
// import { SpotClient } from 'kucoin-api';
// normally you should install this module via npm: `npm install kucoin-api`
⋮----
async function start()
================
File: examples/rest-spot-public.ts
================
import { SpotClient } from '../src/index.ts';
// import { SpotClient } from 'kucoin-api';
// normally you should install this module via npm: `npm install kucoin-api`
⋮----
async function start()
⋮----
// Fetch all symbols
⋮----
// Fetch ticker for a specific symbol
⋮----
// Fetch klines for a specific symbol
================
File: examples/tsconfig.examples.json
================
{
"extends": "../tsconfig.json",
"compilerOptions": {
"module": "commonjs",
"outDir": "dist/cjs",
"target": "esnext",
"rootDir": "../"
},
"include": ["../src/**/*.*", "../examples/**/*.*"]
}
================
File: src/lib/misc-util.ts
================
export function neverGuard(x: never, msg: string): Error
================
File: src/types/request/broker.types.ts
================
export interface GetBrokerInfoRequest {
begin: string;
end: string;
tradeType: '1' | '2';
}
⋮----
export interface GetBrokerSubAccountsRequest {
uid: string;
currentPage?: number;
pageSize?: number;
}
⋮----
export type BrokerSubAccountPermission = 'general' | 'spot' | 'futures';
⋮----
export interface CreateBrokerSubAccountApiRequest {
uid: string;
passphrase: string;
ipWhitelist: string[];
permissions: BrokerSubAccountPermission[];
label: string;
}
⋮----
export interface GetBrokerSubAccountApisRequest {
uid: string;
apiKey?: string;
}
⋮----
export interface UpdateBrokerSubAccountApiRequest {
uid: string;
apiKey: string;
ipWhitelist: string[];
permissions: BrokerSubAccountPermission[];
label: string;
}
⋮----
export interface DeleteBrokerSubAccountApiRequest {
uid: string;
apiKey: string;
}
⋮----
export type BrokerTransferDirection = 'OUT' | 'IN';
export type BrokerAccountType = 'MAIN' | 'TRADE';
⋮----
export interface BrokerTransferRequest {
currency: string;
amount: string;
clientOid: string;
direction: BrokerTransferDirection;
accountType: BrokerAccountType;
specialUid: string;
specialAccountType: BrokerAccountType;
}
⋮----
export interface GetBrokerDepositListRequest {
currency?: string;
status?: 'PROCESSING' | 'SUCCESS' | 'FAILURE';
hash?: string;
startTimestamp?: number;
endTimestamp?: number;
limit?: number;
}
================
File: src/types/request/spot-account.ts
================
export interface GetBalancesRequest {
currency?: string;
type?: 'main' | 'trade';
}
⋮----
export interface GetSpotTransactionsRequest {
currency?: string;
direction?: 'in' | 'out';
bizType?:
| 'DEPOSIT'
| 'WITHDRAW'
| 'TRANSFER'
| 'SUB_TRANSFER'
| 'TRADE_EXCHANGE'
| 'MARGIN_EXCHANGE'
| 'KUCOIN_BONUS'
| 'BROKER_TRANSFER'
| 'REBATE';
startAt?: number;
endAt?: number;
currentPage?: number;
pageSize?: number;
}
⋮----
export interface AccountHFTransactionsRequest {
currency?: string;
direction?: 'in' | 'out';
bizType?:
| 'TRANSFER'
| 'TRADE_EXCHANGE'
| 'RETURNED_FEES'
| 'DEDUCTION_FEES'
| 'OTHER';
lastId?: number;
limit?: number;
startAt?: number;
endAt?: number;
}
⋮----
export interface AccountHFMarginTransactionsRequest {
currency?: string;
direction?: 'in' | 'out';
bizType?:
| 'TRANSFER'
| 'MARGIN_EXCHANGE'
| 'ISOLATED_EXCHANGE'
| 'LIQUIDATION'
| 'ASSERT_RETURN';
lastId?: number;
limit?: number;
startAt?: number;
endAt?: number;
}
⋮----
export interface CreateSubAccountRequest {
password: string;
remarks?: string;
subName: string;
access: string;
}
⋮----
export interface CreateSubAccountAPIRequest {
subName: string;
passphrase: string;
remark: string;
permission?: string;
ipWhitelist?: string;
expire?: string;
}
⋮----
export interface UpdateSubAccountAPIRequest {
subName: string;
apiKey: string;
passphrase: string;
permission?: string;
ipWhitelist?: string;
expire?: string;
}
⋮----
export interface DeleteSubAccountAPIRequest {
apiKey: string;
passphrase: string;
subName: string;
}
================
File: src/types/request/spot-funding.ts
================
/**
*
***********
* Funding
***********
*
*/
⋮----
export interface CreateDepositAddressV3Request {
currency: string;
chain?: string;
to?: 'main' | 'trade';
amount?: string;
}
⋮----
export interface GetMarginBalanceRequest {
quoteCurrency?: string;
queryType?: 'MARGIN' | 'MARGIN_V2' | 'ALL';
}
⋮----
export interface GetIsolatedMarginBalanceRequest {
symbol?: string;
quoteCurrency?: string;
queryType?: 'ISOLATED' | 'ISOLATED_V2' | 'ALL';
}
⋮----
/**
*
* Deposit
*
*/
⋮----
export interface GetDepositsRequest {
currency?: string;
startAt?: number;
endAt?: number;
status?: 'PROCESSING' | 'SUCCESS' | 'FAILURE';
currentPage?: number;
pageSize?: number;
}
⋮----
/**
*
* Withdrawals
*
*/
⋮----
export interface GetWithdrawalsRequest {
currency?: string;
status?: 'PROCESSING' | 'WALLET_PROCESSING' | 'SUCCESS' | 'FAILURE';
startAt?: number;
endAt?: number;
currentPage?: number;
pageSize?: number;
}
⋮----
export interface ApplyWithdrawRequest {
currency: string;
address: string;
amount: number;
memo?: string;
isInner?: boolean;
remark?: string;
chain?: string;
feeDeductType?: 'INTERNAL' | 'EXTERNAL';
}
⋮----
export interface SubmitWithdrawV3Request {
currency: string;
toAddress: string;
amount: number;
memo?: string;
isInner?: boolean;
remark?: string;
chain?: string;
feeDeductType?: 'INTERNAL' | 'EXTERNAL';
withdrawType: 'ADDRESS' | 'UID' | 'MAIL' | 'PHONE';
}
⋮----
/**
*
* Transfer
*
*/
⋮----
export interface GetTransferableRequest {
currency: string;
type:
| 'MAIN'
| 'TRADE'
| 'TRADE_HF'
| 'MARGIN'
| 'ISOLATED'
| 'OPTION'
| 'MARGIN_V2'
| 'ISOLATED_V2';
tag?: string;
}
⋮----
export interface FlexTransferRequest {
clientOid: string;
currency?: string;
amount: string;
fromUserId?: string;
fromAccountType:
| 'MAIN'
| 'TRADE'
| 'CONTRACT'
| 'MARGIN'
| 'ISOLATED'
| 'TRADE_HF'
| 'MARGIN_V2'
| 'ISOLATED_V2'
| 'OPTION';
fromAccountTag?: string;
type: 'INTERNAL' | 'PARENT_TO_SUB' | 'SUB_TO_PARENT';
toUserId?: string;
toAccountType:
| 'MAIN'
| 'TRADE'
| 'CONTRACT'
| 'MARGIN'
| 'ISOLATED'
| 'TRADE_HF'
| 'MARGIN_V2'
| 'ISOLATED_V2'
| 'OPTION';
toAccountTag?: string;
}
⋮----
export interface submitTransferMasterSubRequest {
clientOid: string;
currency: string;
amount: string;
direction: 'OUT' | 'IN';
accountType?:
| 'MAIN'
| 'TRADE'
| 'TRADE_HF'
| 'MARGIN'
| 'CONTRACT'
| 'OPTION';
subAccountType?:
| 'MAIN'
| 'TRADE'
| 'TRADE_HF'
| 'MARGIN'
| 'CONTRACT'
| 'OPTION';
subUserId: string;
}
⋮----
export interface InnerTransferRequest {
clientOid: string;
currency: string;
from:
| 'main'
| 'trade'
| 'trade_hf'
| 'margin'
| 'isolated'
| 'margin_v2'
| 'isolated_v2'
| 'contract'
| 'option';
to:
| 'main'
| 'trade'
| 'trade_hf'
| 'margin'
| 'isolated'
| 'margin_v2'
| 'isolated_v2'
| 'contract'
| 'option';
amount: string;
fromTag?: string;
toTag?: string;
}
================
File: src/types/request/spot-misc.ts
================
export interface GetAnnouncementsRequest {
currentPage?: number;
pageSize?: number;
annType?: string;
lang?: string;
startTime?: number;
endTime?: number;
}
================
File: src/types/response/broker.types.ts
================
export interface BrokerInfo {
accountSize: number;
maxAccountSize: number | null;
level: number;
}
⋮----
export interface CreateBrokerSubAccountResponse {
accountName: string;
uid: string;
createdAt: number;
level: number;
}
⋮----
export interface BrokerSubAccount {
accountName: string;
uid: string;
createdAt: number;
level: number;
}
⋮----
export interface GetBrokerSubAccountsResponse {
currentPage: number;
pageSize: number;
totalNum: number;
totalPage: number;
items: BrokerSubAccount[];
}
⋮----
export interface CreateBrokerSubAccountApiResponse {
uid: string;
label: string;
apiKey: string;
secretKey: string;
apiVersion: number;
permissions: string[];
ipWhitelist: string[];
createdAt: number;
}
⋮----
export interface BrokerSubAccountApi {
uid: string;
label: string;
apiKey: string;
apiVersion: number;
permissions: ('General' | 'Spot' | 'Futures')[];
ipWhitelist: string[];
createdAt: number;
}
⋮----
export type BrokerTransferAccountType =
| 'MAIN'
| 'TRADE'
| 'CONTRACT'
| 'MARGIN'
| 'ISOLATED';
export type BrokerTransferStatus = 'PROCESSING' | 'SUCCESS' | 'FAILURE';
⋮----
export interface BrokerTransferHistory {
orderId: string;
currency: string;
amount: string;
fromUid: number;
fromAccountType: BrokerTransferAccountType;
fromAccountTag: string;
toUid: number;
toAccountType: BrokerTransferAccountType;
toAccountTag: string;
status: BrokerTransferStatus;
reason: string | null;
createdAt: number;
}
⋮----
export interface BrokerDepositRecord {
uid: number;
hash: string;
address: string;
memo: string;
amount: string;
fee: string;
currency: string;
isInner: boolean;
walletTxId: string;
status: BrokerTransferStatus;
remark: string;
chain: string;
createdAt: number;
updatedAt: number;
}
⋮----
export type BrokerWithdrawalStatus =
| 'PROCESSING'
| 'WALLET_PROCESSING'
| 'REVIEW'
| 'SUCCESS'
| 'FAILURE';
⋮----
export interface BrokerWithdrawalRecord {
id: string;
chain: string;
walletTxId: string;
uid: number;
amount: string;
memo: string;
fee: string;
address: string;
remark: string;
isInner: boolean;
currency: string;
status: BrokerWithdrawalStatus;
createdAt: number;
updatedAt: number;
}
================
File: src/types/response/shared.types.ts
================
export interface APISuccessResponse {
code: '200000';
data: TData;
}
⋮----
export interface APIErrorResponse {
msg: string;
code: string;
}
⋮----
export type APIResponse = APISuccessResponse | APIErrorResponse;
⋮----
export interface ServiceStatus {
msg: string;
status: 'cancelonly' | 'close' | 'open';
}
================
File: src/types/response/spot-misc.ts
================
export interface Announcement {
annId: number;
annTitle: string;
annType: string[];
annDesc: string;
cTime: number;
language: string;
annUrl: string;
}
⋮----
export interface Announcements {
totalNum: number;
currentPage: number;
pageSize: number;
totalPage: number;
items: Announcement[];
}
================
File: src/types/response/spot-vip.ts
================
/**
*
***********
* VIP LENDING
***********
*
*/
⋮----
export interface DiscountRateConfig {
currency: string;
usdtLevels: {
left: number;
right: number;
discountRate: string;
}[];
}
⋮----
export interface OtcLoan {
parentUid: string;
orders: {
orderId: string;
currency: string;
principal: string;
interest: string;
}[];
ltv: {
transferLtv: string;
onlyClosePosLtv: string;
delayedLiquidationLtv: string;
instantLiquidationLtv: string;
currentLtv: string;
};
totalMarginAmount: string;
transferMarginAmount: string;
margins: {
marginCcy: string;
marginQty: string;
marginFactor: string;
}[];
}
⋮----
export interface OtcLoanAccount {
uid: string;
marginCcy: string;
marginQty: string;
marginFactor: string;
accountType: 'TRADE' | 'TRADE_HF' | 'CONTRACT';
isParent: boolean;
}
================
File: src/types/response/ws.ts
================
export interface WsServerInfo {
endpoint: string;
encrypt: boolean;
protocol: string;
pingInterval: number;
pingTimeout: number;
}
⋮----
export interface WsConnectionInfo {
token: string;
instanceServers: WsServerInfo[];
}
================
File: src/BrokerClient.ts
================
import { BaseRestClient } from './lib/BaseRestClient.js';
import { REST_CLIENT_TYPE_ENUM, RestClientType } from './lib/requestUtils.js';
import {
BrokerTransferRequest,
CreateBrokerSubAccountApiRequest,
DeleteBrokerSubAccountApiRequest,
GetBrokerDepositListRequest,
GetBrokerInfoRequest,
GetBrokerSubAccountApisRequest,
GetBrokerSubAccountsRequest,
UpdateBrokerSubAccountApiRequest,
} from './types/request/broker.types.js';
import {
BrokerDepositRecord,
BrokerInfo,
BrokerSubAccountApi,
BrokerTransferHistory,
BrokerWithdrawalRecord,
CreateBrokerSubAccountApiResponse,
CreateBrokerSubAccountResponse,
GetBrokerSubAccountsResponse,
} from './types/response/broker.types.js';
import { APISuccessResponse } from './types/response/shared.types.js';
⋮----
/**
*
*/
export class BrokerClient extends BaseRestClient
⋮----
getClientType(): RestClientType
⋮----
/**
* Get Broker Info
*
* This endpoint supports querying the basic information of the current Broker
*/
getBrokerInfo(
params: GetBrokerInfoRequest,
): Promise>
⋮----
/**
* Add SubAccount
*
* This endpoint supports Broker users to create sub-accounts.
* Note that the account name is unique across the exchange.
* It is recommended to add a special identifier to prevent name duplication.
*/
createSubAccount(params: {
accountName: string;
}): Promise>
⋮----
/**
* Get SubAccount
*
* This interface supports querying sub-accounts created by Broker.
* Returns paginated results with default page size of 20 (max 100).
*/
getSubAccounts(
params: GetBrokerSubAccountsRequest,
): Promise>
⋮----
/**
* Add SubAccount API
*
* This interface supports the creation of Broker sub-account APIKEY.
* Supports up to 20 IPs in the whitelist.
* Only General, Spot, and Futures permissions can be set.
* Label must be between 4 and 32 characters.
*/
createSubAccountApi(
params: CreateBrokerSubAccountApiRequest,
): Promise>
⋮----
/**
* Get SubAccount API
*
* This interface supports querying the Broker's sub-account APIKEYs.
* Can optionally filter by specific apiKey.
*/
getSubAccountApis(
params: GetBrokerSubAccountApisRequest,
): Promise>
⋮----
/**
* Modify SubAccount API
*
* This interface supports modifying the Broker's sub-account APIKEY.
* Supports up to 20 IPs in the whitelist.
* Only General, Spot, and Futures permissions can be set.
* Label must be between 4 and 32 characters.
*/
updateSubAccountApi(
params: UpdateBrokerSubAccountApiRequest,
): Promise>
⋮----
/**
* Delete SubAccount API
*
* This interface supports deleting Broker's sub-account APIKEY.
*/
deleteSubAccountApi(
params: DeleteBrokerSubAccountApiRequest,
): Promise>
⋮----
/**
* Transfer
*
* This endpoint supports fund transfer between Broker account and Broker sub-accounts.
* Please be aware that withdrawal from sub-account is not directly supported.
* Broker has to transfer funds from broker sub-account to broker account to initiate the withdrawals.
*
* Direction:
* - OUT: Broker account is transferred to Broker sub-account
* - IN: Broker sub-account is transferred to Broker account
*
* Account Types:
* - MAIN: Funding account
* - TRADE: Spot trading account
*/
submitTransfer(params: BrokerTransferRequest): Promise<
APISuccessResponse<{
orderId: string;
}>
> {
return this.postPrivate('api/v1/broker/nd/transfer', params);
⋮----
/**
* Get Transfer History
*
* This endpoint supports querying transfer records of the broker itself and its created sub-accounts.
*
* Account Types:
* - MAIN: Funding account
* - TRADE: Spot trading account
* - CONTRACT: Contract account
* - MARGIN: Margin account
* - ISOLATED: Isolated margin account
*
* Status:
* - PROCESSING: Processing
* - SUCCESS: Successful
* - FAILURE: Failed
*/
getTransferHistory(params: {
orderId: string;
}): Promise>
⋮----
/**
* Get Deposit List
*
* This endpoint can obtain the deposit records of each sub-account under the ND Broker.
* Default limit is 1000 records (max 1000).
* Results are sorted in descending order by default.
*
* Status:
* - PROCESSING: Processing
* - SUCCESS: Successful
* - FAILURE: Failed
*/
getDeposits(
params?: GetBrokerDepositListRequest,
): Promise>
⋮----
/**
* Get Deposit Detail
*
* This endpoint supports querying the deposit record of sub-accounts created by a Broker
* (excluding main account of nd broker).
*
* Status:
* - PROCESSING: Processing
* - SUCCESS: Successful
* - FAILURE: Failed
*/
getDeposit(params: {
currency: string;
hash: string;
}): Promise>
⋮----
/**
* Get Withdrawal Detail
*
* This endpoint supports querying the withdrawal records of sub-accounts created by a Broker
* (excluding main account of nd broker).
*
* Status:
* - PROCESSING: Processing
* - WALLET_PROCESSING: Wallet Processing
* - REVIEW: Under Review
* - SUCCESS: Successful
* - FAILURE: Failed
*/
getWithdrawal(params: {
withdrawalId: string;
}): Promise>
⋮----
/**
* Get Broker Rebate
*
* This interface supports downloading Broker rebate orders.
* Returns a URL to download a CSV file containing the rebate data.
* The URL is valid for 1 day.
* Maximum interval between begin and end dates is 6 months.
*/
getBrokerRebate(params: {
begin: string;
end: string;
tradeType: '1' | '2';
}): Promise<
APISuccessResponse<{
url: string;
}>
> {
return this.getPrivate('api/v1/broker/nd/rebase/download', params);
================
File: .prettierrc
================
{
"tabWidth": 2,
"singleQuote": true,
"trailingComma": "all"
}
================
File: jest.config.ts
================
/**
* For a detailed explanation regarding each configuration property, visit:
* https://jestjs.io/docs/configuration
*/
⋮----
import type { Config } from 'jest';
⋮----
// All imported modules in your tests should be mocked automatically
// automock: false,
⋮----
// Stop running tests after `n` failures
// bail: 0,
bail: false, // enable to stop test when an error occur,
⋮----
// The directory where Jest should store its cached dependency information
// cacheDirectory: "/private/var/folders/kf/2k3sz4px6c9cbyzj1h_b192h0000gn/T/jest_dx",
⋮----
// Automatically clear mock calls, instances, contexts and results before every test
⋮----
// Indicates whether the coverage information should be collected while executing the test
⋮----
// An array of glob patterns indicating a set of files for which coverage information should be collected
⋮----
// The directory where Jest should output its coverage files
⋮----
// An array of regexp pattern strings used to skip coverage collection
// coveragePathIgnorePatterns: [
// "/node_modules/"
// ],
⋮----
// Indicates which provider should be used to instrument code for coverage
⋮----
// A list of reporter names that Jest uses when writing coverage reports
// coverageReporters: [
// "json",
// "text",
// "lcov",
// "clover"
// ],
⋮----
// An object that configures minimum threshold enforcement for coverage results
// coverageThreshold: undefined,
⋮----
// A path to a custom dependency extractor
// dependencyExtractor: undefined,
⋮----
// Make calling deprecated APIs throw helpful error messages
// errorOnDeprecated: false,
⋮----
// The default configuration for fake timers
// fakeTimers: {
// "enableGlobally": false
// },
⋮----
// Force coverage collection from ignored files using an array of glob patterns
// forceCoverageMatch: [],
⋮----
// A path to a module which exports an async function that is triggered once before all test suites
// globalSetup: undefined,
⋮----
// A path to a module which exports an async function that is triggered once after all test suites
// globalTeardown: undefined,
⋮----
// A set of global variables that need to be available in all test environments
// globals: {},
⋮----
// The maximum amount of workers used to run your tests. Can be specified as % or a number. E.g. maxWorkers: 10% will use 10% of your CPU amount + 1 as the maximum worker number. maxWorkers: 2 will use a maximum of 2 workers.
// maxWorkers: "50%",
⋮----
// An array of directory names to be searched recursively up from the requiring module's location
// moduleDirectories: [
// "node_modules"
// ],
⋮----
// An array of file extensions your modules use
⋮----
// modulePaths: ['src'],
⋮----
// A map from regular expressions to module names or to arrays of module names that allow to stub out resources with a single module
// moduleNameMapper: {},
⋮----
// An array of regexp pattern strings, matched against all module paths before considered 'visible' to the module loader
// modulePathIgnorePatterns: [],
⋮----
// Activates notifications for test results
// notify: false,
⋮----
// An enum that specifies notification mode. Requires { notify: true }
// notifyMode: "failure-change",
⋮----
// A preset that is used as a base for Jest's configuration
// preset: undefined,
⋮----
// Run tests from one or more projects
// projects: undefined,
⋮----
// Use this configuration option to add custom reporters to Jest
// reporters: undefined,
⋮----
// Automatically reset mock state before every test
// resetMocks: false,
⋮----
// Reset the module registry before running each individual test
// resetModules: false,
⋮----
// A path to a custom resolver
// resolver: undefined,
⋮----
// Automatically restore mock state and implementation before every test
// restoreMocks: false,
⋮----
// The root directory that Jest should scan for tests and modules within
// rootDir: undefined,
⋮----
// A list of paths to directories that Jest should use to search for files in
// roots: [
// ""
// ],
⋮----
// Allows you to use a custom runner instead of Jest's default test runner
// runner: "jest-runner",
⋮----
// The paths to modules that run some code to configure or set up the testing environment before each test
// setupFiles: [],
⋮----
// A list of paths to modules that run some code to configure or set up the testing framework before each test
// setupFilesAfterEnv: [],
⋮----
// The number of seconds after which a test is considered as slow and reported as such in the results.
// slowTestThreshold: 5,
⋮----
// A list of paths to snapshot serializer modules Jest should use for snapshot testing
// snapshotSerializers: [],
⋮----
// The test environment that will be used for testing
// testEnvironment: "jest-environment-node",
⋮----
// Options that will be passed to the testEnvironment
// testEnvironmentOptions: {},
⋮----
// Adds a location field to test results
// testLocationInResults: false,
⋮----
// The glob patterns Jest uses to detect test files
⋮----
// "**/__tests__/**/*.[jt]s?(x)",
⋮----
// An array of regexp pattern strings that are matched against all test paths, matched tests are skipped
// testPathIgnorePatterns: [
// "/node_modules/"
// ],
⋮----
// The regexp pattern or array of patterns that Jest uses to detect test files
// testRegex: [],
⋮----
// This option allows the use of a custom results processor
// testResultsProcessor: undefined,
⋮----
// This option allows use of a custom test runner
// testRunner: "jest-circus/runner",
⋮----
// A map from regular expressions to paths to transformers
// transform: undefined,
⋮----
// An array of regexp pattern strings that are matched against all source file paths, matched files will skip transformation
// transformIgnorePatterns: [
// "/node_modules/",
// "\\.pnp\\.[^\\/]+$"
// ],
⋮----
// Prevents import esm module error from v1 axios release, issue #5026
⋮----
// An array of regexp pattern strings that are matched against all modules before the module loader will automatically return a mock for them
// unmockedModulePathPatterns: undefined,
⋮----
// Indicates whether each individual test should be reported during the run
// verbose: undefined,
verbose: true, // report individual test
⋮----
// An array of regexp patterns that are matched against all source file paths before re-running tests in watch mode
// watchPathIgnorePatterns: [],
⋮----
// Whether to use watchman for file crawling
// watchman: true,
================
File: postBuild.sh
================
#!/bin/bash
#
# Add package.json files to cjs/mjs subtrees
#
cat >dist/cjs/package.json <dist/mjs/package.json < console.log('trace', ...params),
⋮----
/**
* Overkill in almost every case, but if you need any optimisation available,
* you can inject a faster sign mechanism such as node's native createHmac:
*/
⋮----
function setWsClientEventListeners(
websocketClient: WebsocketClient,
accountRef: string,
): Promise
⋮----
// console.log('raw message received ', JSON.stringify(data, null, 2));
⋮----
// Simple promise to ensure we're subscribed before trying anything else
⋮----
// Start trading
================
File: examples/WebSockets/subscriptions/README.md
================
# WebSocket Subscriptions
The examples in this folder demonstrate how to connect to Kucoin WebSockets using Node.js, JavaScript & TypeScript, to receive realtime events from either account updates or market data.
================
File: examples/WebSockets/subscriptions/ws-futures-private.ts
================
/* eslint-disable @typescript-eslint/no-unused-vars */
import { DefaultLogger, WebsocketClient } from '../../../src/index.js';
// import { DefaultLogger, WebsocketClient } from 'kucoin-api';
// normally you should install this module via npm: `npm install kucoin-api`
⋮----
async function start()
⋮----
// Optional: inject and customise a logger for more control over internal logging
// const logger: typeof DefaultLogger = {
// ...DefaultLogger,
// trace: (...params) => {
// if (
// [
// 'Sending ping',
// // 'Sending upstream ws message: ',
// 'Received pong',
// ].includes(params[0])
// ) {
// return;
// }
// console.log('trace', JSON.stringify(params, null, 2));
// },
// };
⋮----
passphrase: process.env.API_PASSPHRASE || 'apiPassPhraseHere', // This is NOT your account password
⋮----
// logger,
⋮----
// Data received
⋮----
// Something happened, attempting to reconenct
⋮----
// Reconnect successful
⋮----
// Connection closed. If unexpected, expect reconnect -> reconnected.
⋮----
// Reply to a request, e.g. "subscribe"/"unsubscribe"/"authenticate"
⋮----
// throw new Error('res?');
⋮----
// Optional: await a connection to be ready before subscribing (this is not necessary)
// await client.connect('futuresPrivateV1');
// console.log('connected');
⋮----
/**
* For more detailed usage info, refer to the ws-spot-public.ts example.
*
* Below are some examples for subscribing to private futures websockets.
* Note: all "private" websocket topics should use the "futuresPrivateV1" wsKey.
*/
================
File: examples/WebSockets/subscriptions/ws-futures-public.ts
================
/* eslint-disable @typescript-eslint/no-unused-vars */
import { DefaultLogger, WebsocketClient } from '../../../src/index.js';
// import { DefaultLogger, WebsocketClient } from 'kucoin-api';
// normally you should install this module via npm: `npm install 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);
⋮----
// Data received
⋮----
// Something happened, attempting to reconenct
⋮----
// Reconnect successful
⋮----
// Connection closed. If unexpected, expect reconnect -> reconnected.
⋮----
// Reply to a request, e.g. "subscribe"/"unsubscribe"/"authenticate"
⋮----
// throw new Error('res?');
⋮----
// 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-spot-public.ts example.
*/
================
File: examples/WebSockets/subscriptions/ws-spot-private.ts
================
/* eslint-disable @typescript-eslint/no-unused-vars */
import { DefaultLogger, WebsocketClient } from '../../../src/index.js';
// import { DefaultLogger, WebsocketClient } from 'kucoin-api';
// normally you should install this module via npm: `npm install kucoin-api`
⋮----
async function start()
⋮----
// Optional: inject a custom logger to override internal logging behaviour
// const logger: typeof DefaultLogger = {
// ...DefaultLogger,
// trace: (...params) => {
// if (
// [
// 'Sending ping',
// // 'Sending upstream ws message: ',
// 'Received pong',
// ].includes(params[0])
// ) {
// return;
// }
// console.log('trace', JSON.stringify(params, null, 2));
// },
// };
⋮----
passphrase: process.env.API_PASSPHRASE || 'apiPassPhraseHere', // This is NOT your account password
⋮----
// logger,
⋮----
// Data received
⋮----
// Something happened, attempting to reconenct
⋮----
// Reconnect successful
⋮----
// Connection closed. If unexpected, expect reconnect -> reconnected.
⋮----
// Reply to a request, e.g. "subscribe"/"unsubscribe"/"authenticate"
⋮----
// throw new Error('res?');
⋮----
// Optional: await a connection to be ready before subscribing (this is not necessary)
// await client.connect('spotPrivateV1');
// console.log('connected');
⋮----
/**
* For more detailed usage info, refer to the ws-spot-public.ts example.
*
* Below are some examples for subscribing to private spot & margin websockets.
* Note: all "private" websocket topics should use the "spotPrivateV1" wsKey.
*/
⋮----
/**
* Other margin websocket topics, which also use the "spotPrivateV1" WsKey:
*/
================
File: examples/WebSockets/subscriptions/ws-spot-public.ts
================
/* eslint-disable @typescript-eslint/no-unused-vars */
import {
DefaultLogger,
WebsocketClient,
WsTopicRequest,
} from '../../../src/index.js';
// import { DefaultLogger, WebsocketClient, WsTopicRequest } from 'kucoin-api';
// normally you should install this module via npm: `npm install 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);
⋮----
// Data received
⋮----
// Something happened, attempting to reconenct
⋮----
// Reconnect successful
⋮----
// Connection closed. If unexpected, expect reconnect -> reconnected.
⋮----
// Reply to a request, e.g. "subscribe"/"unsubscribe"/"authenticate"
⋮----
// throw new Error('res?');
⋮----
// Optional: await a connection to be ready before subscribing (this is not necessary)
// await client.connect('spotPublicV1');
⋮----
/**
* Use the client subscribe(topic, market) pattern to subscribe to any websocket topic.
*
* You can subscribe to topics one at a time or many one one request. Topics can be sent as simple strings:
*
*/
⋮----
/**
* Or, as an array of simple strings
*
*/
⋮----
/**
* Or send a more structured object with parameters
*
*/
⋮----
/** 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/websocket/basic-info/subscribe/introduction
*/
⋮----
/**
* Or, send an array of structured objects with parameters, if you wanted to send multiple in one request
*
*/
// client.subscribe([subRequest1, subRequest2, etc], 'spotPublicV1');
⋮----
/**
* Other spot websocket topics:
*/
⋮----
/**
* Other margin websocket topics, which also use the "spotPublicV1" WsKey:
*/
================
File: src/lib/websocket/logger.ts
================
export type LogParams = null | any;
⋮----
// eslint-disable-next-line @typescript-eslint/no-unused-vars
⋮----
// console.log(_params);
⋮----
export type DefaultLogger = typeof DefaultLogger;
================
File: src/lib/websocket/WsStore.types.ts
================
import WebSocket from 'isomorphic-ws';
⋮----
export enum WsConnectionStateEnum {
INITIAL = 0,
CONNECTING = 1,
CONNECTED = 2,
CLOSING = 3,
RECONNECTING = 4,
// ERROR_RECONNECTING = 5,
ERROR = 5,
}
⋮----
// ERROR_RECONNECTING = 5,
⋮----
export interface DeferredPromise {
resolve?: (value: TSuccess) => TSuccess;
reject?: (value: TError) => TError;
promise?: Promise;
}
⋮----
export interface WSConnectedResult {
wsKey: string;
ws: WebSocket;
}
⋮----
export interface WsStoredState {
/** The currently active websocket connection */
ws?: WebSocket;
/** The current lifecycle state of the connection (enum) */
connectionState?: WsConnectionStateEnum;
connectionStateChangedAt?: Date;
/** A timer that will send an upstream heartbeat (ping) when it expires */
activePingTimer?: ReturnType | undefined;
/** A timer tracking that an upstream heartbeat was sent, expecting a reply before it expires */
activePongTimer?: ReturnType | undefined;
/** If a reconnection is in progress, this will have the timer for the delayed reconnect */
activeReconnectTimer?: ReturnType | undefined;
/**
* When a connection attempt is in progress (even for reconnect), a promise is stored here.
*
* This promise will resolve once connected (and will then get removed);
*/
deferredPromiseStore: Record;
/**
* All the topics we are expected to be subscribed to on this connection (and we automatically resubscribe to if the connection drops)
*
* A "Set" and a deep-object-match are used to ensure we only subscribe to a topic once (tracking a list of unique topics we're expected to be connected to)
*/
subscribedTopics: Set;
/** Whether this connection has completed authentication (only applies to private connections) */
isAuthenticated?: boolean;
/**
* Whether this connection has completed authentication before for the Websocket API, so it knows to automatically reauth if reconnected
*/
didAuthWSAPI?: boolean;
/** To reauthenticate on the WS API, which channel do we send to? */
WSAPIAuthChannel?: string;
}
⋮----
/** The currently active websocket connection */
⋮----
/** The current lifecycle state of the connection (enum) */
⋮----
/** A timer that will send an upstream heartbeat (ping) when it expires */
⋮----
/** A timer tracking that an upstream heartbeat was sent, expecting a reply before it expires */
⋮----
/** If a reconnection is in progress, this will have the timer for the delayed reconnect */
⋮----
/**
* When a connection attempt is in progress (even for reconnect), a promise is stored here.
*
* This promise will resolve once connected (and will then get removed);
*/
⋮----
/**
* All the topics we are expected to be subscribed to on this connection (and we automatically resubscribe to if the connection drops)
*
* A "Set" and a deep-object-match are used to ensure we only subscribe to a topic once (tracking a list of unique topics we're expected to be connected to)
*/
⋮----
/** Whether this connection has completed authentication (only applies to private connections) */
⋮----
/**
* Whether this connection has completed authentication before for the Websocket API, so it knows to automatically reauth if reconnected
*/
⋮----
/** To reauthenticate on the WS API, which channel do we send to? */
================
File: src/lib/webCryptoAPI.ts
================
import { neverGuard } from './misc-util.js';
⋮----
function bufferToB64(buffer: ArrayBuffer): string
⋮----
export type SignEncodeMethod = 'hex' | 'base64';
export type SignAlgorithm = 'SHA-256' | 'SHA-512';
⋮----
/**
* Similar to node crypto's `createHash()` function
*/
export async function hashMessage(
message: string,
method: SignEncodeMethod,
algorithm: SignAlgorithm,
): Promise
⋮----
/**
* Sign a message, with a secret, using the Web Crypto API
*/
export async function signMessage(
message: string,
secret: string,
method: SignEncodeMethod,
algorithm: SignAlgorithm,
): Promise
⋮----
export function checkWebCryptoAPISupported()
================
File: src/types/request/spot-convert.ts
================
/**
*
***********
* Spot Convert
***********
*
*/
⋮----
/**
* Get Convert Symbol
*/
export interface GetConvertSymbolRequest {
fromCurrency: string;
toCurrency: string;
orderType?: 'MARKET' | 'LIMIT';
}
⋮----
/**
* Add Convert Order
*/
export interface AddConvertOrderRequest {
clientOrderId: string;
quoteId: string;
accountType?: 'BOTH' | 'FUNDING' | 'TRADING';
}
⋮----
/**
* Get Convert Quote
*/
export interface GetConvertQuoteRequest {
fromCurrency: string;
toCurrency: string;
fromCurrencySize?: number;
toCurrencySize?: number;
}
⋮----
/**
* Get Convert Order Detail
*/
export interface GetConvertOrderDetailRequest {
clientOrderId?: string;
orderId?: string;
}
⋮----
/**
* Get Convert Order History
*/
export interface GetConvertOrderHistoryRequest {
startAt?: number;
endAt?: number;
page?: number;
pageSize?: number;
status?: 'OPEN' | 'SUCCESS' | 'FAIL';
}
⋮----
/**
* Add Convert Limit Order
*/
export interface AddConvertLimitOrderRequest {
clientOrderId: string;
fromCurrency: string;
toCurrency: string;
fromCurrencySize: number;
toCurrencySize: number;
accountType?: 'BOTH' | 'FUNDING' | 'TRADING';
}
⋮----
/**
* Get Convert Limit Quote
*/
export interface GetConvertLimitQuoteRequest {
fromCurrency: string;
toCurrency: string;
fromCurrencySize?: number;
toCurrencySize?: number;
}
⋮----
/**
* Get Convert Limit Order Detail
*/
export interface GetConvertLimitOrderDetailRequest {
clientOrderId?: string;
orderId?: string;
}
⋮----
/**
* Get Convert Limit Orders
*/
export interface GetConvertLimitOrdersRequest {
startAt?: number;
endAt?: number;
page?: number;
pageSize?: number;
status?: 'OPEN' | 'SUCCESS' | 'FAIL' | 'CANCELLED';
}
⋮----
/**
* Cancel Convert Limit Order
*/
export interface CancelConvertLimitOrderRequest {
clientOrderId?: string;
orderId?: string;
}
================
File: src/types/request/spot-earn.ts
================
/**
*
* EARN
*
*/
⋮----
export interface SubscribeEarnFixedIncomeRequest {
productId: string;
amount: string;
accountType: 'MAIN' | 'TRADE';
}
⋮----
export interface InitiateRedemptionRequest {
orderId: string;
amount: string;
fromAccountType?: 'MAIN' | 'TRADE';
confirmPunishRedeem?: '1';
}
⋮----
export interface GetEarnRedeemPreviewRequest {
orderId: string;
fromAccountType?: 'MAIN' | 'TRADE';
}
⋮----
export interface GetEarnFixedIncomeHoldAssetsRequest {
currentPage?: number;
pageSize?: number;
productId?: string;
productCategory?: string;
currency?: string;
}
⋮----
/**
*
* STRUCTURED EARN - DUAL
*
*/
⋮----
export interface StructuredProductPurchaseRequest {
productId: string; // required - Product ID
investCurrency: string; // required - Investment currency
investAmount: string; // required - Subscription amount
accountType: 'MAIN' | 'TRADE'; // required - MAIN (funding account), TRADE (spot trading account)
}
⋮----
productId: string; // required - Product ID
investCurrency: string; // required - Investment currency
investAmount: string; // required - Subscription amount
accountType: 'MAIN' | 'TRADE'; // required - MAIN (funding account), TRADE (spot trading account)
⋮----
export interface GetDualInvestmentProductsRequest {
category: 'DUAL_CLASSIC' | 'DUAL_BOOSTER' | 'DUAL_EXTRA'; // required - Product category
strikeCurrency?: string; // optional - Strike Currency
investCurrency?: string; // optional - Investment Currency
side?: 'CALL' | 'PUT'; // optional - Direction
}
⋮----
category: 'DUAL_CLASSIC' | 'DUAL_BOOSTER' | 'DUAL_EXTRA'; // required - Product category
strikeCurrency?: string; // optional - Strike Currency
investCurrency?: string; // optional - Investment Currency
side?: 'CALL' | 'PUT'; // optional - Direction
⋮----
export interface GetStructuredProductOrdersRequest {
categories: string; // required - Product categories, multiple categories are supported, e.g. DUAL_CLASSIC, DUAL_BOOSTER, DUAL_EXTRA
orderId?: string; // optional - Order Id
investCurrency?: string; // optional - Investment Currency
currentPage?: number; // optional - Current Page, default: 1
pageSize?: number; // optional - Page Size >= 10, <= 500, default: 15
}
⋮----
categories: string; // required - Product categories, multiple categories are supported, e.g. DUAL_CLASSIC, DUAL_BOOSTER, DUAL_EXTRA
orderId?: string; // optional - Order Id
investCurrency?: string; // optional - Investment Currency
currentPage?: number; // optional - Current Page, default: 1
pageSize?: number; // optional - Page Size >= 10, <= 500, default: 15
================
File: src/types/request/spot-trading.ts
================
/**
*
***********
* Spot Trading
***********
*
*/
⋮----
/**
*
* Market data
*
*/
⋮----
export interface GetSpotKlinesRequest {
symbol: string;
startAt?: number;
endAt?: number;
type:
| '1min'
| '3min'
| '5min'
| '15min'
| '30min'
| '1hour'
| '2hour'
| '4hour'
| '6hour'
| '8hour'
| '12hour'
| '1day'
| '1week'
| '1month';
}
⋮----
/**
*
* Spot HF trade
*
*/
⋮----
export interface SubmitHFOrderRequest {
// Required fields
type: 'limit' | 'market';
symbol: string;
side: 'buy' | 'sell';
// Optional base fields
clientOid?: string;
stp?: 'DC' | 'CO' | 'CN' | 'CB';
tags?: string;
remark?: string;
// Limit order fields
price?: string;
size?: string;
timeInForce?: 'GTC' | 'GTT' | 'IOC' | 'FOK';
cancelAfter?: number;
postOnly?: boolean;
hidden?: boolean;
iceberg?: boolean;
visibleSize?: string;
// Market order fields
funds?: string; // Required for market orders if size is not provided
allowMaxTimeWindow?: number; // Order failed after timeout of specified milliseconds, If clientTimestamp + allowMaxTimeWindow < the server reaches time, this order will fail.
clientTimestamp?: number; // Equal to KC-API-TIMESTAMP, Need to be defined if iceberg is specified.
}
⋮----
// Required fields
⋮----
// Optional base fields
⋮----
// Limit order fields
⋮----
// Market order fields
funds?: string; // Required for market orders if size is not provided
⋮----
allowMaxTimeWindow?: number; // Order failed after timeout of specified milliseconds, If clientTimestamp + allowMaxTimeWindow < the server reaches time, this order will fail.
clientTimestamp?: number; // Equal to KC-API-TIMESTAMP, Need to be defined if iceberg is specified.
⋮----
export interface ModifyHFOrderRequest {
symbol: string;
clientOid?: string;
orderId?: string;
newPrice?: string;
newSize?: string;
}
⋮----
export interface CancelSpecifiedNumberHFOrdersRequest {
orderId: string;
symbol: string;
cancelSize: string;
}
⋮----
export interface GetHFCompletedOrdersRequest {
symbol: string;
side?: 'buy' | 'sell';
type?: 'limit' | 'market';
startAt?: number;
endAt?: number;
lastId?: number;
limit?: number;
}
⋮----
export interface GetHFFilledListRequest {
orderId?: string;
symbol: string;
side?: 'buy' | 'sell';
type?: 'limit' | 'market';
startAt?: number;
endAt?: number;
lastId?: number;
limit?: number;
}
⋮----
/**
*
* Orders
*
*/
⋮----
export interface SubmitOrderRequest {
clientOid: string;
side: 'buy' | 'sell';
symbol: string;
type?: 'limit' | 'market';
remark?: string;
stp?: 'CN' | 'CO' | 'CB' | 'DC';
tradeType?: 'TRADE' | 'MARGIN_TRADE';
price?: string;
size?: string;
timeInForce?: 'GTC' | 'GTT' | 'IOC' | 'FOK';
cancelAfter?: number;
postOnly?: boolean;
hidden?: boolean;
iceberg?: boolean;
visibleSize?: string;
funds?: string;
}
⋮----
export interface SubmitMultipleOrdersRequest {
clientOid: string;
side: 'buy' | 'sell';
type?: 'limit';
remark?: string;
stop?: 'loss' | 'entry';
stopPrice?: string;
stp?: 'CN' | 'CO' | 'CB' | 'DC';
tradeType?: 'TRADE';
price: string;
size: string;
timeInForce?: 'GTC' | 'GTT' | 'IOC' | 'FOK';
cancelAfter?: number;
postOnly?: boolean;
hidden?: boolean;
iceberg?: boolean;
visibleSize?: string;
}
⋮----
export interface CancelAllOrdersRequest {
symbol?: string;
tradeType?: 'TRADE' | 'MARGIN_TRADE' | 'MARGIN_ISOLATED_TRADE';
}
⋮----
export interface GetOrderListRequest {
status?: 'active' | 'done';
symbol?: string;
side?: 'buy' | 'sell';
type?: 'limit' | 'market' | 'limit_stop' | 'market_stop';
tradeType?: 'TRADE' | 'MARGIN_TRADE' | 'MARGIN_ISOLATED_TRADE';
startAt?: number;
endAt?: number;
currentPage?: number;
pageSize?: number;
}
⋮----
/**
*
* Fills
*
*/
⋮----
export interface GetFillsRequest {
orderId?: string;
symbol?: string;
side?: 'buy' | 'sell';
type?: 'limit' | 'market' | 'limit_stop' | 'market_stop';
startAt?: number;
endAt?: number;
tradeType: 'TRADE' | 'MARGIN_TRADE' | 'MARGIN_ISOLATED_TRADE';
}
⋮----
/**
*
* Stop order
*
*/
⋮----
export interface SubmitStopOrderRequest {
// Required fields
symbol: string;
side: 'buy' | 'sell';
stopPrice: string;
type: 'limit' | 'market';
// Optional base fields
clientOid?: string;
stp?: 'DC' | 'CO' | 'CN' | 'CB';
remark?: string;
tradeType?: 'TRADE' | 'MARGIN_TRADE' | 'MARGIN_ISOLATED_TRADE';
// Limit order required fields (when type is 'limit')
price?: string;
size?: string;
timeInForce?: 'GTC' | 'GTT' | 'IOC' | 'FOK';
// Optional limit order fields
cancelAfter?: number;
postOnly?: boolean;
hidden?: boolean;
iceberg?: boolean;
visibleSize?: string;
// Market order fields (when type is 'market')
funds?: string; // Required for market orders if size is not provided
}
⋮----
// Required fields
⋮----
// Optional base fields
⋮----
// Limit order required fields (when type is 'limit')
⋮----
// Optional limit order fields
⋮----
// Market order fields (when type is 'market')
funds?: string; // Required for market orders if size is not provided
⋮----
export interface CancelStopOrdersRequest {
symbol?: string;
tradeType?: 'TRADE' | 'MARGIN_TRADE' | 'MARGIN_ISOLATED_TRADE';
orderIds?: string;
}
⋮----
export interface GetStopOrdersListRequest {
symbol?: string;
side?: 'buy' | 'sell';
type?: 'limit' | 'market' | 'limit_stop' | 'market_stop';
tradeType?: 'TRADE' | 'MARGIN_TRADE' | 'MARGIN_ISOLATED_TRADE';
startAt?: number;
endAt?: number;
currentPage?: number;
orderIds?: string;
pageSize?: number;
stop?: 'stop' | 'oco';
}
⋮----
/**
*
* OCO order
*
*/
⋮----
export interface SubmitOCOOrderRequest {
symbol: string;
side: 'buy' | 'sell';
price: string;
size: string;
stopPrice: string;
limitPrice: string;
tradeType?: 'TRADE'; // Currently only supports TRADE
clientOid: string;
remark?: string;
}
⋮----
tradeType?: 'TRADE'; // Currently only supports TRADE
⋮----
export interface GetOCOOrdersRequest {
pageSize: string;
currentPage: string;
symbol?: string;
startAt?: number;
endAt?: number;
orderIds?: string;
}
================
File: src/types/request/uta-types.ts
================
/**
* Unified Trading Account Request Types
*/
⋮----
export interface GetAnnouncementsRequestUTA {
language?:
| 'zh_HK'
| 'ja_JP'
| 'ko_KR'
| 'en_US'
| 'pl_PL'
| 'es_ES'
| 'fr_FR'
| 'ar_AE'
| 'it_IT'
| 'id_ID'
| 'nl_NL'
| 'pt_PT'
| 'vi_VN'
| 'de_DE'
| 'tr_TR'
| 'ms_MY'
| 'ru_RU'
| 'th_TH'
| 'hi_IN'
| 'bn_BD'
| 'fil_PH'
| 'ur_PK';
type?:
| 'latest-announcements'
| 'activities'
| 'product-updates'
| 'vip'
| 'maintenance-updates'
| 'delistings'
| 'others'
| 'api-campaigns'
| 'new-listings'
| 'futures-announcements';
pageNumber?: number;
pageSize?: number;
startTime?: number;
endTime?: number;
}
⋮----
export interface GetCurrencyRequestUTA {
currency?: string;
chain?: string;
}
⋮----
export interface GetSymbolRequestUTA {
tradeType: 'SPOT' | 'FUTURES' | 'ISOLATED' | 'CROSS';
symbol?: string;
}
⋮----
export interface GetTickerRequestUTA {
tradeType: 'SPOT' | 'FUTURES';
symbol?: string;
}
⋮----
export interface GetTradesRequestUTA {
tradeType: 'SPOT' | 'FUTURES';
symbol: string;
}
⋮----
export interface GetOrderBookRequestUTA {
tradeType: 'SPOT' | 'FUTURES';
symbol: string;
limit: '20' | '50' | '100' | 'FULL';
}
⋮----
export interface GetKlinesRequestUTA {
tradeType: 'SPOT' | 'FUTURES';
symbol: string;
interval:
| '1min'
| '3min'
| '5min'
| '15min'
| '30min'
| '1hour'
| '2hour'
| '4hour'
| '6hour'
| '8hour'
| '12hour'
| '1day'
| '1week'
| '1month';
startAt?: number;
endAt?: number;
}
⋮----
export interface GetCurrentFundingRateRequestUTA {
symbol: string;
}
⋮----
export interface GetHistoryFundingRateRequestUTA {
symbol: string;
startAt: number;
endAt: number;
}
⋮----
export interface GetServiceStatusRequestUTA {
tradeType: 'SPOT' | 'FUTURES';
}
================
File: src/types/response/spot-convert.ts
================
/**
*
***********
* Spot Convert
***********
*
*/
⋮----
/**
* Get Convert Symbol Response
*/
export interface ConvertSymbol {
fromCurrency: string;
toCurrency: string;
fromCurrencyMaxSize: string;
fromCurrencyMinSize: string;
fromCurrencyStep: string;
toCurrencyMaxSize: string;
toCurrencyMinSize: string;
toCurrencyStep: string;
}
⋮----
/**
* Convert Currency Info
*/
export interface ConvertCurrency {
currency: string;
maxSize: string;
minSize: string;
step: string;
tradeDirection: string;
}
⋮----
/**
* USDT Currency Limit Info
*/
export interface UsdtCurrencyLimit {
currency: string;
maxSize: string;
minSize: string;
step: string;
}
⋮----
/**
* Get Convert Currencies Response
*/
export interface ConvertCurrencies {
currencies: ConvertCurrency[];
usdtCurrencyLimit: UsdtCurrencyLimit[];
}
⋮----
/**
* Add Convert Order Response
*/
export interface SubmitConvertOrderResponse {
orderId: string;
clientOrderId: string;
}
⋮----
/**
* Get Convert Quote Response
*/
export interface ConvertQuote {
quoteId: string;
price: string;
fromCurrencySize: string;
toCurrencySize: string;
validUntill: number;
}
⋮----
/**
* Convert Order Detail
*/
export interface ConvertOrder {
orderId: number;
clientOrderId: string;
status: 'OPEN' | 'SUCCESS' | 'FAIL';
fromCurrency: string;
toCurrency: string;
fromCurrencySize: string;
toCurrencySize: string;
accountType: 'BOTH' | 'FUNDING' | 'TRADING';
price: string;
orderTime: number;
}
⋮----
/**
* Get Convert Order History Response
*/
export interface ConvertOrderHistory {
currentPage: number;
pageSize: number;
totalNum: number;
totalPage: number;
items: ConvertOrder[];
}
⋮----
/**
* Add Convert Limit Order Response
*/
export interface SumbitConvertLimitResp {
orderId: string;
clientOrderId: string;
}
⋮----
/**
* Get Convert Limit Quote Response
*/
export interface ConvertLimitQuote {
price: string;
validUntill: number;
}
⋮----
/**
* Convert Limit Order Detail
*/
export interface ConvertLimitOrder {
orderId: string;
clientOrderId: string;
status: 'OPEN' | 'SUCCESS' | 'FAIL' | 'CANCELLED';
fromCurrency: string;
toCurrency: string;
fromCurrencySize: string;
toCurrencySize: string;
accountType: string;
price: string;
orderTime: number;
expiryTime: number;
cancelTime?: number;
filledTime?: number;
cancelType?: number;
}
⋮----
/**
* Get Convert Limit Orders Response
*/
export interface ConvertLimitOrdersList {
currentPage: number;
pageSize: number;
totalNum: number;
totalPage: number;
items: ConvertLimitOrder[];
}
================
File: src/types/response/spot-earn.ts
================
/**
*
* EARN
*
*/
⋮----
export interface SubscribeEarnFixedIncomeResponse {
orderId: string;
orderTxId: string;
}
⋮----
export interface InitiateRedemptionResponse {
orderTxId: string;
deliverTime: number;
status: 'SUCCESS' | 'PENDING';
amount: string;
}
⋮----
export interface GetEarnRedeemPreviewResponse {
currency: string;
redeemAmount: string;
penaltyInterestAmount: string;
redeemPeriod: number;
deliverTime: number;
manualRedeemable: boolean;
redeemAll: boolean;
}
⋮----
export interface EarnFixedIncomeHoldAsset {
orderId: string;
productId: string;
productCategory: string;
productType: string;
currency: string;
incomeCurrency: string;
returnRate: string;
holdAmount: string;
redeemedAmount: string;
redeemingAmount: string;
lockStartTime: number;
lockEndTime: number | null;
purchaseTime: number;
redeemPeriod: number;
status: 'LOCKED' | 'REDEEMING';
earlyRedeemSupported: 0 | 1;
}
⋮----
export interface EarnFixedIncomeHoldAssets {
totalNum: number;
items: EarnFixedIncomeHoldAsset[];
currentPage: number;
pageSize: number;
totalPage: number;
}
⋮----
export interface EarnProduct {
id: string;
currency: string;
category: 'DEMAND' | 'ACTIVITY' | 'KCS_STAKING' | 'STAKING' | 'ETH2';
type: 'TIME' | 'DEMAND';
precision: number;
productUpperLimit: string;
userUpperLimit: string;
userLowerLimit: string;
redeemPeriod: number;
lockStartTime: number;
lockEndTime: number | null;
applyStartTime: number;
applyEndTime: number | null;
returnRate: string;
incomeCurrency: string;
earlyRedeemSupported: 0 | 1;
productRemainAmount: string;
status: 'ONGOING' | 'PENDING' | 'FULL' | 'INTERESTING';
redeemType: 'MANUAL' | 'TRANS_DEMAND' | 'AUTO';
incomeReleaseType: 'DAILY' | 'AFTER';
interestDate: number;
duration: number;
newUserOnly: 0 | 1;
}
⋮----
/**
*
* STRUCTURED EARN - DUAL
*
*/
⋮----
export interface StructuredProductPurchaseResponse {
orderId: string; // Holding ID
}
⋮----
orderId: string; // Holding ID
⋮----
export interface DualInvestmentProduct {
category: 'DUAL_CLASSIC' | 'DUAL_BOOSTER' | 'DUAL_EXTRA'; // Product category
productId: string; // Product ID
targetCurrency: string; // Underlying currency of the product
quoteCurrency: string; // Currency used for pricing/quoting the product
investCurrency: string; // Currency used for investment
strikeCurrency: string; // Currency used for settlement if strike price is met
strikePrice: string; // Linked price (strike price) for settlement determination
protectPrice?: string; // Protection price for risk management (if applicable)
annualRate: string; // Annualized rate of return (e.g., 0.05 equals 5%)
expirationTime: number; // Product maturity time, in milliseconds
side: 'CALL' | 'PUT'; // Direction of the product: CALL (bullish), PUT (bearish)
expectSettleTime: number; // Expected settlement time, in milliseconds
duration: string; // Product duration (days)
lowerLimit: string; // Minimum investment amount per order
upperLimit: string; // Maximum investment amount per order
availableScale: string; // Total available subscription amount for the product
soldStatus: 'SOLD_OUT' | 'AVAILABLE'; // Product availability status
increment: string; // Investment step size (amount must be a multiple of this value, within lowerLimit and upperLimit)
}
⋮----
category: 'DUAL_CLASSIC' | 'DUAL_BOOSTER' | 'DUAL_EXTRA'; // Product category
productId: string; // Product ID
targetCurrency: string; // Underlying currency of the product
quoteCurrency: string; // Currency used for pricing/quoting the product
investCurrency: string; // Currency used for investment
strikeCurrency: string; // Currency used for settlement if strike price is met
strikePrice: string; // Linked price (strike price) for settlement determination
protectPrice?: string; // Protection price for risk management (if applicable)
annualRate: string; // Annualized rate of return (e.g., 0.05 equals 5%)
expirationTime: number; // Product maturity time, in milliseconds
side: 'CALL' | 'PUT'; // Direction of the product: CALL (bullish), PUT (bearish)
expectSettleTime: number; // Expected settlement time, in milliseconds
duration: string; // Product duration (days)
lowerLimit: string; // Minimum investment amount per order
upperLimit: string; // Maximum investment amount per order
availableScale: string; // Total available subscription amount for the product
soldStatus: 'SOLD_OUT' | 'AVAILABLE'; // Product availability status
increment: string; // Investment step size (amount must be a multiple of this value, within lowerLimit and upperLimit)
⋮----
export interface StructuredProductOrder {
category: string; // Product category
side: string; // Direction
duration: string; // Duration
apr: string; // Annual percentage rate
investCurrency: string; // Investment currency
strikeCurrency: string; // Strike currency
investAmount: string; // Investment amount
settleAmount: string; // Settlement amount
settleCurrency: string | null; // Settlement currency
targetPrice: string; // Target price
settlePrice: string; // Settlement price
expirationTime: number; // Expiration time in milliseconds
orderId: string; // Order ID
status: string; // Order status
}
⋮----
category: string; // Product category
side: string; // Direction
duration: string; // Duration
apr: string; // Annual percentage rate
investCurrency: string; // Investment currency
strikeCurrency: string; // Strike currency
investAmount: string; // Investment amount
settleAmount: string; // Settlement amount
settleCurrency: string | null; // Settlement currency
targetPrice: string; // Target price
settlePrice: string; // Settlement price
expirationTime: number; // Expiration time in milliseconds
orderId: string; // Order ID
status: string; // Order status
⋮----
export interface StructuredProductOrders {
currentPage: number; // Current page number
pageSize: number; // Number of records per page
totalNum: number; // Total number of records
totalPage: number; // Total number of pages
items: StructuredProductOrder[]; // List of structured product holdings
}
⋮----
currentPage: number; // Current page number
pageSize: number; // Number of records per page
totalNum: number; // Total number of records
totalPage: number; // Total number of pages
items: StructuredProductOrder[]; // List of structured product holdings
================
File: src/types/response/uta-types.ts
================
/**
* Unified Trading Account Response Types
*/
⋮----
export interface AnnouncementItemUTA {
id: number;
title: string;
type: string[];
description: string;
releaseTime: number;
language: string;
url: string;
}
⋮----
export interface GetAnnouncementsResponseUTA {
totalNumber: number;
totalPage: number;
pageNumber: number;
pageSize: number;
list: AnnouncementItemUTA[];
}
⋮----
export interface CurrencyChainUTA {
chainName: string;
minWithdrawSize: string | null;
minDepositSize: string | null;
withdrawFeeRate: string;
minWithdrawFee: string;
isWithdrawEnabled: boolean;
isDepositEnabled: boolean;
confirms: number;
preConfirms: number;
contractAddress: string;
withdrawPrecision: number;
maxWithdrawSize: string | null;
maxDepositSize: string | null;
needTag: boolean;
chainId: string;
}
⋮----
export interface GetCurrencyResponseUTA {
currency: string;
name: string;
fullName: string;
precision: number;
confirms: number | null;
contractAddress: string | null;
isMarginEnabled: boolean;
isDebitEnabled: boolean;
list: CurrencyChainUTA[];
}
⋮----
export interface SymbolUTA {
symbol: string;
name?: string;
baseCurrency: string;
quoteCurrency: string;
market?: string;
minBaseOrderSize?: string;
minQuoteOrderSize?: string;
maxBaseOrderSize?: string | number;
maxQuoteOrderSize?: string;
baseOrderStep?: string;
quoteOrderStep?: string;
tickSize?: string | number;
feeCurrency?: string;
tradingStatus?: string;
marginMode?: string;
priceLimitRatio?: string;
feeCategory?: number;
makerFeeCoefficient?: string;
takerFeeCoefficient?: string;
st?: boolean;
settlementCurrency?: string;
contractType?: string;
isInverse?: boolean;
launchTime?: number;
expiryTime?: number | null;
settlementTime?: number | null;
maxPrice?: string | number;
lotSize?: string | number;
unitSize?: string | number;
makerFeeRate?: string | number;
takerFeeRate?: string | number;
settlementFeeRate?: string | number | null;
maxLeverage?: number;
indexSourceExchanges?: string[];
k?: string | number;
m?: string | number;
f?: string | number;
mmrLimit?: string | number;
mmrLevConstant?: string | number;
alertRiskRatio?: string;
liquidationRiskRatio?: string;
baseBorrowEnable?: boolean | string;
quoteBorrowEnable?: boolean | string;
baseTransferInEnable?: boolean | string;
quoteTransferInEnable?: boolean | string;
}
⋮----
export interface GetSymbolResponseUTA {
tradeType: string;
list: SymbolUTA[];
}
⋮----
export interface TickerUTA {
symbol: string;
name?: string;
bestBidPrice: string;
bestBidSize: string;
bestAskPrice: string;
bestAskSize: string;
high: string;
low: string;
baseVolume: string;
quoteVolume: string;
lastPrice: string;
open: string;
size: string;
}
⋮----
export interface GetTickerResponseUTA {
tradeType: string;
ts: number;
list: TickerUTA[];
}
⋮----
export interface TradeUTA {
sequence: string;
tradeId: string;
price: string;
size: string;
side: 'buy' | 'sell';
ts: number;
}
⋮----
export interface GetTradesResponseUTA {
tradeType: string;
list: TradeUTA[];
}
⋮----
export interface OrderBookLevelUTA {
price: string;
size: string;
}
⋮----
export interface GetOrderBookResponseUTA {
tradeType: string;
symbol: string;
sequence: string;
bids: OrderBookLevelUTA[];
asks: OrderBookLevelUTA[];
}
⋮----
export interface GetKlinesResponseUTA {
tradeType: string;
symbol: string;
list: string[][]; // [time, open, close, high, low, volume, turnover]
}
⋮----
list: string[][]; // [time, open, close, high, low, volume, turnover]
⋮----
export interface GetCurrentFundingRateResponseUTA {
symbol: string;
nextFundingRate: number;
fundingTime: number;
fundingRateCap: number;
fundingRateFloor: number;
}
⋮----
export interface FundingRateHistoryItemUTA {
fundingRate: number;
ts: number;
}
⋮----
export interface GetHistoryFundingRateResponseUTA {
symbol: string;
list: FundingRateHistoryItemUTA[];
}
⋮----
export interface GetCrossMarginConfigResponseUTA {
maxLeverage: number;
alertRiskRatio: string;
liquidationRiskRatio: string;
currencyList: string[];
}
⋮----
export interface GetServiceStatusResponseUTA {
tradeType: string;
serverStatus: 'open' | 'close' | 'cancelonly';
msg: string;
}
================
File: src/types/websockets/ws-events.ts
================
export interface WsDataEvent {
data: TData;
table: string;
wsKey: TWSKey;
}
⋮----
export interface MessageEventLike {
target: WebSocket;
type: 'message';
data: string;
}
⋮----
export function isMessageEvent(msg: unknown): msg is MessageEventLike
================
File: .gitignore
================
examples/futures-private-test.ts
examples/spot-private-test.ts
node_modules
rest-spot-private-ts-test.ts
localtest.sh
testfile.ts
dist
repomix.sh
coverage
privaterepotracker
restClientRegex.ts
================
File: .nvmrc
================
v22.18.0
================
File: LICENSE.md
================
Copyright 2025 Tiago Siebler
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
================
File: tsconfig.json
================
{
"compilerOptions": {
"allowSyntheticDefaultImports": true,
"baseUrl": ".",
"noEmitOnError": true,
"declaration": true,
"esModuleInterop": true,
"forceConsistentCasingInFileNames": false,
"inlineSourceMap": false,
"lib": ["esnext"],
"listEmittedFiles": false,
"listFiles": false,
"moduleResolution": "node",
"noFallthroughCasesInSwitch": true,
"noImplicitAny": true,
"noUnusedParameters": true,
"pretty": true,
"removeComments": false,
"resolveJsonModule": true,
"skipLibCheck": false,
"sourceMap": true,
"strict": true,
"strictNullChecks": true,
"types": ["node", "jest"],
"module": "commonjs",
"outDir": "dist/cjs",
"target": "esnext"
},
"compileOnSave": true,
"exclude": ["node_modules", "dist"],
"include": ["src/**/*.*", "test/**/*.*", ".eslintrc.cjs"]
}
================
File: examples/WebSockets/ws-api-raw-promises.ts
================
/* eslint-disable @typescript-eslint/no-unused-vars */
import { DefaultLogger, WebsocketClient, WS_KEY_MAP } from '../../src/index.js';
// import { DefaultLogger, WebsocketClient, WS_KEY_MAP } from 'kucoin-api';
// normally you should install this module via npm: `npm install kucoin-api`
⋮----
async function start()
⋮----
// Optional: inject a custom logger to override internal logging behaviour
⋮----
// Uncomment the below callback to introduce filtered trace logging in the WebsocketClient.
// trace: (...params) => {
// if (
// [
// 'Sending ping',
// // 'Sending upstream ws message: ',
// 'Received pong',
// ].includes(params[0])
// ) {
// return;
// }
// console.log('trace', JSON.stringify(params, null, 2));
// },
⋮----
passphrase: process.env.API_PASSPHRASE || 'apiPassPhraseHere', // This is NOT your account password
⋮----
// console.log('connecting with ', account);
⋮----
// logger,
⋮----
// Data received
⋮----
// Something happened, attempting to reconenct
⋮----
// Reconnect successful
⋮----
// Connection closed. If unexpected, expect reconnect -> reconnected.
⋮----
// Reply to a request, e.g. "subscribe"/"unsubscribe"/"authenticate"
⋮----
// console.info('response: ', data);
⋮----
/**
*
* Raw events can be routed via the sendWSAPIRequest in the WebsocketClient, as shown below.
* However, for a simpler integration, it is recommended to use the WebsocketAPIClient. The
* WebsocketAPIClient class is a wrapper around sendWSAPIRequest, with clear functions, typed
* requests and typed responses. The simpler WSAPIClient interface behaves much like a REST API
* wrapper, but all calls are routed via the WebSocket API.
*
* For a clearer example, refer to the "ws-api-client.ts" example found in this folder.
*/
⋮----
price: '20000', // Very low price to avoid accidental execution
================
File: src/lib/websocket/websocket-util.ts
================
import WebSocket from 'isomorphic-ws';
⋮----
import { WsRequestOperationKucoin } from '../../types/websockets/ws-api.js';
⋮----
/** Should be one WS key per unique URL */
⋮----
/** This is used to differentiate between each of the available websocket streams */
export type WsKey = (typeof WS_KEY_MAP)[keyof typeof WS_KEY_MAP];
export type WSAPIWsKey =
| typeof WS_KEY_MAP.wsApiFuturesV1
| typeof WS_KEY_MAP.wsApiSpotV1;
⋮----
/**
* Normalised internal format for a request (subscribe/unsubscribe/etc) on a topic, with optional parameters.
*
* - Topic: the topic this event is for
* - Payload: the parameters to include, optional. E.g. auth requires key + sign. Some topics allow configurable parameters.
*/
export interface WsTopicRequest<
TWSTopic extends string = string,
TWSPayload = any,
> {
topic: TWSTopic;
payload?: TWSPayload;
}
⋮----
/**
* Conveniently allow users to request a topic either as string topics or objects (containing string topic + params)
*/
export type WsTopicRequestOrStringTopic<
TWSTopic extends string,
TWSPayload = any,
> = WsTopicRequest | string;
⋮----
/**
* #305: ws.terminate() is undefined in browsers.
* This only works in node.js, not in browsers.
* Does nothing if `ws` is undefined. Does nothing in browsers.
*/
export function safeTerminateWs(
ws?: WebSocket | any,
fallbackToClose?: boolean,
): boolean
⋮----
/**
* WS API promises are stored using a primary key. This key is constructed using
* properties found in every request & reply.
*
* The counterpart to this is in resolveEmittableEvents
*/
export function getPromiseRefForWSAPIRequest(
wsKey: WsKey,
requestEvent: WsRequestOperationKucoin,
): string
⋮----
export function isWSAPIWsKey(wsKey: WsKey): wsKey is WSAPIWsKey
================
File: src/types/request/spot-affiliate.ts
================
export interface GetAffiliateTradeHistoryRequest {
uid: string; // required - Invitee's UID
tradeType?: 'SPOT' | 'FEATURE'; // optional - Trading type
tradeStartAt?: number; // optional - Trade start time (13-digit timestamp)
tradeEndAt?: number; // optional - Trade end time (13-digit timestamp)
page?: number; // optional - Page number >= 1, default: 1
pageSize?: number; // optional - Page size >= 1, <= 500, default: 10
}
⋮----
uid: string; // required - Invitee's UID
tradeType?: 'SPOT' | 'FEATURE'; // optional - Trading type
tradeStartAt?: number; // optional - Trade start time (13-digit timestamp)
tradeEndAt?: number; // optional - Trade end time (13-digit timestamp)
page?: number; // optional - Page number >= 1, default: 1
pageSize?: number; // optional - Page size >= 1, <= 500, default: 10
⋮----
export interface GetAffiliateCommissionRequest {
siteType?: 'all'; // optional - The source site of the commission, default: "all"
rebateType?: 0 | 1 | 2; // optional - Rebate type, default: 0
rebateStartAt?: number; // optional - Start time for commission issuance (13-digit timestamp)
rebateEndAt?: number; // optional - End time for commission issuance (13-digit timestamp)
page?: number; // optional - Page number >= 1, default: 1
pageSize?: number; // optional - Page size >= 1, <= 500, default: 10
}
⋮----
siteType?: 'all'; // optional - The source site of the commission, default: "all"
rebateType?: 0 | 1 | 2; // optional - Rebate type, default: 0
rebateStartAt?: number; // optional - Start time for commission issuance (13-digit timestamp)
rebateEndAt?: number; // optional - End time for commission issuance (13-digit timestamp)
page?: number; // optional - Page number >= 1, default: 1
pageSize?: number; // optional - Page size >= 1, <= 500, default: 10
⋮----
export interface GetAffiliateInviteesRequest {
userType?: '1' | '2' | '3'; // optional - User Type
referralCode?: string; // optional - Which referral code the user registered with
uid?: string; // optional - UID(s) of the users, can pass multiple separated by commas
registrationStartAt?: number; // optional - Registration start timestamp
registrationEndAt?: number; // optional - Registration end timestamp
page?: number; // optional - Page number >= 1, default: 1
pageSize?: number; // optional - Max number of records per page >= 1, <= 500, default: 10
}
⋮----
userType?: '1' | '2' | '3'; // optional - User Type
referralCode?: string; // optional - Which referral code the user registered with
uid?: string; // optional - UID(s) of the users, can pass multiple separated by commas
registrationStartAt?: number; // optional - Registration start timestamp
registrationEndAt?: number; // optional - Registration end timestamp
page?: number; // optional - Page number >= 1, default: 1
pageSize?: number; // optional - Max number of records per page >= 1, <= 500, default: 10
⋮----
export interface GetAffiliateTransactionRequest {
uid?: string; // optional - The uid of the invitee
tradeType?: 'SPOT' | 'FEATURE'; // optional - Trade type
tradeStartAt: number; // required - Transaction start time (13-digit timestamp)
tradeEndAt: number; // required - Transaction end time (13-digit timestamp)
lastId?: number; // optional - The offset ID of the query
direction?: 'PRE' | 'NEXT'; // optional - Page direction, default: 'NEXT'
pageSize?: number; // optional - Page size >= 1, <= 500, default: 10
}
⋮----
uid?: string; // optional - The uid of the invitee
tradeType?: 'SPOT' | 'FEATURE'; // optional - Trade type
tradeStartAt: number; // required - Transaction start time (13-digit timestamp)
tradeEndAt: number; // required - Transaction end time (13-digit timestamp)
lastId?: number; // optional - The offset ID of the query
direction?: 'PRE' | 'NEXT'; // optional - Page direction, default: 'NEXT'
pageSize?: number; // optional - Page size >= 1, <= 500, default: 10
⋮----
export interface GetKuminingRequest {
uid?: string; // optional - User Id
startAt?: number; // optional - Start time
endAt?: number; // optional - End time
lastId?: string; // optional - Last Id
direction?: 'PRE' | 'NEXT'; // optional - Page direction
pageSize?: number; // optional - Page size >= 1, <= 500, default: 10
}
⋮----
uid?: string; // optional - User Id
startAt?: number; // optional - Start time
endAt?: number; // optional - End time
lastId?: string; // optional - Last Id
direction?: 'PRE' | 'NEXT'; // optional - Page direction
pageSize?: number; // optional - Page size >= 1, <= 500, default: 10
================
File: src/types/request/spot-margin-trading.ts
================
/**
*
***********
* Margin Trading
***********
*
*/
⋮----
/**
*
* Margin HF trade
*
*/
⋮----
export interface SubmitHFMarginOrderRequest {
clientOid: string;
side: 'buy' | 'sell';
symbol: string;
type?: 'limit' | 'market';
stp?: 'CN' | 'CO' | 'CB' | 'DC';
isIsolated?: boolean;
autoBorrow?: boolean;
autoRepay?: boolean;
price?: string;
size?: string;
timeInForce?: 'GTC' | 'GTT' | 'IOC' | 'FOK';
cancelAfter?: number;
postOnly?: boolean;
hidden?: boolean;
iceberg?: boolean;
visibleSize?: string;
funds?: string;
}
⋮----
export interface HFMarginRequestOrder {
symbol: string;
tradeType: 'MARGIN_TRADE' | 'MARGIN_ISOLATED_TRADE';
}
⋮----
export interface GetHFMarginFilledRequest {
symbol: string;
tradeType: 'MARGIN_TRADE' | 'MARGIN_ISOLATED_TRADE';
side?: 'buy' | 'sell';
type?: 'limit' | 'market';
startAt?: number;
endAt?: number;
lastId?: number;
limit?: number;
}
⋮----
export interface getHFMarginFillsRequest {
orderId?: string;
symbol: string;
tradeType: 'MARGIN_TRADE' | 'MARGIN_ISOLATED_TRADE';
side?: 'buy' | 'sell';
type?: 'limit' | 'market';
startAt?: number;
endAt?: number;
lastId?: number;
limit?: number;
}
⋮----
/**
*
* Orders
*
*/
⋮----
export interface SubmitMarginOrderRequest {
clientOid: string;
side: 'buy' | 'sell';
symbol: string;
type?: 'limit' | 'market';
remark?: string;
stp?: 'CN' | 'CO' | 'CB' | 'DC';
marginModel?: 'cross' | 'isolated';
autoBorrow?: boolean;
autoRepay?: boolean;
price: string;
size?: string;
timeInForce?: 'GTC' | 'GTT' | 'IOC' | 'FOK';
cancelAfter?: number;
postOnly?: boolean;
hidden?: boolean;
iceberg?: boolean;
visibleSize?: string;
funds?: string;
}
⋮----
/**
*
* Margin info
*
*/
⋮----
export interface MarginRiskLimitRequest {
isIsolated: boolean;
symbol?: string;
currency?: string;
}
⋮----
/**
*
* Isolated Margin
*
*/
⋮----
/**
*
* Margin trading(v3)
*
*/
⋮----
export interface MarginBorrowV3Request {
isIsolated?: boolean;
symbol?: string;
currency: string;
size: number;
timeInForce: 'IOC' | 'FOK';
isHf: boolean;
}
⋮----
export interface MarginRepayV3Request {
isIsolated?: boolean;
symbol?: string;
currency: string;
size: number;
isHf: boolean;
}
⋮----
export interface MarginHistoryV3Request {
currency: string;
isIsolated?: boolean;
symbol?: string;
orderNo?: string;
startTime?: number;
endTime?: number;
currentPage?: number;
pageSize?: number;
}
⋮----
export interface MarginInterestRecordsRequest {
isIsolated?: boolean;
symbol?: string;
currency?: string;
startTime?: number;
endTime?: number;
currentPage?: number;
pageSize?: number;
}
⋮----
/**
*
* Lending market(v3)
*
*/
⋮----
export interface InitiateLendingSubscriptionV3Request {
currency: string;
size: string;
interestRate: string;
}
⋮----
export interface InitiateLendingRedemptionV3Request {
currency: string;
size: string;
purchaseOrderNo: string;
}
⋮----
export interface ModifyLendingSubscriptionOrdersV3Request {
currency: string;
purchaseOrderNo: string;
interestRate: string;
}
⋮----
export interface GetLendingRedemptionOrdersV3Request {
currency: string;
redeemOrderNo?: string;
status: 'DONE' | 'PENDING';
currentPage?: number;
pageSize?: number;
}
⋮----
export interface GetLendingSubscriptionOrdersV3Request {
currency: string;
purchaseOrderNo?: string;
status: 'DONE' | 'PENDING';
currentPage?: number;
pageSize?: number;
}
⋮----
export interface GetBorrowInterestRateRequest {
vipLevel?: number; // optional - If empty, default to current user vip level (0-12)
currency?: string; // optional - Supports multiple currencies (up to 50), comma-separated
}
⋮----
vipLevel?: number; // optional - If empty, default to current user vip level (0-12)
currency?: string; // optional - Supports multiple currencies (up to 50), comma-separated
⋮----
/**
* Margin Stop Order Requests
*/
export interface SubmitMarginStopOrderRequest {
clientOid: string; // Client Order ID
side: 'buy' | 'sell'; // Order side
symbol: string; // Trading symbol
type?: 'limit' | 'market'; // Order type, default: limit
remark?: string; // Order note, max 100 characters
stop?: string; // Stop condition, default: loss
stopPrice: string; // Trigger price (required)
stp?: 'DC' | 'CO' | 'CN' | 'CB'; // Self Trade Prevention
isIsolated: boolean; // True - isolated margin; false - cross margin
autoRepay: boolean; // AutoPay for borrowed assets
autoBorrow: boolean; // Auto borrow for insufficient balance
price?: string; // Order price (required for limit orders)
size?: string; // Order quantity (required for limit orders)
timeInForce?: 'GTC' | 'GTT' | 'IOC' | 'FOK'; // Time in force
cancelAfter?: number; // Cancel after n seconds (GTT strategy)
postOnly?: boolean; // Passive order labels
hidden?: boolean; // Hidden order
iceberg?: boolean; // Iceberg order
visibleSize?: string; // Visible size for iceberg orders
funds?: string; // Order funds (for market orders)
}
⋮----
clientOid: string; // Client Order ID
side: 'buy' | 'sell'; // Order side
symbol: string; // Trading symbol
type?: 'limit' | 'market'; // Order type, default: limit
remark?: string; // Order note, max 100 characters
stop?: string; // Stop condition, default: loss
stopPrice: string; // Trigger price (required)
stp?: 'DC' | 'CO' | 'CN' | 'CB'; // Self Trade Prevention
isIsolated: boolean; // True - isolated margin; false - cross margin
autoRepay: boolean; // AutoPay for borrowed assets
autoBorrow: boolean; // Auto borrow for insufficient balance
price?: string; // Order price (required for limit orders)
size?: string; // Order quantity (required for limit orders)
timeInForce?: 'GTC' | 'GTT' | 'IOC' | 'FOK'; // Time in force
cancelAfter?: number; // Cancel after n seconds (GTT strategy)
postOnly?: boolean; // Passive order labels
hidden?: boolean; // Hidden order
iceberg?: boolean; // Iceberg order
visibleSize?: string; // Visible size for iceberg orders
funds?: string; // Order funds (for market orders)
⋮----
export interface CancelMarginStopOrderByClientOidRequest {
clientOid: string; // Client order ID
}
⋮----
clientOid: string; // Client order ID
⋮----
export interface BatchCancelMarginStopOrdersRequest {
symbol?: string; // Trading symbol
tradeType: 'MARGIN_TRADE' | 'MARGIN_ISOLATED_TRADE'; // Margin type (required)
orderIds?: string; // Comma separated order IDs
}
⋮----
symbol?: string; // Trading symbol
tradeType: 'MARGIN_TRADE' | 'MARGIN_ISOLATED_TRADE'; // Margin type (required)
orderIds?: string; // Comma separated order IDs
⋮----
export interface GetMarginStopOrdersListRequest {
symbol?: string; // Trading symbol
side?: string; // Order side (buy/sell)
type?: 'limit' | 'market' | 'limit_stop' | 'market_stop'; // Order type
tradeType?: 'MARGIN_TRADE' | 'MARGIN_ISOLATED_TRADE'; // Margin type
startAt?: number; // Start time (millisecond)
endAt?: number; // End time (millisecond)
currentPage?: number; // Current page (>=1, default: 1)
orderIds?: string; // Comma separated order IDs
pageSize?: number; // Page size (>=10, <=500, default: 50)
stop?: 'stop' | 'oco'; // Order type
}
⋮----
symbol?: string; // Trading symbol
side?: string; // Order side (buy/sell)
type?: 'limit' | 'market' | 'limit_stop' | 'market_stop'; // Order type
tradeType?: 'MARGIN_TRADE' | 'MARGIN_ISOLATED_TRADE'; // Margin type
startAt?: number; // Start time (millisecond)
endAt?: number; // End time (millisecond)
currentPage?: number; // Current page (>=1, default: 1)
orderIds?: string; // Comma separated order IDs
pageSize?: number; // Page size (>=10, <=500, default: 50)
stop?: 'stop' | 'oco'; // Order type
⋮----
export interface GetMarginStopOrderByOrderIdRequest {
orderId: string; // Order ID
}
⋮----
orderId: string; // Order ID
⋮----
export interface GetMarginStopOrderByClientOidRequest {
clientOid: string; // Client order ID
}
⋮----
clientOid: string; // Client order ID
⋮----
/**
* Margin OCO Order Requests
*/
export interface SubmitMarginOcoOrderRequest {
symbol: string; // Trading symbol (required)
side: 'buy' | 'sell'; // Order side (required)
price: string; // Order price (required)
size: string; // Order quantity (required)
stopPrice: string; // Trigger price (required)
limitPrice: string; // Limit order price after trigger (required)
clientOid: string; // Client Order ID (required)
isIsolated: boolean; // true - isolated, false - cross (required)
autoRepay?: boolean; // Auto repay
autoBorrow?: boolean; // Auto borrow
}
⋮----
symbol: string; // Trading symbol (required)
side: 'buy' | 'sell'; // Order side (required)
price: string; // Order price (required)
size: string; // Order quantity (required)
stopPrice: string; // Trigger price (required)
limitPrice: string; // Limit order price after trigger (required)
clientOid: string; // Client Order ID (required)
isIsolated: boolean; // true - isolated, false - cross (required)
autoRepay?: boolean; // Auto repay
autoBorrow?: boolean; // Auto borrow
⋮----
export interface CancelMarginOcoOrderByOrderIdRequest {
orderId: string; // Order ID
}
⋮----
orderId: string; // Order ID
⋮----
export interface CancelMarginOcoOrderByClientOidRequest {
clientOid: string; // Client order ID
}
⋮----
clientOid: string; // Client order ID
⋮----
export interface BatchCancelMarginOcoOrdersRequest {
orderIds?: string; // Comma separated order IDs
symbol?: string; // Trading symbol
tradeType?: 'MARGIN_TRADE' | 'MARGIN_ISOLATED_TRADE'; // Margin type
}
⋮----
orderIds?: string; // Comma separated order IDs
symbol?: string; // Trading symbol
tradeType?: 'MARGIN_TRADE' | 'MARGIN_ISOLATED_TRADE'; // Margin type
⋮----
export interface GetMarginOcoOrderByClientOidRequest {
clientOid: string; // Client order ID
}
⋮----
clientOid: string; // Client order ID
⋮----
export interface GetMarginOcoOrderDetailByOrderIdRequest {
orderId: string; // Order ID
}
⋮----
orderId: string; // Order ID
⋮----
/**
* Get Margin Collateral Ratio
*/
export interface GetMarginCollateralRatioRequest {
currencyList?: string; // If not specified, all currencies will be returned. Supports multiple currencies, separated by commas.
}
⋮----
currencyList?: string; // If not specified, all currencies will be returned. Supports multiple currencies, separated by commas.
================
File: src/types/response/spot-account.ts
================
export interface SpotAccountSummary {
level: number;
subQuantity: number;
spotSubQuantity: number;
marginSubQuantity: number;
futuresSubQuantity: number;
optionSubQuantity: number;
maxSubQuantity: number;
maxDefaultSubQuantity: number;
maxSpotSubQuantity: number;
maxMarginSubQuantity: number;
maxFuturesSubQuantity: number;
maxOptionSubQuantity: number;
}
⋮----
export interface Balances {
id: string;
currency: string;
type: 'main' | 'trade';
balance: string;
available: string;
holds: string;
}
⋮----
export interface Account {
currency: string;
balance: string;
available: string;
holds: string;
}
⋮----
export interface SpotAccountTransaction {
id: string;
currency: string;
amount: string;
fee: string;
tax: string;
balance: string;
accountType: string; // 'TRADE_HF'
bizType: string;
direction: 'out' | 'in';
createdAt: string;
context: string;
}
⋮----
accountType: string; // 'TRADE_HF'
⋮----
export interface SpotAccountTransactions {
currentPage: number;
pageSize: number;
totalNum: number;
totalPage: number;
items: SpotAccountTransaction[];
}
⋮----
export interface AccountHFMarginTransactions {
id: string;
currency: string;
amount: string;
fee: string;
balance: string;
accountType: 'MARGIN_V2' | 'ISOLATED_V2';
bizType:
| 'TRANSFER'
| 'MARGIN_EXCHANGE'
| 'ISOLATED_EXCHANGE'
| 'LIQUIDATION'
| 'ASSERT_RETURN';
direction: 'out' | 'in';
createdAt: string;
tax: string;
context: string;
}
⋮----
/**
*
* Sub-Account
*
*/
⋮----
export interface SubAccountInfo {
userId: string;
uid: number;
subName: string;
status: number;
type: number;
access: string;
createdAt: number;
remarks: string;
tradeTypes: string[];
openedTradeTypes: string[];
hostedStatus: null | string;
}
⋮----
export interface SubAccountsV2 {
currentPage: number;
pageSize: number;
totalNum: number;
totalPage: number;
items: SubAccountInfo[];
}
⋮----
export interface SubAccountItem {
userId: string;
uid: number;
subName: string;
status: number;
type: number;
access: string;
createdAt: number;
remarks: string;
tradeTypes: string[];
openedTradeTypes: string[];
hostedStatus: null | string;
}
⋮----
export interface CreateSubAccount {
currentPage: number;
pageSize: number;
totalNum: number;
totalPage: number;
items: SubAccountItem[];
}
⋮----
export interface SubAccountBalance {
currency: string;
balance: string;
available: string;
holds: string;
baseCurrency: string;
baseCurrencyPrice: string;
baseAmount: string;
}
⋮----
// deprecated
export interface SubAccountBalances {
subUserId: string;
subName: string;
mainAccounts: SubAccountBalance[];
tradeAccounts: SubAccountBalance[];
marginAccounts: SubAccountBalance[];
}
⋮----
export interface SubAccountBalancesV2 {
currentPage: number;
pageSize: number;
totalNum: number;
totalPage: number;
items: {
subUserId: string;
subName: string;
mainAccounts: SubAccountBalance[];
}[];
}
export interface SubAccountV2Details {
currency?: string;
balance?: string;
available?: string;
holds?: string;
baseCurrency?: string;
baseCurrencyPrice?: string;
baseAmount?: string;
tag?: string;
}
⋮----
export interface SubAccountBalanceItemV2 {
subUserId: string;
subName: string;
mainAccounts: SubAccountV2Details[]; // Funding Account
tradeAccounts: SubAccountV2Details[]; // Spot Account
marginAccounts: SubAccountV2Details[]; // Margin Account
tradeHFAccounts: string[]; // Deprecated, only for old users
}
⋮----
mainAccounts: SubAccountV2Details[]; // Funding Account
tradeAccounts: SubAccountV2Details[]; // Spot Account
marginAccounts: SubAccountV2Details[]; // Margin Account
tradeHFAccounts: string[]; // Deprecated, only for old users
⋮----
/**
*
* Sub-Account API
*
*
*/
⋮----
export interface SubAccountAPIInfo {
subName: string;
remark: string;
apiKey: string;
apiVersion: number;
permission: string;
ipWhitelist: string;
createdAt: number;
uid: number;
isMaster: boolean;
}
⋮----
export interface CreateSubAPI {
subName: string;
remark: string;
apiKey: string;
apiSecret: string;
apiVersion: number;
passphrase: string;
permission: string;
createdAt: number;
}
⋮----
export interface UpdateSubAPI {
apiKey: string;
ipWhitelist: string;
permission: string;
subName: string;
}
⋮----
export interface DeleteSubAccountAPI {
subName: string;
apiKey: string;
}
⋮----
/**
* Get KYC Regions Response
*/
export interface KYCRegion {
code: string; // Two-letter country code
enName: string; // English name of the region
}
⋮----
code: string; // Two-letter country code
enName: string; // English name of the region
⋮----
/**
* Get API Key Info Response
*/
export interface ApiKeyInfo {
uid: number; // Account UID
parentUid?: number; // Master account UID. Returns empty when called by the master account itself
region: string; // KYC region of the account, returns the two-letter country code
kycStatus: 0 | 1; // KYC status
subName?: string; // Sub-account name (not present for the master account)
remark: string; // Remarks
apiKey: string; // API key
apiVersion: number; // API version
permission: string; // Permissions
ipWhitelist?: string; // IP whitelist (comma-separated list of allowed IPs)
isMaster: boolean; // Indicates whether this is the master account
createdAt: number; // API key creation timestamp (Unix milliseconds)
expiredAt?: number | null; // API key expiration timestamp (Unix milliseconds). Returns null if no expiration is set
thirdPartyApp?: string; // Third-party application name. Returns empty string if not associated with any third-party app
}
⋮----
uid: number; // Account UID
parentUid?: number; // Master account UID. Returns empty when called by the master account itself
region: string; // KYC region of the account, returns the two-letter country code
kycStatus: 0 | 1; // KYC status
subName?: string; // Sub-account name (not present for the master account)
remark: string; // Remarks
apiKey: string; // API key
apiVersion: number; // API version
permission: string; // Permissions
ipWhitelist?: string; // IP whitelist (comma-separated list of allowed IPs)
isMaster: boolean; // Indicates whether this is the master account
createdAt: number; // API key creation timestamp (Unix milliseconds)
expiredAt?: number | null; // API key expiration timestamp (Unix milliseconds). Returns null if no expiration is set
thirdPartyApp?: string; // Third-party application name. Returns empty string if not associated with any third-party app
================
File: src/types/response/spot-affiliate.ts
================
export interface AffiliateTradeHistoryItem {
tradeTime: number; // Trade time (13-digit timestamp)
tradeType: string; // Trading type (e.g., "SPOT")
tradeCurrency: string; // Trade currency
tradeAmount: string; // Trade amount
tradeAmountU: string; // Trade amount in USDT
feeU: string; // Fee in USDT
commission: string; // Commission
currency: string; // Currency (e.g., "USDT")
}
⋮----
tradeTime: number; // Trade time (13-digit timestamp)
tradeType: string; // Trading type (e.g., "SPOT")
tradeCurrency: string; // Trade currency
tradeAmount: string; // Trade amount
tradeAmountU: string; // Trade amount in USDT
feeU: string; // Fee in USDT
commission: string; // Commission
currency: string; // Currency (e.g., "USDT")
⋮----
export interface AffiliateTradeHistory {
currentPage: number; // Current page number
pageSize: number; // Page size
totalNum: number; // Total number of records
totalPage: number; // Total number of pages
items: AffiliateTradeHistoryItem[]; // Array of trade history items
}
⋮----
currentPage: number; // Current page number
pageSize: number; // Page size
totalNum: number; // Total number of records
totalPage: number; // Total number of pages
items: AffiliateTradeHistoryItem[]; // Array of trade history items
⋮----
export interface AffiliateCommissionItem {
siteType: string; // Source site of the commission
rebateType: 1 | 2; // Rebate type
payoutTime: number; // Commission payout time (T+1 settlement), 13-digit timestamp (UTC+8)
periodStartTime: number; // Start time of commission calculation period, 13-digit timestamp
periodEndTime: number; // End time of commission calculation period, 13-digit timestamp
status: 1 | 2 | 3 | 4; // Payout status
takerVolume: string; // Invitee's taker trading volume
makerVolume: string; // Invitee's maker trading volume
commission: string; // Total rebate contributed by the invitee
currency: string; // Denomination unit for trading volume/amount (USDT or USDC)
}
⋮----
siteType: string; // Source site of the commission
rebateType: 1 | 2; // Rebate type
payoutTime: number; // Commission payout time (T+1 settlement), 13-digit timestamp (UTC+8)
periodStartTime: number; // Start time of commission calculation period, 13-digit timestamp
periodEndTime: number; // End time of commission calculation period, 13-digit timestamp
status: 1 | 2 | 3 | 4; // Payout status
takerVolume: string; // Invitee's taker trading volume
makerVolume: string; // Invitee's maker trading volume
commission: string; // Total rebate contributed by the invitee
currency: string; // Denomination unit for trading volume/amount (USDT or USDC)
⋮----
export interface AffiliateInviteeItem {
uid: string; // UID of the invitee
nickName: string; // Nickname (partially hidden)
referralCode: string; // Referral code used for registration
country: string; // Country
registrationTime: number; // Registration time (13-digit timestamp)
completedKyc: boolean; // Whether KYC is completed
completedFirstDeposit: boolean; // Whether first deposit is completed
completedFirstTrade: boolean; // Whether first trade is completed
past7dFees: string; // Fees in the past 7 days
past7dCommission: string; // Commission in the past 7 days
totalCommission: string; // Total commission
myCommissionRate: string; // My commission rate (percentage)
cashbackRate: string; // Cashback rate (percentage)
currency: string; // Currency (e.g., "USDT")
}
⋮----
uid: string; // UID of the invitee
nickName: string; // Nickname (partially hidden)
referralCode: string; // Referral code used for registration
country: string; // Country
registrationTime: number; // Registration time (13-digit timestamp)
completedKyc: boolean; // Whether KYC is completed
completedFirstDeposit: boolean; // Whether first deposit is completed
completedFirstTrade: boolean; // Whether first trade is completed
past7dFees: string; // Fees in the past 7 days
past7dCommission: string; // Commission in the past 7 days
totalCommission: string; // Total commission
myCommissionRate: string; // My commission rate (percentage)
cashbackRate: string; // Cashback rate (percentage)
currency: string; // Currency (e.g., "USDT")
⋮----
export interface AffiliateInvitees {
currentPage: number; // Current page number
pageSize: number; // Page size
totalNum: number; // Total number of records
totalPage: number; // Total number of pages
items: AffiliateInviteeItem[]; // Array of invited user items
}
⋮----
currentPage: number; // Current page number
pageSize: number; // Page size
totalNum: number; // Total number of records
totalPage: number; // Total number of pages
items: AffiliateInviteeItem[]; // Array of invited user items
⋮----
export interface AffiliateTransactionItem {
uid: string; // The uid of the invitee
tradeTime: number; // Trade time (13-digit timestamp)
tradeType: 'SPOT' | 'FEATURE'; // Trade type
tradeCurrency: string; // Trade currency
tradeAmount: string; // Trade amount
tradeAmountU: string; // Trade amount transfer to U(USDT or usdt)
feeU: string; // Fee transfer to U(USDT or usdt)
commission: string; // Trade commission
currency: 'USDT' | 'USDC'; // Transaction volume or amount converted to U
}
⋮----
uid: string; // The uid of the invitee
tradeTime: number; // Trade time (13-digit timestamp)
tradeType: 'SPOT' | 'FEATURE'; // Trade type
tradeCurrency: string; // Trade currency
tradeAmount: string; // Trade amount
tradeAmountU: string; // Trade amount transfer to U(USDT or usdt)
feeU: string; // Fee transfer to U(USDT or usdt)
commission: string; // Trade commission
currency: 'USDT' | 'USDC'; // Transaction volume or amount converted to U
⋮----
export interface AffiliateTransaction {
items: AffiliateTransactionItem[]; // Array of transaction items
lastId: string; // The offset ID for pagination
}
⋮----
items: AffiliateTransactionItem[]; // Array of transaction items
lastId: string; // The offset ID for pagination
⋮----
export interface KuminingItem {
uid: string; // User Id
goodsName: string; // Product Name
amount: string; // Product amount
currency: string; // The currency
lastId: string; // Last Id
payTime: number; // Trade time
}
⋮----
uid: string; // User Id
goodsName: string; // Product Name
amount: string; // Product amount
currency: string; // The currency
lastId: string; // Last Id
payTime: number; // Trade time
================
File: src/types/websockets/ws-general.ts
================
import { AxiosRequestConfig } from 'axios';
⋮----
import { RestClientOptions } from '../../lib/requestUtils.js';
⋮----
/** General configuration for the WebsocketClient */
export interface WSClientConfigurableOptions {
/** Your API key */
apiKey?: string;
/** Your API secret */
apiSecret?: string;
/** Your API passphrase (can be anything) that you included when creating this API key */
apiPassphrase?: string;
/** Define a recv window when preparing a private websocket signature. This is in milliseconds, so 5000 == 5 seconds */
recvWindow?: number;
/** How often to check if the connection is alive */
pingInterval?: number;
/** How long to wait for a pong (heartbeat reply) before assuming the connection is dead */
pongTimeout?: number;
/** Delay in milliseconds before respawning the connection */
reconnectTimeout?: number;
restOptions?: RestClientOptions;
requestOptions?: AxiosRequestConfig;
wsOptions?: {
protocols?: string[];
agent?: any;
};
wsUrl?: string;
/**
* Allows you to provide a custom "signMessage" function, e.g. to use node's much faster createHmac method
*
* Look in the examples folder for a demonstration on using node's createHmac instead.
*/
customSignMessageFn?: (message: string, secret: string) => Promise;
/**
* If you authenticated the WS API before, automatically try to re-authenticate the WS API if you're disconnected/reconnected for any reason.
*/
reauthWSAPIOnReconnect?: boolean;
}
⋮----
/** Your API key */
⋮----
/** Your API secret */
⋮----
/** Your API passphrase (can be anything) that you included when creating this API key */
⋮----
/** Define a recv window when preparing a private websocket signature. This is in milliseconds, so 5000 == 5 seconds */
⋮----
/** How often to check if the connection is alive */
⋮----
/** How long to wait for a pong (heartbeat reply) before assuming the connection is dead */
⋮----
/** Delay in milliseconds before respawning the connection */
⋮----
/**
* Allows you to provide a custom "signMessage" function, e.g. to use node's much faster createHmac method
*
* Look in the examples folder for a demonstration on using node's createHmac instead.
*/
⋮----
/**
* If you authenticated the WS API before, automatically try to re-authenticate the WS API if you're disconnected/reconnected for any reason.
*/
⋮----
/**
* WS configuration that's always defined, regardless of user configuration
* (usually comes from defaults if there's no user-provided values)
*/
export interface WebsocketClientOptions extends WSClientConfigurableOptions {
pingInterval: number;
pongTimeout: number;
reconnectTimeout: number;
recvWindow: number;
/**
* If true, require a "receipt" that the connection is ready for use (e.g. a specific event type)
*/
requireConnectionReadyConfirmation: boolean;
authPrivateConnectionsOnConnect: boolean;
authPrivateRequests: boolean;
reauthWSAPIOnReconnect: boolean;
/**
* Whether to use native WebSocket ping/pong frames for heartbeats
*/
useNativeHeartbeats: boolean;
}
⋮----
/**
* If true, require a "receipt" that the connection is ready for use (e.g. a specific event type)
*/
⋮----
/**
* Whether to use native WebSocket ping/pong frames for heartbeats
*/
⋮----
export type WsMarket = 'spot' | 'futures';
⋮----
export type WsEventInternalSrc = 'event' | 'function';
================
File: src/UnifiedAPIClient.ts
================
import { AxiosRequestConfig } from 'axios';
⋮----
import { BaseRestClient } from './lib/BaseRestClient.js';
import {
REST_CLIENT_TYPE_ENUM,
RestClientOptions,
RestClientType,
} from './lib/requestUtils.js';
import {
GetAnnouncementsRequestUTA,
GetCurrencyRequestUTA,
GetCurrentFundingRateRequestUTA,
GetHistoryFundingRateRequestUTA,
GetKlinesRequestUTA,
GetOrderBookRequestUTA,
GetServiceStatusRequestUTA,
GetSymbolRequestUTA,
GetTickerRequestUTA,
GetTradesRequestUTA,
} from './types/request/uta-types.js';
import { APISuccessResponse } from './types/response/shared.types.js';
import {
GetAnnouncementsResponseUTA,
GetCrossMarginConfigResponseUTA,
GetCurrencyResponseUTA,
GetCurrentFundingRateResponseUTA,
GetHistoryFundingRateResponseUTA,
GetKlinesResponseUTA,
GetOrderBookResponseUTA,
GetServiceStatusResponseUTA,
GetSymbolResponseUTA,
GetTickerResponseUTA,
GetTradesResponseUTA,
} from './types/response/uta-types.js';
⋮----
/**
* Unified Trading Account Client
*
* This client provides access to the Unified Trading Account API endpoints
* that unify market data access across Spot, Futures, and Margin trading.
*/
export class UnifiedAPIClient extends BaseRestClient
⋮----
constructor(
restClientOptions: RestClientOptions = {},
requestOptions: AxiosRequestConfig = {},
)
⋮----
getClientType(): RestClientType
⋮----
/**
*
* REST - Unified Trading Account - Market Data
*
*/
⋮----
/**
* Get Announcements
* This interface can obtain the latest news announcements, and the default
* page search is for announcements within a month.
*/
getAnnouncements(
params?: GetAnnouncementsRequestUTA,
): Promise>
⋮----
/**
* Get Currency
* Request the currency details of a specified currency via this endpoint.
*/
getCurrency(
params?: GetCurrencyRequestUTA,
): Promise>
⋮----
/**
* Get Symbol
* Request a list of available currency pairs for trading via this endpoint.
*/
getSymbols(
params: GetSymbolRequestUTA,
): Promise>
⋮----
/**
* Get Ticker
* Request market tickers for the trading pairs in the market (including 24h volume).
*/
getTickers(
params: GetTickerRequestUTA,
): Promise>
⋮----
/**
* Get Trades
* Request via this endpoint to get the latest 100 public trades of the specified symbol.
*/
getTrades(
params: GetTradesRequestUTA,
): Promise>
⋮----
/**
* Get OrderBook
* Query order book depth information (aggregated by price).
*/
getOrderBook(
params: GetOrderBookRequestUTA,
): Promise>
⋮----
/**
* Get Klines
* Get the Kline of the symbol. Data are returned in grouped buckets based on requested type.
*/
getKlines(
params: GetKlinesRequestUTA,
): Promise>
⋮----
/**
* Get Current Funding Rate
* Get current Futures funding fee rate.
*/
getCurrentFundingRate(
params: GetCurrentFundingRateRequestUTA,
): Promise>
⋮----
/**
* Get History Funding Rate
* Query the Futures funding rate at each settlement time point within a certain time range.
*/
getHistoryFundingRate(
params: GetHistoryFundingRateRequestUTA,
): Promise>
⋮----
/**
* Get Cross Margin Config
* Request the configure info of the 'spot cross margin' via this endpoint.
*/
getCrossMarginConfig(): Promise<
APISuccessResponse
> {
return this.get('api/ua/v1/market/cross-config');
⋮----
/**
* Get Service Status
* Get the service status.
*/
getServiceStatus(
params: GetServiceStatusRequestUTA,
): Promise>
================
File: .eslintrc.cjs
================
// 'no-unused-vars': ['warn'],
================
File: src/lib/websocket/WsStore.ts
================
import WebSocket from 'isomorphic-ws';
⋮----
import { DefaultLogger } from './logger.js';
import {
DeferredPromise,
WSConnectedResult,
WsConnectionStateEnum,
WsStoredState,
} from './WsStore.types.js';
⋮----
/**
* Simple comparison of two objects, recursive for nested objects. Adoped from OKX SDK.
*/
export function isDeepObjectMatch(object1: any, object2: any): boolean
⋮----
// console.log('not same key count', { keys1, keys2 });
// not the same amount of keys or keys don't match
⋮----
// console.log('not same key names: ', { keys1, keys2 });
⋮----
type DeferredPromiseRef =
(typeof DEFERRED_PROMISE_REF)[keyof typeof DEFERRED_PROMISE_REF];
⋮----
export class WsStore<
WsKey extends string,
⋮----
constructor(logger: DefaultLogger)
⋮----
/** Get WS stored state for key, optionally create if missing */
get(
key: WsKey,
createIfMissing?: true,
): WsStoredState;
⋮----
get(
key: WsKey,
createIfMissing?: false,
): WsStoredState | undefined;
⋮----
get(
key: WsKey,
createIfMissing?: boolean,
): WsStoredState | undefined
⋮----
getKeys(): WsKey[]
⋮----
create(key: WsKey): WsStoredState | undefined
⋮----
delete(key: WsKey): void
⋮----
// TODO: should we allow this at all? Perhaps block this from happening...
⋮----
/* connection websocket */
⋮----
hasExistingActiveConnection(key: WsKey): boolean
⋮----
getWs(key: WsKey): WebSocket | undefined
⋮----
setWs(key: WsKey, wsConnection: WebSocket): WebSocket
⋮----
/**
* deferred promises
*/
⋮----
getDeferredPromise(
wsKey: WsKey,
promiseRef: string | DeferredPromiseRef,
): DeferredPromise | undefined
⋮----
createDeferredPromise(
wsKey: WsKey,
promiseRef: string | DeferredPromiseRef,
throwIfExists: boolean,
): DeferredPromise
⋮----
// console.log('existing promise');
⋮----
// console.log('create promise');
⋮----
// TODO: Once stable, use Promise.withResolvers in future
⋮----
resolveDeferredPromise(
wsKey: WsKey,
promiseRef: string | DeferredPromiseRef,
value: unknown,
removeAfter: boolean,
): void
⋮----
rejectDeferredPromise(
wsKey: WsKey,
promiseRef: string | DeferredPromiseRef,
value: unknown,
removeAfter: boolean,
): void
⋮----
removeDeferredPromise(
wsKey: WsKey,
promiseRef: string | DeferredPromiseRef,
): void
⋮----
// Just in case it's pending
⋮----
rejectAllDeferredPromises(wsKey: WsKey, reason: string): void
⋮----
// Skip reserved keys, such as the connection promise
⋮----
/** Get promise designed to track a connection attempt in progress. Resolves once connected. */
getConnectionInProgressPromise(
wsKey: WsKey,
): DeferredPromise | undefined
⋮----
getAuthenticationInProgressPromise(
wsKey: WsKey,
): DeferredPromise
⋮----
createAuthenticationInProgressPromise(
wsKey: WsKey,
throwIfExists: boolean,
): DeferredPromise
⋮----
getTopicsAsArray(key: WsKey): TWSTopicSubscribeEventArgs[]
⋮----
getTopicsByKey(): Record>
⋮----
/**
* Find matching "topic" request from the store
* @param key
* @param topic
* @returns
*/
getMatchingTopic(key: WsKey, topic: TWSTopicSubscribeEventArgs)
⋮----
addTopic(key: WsKey, topic: TWSTopicSubscribeEventArgs)
⋮----
// Check for duplicate topic. If already tracked, don't store this one
⋮----
deleteTopic(key: WsKey, topic: TWSTopicSubscribeEventArgs)
⋮----
// Check if we're subscribed to a topic like this
================
File: src/types/request/futures.types.ts
================
/**
* REST - ACCOUNT - BASIC INFO
* Get Account Ledgers - Futures
*/
⋮----
export interface GetTransactionsRequest {
startAt?: number;
endAt?: number;
type?:
| 'RealisedPNL'
| 'Deposit'
| 'Withdrawal'
| 'Transferin'
| 'TransferOut';
offset?: number;
maxCount?: number;
currency?: string;
forward?: boolean;
}
⋮----
/**
* REST - ACCOUNT - SUBACCOUNT API
*/
⋮----
export interface GetSubAPIsRequest {
apiKey?: string;
subName: string;
}
⋮----
export interface CreateSubAPIRequest {
subName: string;
passphrase: string;
remark: string;
permission?: string;
ipWhitelist?: string;
expire?: string;
}
⋮----
export interface UpdateSubAPIRequest {
subName: string;
apiKey: string;
passphrase: string;
permission?: string;
ipWhitelist?: string;
expire?: string;
}
⋮----
export interface DeleteSubAPIRequest {
apiKey: string;
passphrase: string;
subName: string;
}
⋮----
/**
* REST - FUNDING - FUNDING OVERVIEW
*/
⋮----
/**
* REST - FUNDING - TRANSFER
*/
⋮----
export interface SubmitTransfer {
amount: number;
currency: string;
recAccountType: 'MAIN' | 'TRADE';
}
⋮----
export interface GetTransfersRequest {
startAt?: number;
endAt?: number;
status?: 'PROCESSING' | 'SUCCESS' | 'FAILURE';
queryStatus?: 'PROCESSING' | 'SUCCESS' | 'FAILURE'[];
currency?: string;
currentPage?: number;
pageSize?: number;
}
⋮----
/**
*
* Futures Market Data
*
*/
⋮----
export interface GetKlinesRequest {
symbol: string;
granularity: number;
from?: number;
to?: number;
}
⋮----
export interface GetInterestRatesRequest {
symbol: string;
startAt?: number;
endAt?: number;
reverse?: boolean;
offset?: number;
forward?: boolean;
maxCount?: number;
}
⋮----
/**
*
***********
* Account
***********
*
*/
⋮----
/**
*
* Orders
*
*/
⋮----
export interface Order {
clientOid: string;
side: 'buy' | 'sell';
symbol: string;
leverage?: number;
type?: 'limit' | 'market';
remark?: string;
stop?: 'down' | 'up';
stopPriceType?: 'TP' | 'MP' | 'IP';
stopPrice?: string;
reduceOnly?: boolean;
closeOrder?: boolean;
forceHold?: boolean;
stp?: 'CN' | 'CO' | 'CB';
marginMode?: 'ISOLATED' | 'CROSS';
price?: string;
size?: number;
qty?: string;
valueQty?: string;
timeInForce?: 'GTC' | 'IOC';
postOnly?: boolean;
hidden?: boolean;
iceberg?: boolean;
visibleSize?: string;
positionSide?: 'BOTH' | 'LONG' | 'SHORT';
}
⋮----
export interface SLTPOrder {
clientOid: string;
side: 'buy' | 'sell';
symbol: string;
leverage?: number;
type: 'limit' | 'market';
remark?: string;
triggerStopUpPrice?: string;
stopPriceType?: 'TP' | 'MP' | 'IP';
triggerStopDownPrice?: string;
reduceOnly?: boolean;
closeOrder?: boolean;
forceHold?: boolean;
stp?: 'CN' | 'CO' | 'CB';
marginMode?: 'ISOLATED' | 'CROSS';
price?: string;
size?: number;
qty?: string;
valueQty?: string;
timeInForce?: 'GTC' | 'IOC';
postOnly?: boolean;
hidden?: boolean;
iceberg?: boolean;
visibleSize?: string;
}
export interface GetOrdersRequest {
status: 'active' | 'done';
symbol?: string;
side: 'buy' | 'sell';
type: 'limit' | 'market' | 'limit_stop' | 'market_stop';
startAt?: number;
endAt?: number;
currentPage?: number;
pageSize?: number;
}
⋮----
export interface GetStopOrdersRequest {
symbol?: string;
side?: 'buy' | 'sell';
type?: 'limit' | 'market';
startAt?: number;
endAt?: number;
currentPage?: number;
pageSize?: number;
}
⋮----
// Note: Either orderIdsList or clientOidsList must be provided, but not both.
// When both are provided, orderIdsList takes precedence.
export interface BatchCancelOrdersRequest {
orderIdsList?: string[];
clientOidsList?: {
symbol: string;
clientOid: string;
}[];
}
⋮----
/**
*
* Futures Fills
*
*/
⋮----
export interface AccountFillsRequest {
orderId?: string;
symbol?: string;
side?: 'buy' | 'sell';
type?: 'limit' | 'market' | 'limit_stop' | 'market_stop';
startAt?: number;
endAt?: number;
currentPage?: number;
pageSize?: number;
tradeTypes?: string;
}
⋮----
/**
*
* Futures Positions
*
*/
⋮----
export interface MaxOpenSizeRequest {
symbol: string;
price: string;
leverage: number;
}
⋮----
/**
*
* Futures risk limit
*
*/
⋮----
/**
*
* Futures funding fees
*
*/
⋮----
export interface GetFundingRatesRequest {
symbol: string;
from: number;
to: number;
}
⋮----
export interface GetFundingHistoryRequest {
symbol: string;
from?: number;
to?: number;
reverse?: boolean;
offset?: number;
forward?: boolean;
maxCount?: number;
}
⋮----
/**
*
* Futures Copy Trading
*
*/
⋮----
export interface CopyTradeOrderRequest {
clientOid: string;
side: 'buy' | 'sell';
symbol: string;
type: 'limit' | 'market';
leverage?: number;
remark?: string;
stop?: 'up' | 'down';
stopPriceType?: 'TP' | 'MP' | 'IP';
stopPrice?: string;
reduceOnly?: boolean;
closeOrder?: boolean;
forceHold?: boolean;
marginMode?: 'ISOLATED' | 'CROSS';
positionSide?: 'BOTH' | 'LONG' | 'SHORT';
price?: string;
size: number;
timeInForce?: 'GTC' | 'IOC';
postOnly?: boolean;
hidden?: boolean;
iceberg?: boolean;
visibleSize?: string;
}
⋮----
export interface CopyTradeSLTPOrderRequest extends CopyTradeOrderRequest {
triggerStopUpPrice?: string; // Take profit price
triggerStopDownPrice?: string; // Stop loss price
stopPriceType?: 'TP' | 'MP' | 'IP';
}
⋮----
triggerStopUpPrice?: string; // Take profit price
triggerStopDownPrice?: string; // Stop loss price
⋮----
/**
* Switch Margin Mode (Copy Trading)
*/
export interface CopyTradeSwitchMarginModeRequest {
symbol: string;
marginMode: 'ISOLATED' | 'CROSS';
}
⋮----
/**
* Modify Cross Margin Leverage (Copy Trading)
*/
export interface CopyTradeChangeCrossMarginLeverageRequest {
symbol: string;
leverage: string;
}
⋮----
/**
* Get Cross Margin Requirement (Copy Trading)
*/
export interface CopyTradeGetCrossMarginRequirementRequest {
symbol: string;
positionValue: string;
leverage?: string;
}
⋮----
/**
* Switch Position Mode (Copy Trading)
*/
export interface CopyTradeSwitchPositionModeRequest {
positionMode: '0' | '1'; // 0 = one-way mode, 1 = hedge mode
}
⋮----
positionMode: '0' | '1'; // 0 = one-way mode, 1 = hedge mode
================
File: src/types/response/spot-funding.ts
================
/**
*
***********
* Funding
***********
*
*/
⋮----
export interface MarginAccountBalance {
currency: string;
totalBalance: string;
availableBalance: string;
holdBalance: string;
liability: string;
maxBorrowSize: string;
}
⋮----
export interface MarginAccountDetail {
currency: string;
total: string;
available: string;
hold: string;
liability: string;
liabilityPrincipal: string;
liabilityInterest: string;
maxBorrowSize: string;
borrowEnabled: boolean;
transferInEnabled: boolean;
}
⋮----
export interface MarginBalance {
totalAssetOfQuoteCurrency: string;
totalLiabilityOfQuoteCurrency: string;
debtRatio: string;
status: 'EFFECTIVE' | 'BANKRUPTCY' | 'LIQUIDATION' | 'REPAY' | 'BORROW';
accounts: MarginAccountDetail[];
}
export interface IsolatedMarginAssetDetail {
symbol: string;
debtRatio: string;
status: 'EFFECTIVE' | 'BANKRUPTCY' | 'LIQUIDATION' | 'REPAY' | 'BORROW';
baseAsset: MarginAccountDetail;
quoteAsset: MarginAccountDetail;
}
⋮----
export interface IsolatedMarginBalance {
totalAssetOfQuoteCurrency: string;
totalLiabilityOfQuoteCurrency: string;
timestamp: number;
assets: IsolatedMarginAssetDetail[];
}
⋮----
/**
*
* Deposit
*
*/
⋮----
export interface DepositAddress {
address: string;
memo: string;
chain: string;
}
⋮----
export type DepositAddressV2 = DepositAddress & {
contractAddress: string;
};
⋮----
export interface DepositAddressV3 {
address: string;
memo: string;
chainId: string;
to: 'MAIN' | 'TRADE'; // main (funding account), trade (spot trading account)
expirationDate: number;
currency: string;
contractAddress: string;
chainName: string;
}
⋮----
to: 'MAIN' | 'TRADE'; // main (funding account), trade (spot trading account)
⋮----
export interface HistoricalDepositItem {
currency: string;
createAt: number;
amount: string;
walletTxId: string;
isInner: boolean;
status: 'PROCESSING' | 'SUCCESS' | 'FAILURE';
}
export interface DepositItem {
currency?: string;
chain?: string;
status?: 'PROCESSING' | 'SUCCESS' | 'FAILURE';
address?: string;
memo?: string;
isInner?: boolean;
amount?: string;
fee?: string;
walletTxId?: string | null;
createdAt?: number;
updatedAt?: number;
remark?: string;
arrears?: boolean;
}
⋮----
export interface Deposits {
currentPage: number;
pageSize: number;
totalNum: number;
totalPage: number;
items: DepositItem[];
}
⋮----
export interface V1HistoricalDeposits {
currentPage: number;
pageSize: number;
totalNum: number;
totalPage: number;
items: HistoricalDepositItem[];
}
⋮----
export interface CreateDepositAddressV3Response {
address: string;
memo: string | null;
chainName: string;
chainId: string;
to: string;
currency: string;
expirationDate?: string;
}
⋮----
/**
*
* Withdrawals
*
*/
⋮----
interface DetailedWithdrawal {
id: string;
address: string;
memo: string;
currency: string;
chain: string;
amount: string;
fee: string;
walletTxId: string;
isInner: boolean;
status: 'PROCESSING' | 'WALLET_PROCESSING' | 'SUCCESS' | 'FAILURE';
remark: string;
createdAt: number;
updatedAt: number;
}
⋮----
interface HistoricalWithdrawal {
currency: string;
createAt: number;
amount: string;
address: string;
walletTxId: string;
isInner: boolean;
status: 'PROCESSING' | 'SUCCESS' | 'FAILURE';
}
⋮----
export interface Withdrawals {
currentPage: number;
pageSize: number;
totalNum: number;
totalPage: number;
items: DetailedWithdrawal[];
}
⋮----
export interface HistoricalWithdrawalsV1 {
currentPage: number;
pageSize: number;
totalNum: number;
totalPage: number;
items: HistoricalWithdrawal[];
}
⋮----
export interface WithdrawalQuotas {
currency: string;
limitBTCAmount: string;
usedBTCAmount: string;
quotaCurrency: string;
limitQuotaCurrencyAmount: string;
usedQuotaCurrencyAmount: string;
remainAmount: string;
availableAmount: string;
withdrawMinFee: string;
innerWithdrawMinFee: string;
withdrawMinSize: string;
isWithdrawEnabled: boolean;
precision: number;
chain: string;
reason: string | null;
lockedAmount: string;
}
⋮----
export interface WithdrawalById {
id: string;
uid: number;
currency: string;
chainId: string;
chainName: string;
currencyName: string;
status: string;
failureReason: string;
failureReasonMsg: string | null;
address: string;
memo: string;
isInner: boolean;
amount: string;
fee: string;
walletTxId: string | null;
addressRemark: string | null;
remark: string;
createdAt: number;
cancelType: string;
taxes: string | null;
taxDescription: string | null;
returnStatus: string;
returnAmount: string | null;
returnCurrency: string;
}
⋮----
/**
*
* Transfer
*
*/
⋮----
export interface TransferableFunds {
currency: string; // Currency
balance: string; // Total funds in an account.
available: string; // Funds available to withdraw or trade.
holds: string; // Funds on hold (not available for use).
transferable: string; // Funds available to transfer.
}
⋮----
currency: string; // Currency
balance: string; // Total funds in an account.
available: string; // Funds available to withdraw or trade.
holds: string; // Funds on hold (not available for use).
transferable: string; // Funds available to transfer.
================
File: src/types/response/spot-margin-trading.ts
================
/**
*
***********
* Margin Trading
***********
*
*/
⋮----
/**
*
* Margin HF trade
*
*/
⋮----
export interface HFMarginOrder {
id: string;
clientOid: string;
symbol: string;
opType: string;
type: 'limit' | 'market';
side: 'buy' | 'sell';
price: string;
size: string;
funds: string;
dealSize: string;
dealFunds: string;
remainSize: string;
remainFunds: string;
cancelledSize: string;
cancelledFunds: string;
fee: string;
feeCurrency: string;
stp?: 'DC' | 'CO' | 'CN' | 'CB' | null;
stop?: string | null;
stopTriggered: boolean;
stopPrice: string;
timeInForce: 'GTC' | 'GTT' | 'IOC' | 'FOK';
postOnly: boolean;
hidden: boolean;
iceberg: boolean;
visibleSize: string;
cancelAfter: number;
channel: string;
remark?: string | null;
tags?: string | null;
cancelExist: boolean;
tradeType: string;
inOrderBook: boolean;
tax: string;
active: boolean;
createdAt: number;
lastUpdatedAt: number;
cancelReason?: number;
}
⋮----
/** @deprecated not used anymore **/
export type HFMarginFilledOrder = HFMarginOrder & {
inOrderBook: boolean;
active: boolean;
};
⋮----
export interface HFMarginTransactionRecord {
id: number;
symbol: string;
tradeId: number;
orderId: string;
counterOrderId: string;
side: 'buy' | 'sell';
liquidity: 'taker' | 'maker';
forceTaker: boolean;
price: string;
size: string;
funds: string;
fee: string;
feeRate: string;
feeCurrency: string;
stop: string;
tradeType: 'TRADE' | 'MARGIN_TRADE';
tax: string;
taxRate: string;
type: 'limit' | 'market';
createdAt: number;
}
⋮----
/**
*
* Orders
*
*/
⋮----
export interface SubmitMarginOrderResponse {
orderId: string; // An order Id is returned once an order is successfully submitted.
borrowSize?: number; // Borrowed amount. The field is returned only after placing the order under the mode of Auto-Borrow.
loanApplyId?: string; // ID of the borrowing response. The field is returned only after placing the order under the mode of Auto-Borrow.
}
⋮----
orderId: string; // An order Id is returned once an order is successfully submitted.
borrowSize?: number; // Borrowed amount. The field is returned only after placing the order under the mode of Auto-Borrow.
loanApplyId?: string; // ID of the borrowing response. The field is returned only after placing the order under the mode of Auto-Borrow.
⋮----
/**
*
* Margin info
*
*/
⋮----
export interface MarginActivePairsV3 {
symbol: string;
name: string;
enableTrading: boolean;
market: string;
baseCurrency: string;
quoteCurrency: string;
baseIncrement: string;
baseMinSize: string;
baseMaxSize: string;
quoteIncrement: string;
quoteMinSize: string;
quoteMaxSize: string;
priceIncrement: string;
feeCurrency: string;
priceLimitRate: string;
minFunds: string;
}
⋮----
export interface MarginLevTokenInfo {
currency: string; // currency
netAsset: number; // Net worth
targetLeverage: string; // Target leverage
actualLeverage: string; // Actual leverage
issuedSize: string; // The amount of currency issued
basket: string; // basket information
}
⋮----
currency: string; // currency
netAsset: number; // Net worth
targetLeverage: string; // Target leverage
actualLeverage: string; // Actual leverage
issuedSize: string; // The amount of currency issued
basket: string; // basket information
⋮----
export interface MarginMarkPrice {
symbol: string; // symbol
timePoint: number; // Time (millisecond)
value: number; // Mark price
}
⋮----
symbol: string; // symbol
timePoint: number; // Time (millisecond)
value: number; // Mark price
⋮----
export interface MarginConfigInfo {
currencyList: string[]; // Available currencies for margin trade
warningDebtRatio: string; // The warning debt ratio of the forced liquidation
liqDebtRatio: string; // The debt ratio of the forced liquidation
maxLeverage: number; // Max leverage available
}
⋮----
currencyList: string[]; // Available currencies for margin trade
warningDebtRatio: string; // The warning debt ratio of the forced liquidation
liqDebtRatio: string; // The debt ratio of the forced liquidation
maxLeverage: number; // Max leverage available
⋮----
export interface MarginRiskLimit {
timestamp: number;
currency?: string;
symbol?: string;
borrowMaxAmount?: string;
buyMaxAmount?: string;
holdMaxAmount?: string;
borrowCoefficient?: string;
marginCoefficient?: string;
precision?: number;
borrowMinAmount?: string;
borrowMinUnit?: string;
borrowEnabled?: boolean;
baseMaxBorrowAmount?: string;
quoteMaxBorrowAmount?: string;
baseMaxBuyAmount?: string;
quoteMaxBuyAmount?: string;
baseMaxHoldAmount?: string;
quoteMaxHoldAmount?: string;
basePrecision?: number;
quotePrecision?: number;
baseBorrowCoefficient?: string;
quoteBorrowCoefficient?: string;
baseMarginCoefficient?: string;
quoteMarginCoefficient?: string;
baseBorrowMinAmount?: string | null;
quoteBorrowMinAmount?: string | null;
baseBorrowMinUnit?: string | null;
quoteBorrowMinUnit?: string | null;
baseBorrowEnabled?: boolean;
quoteBorrowEnabled?: boolean;
}
⋮----
/**
*
* Isolated Margin
*
*/
⋮----
export interface IsolatedMarginSymbolsConfig {
symbol: string;
symbolName: string;
baseCurrency: string;
quoteCurrency: string;
maxLeverage: number;
flDebtRatio: string;
tradeEnable: boolean;
autoRenewMaxDebtRatio: string;
baseBorrowEnable: boolean;
quoteBorrowEnable: boolean;
baseTransferInEnable: boolean;
quoteTransferInEnable: boolean;
baseBorrowCoefficient: string;
quoteBorrowCoefficient: string;
}
export interface AssetDetail {
currency: string; // Coin type Code
totalBalance: string; // Current coin type asset amount
holdBalance: string; // Current coin type frozen
availableBalance: string; // The available balance
liability: string; // Liability
interest: string; // Interest
borrowableAmount: string; // Borrowable amount
}
⋮----
currency: string; // Coin type Code
totalBalance: string; // Current coin type asset amount
holdBalance: string; // Current coin type frozen
availableBalance: string; // The available balance
liability: string; // Liability
interest: string; // Interest
borrowableAmount: string; // Borrowable amount
⋮----
export interface AssetInfo {
symbol: string; // Trading pairs, with each trading pair indicating a position
status: string; // The position status
debtRatio: string; // Debt ratio
baseAsset: AssetDetail;
quoteAsset: AssetDetail;
}
⋮----
symbol: string; // Trading pairs, with each trading pair indicating a position
status: string; // The position status
debtRatio: string; // Debt ratio
⋮----
export interface IsolatedMarginAccountInfo {
totalConversionBalance: string; // The total balance of the isolated margin account (in the specified coin)
liabilityConversionBalance: string; // Total liabilities of the isolated margin account (in the specified coin)
assets: AssetInfo[];
}
⋮----
totalConversionBalance: string; // The total balance of the isolated margin account (in the specified coin)
liabilityConversionBalance: string; // Total liabilities of the isolated margin account (in the specified coin)
⋮----
export interface SingleIsolatedMarginAccountInfo {
symbol: string; // Trading pair
status: string; // The position status
debtRatio: string; // Debt ratio
baseAsset: AssetDetail;
quoteAsset: AssetDetail;
}
⋮----
symbol: string; // Trading pair
status: string; // The position status
debtRatio: string; // Debt ratio
⋮----
/**
*
* Margin trading(v3)
*
*/
⋮----
export interface MarginSubmitOrderV3Response {
orderId: string;
clientOid: string;
borrowSize: string;
loanApplyId: string;
}
export interface MarginOrderV3 {
timestamp: number;
orderNo: string; // Borrow order number
actualSize: number; // Actual borrowed amount
}
⋮----
orderNo: string; // Borrow order number
actualSize: number; // Actual borrowed amount
⋮----
export interface MarginBorrowHistoryRecord {
orderNo: string; // Borrow order ID
symbol: string; // Isolated margin trading pair; empty for cross margin
currency: string; // Currency
size: number; // Initiated borrowing amount
actualSize: number; // Actual borrowed amount
status: string; // Status
createdTime: number; // Time of borrowing
}
⋮----
orderNo: string; // Borrow order ID
symbol: string; // Isolated margin trading pair; empty for cross margin
currency: string; // Currency
size: number; // Initiated borrowing amount
actualSize: number; // Actual borrowed amount
status: string; // Status
createdTime: number; // Time of borrowing
⋮----
export interface MarginBorrowHistoryV3 {
timestamp: number;
currentPage: number;
pageSize: number;
totalNum: number;
totalPage: number;
items: MarginBorrowHistoryRecord[];
}
export interface MarginRepayHistoryRecord {
orderNo: string;
symbol: string | null;
currency: string;
size: string;
principal: string;
interest: string;
status: string;
createdTime: number;
}
⋮----
export interface MarginRepayHistoryV3 {
timestamp: number;
currentPage: number;
pageSize: number;
totalNum: number;
totalPage: number;
items: MarginRepayHistoryRecord[];
}
⋮----
export interface MarginInterestRecord {
currency: string;
dayRatio: string;
interestAmount: string;
createdTime: number;
}
⋮----
export interface MarginInterestRecords {
timestamp: number;
currentPage: number;
pageSize: number;
totalNum: number;
totalPage: number;
items: MarginInterestRecord[];
}
⋮----
/**
*
* Lending market(v3)
*
*/
⋮----
interface LendingMarketItem {
currency: string; // Currency
purchaseEnable: boolean; // Support subscription
redeemEnable: boolean; // Support redemption
increment: string; // Increment precision for subscription and redemption
minPurchaseSize: string; // Minimum subscription amount
minInterestRate: string; // Minimum annualized interest rate
maxInterestRate: string; // Maximum annualized interest rate
interestIncrement: string; // Increment precision for interest; default is 0.0001
maxPurchaseSize: string; // Maximum subscription limit per user
marketInterestRate: string; // Latest market annualized interest rate
autoPurchaseEnable: boolean; // Auto-Subscribe enabled?: true: enable, false: disable
}
⋮----
currency: string; // Currency
purchaseEnable: boolean; // Support subscription
redeemEnable: boolean; // Support redemption
increment: string; // Increment precision for subscription and redemption
minPurchaseSize: string; // Minimum subscription amount
minInterestRate: string; // Minimum annualized interest rate
maxInterestRate: string; // Maximum annualized interest rate
interestIncrement: string; // Increment precision for interest; default is 0.0001
maxPurchaseSize: string; // Maximum subscription limit per user
marketInterestRate: string; // Latest market annualized interest rate
autoPurchaseEnable: boolean; // Auto-Subscribe enabled?: true: enable, false: disable
⋮----
export interface LendingCurrencyV3 {
currentPage: number;
pageSize: number;
totalNum: number;
totalPage: number;
items: LendingMarketItem[];
}
⋮----
export interface LendingOrder {
currency: string; // Currency
purchaseOrderNo: string; // Subscription order number
redeemOrderNo?: string; // Redemption order number
redeemAmount?: string; // Redemption amount
receiptAmount?: string; // Redeemed amount
purchaseAmount?: string; // Total subscription amount
lendAmount?: string; // Executed amount
interestRate?: string; // Target annualized interest rate
incomeAmount?: string; // Total earnings
applyTime: number; // Time of subscription or redemption
status: 'DONE' | 'PENDING'; // Status: DONE-completed; PENDING-settling
}
⋮----
currency: string; // Currency
purchaseOrderNo: string; // Subscription order number
redeemOrderNo?: string; // Redemption order number
redeemAmount?: string; // Redemption amount
receiptAmount?: string; // Redeemed amount
purchaseAmount?: string; // Total subscription amount
lendAmount?: string; // Executed amount
interestRate?: string; // Target annualized interest rate
incomeAmount?: string; // Total earnings
applyTime: number; // Time of subscription or redemption
status: 'DONE' | 'PENDING'; // Status: DONE-completed; PENDING-settling
⋮----
export interface LendingRedemption {
currentPage: number;
pageSize: number;
totalNum: number;
totalPage: number;
items: LendingOrder[];
}
⋮----
export interface BorrowInterestRateItem {
currency: string; // Currency
hourlyBorrowRate: string; // Hourly borrow rate
annualizedBorrowRate: string; // Annualized borrow rate
}
⋮----
currency: string; // Currency
hourlyBorrowRate: string; // Hourly borrow rate
annualizedBorrowRate: string; // Annualized borrow rate
⋮----
export interface BorrowInterestRate {
vipLevel: number; // The VIP level (0-12)
items: BorrowInterestRateItem[]; // Array of currency borrow rates
}
⋮----
vipLevel: number; // The VIP level (0-12)
items: BorrowInterestRateItem[]; // Array of currency borrow rates
⋮----
/**
* Margin Stop Order Response Types
*/
export interface MarginStopOrderResponse {
orderId: string; // The unique order ID generated by the trading system
clientOid: string; // The user self-defined order ID
}
⋮----
orderId: string; // The unique order ID generated by the trading system
clientOid: string; // The user self-defined order ID
⋮----
export interface CancelMarginOrdersResponse {
cancelledOrderIds: string[]; // Array of cancelled order IDs
}
⋮----
cancelledOrderIds: string[]; // Array of cancelled order IDs
⋮----
export interface MarginStopOrderItem {
id?: string; // Order ID
symbol?: string; // Symbol name
userId?: string; // User ID
status?: 'NEW' | 'TRIGGERED'; // Order status
type?: 'limit' | 'market'; // Order type
side?: 'buy' | 'sell'; // Transaction direction
price?: string; // Order price
size?: string; // Order quantity
funds?: string | null; // Order funds
stp?: string | null; // Self Trade Prevention
timeInForce?: 'GTC' | 'GTT' | 'IOC' | 'FOK'; // Time in force
cancelAfter?: number; // Cancel after seconds
postOnly?: boolean; // Post only
hidden?: boolean; // Hidden order
iceberg?: boolean; // Iceberg order
visibleSize?: string | null; // Visible size for iceberg orders
channel?: string; // Order source
clientOid?: string; // Client order ID
remark?: string | null; // Remarks
tags?: string | null; // Tag order source
relatedNo?: string | null; // Related number
orderTime?: number; // Order time (nanoseconds)
domainId?: string; // Domain ID
tradeSource?: 'USER' | 'MARGIN_SYSTEM'; // Trade source
tradeType?: 'TRADE' | 'MARGIN_TRADE' | 'MARGIN_ISOLATED_TRADE'; // Trade type
feeCurrency?: string; // Fee currency
takerFeeRate?: string; // Taker fee rate
makerFeeRate?: string; // Maker fee rate
createdAt?: number; // Order creation time
stop?: 'loss' | 'entry'; // Stop order type
stopTriggerTime?: number | null; // Stop trigger time
stopPrice?: string; // Stop price
limitPrice?: string | null; // Limit price
pop?: string | null; // POP
activateCondition?: string | null; // Activate condition
}
⋮----
id?: string; // Order ID
symbol?: string; // Symbol name
userId?: string; // User ID
status?: 'NEW' | 'TRIGGERED'; // Order status
type?: 'limit' | 'market'; // Order type
side?: 'buy' | 'sell'; // Transaction direction
price?: string; // Order price
size?: string; // Order quantity
funds?: string | null; // Order funds
stp?: string | null; // Self Trade Prevention
timeInForce?: 'GTC' | 'GTT' | 'IOC' | 'FOK'; // Time in force
cancelAfter?: number; // Cancel after seconds
postOnly?: boolean; // Post only
hidden?: boolean; // Hidden order
iceberg?: boolean; // Iceberg order
visibleSize?: string | null; // Visible size for iceberg orders
channel?: string; // Order source
clientOid?: string; // Client order ID
remark?: string | null; // Remarks
tags?: string | null; // Tag order source
relatedNo?: string | null; // Related number
orderTime?: number; // Order time (nanoseconds)
domainId?: string; // Domain ID
tradeSource?: 'USER' | 'MARGIN_SYSTEM'; // Trade source
tradeType?: 'TRADE' | 'MARGIN_TRADE' | 'MARGIN_ISOLATED_TRADE'; // Trade type
feeCurrency?: string; // Fee currency
takerFeeRate?: string; // Taker fee rate
makerFeeRate?: string; // Maker fee rate
createdAt?: number; // Order creation time
stop?: 'loss' | 'entry'; // Stop order type
stopTriggerTime?: number | null; // Stop trigger time
stopPrice?: string; // Stop price
limitPrice?: string | null; // Limit price
pop?: string | null; // POP
activateCondition?: string | null; // Activate condition
⋮----
export interface MarginStopOrdersList {
currentPage: number; // Current page
pageSize: number; // Page size
totalNum: number; // Total number of stop orders
totalPage: number; // Total pages
items: MarginStopOrderItem[]; // Array of stop orders
}
⋮----
currentPage: number; // Current page
pageSize: number; // Page size
totalNum: number; // Total number of stop orders
totalPage: number; // Total pages
items: MarginStopOrderItem[]; // Array of stop orders
⋮----
/**
* Margin OCO Order Response Types
*/
export interface MarginOcoOrderResponse {
orderId: string; // The unique order ID generated by the trading system
}
⋮----
orderId: string; // The unique order ID generated by the trading system
⋮----
export interface MarginOcoOrderItem {
orderId: string; // Order ID
symbol: string; // Symbol
clientOid: string; // Client Order ID
orderTime: number; // Order placement time (milliseconds)
status: 'NEW' | 'DONE' | 'TRIGGERED' | 'CANCELLED'; // Order status
}
⋮----
orderId: string; // Order ID
symbol: string; // Symbol
clientOid: string; // Client Order ID
orderTime: number; // Order placement time (milliseconds)
status: 'NEW' | 'DONE' | 'TRIGGERED' | 'CANCELLED'; // Order status
⋮----
export interface MarginOcoOrderSubOrder {
id: string; // Sub-order ID
symbol: string; // Symbol of the sub-order
side: 'buy' | 'sell'; // Side of the sub-order
price: string; // Price of the sub-order
stopPrice: string; // Stop price of the sub-order
size: string; // Size of the sub-order
status: 'NEW' | 'DONE' | 'TRIGGERED' | 'CANCELLED'; // Status of the sub-order
}
⋮----
id: string; // Sub-order ID
symbol: string; // Symbol of the sub-order
side: 'buy' | 'sell'; // Side of the sub-order
price: string; // Price of the sub-order
stopPrice: string; // Stop price of the sub-order
size: string; // Size of the sub-order
status: 'NEW' | 'DONE' | 'TRIGGERED' | 'CANCELLED'; // Status of the sub-order
⋮----
export interface MarginOcoOrderDetails {
orderId: string; // Order ID
symbol: string; // Symbol
clientOid: string; // Client Order ID
orderTime: number; // Order placement time (milliseconds)
status: 'NEW' | 'DONE' | 'TRIGGERED' | 'CANCELLED'; // Order status
orders: MarginOcoOrderSubOrder[]; // Sub-orders array
}
⋮----
orderId: string; // Order ID
symbol: string; // Symbol
clientOid: string; // Client Order ID
orderTime: number; // Order placement time (milliseconds)
status: 'NEW' | 'DONE' | 'TRIGGERED' | 'CANCELLED'; // Order status
orders: MarginOcoOrderSubOrder[]; // Sub-orders array
⋮----
/**
* Get Margin Collateral Ratio Response
*/
export interface MarginCollateralRatioItem {
lowerLimit: string;
upperLimit: string;
collateralRatio: string;
}
⋮----
export interface MarginCollateralRatioData {
currencyList: string[];
items: MarginCollateralRatioItem[];
}
⋮----
/**
* Get Market Available Inventory Response
*/
export interface MarketAvailableInventoryItem {
currency: string; // Currency
borrowableAmount: string; // Borrowable Amount
}
⋮----
currency: string; // Currency
borrowableAmount: string; // Borrowable Amount
================
File: src/types/response/spot-trading.ts
================
/**
*
***********
* Spot Trading
***********
*
*/
⋮----
/**
*
* Market data
*
*/
⋮----
interface Chain {
chainName: string;
withdrawalMinSize: string;
depositMinSize: string | null;
withdrawFeeRate: string;
withdrawalMinFee: string;
isWithdrawEnabled: boolean;
isDepositEnabled: boolean;
confirms: number;
preConfirms: number;
contractAddress: string;
withdrawPrecision: number;
maxWithdraw: string | null;
maxDeposit: string | null;
needTag: boolean;
chainId: string;
}
⋮----
export interface CurrencyInfo {
currency: string;
name: string;
fullName: string;
precision: number;
confirms: number | null;
contractAddress: string | null;
isMarginEnabled: boolean;
isDebitEnabled: boolean;
chains: Chain[];
}
⋮----
export interface SymbolInfo {
symbol: string;
name: string;
baseCurrency: string;
quoteCurrency: string;
feeCurrency: string;
market: 'USDS' | 'BTC' | 'ALTS';
baseMinSize: string;
quoteMinSize: string;
baseMaxSize: string;
quoteMaxSize: string;
baseIncrement: string;
quoteIncrement: string;
priceIncrement: string;
priceLimitRate: string;
minFunds: string;
isMarginEnabled: boolean;
enableTrading: boolean;
feeCategory: 1 | 2 | 3;
makerFeeCoefficient: string;
takerFeeCoefficient: string;
st: boolean;
callauctionIsEnabled: boolean;
callauctionPriceFloor: string | null;
callauctionPriceCeiling: string | null;
callauctionFirstStageStartTime: number | null;
callauctionSecondStageStartTime: number | null;
callauctionThirdStageStartTime: number | null;
tradingStartTime: number | null;
}
⋮----
export interface Ticker {
sequence: string;
price: string;
size: string;
bestAsk: string;
bestAskSize: string;
bestBid: string;
bestBidSize: string;
time: number;
}
⋮----
export interface AllTickers {
time: number;
ticker: Ticker[];
}
⋮----
// AllTickers returns different data than asking for one ticker
export interface AllTickersItem {
symbol: string;
symbolName: string;
buy: string;
bestBidSize: string;
sell: string;
bestAskSize: string;
changeRate: string;
changePrice: string;
high: string;
low: string;
vol: string;
volValue: string;
last: string;
averagePrice: string;
takerFeeRate: string;
makerFeeRate: string;
takerCoefficient: string;
makerCoefficient: string;
}
⋮----
export interface Symbol24hrStats {
time: number;
symbol: string;
buy: string;
sell: string;
changeRate: string;
changePrice: string;
high: string;
low: string;
vol: string;
volValue: string;
last: string;
averagePrice: string;
takerFeeRate: string;
makerFeeRate: string;
takerCoefficient: string;
makerCoefficient: string;
}
⋮----
export interface OrderBookLevel {
sequence: string;
time: number;
bids: [string, string][];
asks: [string, string][];
}
⋮----
export interface CallAuctionInfo {
symbol: string; // Symbol (e.g. "BTC-USDT")
estimatedPrice: string; // Estimated price
estimatedSize: string; // Estimated size
sellOrderRangeLowPrice: string; // Sell order minimum price
sellOrderRangeHighPrice: string; // Sell order maximum price
buyOrderRangeLowPrice: string; // Buy order minimum price
buyOrderRangeHighPrice: string; // Buy order maximum price
time: number; // Timestamp (ms)
}
⋮----
symbol: string; // Symbol (e.g. "BTC-USDT")
estimatedPrice: string; // Estimated price
estimatedSize: string; // Estimated size
sellOrderRangeLowPrice: string; // Sell order minimum price
sellOrderRangeHighPrice: string; // Sell order maximum price
buyOrderRangeLowPrice: string; // Buy order minimum price
buyOrderRangeHighPrice: string; // Buy order maximum price
time: number; // Timestamp (ms)
⋮----
export interface TradeHistory {
sequence: string;
time: number;
price: string;
size: string;
side: string;
}
⋮----
export type Kline = [string, string, string, string, string, string, string];
⋮----
/**
*
* Spot HF trade
*
*/
⋮----
export interface SubmitHFOrderSyncResponse {
orderId: string; // An order Id is returned once an order is successfully Submitd.
orderTime: number; // order time
originSize: string; // original order size
dealSize: string; // deal size
remainSize: string; // remain size
canceledSize: string; // Cumulative number of cancellations
status: string; // Order Status. open: the order is active; done: the order has been completed
matchTime: number; // matching time
clientOid: string;
}
⋮----
orderId: string; // An order Id is returned once an order is successfully Submitd.
orderTime: number; // order time
originSize: string; // original order size
dealSize: string; // deal size
remainSize: string; // remain size
canceledSize: string; // Cumulative number of cancellations
status: string; // Order Status. open: the order is active; done: the order has been completed
matchTime: number; // matching time
⋮----
export interface SubmitMultipleHFOrdersResponse {
orderId: string;
success?: boolean;
failMsg?: string; // Reason of failure, optional based on success status
clientOid: string;
}
⋮----
failMsg?: string; // Reason of failure, optional based on success status
⋮----
export interface SubmitMultipleHFOrdersSyncResponse {
orderId: string; // An order Id is returned once an order is successfully Submitd.
orderTime: number; // order time
originSize: string; // original order size
dealSize: string; // deal size
remainSize: string; // remain size
canceledSize: string; // Cumulative number of cancellations
status: string; // Order Status. open: the order is active; done: the order has been completed
matchTime: number; // matching time
success: boolean; // Whether the order was submitted successfully.
clientOid: string;
}
⋮----
orderId: string; // An order Id is returned once an order is successfully Submitd.
orderTime: number; // order time
originSize: string; // original order size
dealSize: string; // deal size
remainSize: string; // remain size
canceledSize: string; // Cumulative number of cancellations
status: string; // Order Status. open: the order is active; done: the order has been completed
matchTime: number; // matching time
success: boolean; // Whether the order was submitted successfully.
⋮----
export interface SyncCancelHFOrderResponse {
clientOid?: string; // client order Id
orderId?: string; // order Id
originSize: string; // original order size
dealSize: string; // deal size
remainSize: string; // remain size
canceledSize: string; // Cumulative number of cancellations
status: string; // Order Status. open: the order is active; done: the order has been completed
}
⋮----
clientOid?: string; // client order Id
orderId?: string; // order Id
originSize: string; // original order size
dealSize: string; // deal size
remainSize: string; // remain size
canceledSize: string; // Cumulative number of cancellations
status: string; // Order Status. open: the order is active; done: the order has been completed
⋮----
export interface CancelAllHFOrdersResponse {
succeedSymbols?: string[]; // Cancel order successful symbol
failedSymbols?: {
symbol: string; // Cancel order failed symbol
error: string; // Error message
}[];
}
⋮----
succeedSymbols?: string[]; // Cancel order successful symbol
⋮----
symbol: string; // Cancel order failed symbol
error: string; // Error message
⋮----
export interface AutoCancelHFOrderSettingQueryResponse {
timeout: number; // Auto cancel order trigger setting time, the unit is second. range: timeout=-1 (meaning unset) or 5 <= timeout <= 86400
symbols: string; // List of trading pairs. Separated by commas, empty means all trading pairs
currentTime: number; // System current time (in seconds)
triggerTime: number; // Trigger cancellation time (in seconds)
}
⋮----
timeout: number; // Auto cancel order trigger setting time, the unit is second. range: timeout=-1 (meaning unset) or 5 <= timeout <= 86400
symbols: string; // List of trading pairs. Separated by commas, empty means all trading pairs
currentTime: number; // System current time (in seconds)
triggerTime: number; // Trigger cancellation time (in seconds)
⋮----
export interface HFFilledOrder {
id: number;
orderId: string;
counterOrderId: string;
tradeId: number;
symbol: string;
side: 'buy' | 'sell';
liquidity: 'taker' | 'maker';
type: 'limit' | 'market';
forceTaker: boolean;
price: string;
size: string;
funds: string;
fee: string;
feeRate: string;
feeCurrency: string;
stop: string;
tradeType: string;
taxRate: string;
tax: string;
createdAt: number;
}
⋮----
export interface HFOrder {
id: string;
clientOid: string;
symbol: string;
opType: string;
type: 'limit' | 'market';
side: 'buy' | 'sell';
price: string;
size: string;
funds: string;
dealSize: string;
dealFunds: string;
remainSize: string;
remainFunds: string;
cancelledSize: string;
cancelledFunds: string;
fee: string;
feeCurrency: string;
stp?: 'DC' | 'CO' | 'CN' | 'CB' | null;
timeInForce: 'GTC' | 'GTT' | 'IOC' | 'FOK';
postOnly: boolean;
hidden: boolean;
iceberg: boolean;
visibleSize: string;
cancelAfter: number;
channel: string;
remark?: string | null;
tags?: string | null;
cancelExist: boolean;
tradeType: string;
inOrderBook: boolean;
active: boolean;
tax: string;
createdAt: number;
lastUpdatedAt: number;
cancelReason: number;
}
⋮----
/**
*
* Orders
*
*/
⋮----
export interface MultipleOrdersResponse {
symbol: string;
type?: string;
side: string;
price: string;
size: string;
funds?: any;
stp?: string;
stop?: string;
stopPrice?: any;
timeInForce?: string;
cancelAfter?: number;
postOnly?: boolean;
hidden?: boolean;
iceberg?: boolean;
visibleSize?: any;
channel: string;
id: string;
status: string;
failMsg?: any;
clientOid: string;
}
export interface SpotOrder {
id: string;
symbol: string;
opType: string;
type: string;
side: string;
price: string;
size: string;
funds: string;
dealFunds: string;
dealSize: string;
fee: string;
feeCurrency: string;
stp: string;
stop: string;
stopTriggered: boolean;
stopPrice: string;
timeInForce: string;
postOnly: boolean;
hidden: boolean;
iceberg: boolean;
visibleSize: string;
cancelAfter: number;
channel: string;
clientOid: string;
remark: string;
tags: string;
isActive: boolean;
cancelExist: boolean;
createdAt: number;
tradeType: string;
}
⋮----
export interface SpotOrderList {
currentPage: number;
pageSize: number;
totalNum: number;
totalPage: number;
items: SpotOrder[];
}
⋮----
/**
*
* Fills
*
*/
⋮----
export interface SpotOrderFill {
symbol: string; // symbol.
tradeId: string; // trade id, it is generated by Matching engine.
orderId: string; // Order ID, unique identifier of an order.
counterOrderId: string; // counter order id.
side: 'buy' | 'sell'; // transaction direction, include buy and sell.
price: string; // order price
size: string; // order quantity
funds: string; // order funds
type: 'limit' | 'market' | 'limit_stop' | 'market_stop'; // order type, e.g. limit, market, stop_limit.
fee: string; // fee
feeCurrency: string; // charge fee currency
stop: string; // stop type, include entry and loss
liquidity: 'taker' | 'maker'; // include taker and maker
forceTaker: boolean; // forced to become taker, include true and false
createdAt: number; // create time
tradeType: 'TRADE' | 'MARGIN_TRADE' | 'MARGIN_ISOLATED_TRADE'; // The type of trading: TRADE(Spot Trading), MARGIN_TRADE (Margin Trading).
}
⋮----
symbol: string; // symbol.
tradeId: string; // trade id, it is generated by Matching engine.
orderId: string; // Order ID, unique identifier of an order.
counterOrderId: string; // counter order id.
side: 'buy' | 'sell'; // transaction direction, include buy and sell.
price: string; // order price
size: string; // order quantity
funds: string; // order funds
type: 'limit' | 'market' | 'limit_stop' | 'market_stop'; // order type, e.g. limit, market, stop_limit.
fee: string; // fee
feeCurrency: string; // charge fee currency
stop: string; // stop type, include entry and loss
liquidity: 'taker' | 'maker'; // include taker and maker
forceTaker: boolean; // forced to become taker, include true and false
createdAt: number; // create time
tradeType: 'TRADE' | 'MARGIN_TRADE' | 'MARGIN_ISOLATED_TRADE'; // The type of trading: TRADE(Spot Trading), MARGIN_TRADE (Margin Trading).
⋮----
export interface SpotOrderFills {
currentPage: number;
pageSize: number;
totalNum: number;
totalPage: number;
items: SpotOrderFill[];
}
⋮----
/**
*
* Stop order
*
*/
⋮----
export interface StopOrderItem {
id?: string;
symbol?: string;
userId?: string;
status?: 'NEW' | 'TRIGGERED';
type?: 'limit' | 'market' | 'limit_stop' | 'market_stop';
side?: 'buy' | 'sell';
price?: string;
size?: string;
funds?: string | null;
stp?: string | null;
timeInForce?: 'GTC' | 'GTT' | 'IOC' | 'FOK';
cancelAfter?: number;
postOnly?: boolean;
hidden?: boolean;
iceberg?: boolean;
visibleSize?: string | null;
channel?: string;
clientOid?: string;
remark?: string | null;
tags?: string | null;
domainId?: string;
tradeSource?: 'USER' | 'MARGIN_SYSTEM';
tradeType?: 'TRADE' | 'MARGIN_TRADE' | 'MARGIN_ISOLATED_TRADE';
feeCurrency?: string;
takerFeeRate?: string;
makerFeeRate?: string;
createdAt?: number;
stop?: 'loss' | 'entry';
stopTriggerTime?: number | null;
stopPrice?: string;
orderTime?: number;
}
⋮----
export interface StopOrders {
currentPage: number;
pageSize: number;
totalNum: number;
totalPage: number;
items: StopOrderItem[];
}
⋮----
/**
*
* OCO order
*
*/
export interface OCOOrderSubOrder {
id: string; // Sub-order ID
symbol: string; // Symbol of the sub-order
side: 'buy' | 'sell'; // Side of the sub-order
price: string; // Price of the sub-order
stopPrice: string; // Stop price of the sub-order
size: string; // Size of the sub-order
status: 'NEW' | 'DONE' | 'TRIGGERED' | 'CANCELLED'; // Status of the sub-order
}
⋮----
id: string; // Sub-order ID
symbol: string; // Symbol of the sub-order
side: 'buy' | 'sell'; // Side of the sub-order
price: string; // Price of the sub-order
stopPrice: string; // Stop price of the sub-order
size: string; // Size of the sub-order
status: 'NEW' | 'DONE' | 'TRIGGERED' | 'CANCELLED'; // Status of the sub-order
⋮----
export interface OCOOrderDetails {
orderId: string; // order id, Unique order id created by users to identify their orders
symbol: string; // symbol, such as, ETH-BTC
clientOid: string; // client order id
orderTime: number; // Order Submitment time, milliseconds
status: 'NEW' | 'DONE' | 'TRIGGERED' | 'CANCELLED'; // Order status
orders: OCOOrderSubOrder[];
}
⋮----
orderId: string; // order id, Unique order id created by users to identify their orders
symbol: string; // symbol, such as, ETH-BTC
clientOid: string; // client order id
orderTime: number; // Order Submitment time, milliseconds
status: 'NEW' | 'DONE' | 'TRIGGERED' | 'CANCELLED'; // Order status
⋮----
export interface OCOOrderListItem {
orderId: string; // order id, Unique order id created by users to identify their orders
symbol: string; // symbol, such as, ETH-BTC
clientOid: string; // client order id
orderTime: number; // Order Submitment time, milliseconds
status: 'NEW' | 'DONE' | 'TRIGGERED' | 'CANCELLED'; // Order status
}
⋮----
orderId: string; // order id, Unique order id created by users to identify their orders
symbol: string; // symbol, such as, ETH-BTC
clientOid: string; // client order id
orderTime: number; // Order Submitment time, milliseconds
status: 'NEW' | 'DONE' | 'TRIGGERED' | 'CANCELLED'; // Order status
⋮----
export interface OCOOrders {
currentPage: number;
pageSize: number;
totalNum: number;
totalPage: number;
items: OCOOrderListItem[];
}
================
File: src/lib/requestUtils.ts
================
/**
* Used to switch how authentication/requests work under the hood
*/
⋮----
/** Spot & Margin */
⋮----
/** Futures */
⋮----
/** Broker */
⋮----
/** Unified Trading Account */
⋮----
export type RestClientType =
(typeof REST_CLIENT_TYPE_ENUM)[keyof typeof REST_CLIENT_TYPE_ENUM];
⋮----
export interface RestClientOptions {
/** Your API key */
apiKey?: string;
/** Your API secret */
apiSecret?: string;
/** Your API passphrase (can be anything) that you set when creating this API key (NOT your account password) */
apiPassphrase?: string;
/**
* Use access token instead of sign, if this is provided.
* For guidance refer to: https://github.com/tiagosiebler/kucoin-api/issues/2
*/
apiAccessToken?: string;
/** The API key version. Defaults to "2" right now. You can see this in your API management page */
apiKeyVersion?: number | string;
/** Default: false. If true, we'll throw errors if any params are undefined */
strictParamValidation?: boolean;
/**
* Optionally override API protocol + domain
* e.g baseUrl: 'https://api.kucoin.com'
**/
baseUrl?: string;
/** Default: true. whether to try and post-process request exceptions (and throw them). */
parseExceptions?: boolean;
customTimestampFn?: () => number;
/**
* Enable keep alive for REST API requests (via axios).
*/
keepAlive?: boolean;
/**
* When using HTTP KeepAlive, how often to send TCP KeepAlive packets over sockets being kept alive. Default = 1000.
* Only relevant if keepAlive is set to true.
* Default: 1000 (defaults comes from https agent)
*/
keepAliveMsecs?: number;
/**
* Allows you to provide a custom "signMessage" function, e.g. to use node's much faster createHmac method
*
* Look in the examples folder for a demonstration on using node's createHmac instead.
*/
customSignMessageFn?: (message: string, secret: string) => Promise;
}
⋮----
/** Your API key */
⋮----
/** Your API secret */
⋮----
/** Your API passphrase (can be anything) that you set when creating this API key (NOT your account password) */
⋮----
/**
* Use access token instead of sign, if this is provided.
* For guidance refer to: https://github.com/tiagosiebler/kucoin-api/issues/2
*/
⋮----
/** The API key version. Defaults to "2" right now. You can see this in your API management page */
⋮----
/** Default: false. If true, we'll throw errors if any params are undefined */
⋮----
/**
* Optionally override API protocol + domain
* e.g baseUrl: 'https://api.kucoin.com'
**/
⋮----
/** Default: true. whether to try and post-process request exceptions (and throw them). */
⋮----
/**
* Enable keep alive for REST API requests (via axios).
*/
⋮----
/**
* When using HTTP KeepAlive, how often to send TCP KeepAlive packets over sockets being kept alive. Default = 1000.
* Only relevant if keepAlive is set to true.
* Default: 1000 (defaults comes from https agent)
*/
⋮----
/**
* Allows you to provide a custom "signMessage" function, e.g. to use node's much faster createHmac method
*
* Look in the examples folder for a demonstration on using node's createHmac instead.
*/
⋮----
export function serializeParams | undefined = {}>(
params: T,
strict_validation: boolean | undefined,
encodeValues: boolean,
prefixWith: string,
): string
⋮----
// Only prefix if there's a value
⋮----
export function getRestBaseUrl(
useTestnet: boolean,
restInverseOptions: RestClientOptions,
restClientType: RestClientType,
): string
================
File: src/types/websockets/ws-api.ts
================
import { WS_KEY_MAP, WsKey } from '../../lib/websocket/websocket-util.js';
import { BatchCancelOrdersRequest, Order } from '../request/futures.types.js';
import { SubmitHFMarginOrderRequest } from '../request/spot-margin-trading.js';
import {
ModifyHFOrderRequest,
SubmitHFOrderRequest,
} from '../request/spot-trading.js';
import {
BatchCancelOrderResult,
SubmitMultipleOrdersFuturesResponse,
} from '../response/futures.types.js';
import { MarginSubmitOrderV3Response } from '../response/spot-margin-trading.js';
import {
SubmitHFOrderSyncResponse,
SyncCancelHFOrderResponse,
} from '../response/spot-trading.js';
⋮----
export type WsOperation =
| 'subscribe'
| 'unsubscribe'
| 'login'
| 'access'
| 'request'
| 'ping';
⋮----
export interface WsRequestOperation {
id: number;
type: WsOperation;
topic: TWSTopic;
privateChannel: boolean;
response: boolean;
}
⋮----
export type Exact = {
// This part says: if there's any key that's not in T, it's an error
// This conflicts sometimes for some reason...
// [K: string]: never;
} & {
[K in keyof T]: T[K];
};
⋮----
// This part says: if there's any key that's not in T, it's an error
// This conflicts sometimes for some reason...
// [K: string]: never;
⋮----
/**
* WS API commands (for sending requests via WS)
*/
⋮----
export type WsAPIOperation = (typeof WS_API_Operations)[number];
⋮----
export interface WsRequestOperationKucoin<
TWSTopic extends string,
TWSParams extends object = any,
> {
id: string;
op: WsOperation | WsAPIOperation;
args?: (TWSTopic | string | number)[] | TWSParams; // Business parameters, same as RestAPI
}
⋮----
args?: (TWSTopic | string | number)[] | TWSParams; // Business parameters, same as RestAPI
⋮----
export interface WSAPIResponse<
TResponseData extends object = object,
TWSAPIOperation = WsAPIOperation,
> {
/** Auto-generated */
id: string;
op: TWSAPIOperation;
msg?: string;
code: '200000' | string;
data: TResponseData;
inTime: number; //Gateway in time(ms)
outTime: number; //Gateway out time(ms)
rateLimit?: { limit: number; reset: number; remaining: number };
wsKey: WsKey;
isWSAPIResponse: boolean;
request?: any;
}
⋮----
/** Auto-generated */
⋮----
inTime: number; //Gateway in time(ms)
outTime: number; //Gateway out time(ms)
⋮----
export interface WsAPIWsKeyTopicMap {
[WS_KEY_MAP.wsApiSpotV1]: WsAPIOperation;
[WS_KEY_MAP.wsApiFuturesV1]: WsAPIOperation;
}
⋮----
export type WSAPICancelOrderRequest = { symbol: string } & (
| { orderId: string }
| { clientOid: string }
);
⋮----
export interface WSAPIOrderResponse {
orderId: string;
clientOid: string;
}
⋮----
export interface WsAPITopicRequestParamMap {
[key: string]: unknown;
subscribe: never;
unsubscribe: never;
login: never;
access: never;
request: never;
ping: void;
'spot.order': SubmitHFOrderRequest;
'margin.order': SubmitHFMarginOrderRequest;
'futures.order': Order;
'spot.cancel': WSAPICancelOrderRequest;
'margin.cancel': WSAPICancelOrderRequest;
'futures.cancel': { orderId: string } | { clientOid: string; symbol: string };
'futures.multi_cancel': BatchCancelOrdersRequest;
'futures.multi_order': Order[];
'spot.sync_order': SubmitHFOrderRequest;
'spot.modify': ModifyHFOrderRequest;
'spot.sync_cancel': WSAPICancelOrderRequest;
}
⋮----
export interface WsAPITopicResponseMap {
[key: string]: unknown;
subscribe: never;
unsubscribe: never;
login: never;
access: never;
request: never;
ping: unknown;
'spot.order': WSAPIResponse;
'margin.order': WSAPIResponse;
'futures.order': WSAPIResponse;
'spot.cancel': WSAPIResponse;
'margin.cancel': WSAPIResponse;
'futures.cancel': WSAPIResponse<
{ cancelledOrderIds: string[] } | { clientOid: string }
>;
'futures.multi_cancel': WSAPIResponse;
'futures.multi_order': WSAPIResponse;
'spot.sync_order': WSAPIResponse;
'spot.modify': WSAPIResponse<{
newOrderId: string;
clientOid: string;
}>;
'spot.sync_cancel': WSAPIResponse;
}
⋮----
export interface WSAPIAuthenticationRequestFromServer {
timestamp: number;
sessionId: string;
}
⋮----
export interface WSAPIAuthenticationConfirmedFromServer {
pingInterval: number;
sessionId: string;
pingTimeout: number;
data: 'welcome';
}
================
File: src/WebsocketAPIClient.ts
================
import { DefaultLogger } from './lib/websocket/logger.js';
import { WS_KEY_MAP, WSAPIWsKey } from './lib/websocket/websocket-util.js';
import {
BatchCancelOrdersRequest,
Order,
} from './types/request/futures.types.js';
import { SubmitHFMarginOrderRequest } from './types/request/spot-margin-trading.js';
import {
ModifyHFOrderRequest,
SubmitHFOrderRequest,
} from './types/request/spot-trading.js';
import {
BatchCancelOrderResult,
SubmitMultipleOrdersFuturesResponse,
} from './types/response/futures.types.js';
import { MarginSubmitOrderV3Response } from './types/response/spot-margin-trading.js';
import {
SubmitHFOrderSyncResponse,
SyncCancelHFOrderResponse,
} from './types/response/spot-trading.js';
import {
WSAPICancelOrderRequest,
WSAPIOrderResponse,
WSAPIResponse,
} from './types/websockets/ws-api.js';
import { WSClientConfigurableOptions } from './types/websockets/ws-general.js';
import { WebsocketClient } from './WebsocketClient.js';
⋮----
/**
* Configurable options specific to only the REST-like WebsocketAPIClient
*/
export interface WSAPIClientConfigurableOptions {
/**
* Default: true
*
* Attach default event listeners, which will console log any high level
* events (opened/reconnecting/reconnected/etc).
*
* If you disable this, you should set your own event listeners
* on the embedded WS Client `wsApiClient.getWSClient().on(....)`.
*/
attachEventListeners: boolean;
}
⋮----
/**
* Default: true
*
* Attach default event listeners, which will console log any high level
* events (opened/reconnecting/reconnected/etc).
*
* If you disable this, you should set your own event listeners
* on the embedded WS Client `wsApiClient.getWSClient().on(....)`.
*/
⋮----
/**
* This is a minimal Websocket API wrapper around the WebsocketClient.
*
* Some methods support passing in a custom "wsKey". This is a reference to which WS connection should
* be used to transmit that message. This is only useful if you wish to use an alternative wss
* domain that is supported by the SDK.
*
* Note: To use testnet, don't set the wsKey - use `testnet: true` in
* the constructor instead.
*
* Note: You can also directly use the sendWSAPIRequest() method to make WS API calls, but some
* may find the below methods slightly more intuitive.
*
* Refer to the WS API promises example for a more detailed example on using sendWSAPIRequest() directly:
* https://github.com/tiagosiebler/binance/blob/master/examples/WebSockets/ws-api-raw-promises.ts#L108
*/
export class WebsocketAPIClient
⋮----
constructor(
options?: WSClientConfigurableOptions &
Partial,
logger?: DefaultLogger,
)
⋮----
public getWSClient(): WebsocketClient
⋮----
/**
* Submit a spot order
*/
submitNewSpotOrder(
params: SubmitHFOrderRequest,
wsKey?: WSAPIWsKey,
): Promise>
⋮----
/**
* Modify a spot order
*/
modifySpotOrder(
params: ModifyHFOrderRequest,
wsKey?: WSAPIWsKey,
): Promise>
⋮----
/**
* Submit a sync spot order
*/
submitSyncSpotOrder(
params: SubmitHFOrderRequest,
wsKey?: WSAPIWsKey,
): Promise>
⋮----
/**
* Cancel a sync spot order
*/
cancelSyncSpotOrder(
params: WSAPICancelOrderRequest,
wsKey?: WSAPIWsKey,
): Promise>
⋮----
/**
* Submit a margin order
*/
submitMarginOrder(
params: SubmitHFMarginOrderRequest,
wsKey?: WSAPIWsKey,
): Promise>
⋮----
/**
* Cancel a margin order
*/
cancelMarginOrder(
params: WSAPICancelOrderRequest,
wsKey?: WSAPIWsKey,
): Promise>
⋮----
/**
* Submit a futures order
*/
submitFuturesOrder(
params: Order,
wsKey?: WSAPIWsKey,
): Promise>
⋮----
/**
* Cancel a futures order
*/
cancelFuturesOrder(
params: { orderId: string } | { clientOid: string; symbol: string },
wsKey?: WSAPIWsKey,
): Promise<
WSAPIResponse<{ cancelledOrderIds: string[] } | { clientOid: string }>
> {
return this.wsClient.sendWSAPIRequest(
wsKey || WS_KEY_MAP.wsApiFuturesV1,
'futures.cancel',
params,
);
⋮----
/**
* Submit multiple futures orders
*/
submitMultipleFuturesOrders(
params: Order[],
wsKey?: WSAPIWsKey,
): Promise>
⋮----
/**
* Cancel multiple futures orders
*/
cancelMultipleFuturesOrders(
params: BatchCancelOrdersRequest,
wsKey?: WSAPIWsKey,
): Promise>
⋮----
/**
*
*
*
*
*
*
*
* Private methods for handling some of the convenience/automation provided by the WS API Client
*
*
*
*
*
*
*
*/
⋮----
public connectWSAPI(wsKey: WSAPIWsKey)
⋮----
private setupDefaultEventListeners()
⋮----
/**
* General event handlers for monitoring the WebsocketClient
*/
⋮----
// Blind JSON.stringify can fail on circular references
⋮----
// JSON.stringify({ ...data, target: 'WebSocket' }),
================
File: examples/WebSockets/ws-api-client.ts
================
/**
* KuCoin WebSocket API Client - Complete Example
*
* This example demonstrates all available WebSocket API operations:
* - Spot trading: submit, modify, cancel, sync operations
* - Margin trading: submit and cancel orders
* - Futures trading: submit, cancel, batch operations
*
* Usage:
* Make sure to set your API credentials in environment variables:
* - API_KEY
* - API_SECRET
* - API_PASSPHRASE
*
* or pass them as arguments to the constructor
*/
⋮----
import { DefaultLogger, WebsocketAPIClient } from '../../src/index.js';
⋮----
async function main()
⋮----
// 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),
⋮----
passphrase: process.env.API_PASSPHRASE || 'apiPassPhraseHere', // This is NOT your account password
⋮----
// 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
⋮----
// Example usage for each WebSocket API operation
⋮----
// 1. Submit Spot Order
⋮----
price: '20000', // Very low price to avoid accidental execution
⋮----
// 2. Submit Sync Spot Order
⋮----
price: '1000', // Very high price to avoid accidental execution
⋮----
// 3. Modify Spot Order (requires existing order ID)
⋮----
orderId: '68cc3476693c1c00072ef1d9', // Replace with actual order ID
⋮----
// 4. Cancel Spot Order
⋮----
orderId: '68cc34c6693c1c0007301929', // Replace with actual order ID
⋮----
// 5. Cancel Sync Spot Order
⋮----
orderId: '68cc3530b9870a0007670294', // Replace with actual client order ID
⋮----
// 6. Submit Margin Order
⋮----
price: '19000', // Very low price to avoid accidental execution
⋮----
isIsolated: false, // false for cross margin, true for isolated
⋮----
// 7. Cancel Margin Order
⋮----
orderId: 'your-margin-order-id-here', // Replace with actual order ID
⋮----
// 8. Submit Futures Order
⋮----
price: '1000', // Very low price to avoid accidental execution
⋮----
positionSide: 'LONG', // needed if trading two-way (hedge) position mode
⋮----
// 9. Cancel Futures Order
⋮----
orderId: '358196976308797441', // Replace with actual order ID
⋮----
// 10. Submit Multiple Futures Orders
⋮----
price: '1000', // Very low price to avoid accidental execution
⋮----
positionSide: 'LONG', // Needed if trading hedge/two-way mode. Optional in one-way mode.
⋮----
price: '1010', // Very low price to avoid accidental execution
⋮----
// 11. Cancel Multiple Futures Orders
⋮----
orderIdsList: ['order-id-1', 'order-id-2'], // Replace with actual order IDs
⋮----
// Start executing the example workflow
================
File: src/FuturesClient.ts
================
import { AxiosRequestConfig } from 'axios';
import { nanoid } from 'nanoid';
⋮----
import { BaseRestClient } from './lib/BaseRestClient.js';
import {
REST_CLIENT_TYPE_ENUM,
RestClientOptions,
RestClientType,
} from './lib/requestUtils.js';
import {
AccountFillsRequest,
BatchCancelOrdersRequest,
CopyTradeChangeCrossMarginLeverageRequest,
CopyTradeGetCrossMarginRequirementRequest,
CopyTradeOrderRequest,
CopyTradeSLTPOrderRequest,
CopyTradeSwitchMarginModeRequest,
CopyTradeSwitchPositionModeRequest,
GetFundingHistoryRequest,
GetFundingRatesRequest,
GetInterestRatesRequest,
GetKlinesRequest,
GetOrdersRequest,
GetStopOrdersRequest,
GetTransactionsRequest,
MaxOpenSizeRequest,
Order,
SLTPOrder,
} from './types/request/futures.types.js';
import {
AccountBalance,
AccountSummary,
AddMargin,
BatchCancelOrderResult,
BatchMarginModeUpdateResponse,
CopyTradeCrossMarginRequirement,
CopyTradePosition,
CopyTradeSwitchMarginModeResponse,
CopyTradeSwitchPositionModeResponse,
CrossMarginRequirement,
CrossMarginRiskLimit,
FullOrderBookDetail,
FuturesAccountFundingRateHistory,
FuturesAccountTransaction,
FuturesActiveOrder,
FuturesClosedPositions,
FuturesCurrentFundingRate,
FuturesFill,
FuturesFills,
FuturesHistoricFundingRate,
FuturesKline,
FuturesMarkPrice,
FuturesOrder,
FuturesOrders,
FuturesPosition,
FuturesRiskLimit,
FuturesSubAccount,
FuturesSymbolInfo,
GetPositionModeResponse,
IndexListItem,
InterestRateItem,
MarketTradeDetail,
MaxOpenSize,
PremiumIndexItem,
SubmitMultipleOrdersFuturesResponse,
TickerDetail,
} from './types/response/futures.types.js';
import {
APISuccessResponse,
ServiceStatus,
} from './types/response/shared.types.js';
import { WsConnectionInfo } from './types/response/ws.js';
⋮----
/**
*
*/
export class FuturesClient extends BaseRestClient
⋮----
constructor(
restClientOptions: RestClientOptions = {},
requestOptions: AxiosRequestConfig = {},
)
⋮----
getClientType(): RestClientType
⋮----
/**
*
* Misc Utility Methods
*
*/
⋮----
generateNewOrderID(): string
⋮----
/**
*
* REST - ACCOUNT INFO - Account & Funding
*
*/
⋮----
/**
* Get Account - Futures
* Request via this endpoint to get the info of the futures account.
*/
getBalance(params?: {
currency?: string;
}): Promise>
⋮----
/**
* Get Account Ledgers - Futures
* This endpoint can query the ledger records of the futures business line
*/
getTransactions(params: GetTransactionsRequest): Promise<
APISuccessResponse<{
hasMore: boolean; // Whether there are more pages
dataList: FuturesAccountTransaction[];
}>
> {
return this.getPrivate('api/v1/transaction-history', params);
⋮----
hasMore: boolean; // Whether there are more pages
⋮----
/**
*
* REST - ACCOUNT INFO - Sub Account
*
*/
⋮----
/**
* Get SubAccount List - Futures Balance(V2)
* This endpoint can be used to get Futures sub-account information.
*/
getSubBalances(params?: { currency?: string }): Promise<
APISuccessResponse<{
summary: AccountSummary;
accounts: FuturesSubAccount[];
}>
> {
return this.getPrivate('api/v1/account-overview-all', params);
⋮----
/**
*
* REST - Account Info - Trade Fee
*
*/
⋮----
/**
* Get Actual Fee - Futures
* This endpoint is for the actual futures fee rate of the trading pair. The fee rate of your sub-account is the same as that of the master account.
*/
getTradingPairFee(params: { symbol: string }): Promise<
APISuccessResponse<{
symbol: string;
takerFeeRate: string;
makerFeeRate: string;
}>
> {
return this.getPrivate('api/v1/trade-fees', params);
⋮----
/**
*
* REST - Futures Trading - Market Data
*
*/
⋮----
/**
* Get Symbol
* Get information of specified contracts that can be traded.
* This API will return a list of tradable contracts, including some key parameters of the contract such as the symbol name, tick size, mark price,etc.
*/
getSymbol(params: {
symbol: string;
}): Promise>
⋮----
/**
* Get Symbol
* Get information of specified contracts that can be traded.
* This API will return a list of tradable contracts, including some key parameters of the contract such as the symbol name, tick size, mark price,etc.
*/
getSymbols(): Promise>
⋮----
/**
* Get Ticker
* This endpoint returns "last traded price/size"、"best bid/ask price/size" etc. of a single symbol.
*/
getTicker(params: {
symbol: string;
}): Promise>
⋮----
/**
* Get All Tickers
* This endpoint returns "last traded price/size"、"best bid/ask price/size" etc. of all symbol.
*/
getTickers(): Promise>
⋮----
/**
* Get Full OrderBook
* Query for Full orderbook depth data. (aggregated by price)
*/
getFullOrderBookLevel2(params: {
symbol: string;
}): Promise>
⋮----
/**
* Get Part OrderBook
* Query for part orderbook depth data. (aggregated by price)
*/
getPartOrderBookLevel2Depth20(params: {
symbol: string;
}): Promise>
⋮----
/**
* Get Part OrderBook
* Query for part orderbook depth data. (aggregated by price)
*/
getPartOrderBookLevel2Depth100(params: {
symbol: string;
}): Promise>
⋮----
/**
* Get Trade History
* Request via this endpoint to get the trade history of the specified symbol, the returned quantity is the last 100 transaction records.
*/
getMarketTrades(params: {
symbol: string;
}): Promise>
⋮----
/**
* Get Klines
* Get the Kline of the symbol. Data are returned in grouped buckets based on requested type.
*/
getKlines(
params: GetKlinesRequest,
): Promise>
⋮----
/**
* Get Mark Price
* Get the mark price of the symbol.
*/
getMarkPrice(params: {
symbol: string;
}): Promise>
⋮----
/**
* Get Spot Index Price
* This endpoint returns the index price of the specified symbol.
*/
getIndex(params: GetInterestRatesRequest): Promise<
APISuccessResponse<{
dataList: IndexListItem[];
hasMore: boolean; // Whether there are more pages
}>
> {
return this.get('api/v1/index/query', params);
⋮----
hasMore: boolean; // Whether there are more pages
⋮----
/**
* Get Interest Rate Index
* This endpoint returns the interest rate index of the specified symbol.
*/
getInterestRates(params: GetInterestRatesRequest): Promise<
APISuccessResponse<{
dataList: InterestRateItem[];
hasMore: boolean; // Whether there are more pages
}>
> {
return this.get('api/v1/interest/query', params);
⋮----
hasMore: boolean; // Whether there are more pages
⋮----
/**
* Get Premium Index
* This endpoint returns the premium index of the specified symbol.
*/
getPremiumIndex(params: GetInterestRatesRequest): Promise<
APISuccessResponse<{
dataList: PremiumIndexItem[];
hasMore: boolean; // Whether there are more pages
}>
> {
return this.get('api/v1/premium/query', params);
⋮----
hasMore: boolean; // Whether there are more pages
⋮----
/**
* Get 24hr Stats
* Get the statistics of the platform futures trading volume in the last 24 hours.
*/
get24HourTransactionVolume(): Promise<
APISuccessResponse<{
turnoverOf24h: number;
}>
> {
return this.get('api/v1/trade-statistics');
⋮----
/**
* Get Server Time
* Get the API server time. This is the Unix timestamp.
*/
getServerTime(): Promise>
⋮----
/**
* Get Service Status
* This endpoint returns the status of the API service.
*/
getServiceStatus(): Promise>
⋮----
/**
*
* REST - Futures Trading - Orders
*
*/
⋮----
/**
* Add Order
* Place order to the futures trading system
*/
submitOrder(params: Order): Promise<
APISuccessResponse<{
orderId?: string;
clientOid?: string;
}>
> {
return this.postPrivate('api/v1/orders', params);
⋮----
/**
* Add Order Test
* Order test endpoint, the request parameters and return parameters of this endpoint are exactly the same as the order endpoint, and can be used to verify whether the signature is correct and other operations.
*/
submitNewOrderTest(params: Order): Promise<
⋮----
/**
* Batch Add Orders
* Place multiple order to the futures trading system
*/
submitMultipleOrders(
params: Order[],
): Promise>
⋮----
/**
* Add Take Profit And Stop Loss Order
* Place take profit and stop loss order supports both take-profit and stop-loss functions, and other functions are exactly the same as the place order endpoint.
*/
submitSLTPOrder(params: SLTPOrder): Promise<
APISuccessResponse<{
orderId?: string;
clientOid?: string;
}>
> {
return this.postPrivate('api/v1/st-orders', params);
⋮----
/**
* Cancel Order By OrderId
* Cancel an order (including a stop order).
*/
cancelOrderById(params: {
orderId: string;
}): Promise>
⋮----
/**
* Cancel All Orders
* Using this endpoint, all open orders (excluding stop orders) can be canceled in batches.
*/
cancelAllOrdersV3(params: {
symbol: string;
}): Promise>
⋮----
/**
* Get Order By Client Order Id
* Get order details by client order id.
*/
getOrderByClientOrderId(params: {
clientOid: string;
}): Promise>
⋮----
/**
* Get Order List
* List your current orders. Any limit order on the exchange order book is in active status.
*/
getOrders(
params?: GetOrdersRequest,
): Promise>
⋮----
/**
* Get Recent Closed Orders
* Get a list of recent 1000 closed orders in the last 24 hours.
*/
getRecentOrders(params?: {
symbol?: string;
}): Promise>
⋮----
/**
* Get Stop Order List
* Get the un-triggered stop orders list. Stop orders that have been triggered can be queried through the general order endpoint
*/
getStopOrders(
params?: GetStopOrdersRequest,
): Promise>
⋮----
/**
* Get Open Order Value
* You can query this endpoint to get the the total number and value of the all your active orders.
*/
getOpenOrderStatistics(params: {
symbol: string;
}): Promise>
⋮----
/**
* Get Recent Trade History
* Get a list of recent 1000 fills in the last 24 hours.
*/
getRecentFills(params?: {
symbol?: string;
}): Promise>
⋮----
/**
* Get Trade History
* Get a list of recent fills.
* If you need to get your recent trade history with low latency, please query endpoint Get List of Orders Completed in 24h. The requested data is not real-time.
*/
getFills(
params?: AccountFillsRequest,
): Promise>
⋮----
/**
*
* REST - Futures Trading - Positions
*
*/
⋮----
/**
* Get Margin Mode
* This endpoint can query the margin mode of the current symbol.
*/
getMarginMode(params: { symbol: string }): Promise<
APISuccessResponse<{
symbol: string;
marginMode: 'ISOLATED' | 'CROSS';
}>
> {
return this.getPrivate('api/v2/position/getMarginMode', params);
⋮----
/**
* Switch Margin Mode
* Modify the margin mode of the current symbol.
*/
updateMarginMode(params: {
symbol: string;
marginMode: 'ISOLATED' | 'CROSS';
}): Promise<
APISuccessResponse<{
symbol: string;
marginMode: 'ISOLATED' | 'CROSS';
}>
> {
return this.postPrivate('api/v2/position/changeMarginMode', params);
⋮----
/**
* Batch Switch Margin Mode
* Batch modify the margin mode of the symbols.
*/
batchSwitchMarginMode(params: {
marginMode: 'ISOLATED' | 'CROSS';
symbols: string[];
}): Promise>
⋮----
/**
* Get Max Open Size
* Get Maximum Open Position Size.
*/
getMaxOpenSize(
params: MaxOpenSizeRequest,
): Promise>
⋮----
/**
* Get Position Details
* Get the position details of a specified position.
* @deprecated Use getPositionV2 instead
*/
getPosition(params: {
symbol: string;
}): Promise>
⋮----
/**
* Get Position Details
* Get the position details of a specified position.
*/
getPositionV2(params: {
symbol: string;
}): Promise>
⋮----
/**
* Get Position List
* Get the position details of a specified position.
*/
getPositions(params?: {
currency?: string;
}): Promise>
⋮----
/**
* Get Positions History
* This endpoint can query position history information records.
*/
getHistoryPositions(params?: {
symbol?: string;
from?: number;
to?: number;
limit?: number;
pageId?: number;
}): Promise>
⋮----
/**
* Get Max Withdraw Margin
* This endpoint can query the maximum amount of margin that the current position supports withdrawal.
*/
getMaxWithdrawMargin(params: {
symbol: string;
}): Promise>
⋮----
/**
* Get Cross Margin Leverage
* This endpoint can query the current symbol's cross-margin leverage multiple.
*/
getCrossMarginLeverage(params: { symbol: string }): Promise<
APISuccessResponse<{
symbol: string;
leverage: string;
}>
> {
return this.getPrivate('api/v2/getCrossUserLeverage', params);
⋮----
/**
* Modify Cross Margin Leverage
* This endpoint can modify the current symbol's cross-margin leverage multiple.
*/
changeCrossMarginLeverage(params: {
symbol: string;
leverage: string;
}): Promise<
APISuccessResponse<{
symbol: string;
leverage: string;
}>
> {
return this.postPrivate('api/v2/changeCrossUserLeverage', params);
⋮----
/**
* Add Isolated Margin
* Add Isolated Margin Manually.
*/
depositMargin(params: {
symbol: string;
margin: number;
bizNo: string;
}): Promise>
⋮----
/**
* Get Cross Margin Risk Limit
* Batch get cross margin risk limit. (It should be noted that the risk limit of cross margin does not have a fixed gear, but is a smooth curve)
*/
getCrossMarginRiskLimit(params: {
symbol: string;
totalMargin?: string;
leverage?: number;
}): Promise>
⋮----
/**
* Remove Isolated Margin
* Remove Isolated Margin Manually.
*/
withdrawMargin(params: {
symbol: string;
withdrawAmount: string;
}): Promise>
⋮----
/**
* Get Cross Margin Requirement
* This endpoint supports querying the cross margin requirements of a symbol by position value.
*/
getCrossMarginRequirement(params: {
symbol: string;
positionValue: string;
leverage?: string;
}): Promise>
⋮----
/**
* Get Isolated Margin Risk Limit
* This endpoint can be used to obtain information about risk limit level of a specific contract(Only valid for isolated Margin).
*/
getRiskLimitLevel(params: {
symbol: string;
}): Promise>
⋮----
/**
* Modify Isolated Margin Risk Limit
* This endpoint is for the adjustment of the risk limit level(Only valid for isolated Margin).
*/
updateRiskLimitLevel(params: {
symbol: string;
level: number;
}): Promise
⋮----
/**
* Get Position Mode
* This interface can query the position mode of this account.
*/
getPositionMode(): Promise>
⋮----
/**
* Switch Position Mode
* This endpoint can switch the position mode of the current symbol.
*/
updatePositionMode(params: { positionMode: '0' | '1' }): Promise<
APISuccessResponse<{
positionMode: '0' | '1';
}>
> {
return this.postPrivate('api/v2/position/switchPositionMode', params);
⋮----
/**
*
* REST - Futures Trading - Funding Fees
*
*/
⋮----
/**
* Get Current Funding Rate
* This endpoint can be used to obtain the current funding rate of the specified symbol.
*/
getFundingRate(params: {
symbol: string;
}): Promise>
⋮----
/**
* Get Public Funding History
* Query the funding rate at each settlement time point within a certain time range of the corresponding contract
*/
getFundingRates(
params: GetFundingRatesRequest,
): Promise>
⋮----
/**
* Get Private Funding History
* Submit request to get the funding history.
*/
getFundingHistory(params: GetFundingHistoryRequest): Promise<
APISuccessResponse<{
dataList: FuturesAccountFundingRateHistory[];
hasMore: boolean; // Whether there are more pages
}>
> {
return this.getPrivate('api/v1/funding-history', params);
⋮----
hasMore: boolean; // Whether there are more pages
⋮----
/**
*
* REST - Futures Trading - CopyTrading
*
*/
⋮----
/**
* Add Order (Copy Trading)
* Place order to the futures trading system for copy trading.
* Max leverage is set to 20x, and marginMode supports both ISOLATED and CROSS.
*/
submitCopyTradeOrder(params: CopyTradeOrderRequest): Promise<
APISuccessResponse<{
orderId: string;
clientOid: string;
}>
> {
return this.postPrivate('api/v1/copy-trade/futures/orders', params);
⋮----
/**
* Add Order Test (Copy Trading)
* Order test endpoint, the request parameters and return parameters of this endpoint are exactly the same as the order endpoint,
* and can be used to verify whether the signature is correct and other operations.
* Max leverage is set to 20x, and marginMode supports both ISOLATED and CROSS.
*/
submitCopyTradeOrderTest(params: CopyTradeOrderRequest): Promise<
APISuccessResponse<{
orderId: string;
clientOid: string;
}>
> {
return this.postPrivate('api/v1/copy-trade/futures/orders/test', params);
⋮----
/**
* Add Take Profit And Stop Loss Order (Copy Trading)
* Place take profit and stop loss order supports both take-profit and stop-loss functions, and other functions are exactly the same as the place order endpoint.
* Max leverage is set to 20x, and marginMode supports both ISOLATED and CROSS.
*/
submitCopyTradeSLTPOrder(params: CopyTradeSLTPOrderRequest): Promise<
APISuccessResponse<{
orderId: string;
clientOid: string;
}>
> {
return this.postPrivate('api/v1/copy-trade/futures/st-orders', params);
⋮----
/**
* Cancel Order By OrderId
* Cancel an order (including a stop order) in copy trading.
*/
cancelCopyTradeOrderById(params: {
orderId: string;
}): Promise
> {
return this.getPrivate(
'api/v1/copy-trade/futures/get-max-open-size',
params,
);
⋮----
/**
* Get Max Withdraw Margin (Copy Trading)
* This endpoint can query the maximum amount of margin that the current position supports withdrawal.
*/
getCopyTradeMaxWithdrawMargin(params: {
symbol: string;
positionSide?: 'BOTH' | 'LONG' | 'SHORT';
}): Promise>
⋮----
/**
* Add Isolated Margin (Copy Trading)
* Add Isolated Margin Manually.
*/
addCopyTradeIsolatedMargin(params: {
symbol: string;
margin: number;
bizNo: string;
positionSide?: 'BOTH' | 'LONG' | 'SHORT';
}): Promise>
⋮----
/**
* Remove Isolated Margin (Copy Trading)
* Remove Isolated Margin Manually.
*/
removeCopyTradeIsolatedMargin(params: {
symbol: string;
withdrawAmount: string;
positionSide?: 'BOTH' | 'LONG' | 'SHORT';
}): Promise>
⋮----
/**
* Modify Isolated Margin Risk Limit
* This endpoint is for the adjustment of the risk limit level(Only valid for isolated Margin).
* To adjust the level will cancel the open order, the response can only indicate whether the submit of the adjustment request is successful or not.
*/
modifyCopyTradeRiskLimitLevel(params: {
symbol: string;
level: number;
}): Promise>
⋮----
/**
* Modify Isolated Margin Auto-Deposit Status (Copy Trading)
* This endpoint is only applicable to isolated margin and is no longer recommended. It is recommended to use cross margin instead.
* @deprecated - It is recommended to use cross margin instead
*/
updateCopyTradeAutoDepositStatus(params: {
symbol: string;
status: boolean;
positionSide?: 'BOTH' | 'LONG' | 'SHORT';
}): Promise>
⋮----
/**
* Switch Margin Mode (Copy Trading)
* Modify the margin mode of the current symbol.
*/
switchCopyTradeMarginMode(
params: CopyTradeSwitchMarginModeRequest,
): Promise>
⋮----
/**
* Modify Cross Margin Leverage (Copy Trading)
* This interface can modify the current symbol's cross-margin leverage multiple.
*/
updateCopyTradeCrossMarginLeverage(
params: CopyTradeChangeCrossMarginLeverageRequest,
): Promise>
⋮----
/**
* Get Cross Margin Requirement (Copy Trading)
* This endpoint supports querying the cross margin requirements of a symbol by position value.
*/
getCopyTradeCrossMarginRequirement(
params: CopyTradeGetCrossMarginRequirementRequest,
): Promise>
⋮----
/**
* Switch Position Mode (Copy Trading)
* This interface is used to toggle between one-way mode and hedge mode for the position mode.
* Applies to all futures trading pairs.
*/
switchCopyTradePositionMode(
params: CopyTradeSwitchPositionModeRequest,
): Promise>
/**
*
* REST - Futures - Broker
*
*/
⋮----
/**
* Get download link for broker rebate orders
*
* trade type 1 = spot, trade type 2 = futures
* @deprecated Use getBrokerRebateOrderDownloadLinkV2 instead
*/
getBrokerRebateOrderDownloadLink(params: {
begin: string;
end: string;
tradeType: 1 | 2;
}): Promise>
⋮----
/**
* Get download link for broker rebate orders
*
* trade type SPOT = spot, FUTURE = futures
*/
getBrokerRebateOrderDownloadLinkV2(params: {
begin: string;
end: string;
tradeType: 'SPOT' | 'FUTURE';
}): Promise>
⋮----
/**
*
* WebSockets
*
*/
⋮----
getPublicWSConnectionToken(): Promise>
⋮----
getPrivateWSConnectionToken(): Promise>
⋮----
/*
*
* DEPRECATED
*
*/
⋮----
/**
* @deprecated - please use universal transfer from SpotClient
*/
submitTransferOut(params: {
currency: string;
amount: number;
recAccountType: 'MAIN' | 'TRADE';
}): Promise>
⋮----
/**
* @deprecated - please use universal transfer from SpotClient
*/
submitTransferIn(params: {
currency: string;
amount: number;
payAccountType: 'MAIN' | 'TRADE';
}): Promise>
⋮----
/**
* @deprecated - please use universal transfer from SpotClient
*/
getTransfers(params?: {
currency?: string;
type?: 'MAIN' | 'TRADE' | 'MARGIN' | 'ISOLATED';
tag?: string[];
startAt?: number;
endAt?: number;
currentPage?: number;
pageSize?: number;
}): Promise>
⋮----
/**
* @deprecated - please use updateMarginMode() instead
*/
updateAutoDepositStatus(params: {
symbol: string;
status: boolean;
}): Promise>
================
File: src/lib/BaseRestClient.ts
================
import axios, { AxiosRequestConfig, AxiosResponse, Method } from 'axios';
import https from 'https';
⋮----
import { neverGuard } from './misc-util.js';
import {
APIIDFutures,
APIIDFuturesSign,
APIIDMain,
APIIDMainSign,
getRestBaseUrl,
REST_CLIENT_TYPE_ENUM,
RestClientOptions,
RestClientType,
serializeParams,
} from './requestUtils.js';
import {
checkWebCryptoAPISupported,
SignAlgorithm,
SignEncodeMethod,
signMessage,
} from './webCryptoAPI.js';
⋮----
export interface SignedRequest {
originalParams: T;
paramsWithSign?: T & { sign: string };
serializedParams: string;
sign: string;
queryParamsWithSign: string;
timestamp: number;
recvWindow: number;
}
⋮----
interface UnsignedRequest {
originalParams: T;
paramsWithSign: T;
}
⋮----
type SignMethod = 'kucoin';
⋮----
// request: {
// url: response.config.url,
// method: response.config.method,
// data: response.config.data,
// headers: response.config.headers,
// },
⋮----
export abstract class BaseRestClient
⋮----
/** Defines the client type (affecting how requests & signatures behave) */
abstract getClientType(): RestClientType;
⋮----
/**
* Create an instance of the REST client. Pass API credentials in the object in the first parameter.
* @param {RestClientOptions} [restClientOptions={}] options to configure REST API connectivity
* @param {AxiosRequestConfig} [networkOptions={}] HTTP networking options for axios
*/
constructor(
restClientOptions: RestClientOptions = {},
networkOptions: AxiosRequestConfig = {},
)
⋮----
/** Throw errors if any request params are empty */
⋮----
/** in ms == 5 minutes by default */
⋮----
/** inject custom rquest options based on axios specs - see axios docs for more guidance on AxiosRequestConfig: https://github.com/axios/axios#request-config */
⋮----
// If enabled, configure a https agent with keepAlive enabled
⋮----
// Extract existing https agent parameters, if provided, to prevent the keepAlive flag from overwriting an existing https agent completely
⋮----
// For more advanced configuration, raise an issue on GitHub or use the "networkOptions"
// parameter to define a custom httpsAgent with the desired properties
⋮----
// Check Web Crypto API support when credentials are provided
⋮----
// Throw if one of the 3 values is missing, but at least one of them is set
⋮----
/**
* Generates a timestamp for signing API requests.
*
* This method can be overridden or customized using `customTimestampFn`
* to implement a custom timestamp synchronization mechanism.
* If no custom function is provided, it defaults to the current system time.
*/
private getSignTimestampMs(): number
⋮----
private hasValidCredentials()
⋮----
setAccessToken(newAccessToken: string)
⋮----
hasAccessToken(): boolean
⋮----
get(endpoint: string, params?: any)
⋮----
post(endpoint: string, params?: any)
⋮----
getPrivate(endpoint: string, params?: any)
⋮----
postPrivate(endpoint: string, params?: any)
⋮----
deletePrivate(endpoint: string, params?: any)
⋮----
/**
* @private Make a HTTP request to a specific endpoint. Private endpoint API calls are automatically signed.
*/
private async _call(
method: Method,
endpoint: string,
params?: any,
isPublicApi?: boolean,
): Promise
⋮----
// Sanity check to make sure it's only ever prefixed by one forward slash
⋮----
// Build a request and handle signature process
⋮----
// Dispatch request
⋮----
// Throw if API returns an error (e.g. insufficient balance)
⋮----
/**
* @private generic handler to parse request exceptions
*/
parseException(e: any, requestParams: any): unknown
⋮----
// Something happened in setting up the request that triggered an error
⋮----
// request made but no response received
⋮----
// The request was made and the server responded with a status code
// that falls out of the range of 2xx
⋮----
// console.error('err: ', response?.data);
⋮----
// Prevent credentials from leaking into error messages
⋮----
private async signMessage(
paramsStr: string,
secret: string,
method: SignEncodeMethod,
algorithm: SignAlgorithm,
): Promise
⋮----
/**
* @private sign request and set recv window
*/
private async signRequest(
data: T,
endpoint: string,
method: Method,
signMethod: SignMethod,
): Promise>
⋮----
// Only sign when no access token is provided
⋮----
private async prepareSignParams(
method: Method,
endpoint: string,
signMethod: SignMethod,
params?: TParams,
isPublicApi?: true,
): Promise>;
⋮----
private async prepareSignParams(
method: Method,
endpoint: string,
signMethod: SignMethod,
params?: TParams,
isPublicApi?: false | undefined,
): Promise>;
⋮----
private async prepareSignParams(
method: Method,
endpoint: string,
signMethod: SignMethod,
params?: TParams,
isPublicApi?: boolean,
)
⋮----
/** Returns an axios request object. Handles signing process automatically if this is a private API call */
private async buildRequest(
method: Method,
endpoint: string,
url: string,
params?: any,
isPublicApi?: boolean,
): Promise
⋮----
// Support for Authorization header, if provided:
// https://github.com/tiagosiebler/kucoin-api/issues/2
// Use restClient.setAccessToken(newToken), if you need to store a new access token
================
File: src/types/response/futures.types.ts
================
/**
* REST - ACCOUNT - BASIC INFO
* Get Account Ledgers - Futures
*/
⋮----
export interface FuturesAccountTransaction {
time: number; // Event time
type: 'RealisedPNL' | 'Deposit' | 'Withdrawal' | 'TransferIn' | 'TransferOut'; // Type
amount: number; // Transaction amount
fee: number | null; // Fees
accountEquity: number; // Account equity
status: 'Completed' | 'Pending'; // Status
remark: string; // Ticker symbol of the contract
offset: number; // Offset
currency: string; // Currency
}
⋮----
time: number; // Event time
type: 'RealisedPNL' | 'Deposit' | 'Withdrawal' | 'TransferIn' | 'TransferOut'; // Type
amount: number; // Transaction amount
fee: number | null; // Fees
accountEquity: number; // Account equity
status: 'Completed' | 'Pending'; // Status
remark: string; // Ticker symbol of the contract
offset: number; // Offset
currency: string; // Currency
⋮----
/**
* REST - ACCOUNT - SUBACCOUNT API
*/
⋮----
export interface SubAccountAPI {
apiKey: string; // API-Key
createdAt: number; // Time of the event
ipWhitelist: string; // IP whitelist
permission: string; // Permissions
remark: string; // Remarks
subName: string; // Sub-account name
}
⋮----
apiKey: string; // API-Key
createdAt: number; // Time of the event
ipWhitelist: string; // IP whitelist
permission: string; // Permissions
remark: string; // Remarks
subName: string; // Sub-account name
⋮----
export type CreateSubAccountAPI = SubAccountAPI & {
apiSecret: string; // API secret
passphrase: string; // Password
};
⋮----
apiSecret: string; // API secret
passphrase: string; // Password
⋮----
export interface UpdateSubAccountAPI {
apiKey: string; // API-Key
ipWhitelist: string; // IP whitelist
permission: string; // Permissions
subName: string; // Sub-account name
}
⋮----
apiKey: string; // API-Key
ipWhitelist: string; // IP whitelist
permission: string; // Permissions
subName: string; // Sub-account name
⋮----
/**
* REST - FUNDING - FUNDING OVERVIEW
*/
⋮----
export interface AccountBalance {
accountEquity: number; // Account equity = marginBalance + Unrealised PNL
unrealisedPNL: number; // Unrealised profit and loss
marginBalance: number; // Margin balance = positionMargin + orderMargin + frozenFunds + availableBalance - unrealisedPNL
positionMargin: number; // Position margin
orderMargin: number; // Order margin
frozenFunds: number; // Frozen funds for withdrawal and out-transfer
availableBalance: number; // Available balance
currency: string; // currency code
riskRatio: number; // Cross margin risk ratio
maxWithdrawAmount: number; // Maximum withdrawal amount
availableMargin: number; // Cross margin available balance
}
⋮----
accountEquity: number; // Account equity = marginBalance + Unrealised PNL
unrealisedPNL: number; // Unrealised profit and loss
marginBalance: number; // Margin balance = positionMargin + orderMargin + frozenFunds + availableBalance - unrealisedPNL
positionMargin: number; // Position margin
orderMargin: number; // Order margin
frozenFunds: number; // Frozen funds for withdrawal and out-transfer
availableBalance: number; // Available balance
currency: string; // currency code
riskRatio: number; // Cross margin risk ratio
maxWithdrawAmount: number; // Maximum withdrawal amount
availableMargin: number; // Cross margin available balance
⋮----
export interface AccountSummary {
accountEquityTotal: number; // Total Account Equity
unrealisedPNLTotal: number; // Total unrealisedPNL
marginBalanceTotal: number; // Total Margin Balance
positionMarginTotal: number; // Total Position margin
orderMarginTotal: number; // Total Order Margin
frozenFundsTotal: number; // Total frozen funds for withdrawal and out-transfer
availableBalanceTotal: number; // total available balance
currency: string; // currency
}
⋮----
accountEquityTotal: number; // Total Account Equity
unrealisedPNLTotal: number; // Total unrealisedPNL
marginBalanceTotal: number; // Total Margin Balance
positionMarginTotal: number; // Total Position margin
orderMarginTotal: number; // Total Order Margin
frozenFundsTotal: number; // Total frozen funds for withdrawal and out-transfer
availableBalanceTotal: number; // total available balance
currency: string; // currency
⋮----
export interface FuturesSubAccount {
accountName: string;
accountEquity: number;
unrealisedPNL: number;
marginBalance: number;
positionMargin: number;
orderMargin: number;
frozenFunds: number;
availableBalance: number;
currency: string;
}
⋮----
/**
* REST - FUNDING - TRANSFER
*/
⋮----
export interface TransferDetail {
applyId: string; // Transfer-out request ID
bizNo: string; // Business number
payAccountType: string; // Pay account type
payTag: string; // Pay account sub type
remark: string; // User remark
recAccountType: string; // Receive account type
recTag: string; // Receive account sub type
recRemark: string; // Receive account tx remark
recSystem: string; // Receive system
status: string; // Status: APPLY, PROCESSING, PENDING_APPROVAL, APPROVED, REJECTED, PENDING_CANCEL, CANCEL, SUCCESS
currency: string; // Currency
amount: string; // Transfer amount
fee: string; // Transfer fee
sn: number; // Serial number
reason: string; // Fail Reason
createdAt: number; // Create time
updatedAt: number; // Update time
}
⋮----
applyId: string; // Transfer-out request ID
bizNo: string; // Business number
payAccountType: string; // Pay account type
payTag: string; // Pay account sub type
remark: string; // User remark
recAccountType: string; // Receive account type
recTag: string; // Receive account sub type
recRemark: string; // Receive account tx remark
recSystem: string; // Receive system
status: string; // Status: APPLY, PROCESSING, PENDING_APPROVAL, APPROVED, REJECTED, PENDING_CANCEL, CANCEL, SUCCESS
currency: string; // Currency
amount: string; // Transfer amount
fee: string; // Transfer fee
sn: number; // Serial number
reason: string; // Fail Reason
createdAt: number; // Create time
updatedAt: number; // Update time
⋮----
interface TransferOutRequestRecord {
applyId: string; // Transfer-out request ID
currency: string; // Currency
recRemark: string; // Receive account tx remark
recSystem: string; // Receive system
status: string; // Status: PROCESSING, SUCCESS, FAILURE
amount: string; // Transaction amount
reason: string; // Reason caused the failure
offset: number; // Offset
createdAt: number; // Request application time
remark: string; // User remark
}
⋮----
applyId: string; // Transfer-out request ID
currency: string; // Currency
recRemark: string; // Receive account tx remark
recSystem: string; // Receive system
status: string; // Status: PROCESSING, SUCCESS, FAILURE
amount: string; // Transaction amount
reason: string; // Reason caused the failure
offset: number; // Offset
createdAt: number; // Request application time
remark: string; // User remark
⋮----
export interface FuturesTransferRecords {
currentPage: number;
pageSize: number;
totalNum: number;
totalPage: number;
items: TransferOutRequestRecord[];
}
⋮----
/**
*
* Futures Market Data
*
*/
⋮----
export interface FuturesSymbolInfo {
symbol: string;
rootSymbol: string;
type: 'FFWCSX' | 'FFICSX';
firstOpenDate: number;
expireDate: number | null;
settleDate: number | null;
baseCurrency: string;
quoteCurrency: string;
settleCurrency: string;
maxOrderQty: number;
maxPrice: number;
lotSize: number;
tickSize: number;
indexPriceTickSize: number;
multiplier: number;
initialMargin: number;
maintainMargin: number;
maxRiskLimit: number;
minRiskLimit: number;
riskStep: number;
makerFeeRate: number;
takerFeeRate: number;
takerFixFee: number;
makerFixFee: number;
settlementFee: number | null;
isDeleverage: boolean;
isQuanto: boolean;
isInverse: boolean;
markMethod: 'FairPrice';
fairMethod: 'FundingRate';
fundingBaseSymbol: string;
fundingQuoteSymbol: string;
fundingRateSymbol: string;
indexSymbol: string;
settlementSymbol: string | null;
status:
| 'Init'
| 'Open'
| 'BeingSettled'
| 'Settled'
| 'Paused'
| 'Closed'
| 'CancelOnly';
fundingFeeRate: number;
predictedFundingFeeRate: number;
fundingRateGranularity: number;
effectiveFundingRateCycleStartTime: number; // Funding rate time interval (fundingRateGranularity) configuration start effective time
currentFundingRateGranularity: number; // Current effective funding rate period granularity (e.g., 8 hours/4 hours)
openInterest: string;
turnoverOf24h: number;
volumeOf24h: number;
markPrice: number;
indexPrice: number;
lastTradePrice: number;
nextFundingRateTime: number;
maxLeverage: number;
sourceExchanges: string[];
premiumsSymbol1M: string;
premiumsSymbol8H: string;
fundingBaseSymbol1M: string;
fundingQuoteSymbol1M: string;
lowPrice: number;
highPrice: number;
priceChgPct: number;
priceChg: number;
k: number;
m: number;
f: number;
mmrLimit: number;
mmrLevConstant: number;
supportCross: boolean;
}
⋮----
effectiveFundingRateCycleStartTime: number; // Funding rate time interval (fundingRateGranularity) configuration start effective time
currentFundingRateGranularity: number; // Current effective funding rate period granularity (e.g., 8 hours/4 hours)
⋮----
export interface TickerDetail {
sequence: number; // Sequence number
symbol: string; // Symbol
side: string; // Side of liquidity taker
size: number; // Filled quantity
price: string; // Filled price
bestBidSize: number; // Best bid size
bestBidPrice: string; // Best bid price
bestAskSize: number; // Best ask size
bestAskPrice: string; // Best ask price
tradeId: string; // Transaction ID
ts: number; // Filled time - nanosecond
}
⋮----
sequence: number; // Sequence number
symbol: string; // Symbol
side: string; // Side of liquidity taker
size: number; // Filled quantity
price: string; // Filled price
bestBidSize: number; // Best bid size
bestBidPrice: string; // Best bid price
bestAskSize: number; // Best ask size
bestAskPrice: string; // Best ask price
tradeId: string; // Transaction ID
ts: number; // Filled time - nanosecond
⋮----
export interface MarketTradeDetail {
sequence: number; // Sequence number
tradeId: string; // Transaction ID
takerOrderId: string; // Taker order ID
makerOrderId: string; // Maker order ID
price: string; // Filled price
size: number; // Filled quantity
side: string; // Side-taker
ts: number; // Filled time - nanosecond
}
⋮----
sequence: number; // Sequence number
tradeId: string; // Transaction ID
takerOrderId: string; // Taker order ID
makerOrderId: string; // Maker order ID
price: string; // Filled price
size: number; // Filled quantity
side: string; // Side-taker
ts: number; // Filled time - nanosecond
⋮----
export interface FullOrderBookDetail {
symbol: string; // Symbol
sequence: number; // Ticker sequence number
asks: [number, number][]; // asks. [Price, quantity]
bids: [number, number][]; // bids. [Price, quantity]
ts: number; // Timestamp
}
⋮----
symbol: string; // Symbol
sequence: number; // Ticker sequence number
asks: [number, number][]; // asks. [Price, quantity]
bids: [number, number][]; // bids. [Price, quantity]
ts: number; // Timestamp
⋮----
export type FuturesKline = [
number, // Time
number, // Entry price
number, // Highest price
number, // Lowest price
number, // Close price
number, // Trading volume(lots)
number, // Trading volume
];
⋮----
number, // Time
number, // Entry price
number, // Highest price
number, // Lowest price
number, // Close price
number, // Trading volume(lots)
number, // Trading volume
⋮----
export interface InterestRateItem {
symbol: string; // Symbol of the Bitcoin Lending Rate
granularity: number; // Granularity (millisecond)
timePoint: number; // Time point (millisecond)
value: number; // Interest rate value
}
⋮----
symbol: string; // Symbol of the Bitcoin Lending Rate
granularity: number; // Granularity (millisecond)
timePoint: number; // Time point (millisecond)
value: number; // Interest rate value
⋮----
export interface IndexListItem {
symbol: string; // Symbol of Bitcoin spot
granularity: number; // Granularity (millisecond)
timePoint: number; // Time point (millisecond)
value: number; // Index Value
decomposionList: {
exchange: string; // Exchange
price: number; // Last traded price
weight: number; // Weight
}[];
}
⋮----
symbol: string; // Symbol of Bitcoin spot
granularity: number; // Granularity (millisecond)
timePoint: number; // Time point (millisecond)
value: number; // Index Value
⋮----
exchange: string; // Exchange
price: number; // Last traded price
weight: number; // Weight
⋮----
export interface FuturesMarkPrice {
symbol: string; // Symbol
granularity: number; // Granularity (millisecond)
timePoint: number; // Time point (millisecond)
value: number; // Mark price
indexPrice: number; // Index price
}
⋮----
symbol: string; // Symbol
granularity: number; // Granularity (millisecond)
timePoint: number; // Time point (millisecond)
value: number; // Mark price
indexPrice: number; // Index price
⋮----
export interface PremiumIndexItem {
symbol: string; // Premium index symbol
granularity: number; // Granularity (millisecond)
timePoint: number; // Time point (millisecond)
value: number; // Premium index
}
⋮----
symbol: string; // Premium index symbol
granularity: number; // Granularity (millisecond)
timePoint: number; // Time point (millisecond)
value: number; // Premium index
⋮----
/**
*
***********
* Account
***********
*
*/
⋮----
/**
*
* Orders
*
*/
⋮----
export interface FuturesOrder {
id: string;
symbol: string;
type: 'market' | 'limit';
side: 'buy' | 'sell';
price: string;
size: number;
value: string;
dealValue: string;
dealSize: number;
stp: 'CN' | 'CO' | 'CB' | '';
stop: string;
stopPriceType: 'TP' | 'MP' | 'IP' | '';
stopTriggered: boolean;
stopPrice: number | null;
timeInForce: string;
postOnly: boolean;
hidden: boolean;
iceberg: boolean;
leverage: string;
forceHold: boolean;
closeOrder: boolean;
visibleSize: number;
clientOid: string;
remark: string | null;
tags: string;
isActive: boolean;
cancelExist: boolean;
createdAt: number;
updatedAt: number;
endAt: number | null;
orderTime: number;
settleCurrency: string;
marginMode: 'ISOLATED' | 'CROSS';
avgDealPrice: string;
filledSize: number;
filledValue: string;
status: 'open' | 'done';
reduceOnly: boolean;
}
⋮----
export interface BatchCancelOrderResult {
orderId: string | null;
clientOid: string | null;
code: string;
msg: string;
}
⋮----
export interface SubmitMultipleOrdersFuturesResponse {
orderId: string;
clientOid: string;
symbol: string;
code: string;
msg: string;
}
⋮----
export interface FuturesOrders {
currentPage: number;
pageSize: number;
totalNum: number;
totalPage: number;
items: FuturesOrder[];
}
⋮----
/**
*
* Futures Fills
*
*/
⋮----
export interface FuturesFill {
symbol: string;
tradeId: string;
orderId: string;
side: 'buy' | 'sell';
liquidity: 'taker' | 'maker';
forceTaker: boolean;
price: string;
size: number;
value: string;
openFeePay: string;
closeFeePay: string;
stop: string;
feeRate: string;
fixFee: string; // Deprecated field
feeCurrency: string;
marginMode: 'ISOLATED' | 'CROSS';
fee: string;
settleCurrency: string;
orderType: 'market' | 'limit';
displayType: 'limit' | 'market' | 'limit_stop' | 'market_stop';
tradeType: 'trade' | 'cancel' | 'liquid' | 'adl' | 'settlement';
subTradeType: string | null; // Deprecated field
tradeTime: number;
createdAt: number;
}
⋮----
fixFee: string; // Deprecated field
⋮----
subTradeType: string | null; // Deprecated field
⋮----
export interface FuturesFills {
currentPage: number;
pageSize: number;
totalNum: number;
totalPage: number;
items: FuturesFill[];
}
⋮----
export interface FuturesActiveOrder {
openOrderBuySize: number; // Total number of the unexecuted buy orders
openOrderSellSize: number; // Total number of the unexecuted sell orders
openOrderBuyCost: string; // Value of all the unexecuted buy orders
openOrderSellCost: string; // Value of all the unexecuted sell orders
settleCurrency: string; // settlement currency
}
⋮----
openOrderBuySize: number; // Total number of the unexecuted buy orders
openOrderSellSize: number; // Total number of the unexecuted sell orders
openOrderBuyCost: string; // Value of all the unexecuted buy orders
openOrderSellCost: string; // Value of all the unexecuted sell orders
settleCurrency: string; // settlement currency
⋮----
/**
*
* Futures Positions
*
*/
⋮----
export interface BatchMarginModeUpdateResponse {
marginMode: {
[symbol: string]: 'ISOLATED' | 'CROSS';
};
errors: {
code: string;
msg: string;
symbol: string;
}[];
}
⋮----
export interface GetPositionModeResponse {
positionMode: 0 | 1; // 0 = one-way mode, 1 = hedge mode
}
⋮----
positionMode: 0 | 1; // 0 = one-way mode, 1 = hedge mode
⋮----
export interface MaxOpenSize {
symbol: string;
maxBuyOpenSize: number;
maxSellOpenSize: number;
}
⋮----
export interface FuturesPosition {
id: string;
symbol: string;
marginMode: 'CROSS' | 'ISOLATED';
crossMode: boolean;
delevPercentage: number;
openingTimestamp: number;
currentTimestamp: number;
currentQty: number;
currentCost: number;
currentComm: number;
realisedGrossPnl: number;
realisedGrossCost: number;
realisedCost: number;
unrealisedCost: number;
unrealisedPnlPcnt: number;
unrealisedPnl: number;
unrealisedRoePcnt: number;
isOpen: boolean;
markPrice: number;
markValue: number;
posCost: number;
posInit: number;
posMargin: number;
realisedPnl: number;
avgEntryPrice: number;
liquidationPrice: number;
bankruptPrice: number;
settleCurrency: string;
isInverse: boolean;
positionSide: 'BOTH';
leverage: number;
// Isolated margin specific fields
autoDeposit?: boolean;
maintMarginReq?: number;
riskLimit?: number;
realLeverage?: number;
posCross?: number;
posCrossMargin?: number;
posComm?: number;
posCommCommon?: number;
posLoss?: number;
posFunding?: number;
posMaint?: number;
maintMargin?: number;
maintainMargin?: number;
riskLimitLevel?: number;
}
⋮----
// Isolated margin specific fields
⋮----
export interface AddMargin {
id: string; // Position ID
symbol: string; // Symbol of the contract
autoDeposit: boolean; // Auto deposit margin or not
maintMarginReq: number; // Maintenance margin requirement
riskLimit: number; // Risk limit
realLeverage: number; // Leverage of the order
crossMode: boolean; // Cross mode or not
delevPercentage: number; // ADL ranking percentile
openingTimestamp: number; // Open time
currentTimestamp: number; // Current timestamp
currentQty: number; // Current position quantity
currentCost: number; // Current position value
currentComm: number; // Current commission
unrealisedCost: number; // Unrealised value
realisedGrossCost: number; // Accumulated realised gross profit value
realisedCost: number; // Current realised position value
isOpen: boolean; // Opened position or not
markPrice: number; // Mark price
markValue: number; // Mark value
posCost: number; // Position value
posCross: number; // added margin
posInit: number; // Leverage margin
posComm: number; // Bankruptcy cost
posLoss: number; // Funding fees paid out
posMargin: number; // Position margin
posMaint: number; // Maintenance margin
maintMargin: number; // Position margin
realisedGrossPnl: number; // Accumulated realised gross profit value
realisedPnl: number; // Realised profit and loss
unrealisedPnl: number; // Unrealised profit and loss
unrealisedPnlPcnt: number; // Profit-loss ratio of the position
unrealisedRoePcnt: number; // Rate of return on investment
avgEntryPrice: number; // Average entry price
liquidationPrice: number; // Liquidation price
bankruptPrice: number; // Bankruptcy price
settleCurrency: string; // Currency used to clear and settle the trades
userId: number; // userId
}
⋮----
id: string; // Position ID
symbol: string; // Symbol of the contract
autoDeposit: boolean; // Auto deposit margin or not
maintMarginReq: number; // Maintenance margin requirement
riskLimit: number; // Risk limit
realLeverage: number; // Leverage of the order
crossMode: boolean; // Cross mode or not
delevPercentage: number; // ADL ranking percentile
openingTimestamp: number; // Open time
currentTimestamp: number; // Current timestamp
currentQty: number; // Current position quantity
currentCost: number; // Current position value
currentComm: number; // Current commission
unrealisedCost: number; // Unrealised value
realisedGrossCost: number; // Accumulated realised gross profit value
realisedCost: number; // Current realised position value
isOpen: boolean; // Opened position or not
markPrice: number; // Mark price
markValue: number; // Mark value
posCost: number; // Position value
posCross: number; // added margin
posInit: number; // Leverage margin
posComm: number; // Bankruptcy cost
posLoss: number; // Funding fees paid out
posMargin: number; // Position margin
posMaint: number; // Maintenance margin
maintMargin: number; // Position margin
realisedGrossPnl: number; // Accumulated realised gross profit value
realisedPnl: number; // Realised profit and loss
unrealisedPnl: number; // Unrealised profit and loss
unrealisedPnlPcnt: number; // Profit-loss ratio of the position
unrealisedRoePcnt: number; // Rate of return on investment
avgEntryPrice: number; // Average entry price
liquidationPrice: number; // Liquidation price
bankruptPrice: number; // Bankruptcy price
settleCurrency: string; // Currency used to clear and settle the trades
userId: number; // userId
⋮----
export interface CrossMarginRiskLimit {
symbol: string;
maxOpenSize: number;
maxOpenValue: string;
totalMargin: string;
price: string;
leverage: string;
mmr: string;
imr: string;
currency: string;
}
⋮----
export interface CrossMarginRequirement {
symbol: string;
imr: string;
mmr: string;
size: number;
positionValue: string;
price: string;
}
⋮----
/**
*
* Futures risk limit
*
*/
⋮----
export interface FuturesRiskLimit {
symbol: string; // Path parameter. Symbol of the contract.
level: number; // level
maxRiskLimit: number; // Upper limit (includes)
minRiskLimit: number; // Lower limit
maxLeverage: number; // Max leverage
initialMargin: number; // Initial margin rate
maintainMargin: number; // Maintenance margin rate
}
⋮----
symbol: string; // Path parameter. Symbol of the contract.
level: number; // level
maxRiskLimit: number; // Upper limit (includes)
minRiskLimit: number; // Lower limit
maxLeverage: number; // Max leverage
initialMargin: number; // Initial margin rate
maintainMargin: number; // Maintenance margin rate
⋮----
/**
*
* Futures funding fees
*
*/
⋮----
export interface FuturesCurrentFundingRate {
symbol: string; // Funding Rate Symbol
granularity: number; // Granularity (milliseconds)
timePoint: number; // Time point (milliseconds)
value: number; // Funding rate
predictedValue: number; // Predicted funding rate
fundingRateCap: number; // Funding rate cap
fundingRateFloor: number; // Funding rate floor
period: number; // Funding rate period
fundingTime: number; // Funding time
}
⋮----
symbol: string; // Funding Rate Symbol
granularity: number; // Granularity (milliseconds)
timePoint: number; // Time point (milliseconds)
value: number; // Funding rate
predictedValue: number; // Predicted funding rate
fundingRateCap: number; // Funding rate cap
fundingRateFloor: number; // Funding rate floor
period: number; // Funding rate period
fundingTime: number; // Funding time
⋮----
export interface FuturesHistoricFundingRate {
symbol: string; // Symbol of the contract
timePoint: number; // Time point (milliseconds)
fundingRate: number; // Funding rate
}
⋮----
symbol: string; // Symbol of the contract
timePoint: number; // Time point (milliseconds)
fundingRate: number; // Funding rate
⋮----
export interface FuturesAccountFundingRateHistory {
id: number;
symbol: string;
timePoint: number;
fundingRate: number;
markPrice: number;
positionQty: number;
positionCost: number;
funding: number;
settleCurrency: string;
context: string; // JSON string containing additional details
marginMode: 'ISOLATED' | 'CROSS';
}
⋮----
context: string; // JSON string containing additional details
⋮----
export interface FuturesClosedPosition {
closeId: string;
userId: string;
symbol: string;
settleCurrency: string;
leverage: string;
type: string;
pnl: string;
realisedGrossCost: string;
withdrawPnl: string;
tradeFee: string;
fundingFee: string;
openTime: number;
closeTime: number;
openPrice: string;
closePrice: string;
marginMode: 'CROSS' | 'ISOLATED';
}
⋮----
export interface FuturesClosedPositions {
currentPage: number;
pageSize: number;
totalNum: number;
totalPage: number;
items: FuturesClosedPosition[];
}
⋮----
/**
*
* Copy Trading
*
*/
⋮----
export interface CopyTradePosition {
id: string;
symbol: string;
autoDeposit: boolean;
maintMarginReq: string;
riskLimit: number;
realLeverage: string;
crossMode: boolean;
marginMode: string;
positionSide: string;
leverage: string;
delevPercentage: number;
openingTimestamp: number;
currentTimestamp: number;
currentQty: number;
currentCost: string;
currentComm: string;
unrealisedCost: string;
realisedGrossCost: string;
realisedCost: string;
isOpen: boolean;
markPrice: string;
markValue: string;
posCost: string;
posCross: string;
posInit: string;
posComm: string;
posLoss: string;
posMargin: string;
posMaint: string;
maintMargin: string;
realisedGrossPnl: string;
realisedPnl: string;
unrealisedPnl: string;
unrealisedPnlPcnt: string;
unrealisedRoePcnt: string;
avgEntryPrice: string;
liquidationPrice: string;
bankruptPrice: string;
settleCurrency: string;
}
⋮----
/**
* Switch Margin Mode Response (Copy Trading)
*/
export interface CopyTradeSwitchMarginModeResponse {
symbol: string;
marginMode: 'ISOLATED' | 'CROSS';
}
⋮----
/**
* Get Cross Margin Requirement Response (Copy Trading)
*/
export interface CopyTradeCrossMarginRequirement {
imr: string;
mmr: string;
positionValue: string;
price: string;
size: number;
symbol: string;
}
⋮----
/**
* Switch Position Mode Response (Copy Trading)
*/
export interface CopyTradeSwitchPositionModeResponse {
positionMode: '0' | '1'; // 0 = one-way mode, 1 = hedge mode
}
⋮----
positionMode: '0' | '1'; // 0 = one-way mode, 1 = hedge mode
================
File: src/index.ts
================
================
File: src/lib/BaseWSClient.ts
================
import EventEmitter from 'events';
import WebSocket from 'isomorphic-ws';
⋮----
import { WsOperation } from '../types/websockets/ws-api.js';
import {
isMessageEvent,
MessageEventLike,
} from '../types/websockets/ws-events.js';
import {
WebsocketClientOptions,
WSClientConfigurableOptions,
WsEventInternalSrc,
} from '../types/websockets/ws-general.js';
import { WS_LOGGER_CATEGORY } from '../WebsocketClient.js';
import { checkWebCryptoAPISupported } from './webCryptoAPI.js';
import { DefaultLogger } from './websocket/logger.js';
import {
safeTerminateWs,
WsTopicRequest,
WsTopicRequestOrStringTopic,
} from './websocket/websocket-util.js';
import { WsStore } from './websocket/WsStore.js';
import {
WSConnectedResult,
WsConnectionStateEnum,
} from './websocket/WsStore.types.js';
⋮----
type UseTheExceptionEventInstead = never;
⋮----
interface WSClientEventMap {
/** Connection opened. If this connection was previously opened and reconnected, expect the reconnected event instead */
open: (evt: {
wsKey: WsKey;
event: any;
wsUrl: string;
ws: WebSocket;
}) => void;
/** Reconnecting a dropped connection */
reconnect: (evt: { wsKey: WsKey; event: any }) => void;
/** Successfully reconnected a connection that dropped */
reconnected: (evt: {
wsKey: WsKey;
event: any;
wsUrl: string;
ws: WebSocket;
}) => void;
/** Connection closed */
close: (evt: { wsKey: WsKey; event: any }) => void;
/** Received reply to websocket command (e.g. after subscribing to topics) */
response: (response: any & { wsKey: WsKey }) => void;
/** Received data for topic */
update: (response: any & { wsKey: WsKey }) => void;
/** Exception from ws client OR custom listeners (e.g. if you throw inside your event handler) */
exception: (response: any & { wsKey: WsKey }) => void;
/**
* See for more information: https://github.com/tiagosiebler/bybit-api/issues/413
* @deprecated Use the 'exception' event instead. The 'error' event had the unintended consequence of throwing an unhandled promise rejection.
*/
error: UseTheExceptionEventInstead;
/** Confirmation that a connection successfully authenticated */
authenticated: (event: { wsKey: WsKey; event: any }) => void;
}
⋮----
/** Connection opened. If this connection was previously opened and reconnected, expect the reconnected event instead */
⋮----
/** Reconnecting a dropped connection */
⋮----
/** Successfully reconnected a connection that dropped */
⋮----
/** Connection closed */
⋮----
/** Received reply to websocket command (e.g. after subscribing to topics) */
⋮----
/** Received data for topic */
⋮----
/** Exception from ws client OR custom listeners (e.g. if you throw inside your event handler) */
⋮----
/**
* See for more information: https://github.com/tiagosiebler/bybit-api/issues/413
* @deprecated Use the 'exception' event instead. The 'error' event had the unintended consequence of throwing an unhandled promise rejection.
*/
⋮----
/** Confirmation that a connection successfully authenticated */
⋮----
export interface EmittableEvent {
eventType:
| 'response'
| 'update'
| 'exception'
| 'connectionReadyForAuth' // tied to specific events we need to wait for, before we can begin post-connect auth
| 'authenticated'
| 'connectionReady'; // tied to "requireConnectionReadyConfirmation"
event: TEvent;
isWSAPIResponse?: boolean;
}
⋮----
| 'connectionReadyForAuth' // tied to specific events we need to wait for, before we can begin post-connect auth
⋮----
| 'connectionReady'; // tied to "requireConnectionReadyConfirmation"
⋮----
// Type safety for on and emit handlers: https://stackoverflow.com/a/61609010/880837
export interface BaseWebsocketClient {
on>(
event: U,
listener: WSClientEventMap[U],
): this;
emit>(
event: U,
...args: Parameters[U]>
): boolean;
}
⋮----
on>(
event: U,
listener: WSClientEventMap[U],
): this;
⋮----
emit>(
event: U,
...args: Parameters[U]>
): boolean;
⋮----
/**
* Appends wsKey and isWSAPIResponse to all events.
* Some events are arrays, this handles that nested scenario too.
*/
function getFinalEmittable(
emittable: EmittableEvent | EmittableEvent[],
wsKey: any,
isWSAPIResponse?: boolean,
): any
⋮----
// Some topics just emit an array.
// This is consistent with how it was before the WS API upgrade:
⋮----
// const { event, ...others } = emittable;
// return {
// ...others,
// event: event.map((subEvent) =>
// getFinalEmittable(subEvent, wsKey, isWSAPIResponse),
// ),
// };
⋮----
/**
* Users can conveniently pass topics as strings or objects (object has topic name + optional params).
*
* This method normalises topics into objects (object has topic name + optional params).
*/
function getNormalisedTopicRequests(
wsTopicRequests: WsTopicRequestOrStringTopic[],
): WsTopicRequest[]
⋮----
// passed as string, convert to object
⋮----
// already a normalised object, thanks to user
⋮----
type WSTopic = string;
⋮----
// eslint-disable-next-line @typescript-eslint/no-unsafe-declaration-merging
export abstract class BaseWebsocketClient<
TWSKey extends string,
⋮----
constructor(options?: WSClientConfigurableOptions, logger?: DefaultLogger)
⋮----
// Requires a confirmation "response" from the ws connection before assuming it is ready
⋮----
// Automatically auth after opening a connection?
⋮----
// Automatically include auth/sign with every WS request
⋮----
// Automatically re-auth WS API, if we were auth'd before and get reconnected
⋮----
// Whether to use native heartbeats (depends on the exchange)
⋮----
// Check Web Crypto API support when credentials are provided and no custom sign function is used
⋮----
protected abstract sendPingEvent(wsKey: TWSKey, ws: WebSocket): void;
⋮----
protected abstract sendPongEvent(wsKey: TWSKey, ws: WebSocket): void;
⋮----
protected abstract isWsPing(data: any): boolean;
⋮----
protected abstract isWsPong(data: any): boolean;
⋮----
protected abstract getWsAuthRequestEvent(
wsKey: TWSKey,
eventToAuth?: object,
): Promise