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/ 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 ws-futures-private.ts ws-futures-public.ts ws-spot-private.ts ws-spot-public.ts 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 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 ws.ts websockets/ client.ts events.ts requests.ts wsAPI.ts BrokerClient.ts FuturesClient.ts index.ts SpotClient.ts WebsocketClient.ts .eslintrc.cjs .gitignore .nvmrc .prettierrc jest.config.ts 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

SDK Logo

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

SDK Logo

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-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: examples/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/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/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/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); ================ 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 = 5, ⋮---- export interface DeferredPromise { resolve?: (value: TSuccess) => TSuccess; reject?: (value: TError) => TError; promise?: Promise; } ⋮---- export interface WSConnectedResult { wsKey: string; } ⋮---- export interface WsStoredState { /** The currently active websocket connection */ ws?: WebSocket; /** The current lifecycle state of the connection (enum) */ connectionState?: WsConnectionStateEnum; /** 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); */ // connectionInProgressPromise?: DeferredPromise | undefined; 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 is ready for events (welcome message received after connection) */ isReadyForEvents?: boolean; /** 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); */ // connectionInProgressPromise?: DeferredPromise | undefined; ⋮---- /** * 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 is ready for events (welcome message received after connection) */ ⋮---- /** 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/misc-util.ts ================ export function neverGuard(x: never, msg: string): Error ================ 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-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; } ================ 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/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/ws.ts ================ export interface WsServerInfo { endpoint: string; encrypt: boolean; protocol: string; pingInterval: number; pingTimeout: number; } ⋮---- export interface WsConnectionInfo { token: string; instanceServers: WsServerInfo[]; } ================ File: src/types/websockets/events.ts ================ export interface WsDataEvent { data: TData; table: string; wsKey: TWSKey; } ================ File: src/types/websockets/requests.ts ================ export type WsOperation = | 'subscribe' | 'unsubscribe' | 'login' | 'access' | 'request'; ⋮---- export interface WsRequestOperation { id: number; type: WsOperation; topic: TWSTopic; privateChannel: boolean; response: boolean; } ================ File: src/types/websockets/wsAPI.ts ================ export interface WsAPIWsKeyTopicMap { [k: string]: never; } ⋮---- export interface WsAPITopicRequestParamMap { [k: string]: never; } ⋮---- export interface WsAPITopicResponseMap { [k: string]: never; } ================ 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 < { 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; ⋮---- export interface MessageEventLike { target: WebSocket; type: 'message'; data: string; } ⋮---- export function isMessageEvent(msg: unknown): msg is MessageEventLike ⋮---- /** * #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 ================ 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, only checks 1-level deep (nested objects won't match) */ export function isDeepObjectMatch(object1: unknown, object2: unknown): boolean ⋮---- type DeferredPromiseRef = (typeof DEFERRED_PROMISE_REF)[keyof typeof DEFERRED_PROMISE_REF]; ⋮---- export class WsStore< WsKey extends string, ⋮---- constructor(logger: typeof 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 ⋮---- 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 ⋮---- /** * Create a deferred promise designed to track a connection attempt in progress. * * Will throw if existing promise is found. */ createConnectionInProgressPromise( wsKey: WsKey, throwIfExists: boolean, ): DeferredPromise ⋮---- /** Remove promise designed to track a connection attempt in progress */ removeConnectingInProgressPromise(wsKey: WsKey): void ⋮---- /* connection state */ ⋮---- isWsOpen(key: WsKey): boolean ⋮---- getConnectionState(key: WsKey): WsConnectionStateEnum ⋮---- setConnectionState(key: WsKey, state: WsConnectionStateEnum) ⋮---- // console.log(new Date(), `setConnectionState(${key}, ${state})`); ⋮---- isConnectionState(key: WsKey, state: WsConnectionStateEnum): boolean ⋮---- /** * Check if we're currently in the process of opening a connection for any reason. Safer than only checking "CONNECTING" as the state * @param key * @returns */ isConnectionAttemptInProgress(key: WsKey): boolean ⋮---- /* subscribed topics */ ⋮---- getTopics(key: WsKey): Set ⋮---- getTopicsByKey(): Record> ⋮---- // Since topics are objects we can't rely on the set to detect duplicates /** * Find matching "topic" request from the store * @param key * @param topic * @returns */ getMatchingTopic(key: WsKey, topic: TWSTopicSubscribeEventArgs) ⋮---- // if (typeof topic === 'string') { // return this.getMatchingTopic(key, { channel: topic }); // } ⋮---- addTopic(key: WsKey, topic: TWSTopicSubscribeEventArgs) ⋮---- // console.log(`wsStore.addTopic(${key}, ${topic})`); // 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/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-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 ================ 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/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/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 ================ 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/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: .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.13.0 ================ 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: src/lib/BaseWSClient.ts ================ import EventEmitter from 'events'; import WebSocket from 'isomorphic-ws'; ⋮---- import { WebsocketClientOptions, WSClientConfigurableOptions, } from '../types/websockets/client.js'; import { WsOperation } from '../types/websockets/requests.js'; import { WS_LOGGER_CATEGORY } from '../WebsocketClient.js'; import { checkWebCryptoAPISupported } from './webCryptoAPI.js'; import { DefaultLogger } from './websocket/logger.js'; import { isMessageEvent, MessageEventLike, safeTerminateWs, WsTopicRequest, WsTopicRequestOrStringTopic, } from './websocket/websocket-util.js'; import { WsStore } from './websocket/WsStore.js'; import { WSConnectedResult, WsConnectionStateEnum, } from './websocket/WsStore.types.js'; ⋮---- interface WSClientEventMap { /** Connection opened. If this connection was previously opened and reconnected, expect the reconnected event instead */ open: (evt: { wsKey: WsKey; event: any }) => void; /** Reconnecting a dropped connection */ reconnect: (evt: { wsKey: WsKey; event: any }) => void; /** Successfully reconnected a connection that dropped */ reconnected: (evt: { wsKey: WsKey; event: any }) => 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; error: (response: any & { wsKey: WsKey }) => void; /** 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) */ ⋮---- /** Confirmation that a connection successfully authenticated */ ⋮---- export interface EmittableEvent { eventType: | 'response' | 'update' | 'exception' | 'authenticated' | 'connectionReady'; // tied to "requireConnectionReadyConfirmation" event: TEvent; } ⋮---- | '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; ⋮---- /** * 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?: typeof 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 ⋮---- // 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 isWsPong(data: any): boolean; ⋮---- protected abstract isWsPing(data: any): boolean; ⋮---- protected abstract getWsAuthRequestEvent(wsKey: TWSKey): Promise; ⋮---- protected abstract isPrivateTopicRequest( request: WsTopicRequest, wsKey: TWSKey, ): boolean; ⋮---- /** * Returns a list of string events that can be individually sent upstream to complete subscribing/unsubscribing/etc to these topics */ protected abstract getWsOperationEventsForTopics( topics: WsTopicRequest[], wsKey: TWSKey, operation: WsOperation, ): Promise; ⋮---- protected abstract getPrivateWSKeys(): TWSKey[]; ⋮---- protected abstract getWsUrl(wsKey: TWSKey): Promise; ⋮---- protected abstract getMaxTopicsPerSubscribeEvent( wsKey: TWSKey, ): number | null; ⋮---- /** * Abstraction called to sort ws events into emittable event types (response to a request, data update, etc) */ protected abstract resolveEmittableEvents( wsKey: TWSKey, event: MessageEventLike, ): EmittableEvent[]; ⋮---- /** * Request connection of all dependent (public & private) websockets, instead of waiting for automatic connection by library */ protected abstract connectAll(): Promise<(WSConnectedResult | undefined)[]>; ⋮---- protected isPrivateWsKey(wsKey: TWSKey): boolean ⋮---- /** Returns auto-incrementing request ID, used to track promise references for async requests */ protected getNewRequestId(): string ⋮---- protected abstract sendWSAPIRequest( wsKey: TWSKey, channel: WSTopic, params?: any, ): Promise; ⋮---- protected abstract sendWSAPIRequest( wsKey: TWSKey, channel: WSTopic, params: any, ): Promise; ⋮---- /** * Subscribe to one or more topics on a WS connection (identified by WS Key). * * - Topics are automatically cached * - Connections are automatically opened, if not yet connected * - Authentication is automatically handled * - Topics are automatically resubscribed to, if something happens to the connection, unless you call unsubsribeTopicsForWsKey(topics, key). * * @param wsTopicRequests array of topics to subscribe to * @param wsKey ws key referring to the ws connection these topics should be subscribed on */ public subscribeTopicsForWsKey( wsTopicRequests: WsTopicRequestOrStringTopic[], wsKey: TWSKey, ) ⋮---- // Store topics, so future automation (post-auth, post-reconnect) has everything needed to resubscribe automatically ⋮---- // start connection process if it hasn't yet begun. Topics are automatically subscribed to on-connect ⋮---- // Subscribe should happen automatically once connected, nothing to do here after topics are added to wsStore. ⋮---- /** * Are we in the process of connection? Nothing to send yet. */ ⋮---- // We're connected. Check if auth is needed and if already authenticated ⋮---- /** * If not authenticated yet and auth is required, don't request topics yet. * * Auth should already automatically be in progress, so no action needed from here. Topics will automatically subscribe post-auth success. */ ⋮---- // Finally, request subscription to topics if the connection is healthy and ready ⋮---- protected unsubscribeTopicsForWsKey( wsTopicRequests: WsTopicRequestOrStringTopic[], wsKey: TWSKey, ) ⋮---- // Store topics, so future automation (post-auth, post-reconnect) has everything needed to resubscribe automatically ⋮---- // If not connected, don't need to do anything. // Removing the topic from the store is enough to stop it from being resubscribed to on reconnect. ⋮---- // We're connected. Check if auth is needed and if already authenticated ⋮---- /** * If not authenticated yet and auth is required, don't need to do anything. * We don't subscribe to topics until auth is complete anyway. */ ⋮---- // Finally, request subscription to topics if the connection is healthy and ready ⋮---- /** * Splits topic requests into two groups, public & private topic requests */ private sortTopicRequestsIntoPublicPrivate( wsTopicRequests: WsTopicRequest[], wsKey: TWSKey, ): ⋮---- /** Get the WsStore that tracks websockets & topics */ public getWsStore(): WsStore> ⋮---- public close(wsKey: TWSKey, force?: boolean) ⋮---- public closeAll(force?: boolean) ⋮---- public isConnected(wsKey: TWSKey): boolean ⋮---- /** * Request connection to a specific websocket, instead of waiting for automatic connection. */ public async connect(wsKey: TWSKey): Promise ⋮---- private connectToWsUrl(url: string, wsKey: TWSKey): WebSocket ⋮---- private parseWsError(context: string, error: any, wsKey: TWSKey) ⋮---- /** Get a signature, build the auth request and send it */ private async sendAuthRequest(wsKey: TWSKey): Promise ⋮---- private reconnectWithDelay(wsKey: TWSKey, connectionDelayMs: number) ⋮---- private ping(wsKey: TWSKey) ⋮---- private clearTimers(wsKey: TWSKey) ⋮---- // Send a ping at intervals private clearPingTimer(wsKey: TWSKey) ⋮---- // Expect a pong within a time limit private clearPongTimer(wsKey: TWSKey) ⋮---- // this.logger.trace(`Cleared pong timeout for "${wsKey}"`); ⋮---- // this.logger.trace(`No active pong timer for "${wsKey}"`); ⋮---- /** * Simply builds and sends subscribe events for a list of topics for a ws key * * @private Use the `subscribe(topics)` or `subscribeTopicsForWsKey(topics, wsKey)` method to subscribe to topics. Send WS message to subscribe to topics. */ private async requestSubscribeTopics( wsKey: TWSKey, topics: WsTopicRequest[], ) ⋮---- // Automatically splits requests into smaller batches, if needed ⋮---- `Subscribing to ${topics.length} "${wsKey}" topics in ${subscribeWsMessages.length} batches.`, // Events: "${JSON.stringify(topics)}" ⋮---- // this.logger.trace(`Sending batch via message: "${wsMessage}"`); ⋮---- /** * Simply builds and sends unsubscribe events for a list of topics for a ws key * * @private Use the `unsubscribe(topics)` method to unsubscribe from topics. Send WS message to unsubscribe from topics. */ private async requestUnsubscribeTopics( wsKey: TWSKey, wsTopicRequests: WsTopicRequest[], ) ⋮---- /** * Try sending a string event on a WS connection (identified by the WS Key) */ public tryWsSend(wsKey: TWSKey, wsMessage: string) ⋮---- private async onWsOpen(event: any, wsKey: TWSKey) ⋮---- /** * Called automatically once a connection is ready. * - Some exchanges are ready immediately after the connections open. * - Some exchanges send an event to confirm the connection is ready for us. * * This method is called to act when the connection is ready. Use `requireConnectionReadyConfirmation` to control how this is called. */ private async onWsReadyForEvents(wsKey: TWSKey) ⋮---- // Resolve & cleanup deferred "connection attempt in progress" promise ⋮---- // Remove before resolving, in case there's more requests queued ⋮---- // Some websockets require an auth packet to be sent after opening the connection ⋮---- // Reconnect to topics known before it connected ⋮---- // Request sub to public topics, if any ⋮---- // Request sub to private topics, if auth on connect isn't needed ⋮---- /** * Handle subscription to private topics _after_ authentication successfully completes asynchronously. * * Only used for exchanges that require auth before sending private topic subscription requests */ private onWsAuthenticated( wsKey: TWSKey, event: { isWSAPI?: boolean; WSAPIAuthChannel?: string }, ) ⋮---- private onWsMessage(event: unknown, wsKey: TWSKey, ws: WebSocket) ⋮---- // any message can clear the pong timer - wouldn't get a message if the ws wasn't working ⋮---- // console.log(`raw event: `, { data, dataType, emittableEvents }); ⋮---- private onWsClose(event: unknown, wsKey: TWSKey) ⋮---- // clean up any pending promises for this connection ⋮---- // clean up any pending promises for this connection ⋮---- private getWs(wsKey: TWSKey) ⋮---- private setWsState(wsKey: TWSKey, state: WsConnectionStateEnum) ⋮---- /** * Promise-driven method to assert that a ws has successfully connected (will await until connection is open) */ protected async assertIsConnected(wsKey: TWSKey): Promise ⋮---- // Already in progress? Await shared promise and retry ⋮---- // Start connection, it should automatically store/return a promise. ================ 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/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; } ================ 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: .eslintrc.cjs ================ // 'no-unused-vars': ['warn'], ================ File: src/lib/requestUtils.ts ================ /** * Used to switch how authentication/requests work under the hood */ ⋮---- /** Spot & Margin */ ⋮---- /** Futures */ ⋮---- /** Broker */ ⋮---- 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; /** 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; } ⋮---- /** Your API key */ ⋮---- /** Your API secret */ ⋮---- /** Your API passphrase (can be anything) that you set when creating this API key (NOT your account password) */ ⋮---- /** 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) */ ⋮---- 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/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; } ⋮---- 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'; 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 ================ 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/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; } ⋮---- /** @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[]; } ================ File: src/types/websockets/client.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; } ⋮---- /** * If true, require a "receipt" that the connection is ready for use (e.g. a specific event type) */ ⋮---- export type WsMarket = 'spot' | 'futures'; ================ 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, signMessage } from './webCryptoAPI.js'; ⋮---- 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 ⋮---- 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 sign request and set recv window */ private async signRequest( data: T, endpoint: string, method: Method, signMethod: SignMethod, ): Promise> ⋮---- 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 ================ 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; } ⋮---- /** * * 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/index.ts ================ ================ File: src/WebsocketClient.ts ================ import { FuturesClient } from './FuturesClient.js'; import { BaseWebsocketClient, EmittableEvent } from './lib/BaseWSClient.js'; import { neverGuard } from './lib/misc-util.js'; import { RestClientOptions } from './lib/requestUtils.js'; import { MessageEventLike, WS_KEY_MAP, WsKey, WsTopicRequest, } from './lib/websocket/websocket-util.js'; import { WSConnectedResult } from './lib/websocket/WsStore.types.js'; import { SpotClient } from './SpotClient.js'; import { APISuccessResponse } from './types/response/shared.types.js'; import { WsConnectionInfo } from './types/response/ws.js'; import { WsMarket } from './types/websockets/client.js'; import { WsOperation, WsRequestOperation, } from './types/websockets/requests.js'; import { WsAPITopicRequestParamMap, WsAPITopicResponseMap, WsAPIWsKeyTopicMap, } from './types/websockets/wsAPI.js'; ⋮---- function getRandomInt(max: number) ⋮---- /** Any WS keys in this list will trigger auth on connect, if credentials are available */ ⋮---- /** Any WS keys in this list will ALWAYS skip the authentication process, even if credentials are available */ ⋮---- /** * WS topics are always a string for this exchange. Some exchanges use complex objects. */ type WsTopic = string; ⋮---- export class WebsocketClient extends BaseWebsocketClient ⋮---- private getRESTClient(wsKey: WsKey): SpotClient | FuturesClient ⋮---- const getClientType = (wsKey: WsKey): 'spot' | 'futures' | null => ⋮---- private getRestClientOptions(): RestClientOptions ⋮---- private async getWSConnectionInfo( wsKey: WsKey, ): Promise> ⋮---- /** * Request connection of all dependent (public & private) websockets, instead of waiting for automatic connection by library */ public connectAll(): Promise<(WSConnectedResult | undefined)[]> ⋮---- /** * Request subscription to one or more topics. Pass topics as either an array of strings, or array of objects (if the topic has parameters). * Objects should be formatted as {topic: string, params: object}. * * - Subscriptions are automatically routed to the correct websocket connection. * - Authentication/connection is automatic. * - Resubscribe after network issues is automatic. * * Call `unsubscribe(topics)` to remove topics */ public subscribe( requests: | (WsTopicRequest | WsTopic) | (WsTopicRequest | WsTopic)[], wsKey: WsKey, ) ⋮---- /** * Unsubscribe from one or more topics. Similar to subscribe() but in reverse. * * - Requests are automatically routed to the correct websocket connection. * - These topics will be removed from the topic cache, so they won't be subscribed to again. */ public unsubscribe( requests: | (WsTopicRequest | WsTopic) | (WsTopicRequest | WsTopic)[], wsKey: WsKey, ) ⋮---- /** * Not supported by Kucoin, do not use */ ⋮---- // This overload allows the caller to omit the 3rd param, if it isn't required (e.g. for the login call) async sendWSAPIRequest< TWSKey extends keyof WsAPIWsKeyTopicMap, TWSChannel extends WsAPIWsKeyTopicMap[TWSKey] = WsAPIWsKeyTopicMap[TWSKey], TWSParams extends WsAPITopicRequestParamMap[TWSChannel] = WsAPITopicRequestParamMap[TWSChannel], TWSAPIResponse extends | WsAPITopicResponseMap[TWSChannel] | object = WsAPITopicResponseMap[TWSChannel], >( wsKey: TWSKey, channel: TWSChannel, ...params: TWSParams extends undefined ? [] : [TWSParams] ): Promise; ⋮---- async sendWSAPIRequest< TWSKey extends keyof WsAPIWsKeyTopicMap = keyof WsAPIWsKeyTopicMap, TWSChannel extends WsAPIWsKeyTopicMap[TWSKey] = WsAPIWsKeyTopicMap[TWSKey], TWSParams extends WsAPITopicRequestParamMap[TWSChannel] = WsAPITopicRequestParamMap[TWSChannel], >( wsKey: TWSKey, channel: TWSChannel, params?: TWSParams, ): Promise ⋮---- /** * * Internal methods * */ ⋮---- /** * Whatever url this method returns, it's connected to as-is! * * If a token or anything else is needed in the URL, this is a good place to add it. */ protected async getWsUrl(wsKey: WsKey): Promise ⋮---- protected sendPingEvent(wsKey: WsKey) ⋮---- protected sendPongEvent(wsKey: WsKey) ⋮---- // Send a protocol layer pong ⋮---- // Not really used for kucoin - they don't send pings protected isWsPing(msg: any): boolean ⋮---- protected isWsPong(msg: any): boolean ⋮---- // this.logger.info(`Not a pong: `, msg); ⋮---- protected resolveEmittableEvents( wsKey: WsKey, event: MessageEventLike, ): EmittableEvent[] ⋮---- // These are request/reply pattern events (e.g. after subscribing to topics or authenticating) ⋮---- // Request/reply pattern for authentication success ⋮---- /** * Determines if a topic is for a private channel, using a hardcoded list of strings */ protected isPrivateTopicRequest( request: WsTopicRequest, wsKey: WsKey, ): boolean ⋮---- protected getWsKeyForMarket(market: WsMarket, isPrivate: boolean): WsKey ⋮---- protected getWsMarketForWsKey(key: WsKey): WsMarket ⋮---- protected getPrivateWSKeys(): WsKey[] ⋮---- /** Force subscription requests to be sent in smaller batches, if a number is returned */ protected getMaxTopicsPerSubscribeEvent(wsKey: WsKey): number | null ⋮---- // Return a number if there's a limit on the number of sub topics per rq // Always 1 at a time for this exchange ⋮---- /** * Map one or more topics into fully prepared "subscribe request" events (already stringified and ready to send) */ protected async getWsOperationEventsForTopics( topicRequests: WsTopicRequest[], wsKey: WsKey, operation: WsOperation, ): Promise ⋮---- // Operations structured in a way that this exchange understands ⋮---- // Events that are ready to send (usually stringified JSON) ⋮---- // Not used for kucoin - auth is part of the WS URL protected async getWsAuthRequestEvent(wsKey: WsKey): Promise ================ 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: README.md ================ # Node.js & JavaScript SDK for Kucoin REST APIs & Websockets

SDK Logo

[![npm version](https://img.shields.io/npm/v/kucoin-api)][1] [![npm size](https://img.shields.io/bundlephobia/min/kucoin-api/latest)][1] [![npm downloads](https://img.shields.io/npm/dt/kucoin-api)][1] [![Build & Test](https://github.com/tiagosiebler/kucoin-api/actions/workflows/e2etest.yml/badge.svg?branch=master)](https://github.com/tiagosiebler/kucoin-api/actions/workflows/e2etest.yml) [![last commit](https://img.shields.io/github/last-commit/tiagosiebler/kucoin-api)][1] [![Telegram](https://img.shields.io/badge/chat-on%20telegram-blue.svg)](https://t.me/nodetraders) [1]: https://www.npmjs.com/package/kucoin-api Updated & performant JavaScript & Node.js SDK for the Kucoin REST APIs and WebSockets: - Professional, robust & performant Kucoin SDK with extensive production use in live trading environments. - Complete integration with all Kucoin REST APIs and WebSockets. - Dedicated REST clients for Spot, Futures, and Broker operations - Unified WebSocket client for all markets - Complete TypeScript support (with type declarations for most API requests & responses). - Strongly typed requests and responses. - Automated end-to-end tests ensuring reliability. - Actively maintained with a modern, promise-driven interface. - Robust WebSocket integration with configurable connection heartbeats & automatic reconnect then resubscribe workflows. - Event driven messaging. - Smart WebSocket persistence with automatic reconnection handling. - Emit `reconnected` event when dropped connection is restored. - Support for both public and private WebSocket streams. - Browser-friendly HMAC signature mechanism. - Automatically supports both ESM and CJS projects. - Heavy automated end-to-end testing with real API calls. - Proxy support via axios integration. - Active community support & collaboration in telegram: [Node.js Algo Traders](https://t.me/nodetraders). ## Table of Contents - [Installation](#installation) - [Examples](#examples) - [Issues & Discussion](#issues--discussion) - [Related Projects](#related-projects) - [Documentation](#documentation) - [Structure](#structure) - [Usage](#usage) - [REST API Clients](#rest-api) - [Spot & Margin Trading](#spot--margin-trading) - [Futures Trading](#futures-trading) - [Broker Operations](#broker-operations) - [WebSocket Client](#websockets) - [Public WebSocket Streams](#public-websocket-streams) - [Private WebSocket Streams](#private-websocket-streams) - [Customise Logging](#customise-logging) - [LLMs & AI](#use-with-llms--ai) - [Used By](#used-by) - [Contributions & Thanks](#contributions--thanks) ## Installation `npm install --save kucoin-api` ## Examples Refer to the [examples](./examples) folder for implementation demos. ## Issues & Discussion - Issues? Check the [issues tab](https://github.com/tiagosiebler/kucoin-api/issues). - Discuss & collaborate with other node devs? Join our [Node.js Algo Traders](https://t.me/nodetraders) engineering community on telegram. - Follow our announcement channel for real-time updates on [X/Twitter](https://x.com/sieblyio) ## Related projects Check out my related JavaScript/TypeScript/Node.js projects: - Try my REST API & WebSocket SDKs: - [Bybit-api Node.js SDK](https://www.npmjs.com/package/bybit-api) - [Okx-api Node.js SDK](https://www.npmjs.com/package/okx-api) - [Binance Node.js SDK](https://www.npmjs.com/package/binance) - [Gateio-api Node.js SDK](https://www.npmjs.com/package/gateio-api) - [Bitget-api Node.js SDK](https://www.npmjs.com/package/bitget-api) - [Kucoin-api Node.js SDK](https://www.npmjs.com/package/kucoin-api) - [Coinbase-api Node.js SDK](https://www.npmjs.com/package/coinbase-api) - [Bitmart-api Node.js SDK](https://www.npmjs.com/package/bitmart-api) - Try my misc utilities: - [OrderBooks Node.js](https://www.npmjs.com/package/orderbooks) - [Crypto Exchange Account State Cache](https://www.npmjs.com/package/accountstate) - Check out my examples: - [awesome-crypto-examples Node.js](https://github.com/tiagosiebler/awesome-crypto-examples) ## Documentation Most methods accept JS objects. These can be populated using parameters specified by Kucoin's API documentation, or check the type definition in each class within this repository. ### API Documentation Links - [Kucoin API Documentation](https://www.kucoin.com/docs-new/introduction) ### SDK Documentation & Guides - Node.js Quick Start Guides - [Spot Node.js Kucoin Quick Start Guide](./examples/kucoin-SPOT-examples-nodejs.md) - [Futures Node.js Kucoin Quick Start Guide](./examples/kucoin-FUTURES-examples-nodejs.md) - [Futures Node.js Kucoin Order Placement Guide](./examples/rest-futures-orders-guide.ts) - [REST Endpoint Function List](./docs/endpointFunctionList.md) ## Structure This project uses typescript. Resources are stored in 2 key structures: - [src](./src) - the whole connector written in typescript - [examples](./examples) - some implementation examples & demonstrations. Contributions are welcome! --- # Usage Create API credentials on Kucoin's website: - [Kucoin API Key Management](https://www.kucoin.com/account/api) ## REST API The SDK provides dedicated REST clients for different trading products: - **SpotClient** - for spot trading and margin operations - **FuturesClient** - for futures trading operations - **BrokerClient** - for broker and sub-account management ### Spot & Margin Trading To use Kucoin's Spot and Margin APIs, import (or require) the `SpotClient`: ```javascript const { SpotClient, FuturesClient } = require('kucoin-api'); const client = new SpotClient({ apiKey: 'apiKeyHere', apiSecret: 'apiSecretHere', apiPassphrase: 'apiPassPhraseHere', }); try { const spotBuyResult = await client.submitHFOrder({ clientOid: client.generateNewOrderID(), side: 'buy', type: 'market', symbol: 'BTC-USDT', size: '0.00001', }); console.log('spotBuy ', JSON.stringify(spotBuyResult, null, 2)); const spotSellResult = await client.submitHFOrder({ clientOid: client.generateNewOrderID(), side: 'sell', type: 'market', symbol: 'BTC-USDT', size: '0.00001', }); console.log('spotSellResult ', JSON.stringify(spotSellResult, null, 2)); } catch (e) { console.error(`Req error: `, e); } ``` See [SpotClient](./src/SpotClient.ts) for further information, or the [examples](./examples/) for lots of usage examples. ### Futures Trading Use the `FuturesClient` for futures trading operations. See [FuturesClient](./src/FuturesClient.ts) for complete API coverage. ### Broker Operations Use the `BrokerClient` for broker and sub-account management operations. See [BrokerClient](./src/BrokerClient.ts) for complete API coverage. ## WebSockets All WebSocket functionality is supported via the unified `WebsocketClient`. This client handles both spot and futures WebSocket streams with automatic connection management and reconnection. Key WebSocket features: - Event driven messaging - Smart WebSocket persistence with automatic reconnection - Heartbeat mechanisms to detect disconnections - Automatic resubscription after reconnection - Support for both public and private WebSocket streams - Unified client for spot and futures markets ### Public WebSocket Streams For public market data, API credentials are not required: All available WebSockets can be used via a shared `WebsocketClient`. The WebSocket client will automatically open/track/manage connections as needed. Each unique connection (one per server URL) is tracked using a WsKey (each WsKey is a string - see [WS_KEY_MAP](src/lib/websocket/websocket-util.ts) for a list of supported values). Any subscribe/unsubscribe events will need to include a WsKey, so the WebSocket client understands which connection the event should be routed to. See examples below or in the [examples](./examples/) folder on GitHub. Data events are emitted from the WebsocketClient via the `update` event, see example below: ```javascript const { WebsocketClient } = require('kucoin-api'); const client = new WebsocketClient(); client.on('open', (data) => { console.log('open: ', data?.wsKey); }); // Data received client.on('update', (data) => { console.info('data received: ', JSON.stringify(data)); }); // Something happened, attempting to reconenct client.on('reconnect', (data) => { console.log('reconnect: ', data); }); // Reconnect successful client.on('reconnected', (data) => { console.log('reconnected: ', data); }); // Connection closed. If unexpected, expect reconnect -> reconnected. client.on('close', (data) => { console.error('close: ', data); }); // Reply to a request, e.g. "subscribe"/"unsubscribe"/"authenticate" client.on('response', (data) => { console.info('response: ', data); // throw new Error('res?'); }); client.on('exception', (data) => { console.error('exception: ', { msg: data.msg, errno: data.errno, code: data.code, syscall: data.syscall, hostname: data.hostname, }); }); try { // Optional: await a connection to be ready before subscribing (this is not necessary) // await client.connect('futuresPublicV1'); /** * Examples for public futures websocket topics (that don't require authentication). * * These should all subscribe via the "futuresPublicV1" wsKey. For detailed usage, refer to the ws-spot-public.ts example. */ client.subscribe( [ '/contractMarket/tickerV2:XBTUSDM', '/contractMarket/ticker:XBTUSDM', '/contractMarket/level2:XBTUSDM', '/contractMarket/execution:XBTUSDM', '/contractMarket/level2Depth5:XBTUSDM', '/contractMarket/level2Depth50:XBTUSDM', '/contractMarket/limitCandle:XBTUSDTM_1hour', '/contract/instrument:XBTUSDM', '/contract/announcement', '/contractMarket/snapshot:XBTUSDM', ], 'futuresPublicV1', ); } catch (e) { console.error(`Subscribe exception: `, e); } ``` ### Private WebSocket Streams For private account data streams, API credentials are required. The WebsocketClient will automatically handle authentication when you provide API credentials. See [WebsocketClient](./src/WebsocketClient.ts) for further information and make sure to check the [examples](./examples/) folder for much more detail, especially [ws-spot-public.ts](./examples/ws-spot-public.ts), which explains a lot of detail. --- ## Customise Logging Pass a custom logger which supports the log methods `trace`, `info` and `error`, or override methods from the default logger as desired. ```javascript const { WebsocketClient, DefaultLogger } = require('kucoin-api'); // E.g. customise logging for only the trace level: const logger = { // Inherit existing logger methods, using an object spread ...DefaultLogger, // Define a custom trace function to override only that function trace: (...params) => { if ( [ 'Sending ping', // 'Sending upstream ws message: ', 'Received pong', ].includes(params[0]) ) { return; } console.log('trace', JSON.stringify(params, null, 2)); }, }; const ws = new WebsocketClient( { apiKey: 'apiKeyHere', apiSecret: 'apiSecretHere', apiPassphrase: 'apiPassPhraseHere', }, logger, ); ``` ## Use with LLMs & AI This SDK includes a bundled `llms.txt` file in the root of the repository. If you're developing with LLMs, use the included `llms.txt` with your LLM - it will significantly improve the LLMs understanding of how to correctly use this SDK. This file contains AI optimised structure of all the functions in this package, and their parameters for easier use with any learning models or artificial intelligence. --- ## Used By [![Repository Users Preview Image](https://dependents.info/tiagosiebler/kucoin-api/image)](https://github.com/tiagosiebler/kucoin-api/network/dependents) --- ### Contributions & Thanks Have my projects helped you? Share the love, there are many ways you can show your thanks: - Star & share my projects. - Are my projects useful? Sponsor me on Github and support my effort to maintain & improve them: https://github.com/sponsors/tiagosiebler - Have an interesting project? Get in touch & invite me to it. - Or buy me all the coffee: - ETH(ERC20): `0xA3Bda8BecaB4DCdA539Dc16F9C54a592553Be06C` ### Contributions & Pull Requests Contributions are encouraged, I will review any incoming pull requests. See the issues tab for todo items. ## Star History [![Star History Chart](https://api.star-history.com/svg?repos=tiagosiebler/bybit-api,tiagosiebler/okx-api,tiagosiebler/binance,tiagosiebler/bitget-api,tiagosiebler/bitmart-api,tiagosiebler/gateio-api,tiagosiebler/kucoin-api,tiagosiebler/coinbase-api,tiagosiebler/orderbooks,tiagosiebler/accountstate,tiagosiebler/awesome-crypto-examples&type=Date)](https://star-history.com/#tiagosiebler/bybit-api&tiagosiebler/okx-api&tiagosiebler/binance&tiagosiebler/bitget-api&tiagosiebler/bitmart-api&tiagosiebler/gateio-api&tiagosiebler/kucoin-api&tiagosiebler/coinbase-api&tiagosiebler/orderbooks&tiagosiebler/accountstate&tiagosiebler/awesome-crypto-examples&Date) ================ 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 } ⋮---- 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 ⋮---- 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; 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; } ⋮---- 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 ]; ⋮---- number, // Time number, // Entry price number, // Highest price number, // Lowest price number, // Close price 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 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; } ================ 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, CopyTradeOrderRequest, CopyTradeSLTPOrderRequest, GetFundingHistoryRequest, GetFundingRatesRequest, GetInterestRatesRequest, GetKlinesRequest, GetOrdersRequest, GetStopOrdersRequest, GetTransactionsRequest, MaxOpenSizeRequest, Order, SLTPOrder, } from './types/request/futures.types.js'; import { AccountBalance, AccountSummary, AddMargin, BatchCancelOrderResult, BatchMarginModeUpdateResponse, CopyTradePosition, CrossMarginRequirement, CrossMarginRiskLimit, FullOrderBookDetail, FuturesAccountFundingRateHistory, FuturesAccountTransaction, FuturesActiveOrder, FuturesClosedPositions, FuturesCurrentFundingRate, FuturesFill, FuturesFills, FuturesHistoricFundingRate, FuturesKline, FuturesMarkPrice, FuturesOrder, FuturesOrders, FuturesPosition, FuturesRiskLimit, FuturesSubAccount, FuturesSymbolInfo, 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. */ getPosition(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 ⋮---- /** * * 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 * Place order to the futures trading system for copy trading */ submitCopyTradeOrder(params: CopyTradeOrderRequest): Promise< APISuccessResponse<{ orderId: string; clientOid: string; }> > { return this.postPrivate('api/v1/copy-trade/futures/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. */ 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 * 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. */ 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 * This endpoint can query the maximum amount of margin that the current position supports withdrawal. */ getCopyTradeMaxWithdrawMargin(params: { symbol: string; }): Promise> ⋮---- /** * Add Isolated Margin * Add Isolated Margin Manually. */ addCopyTradeIsolatedMargin(params: { symbol: string; margin: number; bizNo: string; }): Promise> ⋮---- /** * Remove Isolated Margin * Remove Isolated Margin Manually. */ removeCopyTradeIsolatedMargin(params: { symbol: string; withdrawAmount: string; }): 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 * 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; }): Promise> /** * * REST - Futures - Broker * */ ⋮---- /** * Get download link for broker rebate orders * * trade type 1 = spot, trade type 2 = futures */ getBrokerRebateOrderDownloadLink(params: { begin: string; end: string; tradeType: 1 | 2; }): 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/SpotClient.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 { AccountHFMarginTransactionsRequest, AccountHFTransactionsRequest, CreateSubAccountAPIRequest, CreateSubAccountRequest, DeleteSubAccountAPIRequest, GetBalancesRequest, GetSpotTransactionsRequest, UpdateSubAccountAPIRequest, } from './types/request/spot-account.js'; import { GetAffiliateCommissionRequest, GetAffiliateInviteesRequest, GetAffiliateTradeHistoryRequest, } from './types/request/spot-affiliate.js'; import { AddConvertLimitOrderRequest, AddConvertOrderRequest, CancelConvertLimitOrderRequest, GetConvertLimitOrderDetailRequest, GetConvertLimitOrdersRequest, GetConvertLimitQuoteRequest, GetConvertOrderDetailRequest, GetConvertOrderHistoryRequest, GetConvertQuoteRequest, GetConvertSymbolRequest, } from './types/request/spot-convert.js'; import { GetDualInvestmentProductsRequest, GetEarnFixedIncomeHoldAssetsRequest, GetEarnRedeemPreviewRequest, GetStructuredProductOrdersRequest, InitiateRedemptionRequest, StructuredProductPurchaseRequest, SubscribeEarnFixedIncomeRequest, } from './types/request/spot-earn.js'; import { ApplyWithdrawRequest, CreateDepositAddressV3Request, FlexTransferRequest, GetDepositsRequest, GetIsolatedMarginBalanceRequest, GetMarginBalanceRequest, GetTransferableRequest, GetWithdrawalsRequest, InnerTransferRequest, submitTransferMasterSubRequest, SubmitWithdrawV3Request, } from './types/request/spot-funding.js'; import { GetHFMarginFilledRequest, getHFMarginFillsRequest, GetLendingRedemptionOrdersV3Request, GetLendingSubscriptionOrdersV3Request, HFMarginRequestOrder, InitiateLendingRedemptionV3Request, InitiateLendingSubscriptionV3Request, MarginBorrowV3Request, MarginHistoryV3Request, MarginInterestRecordsRequest, MarginRepayV3Request, MarginRiskLimitRequest, ModifyLendingSubscriptionOrdersV3Request, SubmitHFMarginOrderRequest, SubmitMarginOrderRequest, } from './types/request/spot-margin-trading.js'; import { GetAnnouncementsRequest } from './types/request/spot-misc.js'; import { CancelAllOrdersRequest, CancelSpecifiedNumberHFOrdersRequest, CancelStopOrdersRequest, GetFillsRequest, GetHFCompletedOrdersRequest, GetHFFilledListRequest, GetOCOOrdersRequest, GetOrderListRequest, GetSpotKlinesRequest, GetStopOrdersListRequest, ModifyHFOrderRequest, SubmitHFOrderRequest, SubmitMultipleOrdersRequest, SubmitOCOOrderRequest, SubmitOrderRequest, SubmitStopOrderRequest, } from './types/request/spot-trading.js'; import { APISuccessResponse, ServiceStatus, } from './types/response/shared.types.js'; import { Account, AccountHFMarginTransactions, Balances, CreateSubAccount, CreateSubAPI, DeleteSubAccountAPI, SpotAccountSummary, SpotAccountTransaction, SpotAccountTransactions, SubAccountAPIInfo, SubAccountBalance, SubAccountBalancesV2, SubAccountInfo, SubAccountsV2, UpdateSubAPI, } from './types/response/spot-account.js'; import { AffiliateCommissionItem, AffiliateInvitees, AffiliateTradeHistory, } from './types/response/spot-affiliate.js'; import { ConvertCurrencies, ConvertLimitOrder, ConvertLimitOrdersList, ConvertLimitQuote, ConvertOrder, ConvertOrderHistory, ConvertQuote, ConvertSymbol, SubmitConvertOrderResponse, SumbitConvertLimitResp, } from './types/response/spot-convert.js'; import { DualInvestmentProduct, EarnFixedIncomeHoldAssets, EarnProduct, GetEarnRedeemPreviewResponse, InitiateRedemptionResponse, StructuredProductOrders, StructuredProductPurchaseResponse, SubscribeEarnFixedIncomeResponse, } from './types/response/spot-earn.js'; import { CreateDepositAddressV3Response, DepositAddress, DepositAddressV2, DepositAddressV3, Deposits, HistoricalWithdrawalsV1, IsolatedMarginBalance, MarginAccountBalance, MarginBalance, TransferableFunds, V1HistoricalDeposits, WithdrawalById, WithdrawalQuotas, Withdrawals, } from './types/response/spot-funding.js'; import { HFMarginOrder, HFMarginTransactionRecord, IsolatedMarginAccountInfo, IsolatedMarginSymbolsConfig, LendingCurrencyV3, LendingRedemption, MarginActivePairsV3, MarginBorrowHistoryV3, MarginConfigInfo, MarginInterestRecords, MarginLevTokenInfo, MarginMarkPrice, MarginOrderV3, MarginRepayHistoryV3, MarginRiskLimit, MarginSubmitOrderV3Response, SingleIsolatedMarginAccountInfo, SubmitMarginOrderResponse, } from './types/response/spot-margin-trading.js'; import { Announcements } from './types/response/spot-misc.js'; import { AllTickers, AutoCancelHFOrderSettingQueryResponse, CallAuctionInfo, CancelAllHFOrdersResponse, CurrencyInfo, HFFilledOrder, HFOrder, Kline, MultipleOrdersResponse, OCOOrderDetails, OCOOrderListItem, OCOOrders, OrderBookLevel, SpotOrder, SpotOrderFill, SpotOrderFills, SpotOrderList, StopOrderItem, StopOrders, SubmitHFOrderSyncResponse, SubmitMultipleHFOrdersResponse, SubmitMultipleHFOrdersSyncResponse, Symbol24hrStats, SymbolInfo, SyncCancelHFOrderResponse, Ticker, TradeHistory, } from './types/response/spot-trading.js'; import { DiscountRateConfig, OtcLoan, OtcLoanAccount, } from './types/response/spot-vip.js'; import { WsConnectionInfo } from './types/response/ws.js'; ⋮---- /** * */ export class SpotClient extends BaseRestClient ⋮---- constructor( restClientOptions: RestClientOptions = {}, requestOptions: AxiosRequestConfig = {}, ) ⋮---- getClientType(): RestClientType ⋮---- /** * * Misc SDK Methods * */ ⋮---- /** * This method is used to get the latency and time sync between the client and the server. * This is not official API endpoint and is only used for internal testing purposes. * Use this method to check the latency and time sync between the client and the server. * Final values might vary slightly, but it should be within few ms difference. * If you have any suggestions or improvements to this measurement, please create an issue or pull request on GitHub. */ async fetchLatencySummary(): Promise ⋮---- // Adjust server time by adding estimated one-way latency ⋮---- // Calculate time difference between adjusted server time and local time ⋮---- /** * * Misc Utility Methods * */ ⋮---- generateNewOrderID(): string ⋮---- getMyIp(): Promise> ⋮---- getServerTime(): Promise> ⋮---- getServiceStatus(): Promise> ⋮---- /** * * REST - Account Info - Account & Funding * */ ⋮---- /** * Get Account Summary Info * * This endpoint can be used to obtain account summary information. */ getAccountSummary(): Promise> ⋮---- /** * Get API Key Information * * Get information about the API key being used. Works for both master and sub user API keys. */ getApikeyInfo(): Promise< APISuccessResponse<{ remark: string; apiKey: string; apiVersion: number; permission: string; ipWhitelist: string; createdAt: number; uid: number; isMaster: boolean; }> > { return this.getPrivate('api/v1/user/api-key'); ⋮---- /** * Get Account Type - Spot * * This endpoint determines whether the current user is a spot high-frequency user or a spot low-frequency user. */ getUserType(): Promise> ⋮---- /** * Get a list of acounts and their balance states (spot/margin/trade_hf) * * Get Account List - Spot */ getBalances( params?: GetBalancesRequest, ): Promise> ⋮---- /** * Get Account Detail - Spot * * Get Information for a single spot account. Use this endpoint when you know the accountId. */ getAccountDetail(params: { accountId: any; }): Promise> ⋮---- /** * Get Account - Cross Margin * * Request via this endpoint to get the info of the cross margin account. */ getMarginBalance( params?: GetMarginBalanceRequest, ): Promise> ⋮---- /** * Get Account - Isolated Margin * * Request via this endpoint to get the info of the isolated margin account. */ getIsolatedMarginBalance( params?: GetIsolatedMarginBalanceRequest, ): Promise> ⋮---- /** * Get Account Ledgers - Spot/Margin * * This endpoint is for transaction records from all types of your accounts, supporting inquiry of various currencies. * Items are paginated and sorted to show the latest first. * See the Pagination section for retrieving additional entries after the first page. */ getTransactions( params?: GetSpotTransactionsRequest, ): Promise> ⋮---- /** * Get Account Ledgers - trade_hf * * This API endpoint returns all transfer (in and out) records in high-frequency trading account and supports multi-coin queries. * The query results are sorted in descending order by createdAt and id. */ getHFTransactions( params: AccountHFTransactionsRequest, ): Promise> ⋮---- /** * Get Account Ledgers - margin_hf * * This API endpoint returns all transfer (in and out) records in high-frequency margin trading account and supports multi-coin queries. * The query results are sorted in descending order by createdAt and id. */ getHFMarginTransactions( params: AccountHFMarginTransactionsRequest, ): Promise> ⋮---- /** * * REST - Account Info - Sub Account * */ ⋮---- /** * Add SubAccount * * This endpoint is used to create a sub-account. */ createSubAccount( params: CreateSubAccountRequest, ): Promise> ⋮---- /** * Add SubAccount Margin Permission * * This endpoint can be used to add sub-accounts Margin permission. * Before using this endpoints, you need to ensure that the master account apikey has Margin permissions and the Margin function has been activated. */ enableSubAccountMargin(params: ⋮---- /** * Add SubAccount Futures Permission * * This endpoint can be used to add sub-accounts Futures permission. * Before using this endpoints, you need to ensure that the master account apikey has Futures permissions and the Futures function has been activated. */ enableSubAccountFutures(params: ⋮---- /** * Get SubAccount List - Summary Info * * This endpoint can be used to get a paginated list of sub-accounts. Pagination is required. */ getSubAccountsV2(params?: { currentPage?: number; pageSize?: number; }): Promise> ⋮---- /** * Get sub-account Detail - Balance * * This endpoint returns the account info of a sub-user specified by the subUserId. */ getSubAccountBalance(params: { subUserId: string; includeBaseAmount: boolean; baseCurrency?: string; baseAmount?: string; }): Promise> ⋮---- /** * Get SubAccount List - Spot Balance(V2) * * This endpoint can be used to get paginated Spot sub-account information. * Pagination is required. */ getSubAccountBalancesV2(params?: { currentPage?: number; pageSize?: number; }): Promise> ⋮---- /** * * REST - Account Info - Sub Account API * */ ⋮---- /** * Add SubAccount API * * This endpoint can be used to create APIs for sub-accounts. */ createSubAPI( params: CreateSubAccountAPIRequest, ): Promise> ⋮---- /** * Modify SubAccount API * * This endpoint can be used to update APIs for sub-accounts. */ updateSubAPI( params: UpdateSubAccountAPIRequest, ): Promise> ⋮---- /** * Get SubAccount API List * * This endpoint can be used to obtain a list of APIs pertaining to a sub-account. * (Not contain ND Broker Sub Account) */ getSubAPIs(params: { apiKey?: string; subName: string; }): Promise> ⋮---- /** * Delete SubAccount API * * This endpoint can be used to delete an API for a sub-account. */ deleteSubAPI( params: DeleteSubAccountAPIRequest, ): Promise> ⋮---- /** * * REST - Account Info - Deposit * */ ⋮---- /** * Add Deposit Address(V3) * * Request via this endpoint to create a deposit address for a currency you intend to deposit. */ createDepositAddressV3( params: CreateDepositAddressV3Request, ): Promise> ⋮---- /** * Get Deposit Address(V3) * * Get all deposit addresses for the currency you intend to deposit. * If the returned data is empty, you may need to Add Deposit Address first. */ getDepositAddressesV3(params: { currency: string; amount?: string; chain?: string; }): Promise> ⋮---- /** * Get Deposit History * * Request via this endpoint to get deposit list Items are paginated and sorted to show the latest first. * See the Pagination section for retrieving additional entries after the first page. */ getDeposits( params?: GetDepositsRequest, ): Promise> ⋮---- /** * * REST - Account Info - Withdrawals * */ ⋮---- /** * Get Withdrawal Quotas * * This endpoint can obtain the withdrawal quotas information of this currency. */ getWithdrawalQuotas(params: { currency: string; chain?: string; }): Promise> ⋮---- /** * Withdraw(V3) * * Use this endpoint to withdraw the specified currency */ submitWithdrawV3(params: SubmitWithdrawV3Request): Promise< APISuccessResponse<{ withdrawalId: string; }> > { return this.postPrivate('api/v3/withdrawals', params); ⋮---- /** * Cancel Withdrawal * * This endpoint can cancel the withdrawal, Only withdrawals requests of PROCESSING status could be canceled. */ cancelWithdrawal(params: { withdrawalId: string; }): Promise> ⋮---- /** * Get Withdrawal History * * Request via this endpoint to get withdrawal list Items are paginated and sorted to show the latest first. * See the Pagination section for retrieving additional entries after the first page. */ getWithdrawals( params?: GetWithdrawalsRequest, ): Promise> ⋮---- /** * Get Withdrawal History By ID * * Request a withdrawal history by id via this endpoint. */ getWithdrawalById(params: { withdrawalId: string; }): Promise> ⋮---- /** * * REST - Account Info - Transfer * */ ⋮---- /** * Get Transfer Quotas * * This endpoint returns the transferable balance of a specified account. */ getTransferable( params: GetTransferableRequest, ): Promise> ⋮---- /** * Flex Transfer * * This endpoint can be used for transfers between master and sub accounts and inner transfers */ submitFlexTransfer(params: FlexTransferRequest): Promise< APISuccessResponse<{ orderId: string; }> > { return this.postPrivate('api/v3/accounts/universal-transfer', params); ⋮---- /** * * REST - Account Info - Trade Fee * */ ⋮---- /** * Get Basic Fee - Spot/Margin * * This endpoint is for the spot/margin basic fee rate of users */ getBasicUserFee(params: { currencyType: number }): Promise< APISuccessResponse<{ takerFeeRate: string; makerFeeRate: string; }> > { return this.getPrivate('api/v1/base-fee', params); ⋮---- /** * Get Actual Fee - Spot/Margin * * This endpoint is for the actual fee rate of the trading pair. * You can inquire about fee rates of 10 trading pairs each time at most. * 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 - SPOT TRADING - Market Data * */ ⋮---- /** * Get Announcements * * This endpoint can obtain the latest news announcements, and the default page search is for announcements within a month. */ getAnnouncements( params?: GetAnnouncementsRequest, ): Promise> ⋮---- /** * Get Currency * * Request via this endpoint to get the currency details of a specified currency. */ getCurrency(params: { currency: string; chain?: string; }): Promise> ⋮---- /** * Get All Currencies * * Request via this endpoint to get the currency list. Not all currencies currently can be used for trading. */ getCurrencies(): Promise> ⋮---- /** * Get Symbol * * Request via this endpoint to get detail currency pairs for trading. * If you want to get the market information of the trading symbol, please use Get All Tickers. */ getSymbol(params: { symbol: string; }): Promise> ⋮---- /** * Get All Symbols * * Request via this endpoint to get detail currency pairs for trading. * If you want to get the market information of the trading symbol, please use Get All Tickers. */ getSymbols(params?: { market?: string; }): Promise> ⋮---- /** * Get Ticker * * Request via this endpoint to get Level 1 Market Data. * The returned value includes the best bid price and size, * the best ask price and size as well as the last traded price and the last traded size. */ getTicker(params: ⋮---- /** * Get All Tickers * * Request market tickers for all the trading pairs in the market (including 24h volume), takes a snapshot every 2 seconds. */ getTickers(): 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. */ ⋮---- getTradeHistories(params: { symbol: string; }): Promise> ⋮---- /** * Get Klines * * Get the Kline of the symbol. * Data are returned in grouped buckets based on requested type. */ getKlines( params: GetSpotKlinesRequest, ): Promise> ⋮---- /** * Get Part OrderBook * * Query for part orderbook depth data. Level 20(aggregated by price) */ getOrderBookLevel20(params: { symbol: string; }): Promise> ⋮---- /** * Get Part OrderBook * * Query for part orderbook depth data. Level 100(aggregated by price) */ getOrderBookLevel100(params: { symbol: string; }): Promise> ⋮---- /** * Get Full OrderBook * * Query for full orderbook depth data. (aggregated by price) */ getFullOrderBook(params: { symbol: string; }): Promise> ⋮---- /** * Get Call Auction Part OrderBook * * Query for call auction part orderbook depth data (aggregated by price). * It is recommended that you submit requests via this endpoint as the system response will be faster and consume less traffic. */ getCallAuctionPartOrderBook(params: { symbol: string; size: 20 | 100; }): Promise> ⋮---- /** * Get Call Auction Info * * Get call auction data. This endpoint will return the following information for the specified symbol * during the call auction phase: estimated transaction price, estimated transaction quantity, * bid price range, and ask price range. */ getCallAuctionInfo(params: { symbol: string; }): Promise> ⋮---- /** * Get Fiat Price * * Request via this endpoint to get the fiat price of the currencies for the available trading pairs. */ getFiatPrice(params?: ⋮---- /** * Get 24hr Stats * * Request via this endpoint to get the statistics of the specified ticker in the last 24 hours. */ get24hrStats(params: { symbol: string; }): Promise> ⋮---- /** * Get Market List * * Request via this endpoint to get the transaction currency for the entire trading market. */ getMarkets(): Promise> ⋮---- /** * * REST - SPOT TRADING - Orders * */ ⋮---- /** * Add Order * * Place order to the Spot trading system, you can place two major types of orders: limit and market. * Orders can only be placed if your account has sufficient funds. Once an order is placed, your funds will be put on hold for the duration of the order. * The amount of funds on hold depends on the order type and parameters specified. */ submitHFOrder(params: SubmitHFOrderRequest): Promise< APISuccessResponse<{ orderId: string; clientOid: string; }> > { return this.postPrivate('api/v1/hf/orders', params); ⋮---- /** * Add Order Sync * * Place order to the spot trading system * * The difference between this endpoint and "SubmitHFOrder()" is that this endpoint will synchronously return the order information after the order matching is completed. */ submitHFOrderSync( params: SubmitHFOrderRequest, ): Promise> ⋮---- /** * 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. After placing an order, the order will not enter the matching system, and the order cannot be queried. */ submitHFOrderTest(params: SubmitHFOrderRequest): Promise ⋮---- /** * Batch Add Orders * * This endpoint supports sequential batch order placement from a single endpoint. A maximum of 20 orders can be placed simultaneously. */ submitHFMultipleOrders(params: { orderList: SubmitHFOrderRequest[]; }): Promise> ⋮---- /** * Batch Add Orders Sync * * This endpoint supports sequential batch order placement from a single endpoint. A maximum of 20 orders can be placed simultaneously. * The difference between this endpoint and "submitHFMultipleOrders()" is that this endpoint will synchronously return the order information after the order matching is completed. */ submitHFMultipleOrdersSync(params: { orderList: SubmitHFOrderRequest[]; }): Promise> ⋮---- /** * Cancel Order By OrderId * * This endpoint can be used to cancel a spot order by orderId. * This endpoint only sends cancellation requests. The results of the requests must be obtained by checking the order status or subscribing to websocket. */ cancelHFOrder(params: { orderId: string; symbol: string }): Promise< APISuccessResponse<{ orderId: string; }> > { return this.deletePrivate(`api/v1/hf/orders/$ ⋮---- /** * Cancel Order By OrderId Sync * * This endpoint can be used to cancel a spot order by orderId. * The difference between this endpoint and "cancelHFOrder()" is that this endpoint will synchronously return the order information after the order canceling is completed. */ cancelHFOrderSync(params: { orderId: string; symbol: string; }): Promise> ⋮---- /** * Cancel Order By ClientOid * * This endpoint can be used to cancel a spot order by clientOid. * This endpoint only sends cancellation requests. The results of the requests must be obtained by checking the order status or subscribing to websocket. */ cancelHFOrderByClientOId(params: { clientOid: string; symbol: string; }): Promise< APISuccessResponse<{ clientOid: string; }> > { return this.deletePrivate( `api/v1/hf/orders/client-order/${params.clientOid}`, params, ); ⋮---- /** * Cancel Order By ClientOid Sync * * This endpoint can be used to cancel a spot order by clientOid. * The difference between this endpoint and "cancelHFOrderByClientOId()" is that this endpoint will synchronously return the order information after the order canceling is completed. */ cancelHFOrderSyncByClientOId(params: { clientOid: string; symbol: string; }): Promise> ⋮---- /** * Cancel Partial Order * * This endpoint can cancel the specified quantity of the order according to the orderId. */ cancelHFOrdersNumber(params: CancelSpecifiedNumberHFOrdersRequest): Promise< ⋮---- /** * Cancel All Orders By Symbol * * This endpoint can cancel all spot orders for specific symbol. */ cancelHFAllOrdersBySymbol(params: { symbol: string; }): Promise> ⋮---- /** * Cancel All Orders * * This endpoint can cancel all spot orders for all symbol. */ cancelHFAllOrders(): Promise> ⋮---- /** * Modify Order * * This endpoint can modify the price and quantity of the order according to orderId or clientOid. */ updateHFOrder(params: ModifyHFOrderRequest): Promise< APISuccessResponse<{ newOrderId: string; clientOid: string; }> > { return this.postPrivate('api/v1/hf/orders/alter', params); ⋮---- /** * Get Order By OrderId * * This endpoint can be used to obtain information for a single Spot order using the order id. */ getHFOrderDetailsByOrderId(params: { orderId: string; symbol: string; }): Promise> ⋮---- /** * Get Order By ClientOid * * This endpoint can be used to obtain information for a single Spot order using the clientOid. */ getHFOrderDetailsByClientOid(params: { clientOid: string; symbol: string; }): Promise> ⋮---- /** * Get Symbols With Open Order * * This endpoint can query all spot symbol that has active orders */ getHFActiveSymbols(): Promise< APISuccessResponse<{ symbols: string[]; }> > { return this.getPrivate('api/v1/hf/orders/active/symbols'); ⋮---- /** * @deprecated as of 13-03-2025- use getHFActiveOrdersPaginated() instead * Get Open Orders * * This endpoint is to obtain all Spot active order lists, and the return value of the active order endpoint is the paged data of all uncompleted order lists. * The returned data is sorted in descending order according to the latest update time of the order. */ getHFActiveOrders(params: { symbol: string; }): Promise> ⋮---- /** * Get Open Orders By Page * * This interface is to obtain Spot active order (uncompleted order) lists by page. * The returned data is sorted in descending order according to the create time of the order. */ getHFActiveOrdersPaginated(params: { symbol: string; pageNum?: number; pageSize?: number; }): Promise< APISuccessResponse<{ currentPage: number; pageSize: number; totalNum: number; totalPage: number; items: HFOrder[]; }> > { return this.getPrivate('api/v1/hf/orders/active/page', params); ⋮---- /** * Get Closed Orders * * This endpoint is to obtain all Spot completed order lists, and the return value of the completed order endpoint is the paged data of all completed order lists. * The returned data is sorted in descending order according to the latest update time of the order. */ getHFCompletedOrders(params: GetHFCompletedOrdersRequest): Promise< APISuccessResponse<{ lastId: number; items: HFOrder[]; }> > { return this.getPrivate('api/v1/hf/orders/done', params); ⋮---- /** * Get Trade History * * This endpoint can be used to obtain a list of the latest Spot transaction details. */ getHFFilledOrders(params: GetHFFilledListRequest): Promise< APISuccessResponse<{ items: HFFilledOrder[]; lastId: number; }> > { return this.getPrivate('api/v1/hf/fills', params); ⋮---- /** * Get DCP * * Get Disconnection Protect(Deadman Swich) * Through this endpoint, you can query the settings of automatic order cancellation */ cancelHFOrderAutoSettingQuery(): Promise< APISuccessResponse > { return this.getPrivate('api/v1/hf/orders/dead-cancel-all/query'); ⋮---- /** * Set DCP * * Set Disconnection Protect(Deadman Swich) * Through this endpoint, Call this endpoint to automatically cancel all orders of the set trading pair after the specified time. * If this endpoint is not called again for renewal or cancellation before the set time, the system will help the user to cancel the order of the corresponding trading pair. Otherwise it will not. */ cancelHFOrderAutoSetting(params: { timeout: number; symbols?: string; }): Promise< APISuccessResponse<{ currentTime: number; triggerTime: number; }> > { return this.postPrivate('api/v1/hf/orders/dead-cancel-all', params); ⋮---- /** * Add Stop Order * * Place stop order to the Spot trading system. */ submitStopOrder( params: SubmitStopOrderRequest, ): Promise > { return this.deletePrivate( 'api/v1/stop-order/cancelOrderByClientOid', params, ); ⋮---- /** * Cancel Stop Order By OrderId * * Request via this endpoint to cancel a single stop order previously placed. */ cancelStopOrderById(params: { orderId: string }): Promise< APISuccessResponse<{ cancelledOrderIds: string[]; // Unique ID of the cancelled order }> > { return this.deletePrivate(`api/v1/stop-order/$ ⋮---- cancelledOrderIds: string[]; // Unique ID of the cancelled order ⋮---- /** * Batch Cancel Stop Orders * * Request via this endpoint to cancel a batch of stop orders. */ cancelStopOrders(params?: CancelStopOrdersRequest): Promise< APISuccessResponse<{ cancelledOrderIds: string[]; // Unique IDs of the cancelled orders }> > { return this.deletePrivate('api/v1/stop-order/cancel', params); ⋮---- cancelledOrderIds: string[]; // Unique IDs of the cancelled orders ⋮---- /** * Get Stop Orders List * * Request via this endpoint to get your current untriggered stop order list. */ getStopOrders( params?: GetStopOrdersListRequest, ): Promise> ⋮---- /** * Get Stop Order By OrderId * * Request via this endpoint to get a stop order information via the order ID. */ getStopOrderByOrderId(params: { orderId: string; }): Promise> ⋮---- /** * Get Stop Order By ClientOid * * */ getStopOrderByClientOid(params: { clientOid: string; symbol?: string; }): Promise> ⋮---- /** * Add OCO Order * * Place OCO order to the Spot trading system */ submitOCOOrder(params: SubmitOCOOrderRequest): Promise< APISuccessResponse<{ orderId: string; // An order Id is returned once an order is successfully submitd. }> > { return this.postPrivate('api/v3/oco/order', params); ⋮---- orderId: string; // An order Id is returned once an order is successfully submitd. ⋮---- /** * Cancel OCO Order By OrderId * * Request via this endpoint to cancel a single oco order previously placed. */ cancelOCOOrderById(params: { orderId: string }): Promise< APISuccessResponse<{ cancelledOrderIds: string[]; }> > { return this.deletePrivate(`api/v3/oco/order/$ ⋮---- /** * Cancel OCO Order By ClientOid * * Request via this endpoint to cancel a single oco order previously placed. */ cancelOCOOrderByClientOid(params: { clientOid: string }): Promise< APISuccessResponse<{ cancelledOrderIds: string[]; }> > { return this.deletePrivate(`api/v3/oco/client-order/$ ⋮---- /** * Batch Cancel OCO Order * * This endpoint can batch cancel OCO orders through orderIds. */ cancelMultipleOCOOrders(params?: { orderIds?: string; symbol?: string; }): Promise< APISuccessResponse<{ cancelledOrderIds: string[]; }> > { return this.deletePrivate('api/v3/oco/orders', params); ⋮---- /** * Get OCO Order By OrderId * * Request via this endpoint to get a oco order information via the order ID. */ getOCOOrderByOrderId(params: { orderId: string; }): Promise> ⋮---- /** * Get OCO Order By ClientOid * * Request via this endpoint to get a oco order information via the clientOid. */ getOCOOrderByClientOid(params: { clientOid: string; }): Promise> ⋮---- /** * Get OCO Order Details * * Request via this endpoint to get a oco order information via the order ID. */ getOCOOrderDetails(params: { orderId: string; }): Promise> ⋮---- /** * Get OCO Order List * * Request via this endpoint to get your current OCO order list. */ getOCOOrders( params: GetOCOOrdersRequest, ): Promise> ⋮---- /** * * REST - MARGIN TRADING - Market Data * */ ⋮---- /** * Get Symbols - Cross Margin * * This endpoint allows querying the configuration of cross margin symbol. */ getMarginActivePairsV3(params?: { symbol?: string; }): Promise< APISuccessResponse<{ timestamp: number; items: MarginActivePairsV3[] }> > { return this.getPrivate('api/v3/margin/symbols', params); ⋮---- /** * Get Margin Config * * Request via this endpoint to get the configure info of the cross margin. */ getMarginConfigInfo(): Promise> ⋮---- /** * Get ETF Info * * This endpoint returns leveraged token information */ getMarginLeveragedToken(params?: { currency?: string; }): Promise> ⋮---- /** * Get Mark Price List * * This endpoint returns the current Mark price for all margin trading pairs. */ getMarginMarkPrices(): Promise> ⋮---- /** * Get Mark Price Detail * * This endpoint returns the current Mark price for specified margin trading pairs. */ getMarginMarkPrice(params: { symbol: string; }): Promise> ⋮---- /** * Get Symbols - Isolated Margin * * This endpoint allows querying the configuration of isolated margin symbol. */ getIsolatedMarginSymbolsConfig(): Promise< APISuccessResponse > { return this.getPrivate('api/v1/isolated/symbols'); ⋮---- /** * * REST - MARGIN TRADING - Orders * */ ⋮---- /** * Add Order * * Place order to the Cross-margin or Isolated-margin trading system */ submitHFMarginOrder( params: SubmitHFMarginOrderRequest, ): Promise> ⋮---- /** * Add Order Test * * This endpoint is used to test the order submission. */ submitHFMarginOrderTest( params: SubmitHFMarginOrderRequest, ): Promise ⋮---- /** * Cancel Order By OrderId * * This endpoint can be used to cancel a margin order by orderId. */ cancelHFMarginOrder(params: { orderId: string; symbol: string }): Promise< APISuccessResponse<{ orderId: string; }> > { return this.deletePrivate( `api/v3/hf/margin/orders/${params.orderId}`, params, ); ⋮---- /** * Cancel Order By ClientOid * * This endpoint can be used to cancel a margin order by clientOid. */ cancelHFMarginOrderByClientOid(params: { clientOid: string; symbol: string; }): Promise< APISuccessResponse<{ clientOid: string; }> > { return this.deletePrivate( `api/v3/hf/margin/orders/client-order/${params.clientOid}`, params, ); ⋮---- /** * Cancel All Orders By Symbol * * This endpoint can cancel all open Margin orders by symbol */ cancelHFAllMarginOrders(params: { symbol: string; tradeType: string; }): Promise ⋮---- /** * Get Symbols With Open Order * * This endpoint can query all Margin symbol that has active orders */ getHFMarginOpenSymbols(params: { tradeType: string; }): Promise> ⋮---- /** * Get Closed Orders * * This endpoint is to obtain all Margin Closed order lists */ getHFMarginFilledOrders(params: GetHFMarginFilledRequest): Promise< APISuccessResponse<{ lastId: number; items: HFMarginOrder[]; }> > { return this.getPrivate('api/v3/hf/margin/orders/done', params); ⋮---- /** * Get Trade History * * This endpoint can be used to obtain a list of the latest Margin transaction details. */ getHFMarginFills(params: getHFMarginFillsRequest): Promise< APISuccessResponse<{ lastId: number; items: HFMarginTransactionRecord[]; }> > { return this.getPrivate('api/v3/hf/margin/fills', params); ⋮---- /** * Get Order By OrderId * * This endpoint can be used to obtain a Margin order by orderId. */ getHFMarginOrderByOrderId(params: { orderId: string; symbol: string; }): Promise> ⋮---- /** * Get Order By ClientOid * * This endpoint can be used to obtain a Margin order by clientOid. */ getHFMarginOrderByClientOid(params: { clientOid: string; symbol: string; }): Promise> ⋮---- /** * * REST - MARGIN TRADING - Debit * */ ⋮---- /** * Borrow * * This API endpoint is used to initiate an application for cross or isolated margin borrowing. */ marginBorrowV3( params: MarginBorrowV3Request, ): Promise> ⋮---- /** * Get Borrow History * * This API endpoint is used to get the borrowing orders for cross and isolated margin accounts */ getMarginBorrowHistoryV3( params: MarginHistoryV3Request, ): Promise> ⋮---- /** * Repay * * This API endpoint is used to initiate an application for cross or isolated margin repayment. */ marginRepayV3( params: MarginRepayV3Request, ): Promise> ⋮---- /** * Get Repay History * * This API endpoint is used to get the repayment orders for cross and isolated margin accounts */ getMarginRepayHistoryV3( params: MarginHistoryV3Request, ): Promise> ⋮---- /** * Get Interest History * * Request via this endpoint to get the interest records of the cross/isolated margin lending. */ getMarginInterestRecordsV3( params?: MarginInterestRecordsRequest, ): Promise> ⋮---- /** * Modify Leverage * * This endpoint allows modifying the leverage multiplier for cross margin or isolated margin. */ updateMarginLeverageV3(params: { symbol?: string; leverage: string; isIsolated?: boolean; }): Promise> ⋮---- /** * * REST - MARGIN TRADING - Credit * */ ⋮---- /** * Get Loan Market * * This API endpoint is used to get the information about the currencies available for lending. */ getLendingCurrencyV3(params?: { currency?: string; }): Promise> ⋮---- /** * Get Loan Market Interest Rate * * This API endpoint is used to get the interest rates of the margin lending market over the past 7 days. */ getLendingInterestRateV3(params: { currency: string }): Promise< APISuccessResponse< { time: string; // Time: YYYYMMDDHH00 marketInterestRate: string; // Market interest rate }[] > > { return this.get('api/v3/project/marketInterestRate', params); ⋮---- time: string; // Time: YYYYMMDDHH00 marketInterestRate: string; // Market interest rate ⋮---- /** * Purchase * * Invest credit in the market and earn interest,Please ensure that the funds are in the main(funding) account */ submitLendingSubscriptionV3( params: InitiateLendingSubscriptionV3Request, ): Promise< APISuccessResponse< { orderNo: string; }[] > > { return this.postPrivate('api/v3/purchase', params); ⋮---- /** * Modify Purchase * * This API endpoint is used to update the interest rates of subscription orders, which will take effect at the beginning of the next hour. */ updateLendingSubscriptionOrdersV3( params: ModifyLendingSubscriptionOrdersV3Request, ): Promise ⋮---- /** * Get Purchase Orders * * This API endpoint provides pagination query for the purchase orders. */ getLendingSubscriptionOrdersV3( params: GetLendingSubscriptionOrdersV3Request, ): Promise> ⋮---- /** * Redeem * * Redeem your loan order */ submitLendingRedemptionV3( params: InitiateLendingRedemptionV3Request, ): Promise< APISuccessResponse< { orderNo: string; }[] > > { return this.postPrivate('api/v3/redeem', params); ⋮---- /** * Get Redeem Orders * * This API endpoint provides pagination query for the redeem orders. */ getLendingRedemptionOrdersV3( params: GetLendingRedemptionOrdersV3Request, ): Promise> ⋮---- /** * * REST - MARGIN TRADING - Risk Limit * */ ⋮---- /** * Get Margin Risk Limit * * Request via this endpoint to get the Configure and Risk limit info of the margin. */ getMarginRiskLimitConfig( params: MarginRiskLimitRequest, ): Promise> ⋮---- /** * * REST - CONVERT * */ ⋮---- /** * Get Convert Symbol * * Request via this endpoint to get detail currency pairs for convert. */ getConvertSymbol( params: GetConvertSymbolRequest, ): Promise> ⋮---- /** * Get Convert Currencies * * Request via this endpoint to get the list of cryptocurrencies available for convert. */ getConvertCurrencies(): Promise> ⋮---- /** * Add Convert Order * * Place market order for convert */ submitConvertOrder( params: AddConvertOrderRequest, ): Promise> ⋮---- /** * Get Convert Quote * * Request via this endpoint to get the quote for convert. */ getConvertQuote( params: GetConvertQuoteRequest, ): Promise> ⋮---- /** * Get Convert Order Detail * * Query convert market order details */ getConvertOrder( params: GetConvertOrderDetailRequest, ): Promise> ⋮---- /** * Get Convert Order History * * Query convert market order history */ getConvertOrderHistory( params?: GetConvertOrderHistoryRequest, ): Promise> ⋮---- /** * Add Convert Limit Order * * Place Convert Limit Order */ submitConvertLimitOrder( params: AddConvertLimitOrderRequest, ): Promise> ⋮---- /** * Get Convert Limit Quote * * Query the protection price threshold for limit orders for convert,user's order price must be ≥ the protection price */ getConvertLimitQuote( params: GetConvertLimitQuoteRequest, ): Promise> ⋮---- /** * Get Convert Limit Order Detail * * Query convert limit order detail */ getConvertLimitOrder( params: GetConvertLimitOrderDetailRequest, ): Promise> ⋮---- /** * Get Convert Limit Orders * * Query Active and Historical Convert Limit Orders */ getConvertLimitOrders( params?: GetConvertLimitOrdersRequest, ): Promise> ⋮---- /** * Cancel Convert Limit Order * * Cancel Convert Limit Order */ cancelConvertLimitOrder( params: CancelConvertLimitOrderRequest, ): Promise> ⋮---- /** * * REST - EARN - Simple earn * */ ⋮---- /** /** * Earn Purchase * * This endpoint allows subscribing earn product */ subscribeEarnFixedIncome( params: SubscribeEarnFixedIncomeRequest, ): Promise> ⋮---- /** * Get Earn Redeem Preview * * This endpoint retrieves redemption preview information by holding ID. If the current holding is fully redeemed or in the process of being redeemed, it indicates that the holding does not exist. */ getEarnRedeemPreview( params: GetEarnRedeemPreviewRequest, ): Promise> ⋮---- /** * Earn Redeem * * This endpoint allows initiating redemption by holding ID. If the current holding is fully redeemed or in the process of being redeemed, it indicates that the holding does not exist. */ submitRedemption( params: InitiateRedemptionRequest, ): Promise> ⋮---- /** * Get Earn Savings Products * * This endpoint retrieves savings products. If no savings products are available, an empty list is returned. */ getEarnSavingsProducts(params?: { currency?: string; }): Promise> ⋮---- /** * Get Earn Limited-Time Promotion Products * * This endpoint retrieves limited-time promotion products. If no products are available, an empty list is returned. */ getEarnPromotionProducts(params?: { currency?: string; }): Promise> ⋮---- /** * Get Earn Account Holdings * * This endpoint retrieves current holding assets of fixed income products. If no current holding assets are available, an empty list is returned. */ getEarnFixedIncomeHoldAssets( params?: GetEarnFixedIncomeHoldAssetsRequest, ): Promise> ⋮---- /** * Get Earn Staking Products * * This endpoint retrieves staking products. If no staking products are available, an empty list is returned. */ getEarnStakingProducts(params?: { currency?: string; }): Promise> ⋮---- /** * Get Earn KCS Staking Products * * This endpoint retrieves KCS Staking products. If no KCS Staking products are available, an empty list is returned. * */ getEarnKcsStakingProducts(params?: { currency?: string; }): Promise> ⋮---- /** * Get Earn ETH Staking Products * * This endpoint retrieves ETH Staking products. If no ETH Staking products are available, an empty list is returned. * */ getEarnEthStakingProducts(params?: { currency: string; }): Promise> ⋮---- /** * * REST - EARN - Structured earn(Dual) * */ ⋮---- /** * Structured Product Purchase * * This endpoint allows you to subscribe Struct-Earn products. */ submitStructuredProductPurchase( params: StructuredProductPurchaseRequest, ): Promise> ⋮---- /** * Get Dual Investment Products * * Available dual investment products can be obtained at this endpoint. If no products are available, an empty list is returned. */ getDualInvestmentProducts( params: GetDualInvestmentProductsRequest, ): Promise> ⋮---- /** * Get Structured Product Orders * * This endpoint is to query structured product orders */ getStructuredProductOrders( params: GetStructuredProductOrdersRequest, ): Promise> ⋮---- /** * * REST - VIP LENDING * */ ⋮---- /** * Get Discount Rate Configs * * Get the gradient discount rate of each currency. * Returns the discount rate configuration for different USDT value ranges per currency. */ getDiscountRateConfigs(): Promise> ⋮---- /** * Get Account Detail - VIP Lending * * The following information is only applicable to loans. * Get information on off-exchange funding and loans. * This endpoint is only for querying accounts that are currently involved in loans. */ getOtcLoan(): Promise> ⋮---- /** * Get Accounts - VIP Lending * * Accounts participating in OTC lending, This endpoint is only for querying accounts currently running OTC lending. */ getOtcLoanAccounts(): Promise> ⋮---- /** * * REST - AFFILIATE * */ ⋮---- /** * @deprecated This method is deprecated. Use other affiliate endpoints instead. * Get Affiliate User Rebate Information * * This endpoint allows getting affiliate user rebate information. */ getAffiliateUserRebateInfo(): Promise> ⋮---- /** * Get Trade History * * Trade history information can be obtained at this endpoint. */ getAffiliateTradeHistory( params: GetAffiliateTradeHistoryRequest, ): Promise> ⋮---- /** * Get Commission * * My commission information can be obtained at this endpoint. */ getAffiliateCommission( params?: GetAffiliateCommissionRequest, ): Promise> ⋮---- /** * Get Invited * * Affiliate user invited information can be obtained at this endpoint. */ getAffiliateInvitees( params?: GetAffiliateInviteesRequest, ): Promise> ⋮---- /** * * REST - BROKER * */ ⋮---- /** * Get download link for broker rebate orders * * trade type 1 = spot, trade type 2 = futures */ getBrokerRebateOrderDownloadLink(params: { begin: string; end: string; tradeType: 1 | 2; }): Promise> ⋮---- /** * * WebSockets * */ ⋮---- getPublicWSConnectionToken(): Promise> ⋮---- getPrivateWSConnectionToken(): Promise> ⋮---- /** * * DEPRECATED * */ ⋮---- /** * * REST - ACCOUNT - Sub-Account * DEPRECATED */ ⋮---- /** * @deprecated This method is deprecated. * It is recommended to use the getSubAccountsV2() endpoint instead of this endpoint */ getSubAccountsV1(): Promise> ⋮---- /** * @deprecated This method is deprecated. * It is recommended to use the getSubAccountsV2() endpoint instead of this endpoint */ getSubAccountBalancesV1(): Promise> ⋮---- /** * * REST - FUNDING - Funding overview * DEPRECATED */ ⋮---- /** * @deprecated This method is deprecated. * It is recommended to use the getMarginBalance() endpoint instead of this endpoint */ getMarginBalances(): Promise< APISuccessResponse<{ debtRatio: string; accounts: MarginAccountBalance[]; }> > { return this.getPrivate('api/v1/margin/account'); ⋮---- /** * * REST - FUNDING -Deposit * DEPRECATED */ ⋮---- /** * @deprecated This method is deprecated. Please use createDepositAddressV3() instead. */ createDepositAddress(params: { currency: string; chain?: string; }): Promise> ⋮---- /** * @deprecated This method is deprecated. Please use getDepositAddressesV3() instead. */ getDepositAddressesV2(params: { currency: string; }): Promise> ⋮---- /** * @deprecated This method is deprecated. Please use getDepositAddressesV3() instead. */ getDepositAddressV1(params: { currency: string; chain?: string; }): Promise> ⋮---- /** * @deprecated This method is deprecated. * It is recommended to use the getDeposits() endpoint instead of this endpoint */ getHistoricalDepositsV1( params?: GetDepositsRequest, ): Promise> ⋮---- /** * * REST - FUNDING -Withdrawals * DEPRECATED */ ⋮---- /** * @deprecated This method is deprecated. * It is recommended to use the getWithdrawals() endpoint instead of this endpoint */ getHistoricalWithdrawalsV1( params?: GetWithdrawalsRequest, ): Promise> ⋮---- /** * @deprecated This method is deprecated. Please use submitWithdrawV3() instead. */ submitWithdraw( params: ApplyWithdrawRequest, ): Promise > { return this.postPrivate('api/v2/accounts/sub-transfer', params); ⋮---- /** * @deprecated This method is deprecated. * It is recommended to use the submitFlexTransfer() endpoint instead of this endpoint */ submitInnerTransfer(params: InnerTransferRequest): Promise< APISuccessResponse<{ orderId: string; }> > { return this.postPrivate('api/v2/accounts/inner-transfer', params); ⋮---- /** * * REST - SPOT TRADING - Orders * DEPRECATED */ ⋮---- /** * @deprecated This method is deprecated. * It is recommended to use the submitHFOrder() endpoint instead of this endpoint */ submitOrder(params: SubmitOrderRequest): Promise< APISuccessResponse<{ orderId: string; // An order Id is returned once an order is successfully submitd. }> > { return this.postPrivate('api/v1/orders', params); ⋮---- orderId: string; // An order Id is returned once an order is successfully submitd. ⋮---- /** * @deprecated This method is deprecated. * It is recommended to use the submitHFOrderTest() endpoint instead of this endpoint */ submitOrderTest(): Promise ⋮---- /** * @deprecated This method is deprecated. * It is recommended to use the submitMultipleHFOrders() endpoint instead of this endpoint */ submitMultipleOrders(params: { symbol: string; orderList: SubmitMultipleOrdersRequest[]; }): Promise> ⋮---- /** * @deprecated This method is deprecated. * It is recommended to use the cancelHFOrder() endpoint instead of this endpoint */ cancelOrderById(params: { orderId: string }): Promise< APISuccessResponse<{ cancelledOrderIds: string[]; }> > { return this.deletePrivate(`api/v1/orders/$ ⋮---- /** * @deprecated This method is deprecated. * It is recommended to use the cancelHFOrderByClientOid() endpoint instead of this endpoint */ cancelOrderByClientOid(params: { clientOid: string }): Promise< APISuccessResponse<{ cancelledOrderId: string; clientOid: string; }> > { return this.deletePrivate(`api/v1/order/client-order/$ ⋮---- /** * @deprecated This method is deprecated. * It is recommended to use the cancelHFAllOrders() endpoint instead of this endpoint */ cancelAllOrders(params?: CancelAllOrdersRequest): Promise< APISuccessResponse<{ cancelledOrderIds: string[]; }> > { return this.deletePrivate('api/v1/orders', params); ⋮---- /** * @deprecated This method is deprecated. * It is recommended to use the getHfOrderDetails() endpoint instead of this endpoint */ getOrders( params?: GetOrderListRequest, ): Promise> ⋮---- /** * @deprecated This method is deprecated. * It is recommended to use the getHFOrders() endpoint instead of this endpoint */ getRecentOrders(params?: { currentPage?: number; pageSize?: number; }): Promise> ⋮---- /** * @deprecated This method is deprecated. * It is recommended to use the getHFOrderDetailsByOrderId() instead of this endpoint */ getOrderByOrderId(params: { orderId: string; }): Promise> ⋮---- /** * @deprecated This method is deprecated. * It is recommended to use the getHFOrderDetailsByClientOid() instead of this endpoint */ getOrderByClientOid(params: { clientOid: string; }): Promise> ⋮---- /** * * REST - SPOT TRADING -Fills * DEPRECATED */ ⋮---- /** * @deprecated This method is deprecated. * It is recommended to use the getHFFilledOrders() instead of this endpoint */ getFills( params?: GetFillsRequest, ): Promise> ⋮---- /** * @deprecated This method is deprecated. * It is recommended to use the getHFFilledOrders() instead of this endpoint */ getRecentFills(): Promise> ⋮---- /** * * REST - MARGIN TRADING - Orders * DEPRECATED */ ⋮---- /** * @deprecated This method is deprecated. * It is recommended to use the submitHFMarginOrder() endpoint instead of this endpoint */ submitMarginOrder( params: SubmitMarginOrderRequest, ): Promise> ⋮---- /** * @deprecated This method is deprecated. * It is recommended to use the submitHFMarginOrderTest() endpoint instead of this endpoint */ submitMarginOrderTest(): Promise ⋮---- /** * * REST - MARGIN TRADING - Isolated Margin * DEPRECATED */ ⋮---- /** * @deprecated This method is deprecated. * It is recommended to use the getMarginBalance() endpoint instead of this endpoint */ getIsolatedMarginAccounts(params?: { balanceCurrency?: 'USDT' | 'KCS' | 'BTC'; }): Promise> ⋮---- /** * @deprecated This method is deprecated. * It is recommended to use the getIsolatedMarginBalance() endpoint instead of this endpoint */ getIsolatedMarginAccount(params: { symbol: string; }): Promise> ================ File: package.json ================ { "name": "kucoin-api", "version": "2.1.20", "description": "Complete & robust Node.js SDK for Kucoin's REST APIs and WebSockets, with TypeScript & strong end to end tests.", "scripts": { "clean": "rm -rf dist", "build": "npm run clean && tsc -p tsconfig.esm.json && tsc -p tsconfig.cjs.json && bash ./postBuild.sh", "test": "jest --passWithNoTests", "lint": "eslint src" }, "main": "dist/cjs/index.js", "module": "dist/mjs/index.js", "types": "dist/mjs/index.d.ts", "exports": { ".": { "import": "./dist/mjs/index.js", "require": "./dist/cjs/index.js", "types": "./dist/mjs/index.d.ts" } }, "type": "module", "files": [ "dist/*", "llms.txt" ], "author": "Tiago Siebler (https://github.com/tiagosiebler)", "contributors": [ "Jerko J (https://github.com/JJ-Cro)" ], "dependencies": { "axios": "^1.10.0", "isomorphic-ws": "^4.0.1", "nanoid": "^3.3.11", "ws": "^7.4.0" }, "devDependencies": { "@types/jest": "^29.5.12", "@types/node": "^22.11.6", "@types/ws": "^8.5.10", "@typescript-eslint/eslint-plugin": "^8.18.0", "@typescript-eslint/parser": "^8.18.0", "eslint": "^8.29.0", "eslint-config-prettier": "^9.1.0", "eslint-plugin-prettier": "^5.1.3", "eslint-plugin-require-extensions": "^0.1.3", "eslint-plugin-simple-import-sort": "^12.1.1", "jest": "^29.7.0", "prettier": "^3.3.3", "ts-jest": "^29.2.4", "ts-node": "^10.9.2", "typescript": "^5.7.3" }, "keywords": [ "kucoin", "kucoin api", "kucoin nodejs", "kucoin javascript", "kucoin typescript", "algo trading", "api", "websocket", "rest", "rest api", "usdt", "trading bots", "nodejs", "node", "trading", "cryptocurrency", "bitcoin", "best" ], "funding": { "type": "individual", "url": "https://github.com/sponsors/tiagosiebler" }, "license": "MIT", "repository": { "type": "git", "url": "https://github.com/tiagosiebler/kucoin-api" }, "bugs": { "url": "https://github.com/tiagosiebler/kucoin-api/issues" }, "homepage": "https://github.com/tiagosiebler/kucoin-api#readme" } ================================================================ End of Codebase ================================================================