UNPKG

kucoin-api

Version:

Complete & robust Node.js SDK for Kucoin's REST APIs and WebSockets, with TypeScript & strong end to end tests.

1,975 lines (1,703 loc) 389 kB
This file is a merged representation of a subset of the codebase, containing files not matching ignore patterns, combined into a single document by Repomix. The content has been processed where content has been compressed (code blocks are separated by ⋮---- delimiter). ================================================================ File Summary ================================================================ Purpose: -------- This file contains a packed representation of a subset of the repository's contents that is considered the most important context. It is designed to be easily consumable by AI systems for analysis, code review, or other automated processes. File Format: ------------ The content is organized as follows: 1. This summary section 2. Repository information 3. Directory structure 4. Repository files (if enabled) 5. Multiple file entries, each consisting of: a. A separator line (================) b. The file path (File: path/to/file) c. Another separator line d. The full contents of the file e. A blank line Usage Guidelines: ----------------- - This file should be treated as read-only. Any changes should be made to the original repository files, not this packed version. - When processing this file, use the file path to distinguish between different files in the repository. - Be aware that this file may contain sensitive information. Handle it with the same level of security as you would the original repository. Notes: ------ - Some files may have been excluded based on .gitignore rules and Repomix's configuration - Binary files are not included in this packed representation. Please refer to the Repository Structure section for a complete list of file paths, including binary files - Files matching these patterns are excluded: .github/, examples/apidoc/, docs/images/, docs/endpointFunctionList.md, test/, src/util/ - Files matching patterns in .gitignore are excluded - Files matching default ignore patterns are excluded - Content has been compressed - code blocks are separated by ⋮---- delimiter - Files are sorted by Git change count (files with more changes are at the bottom) ================================================================ Directory Structure ================================================================ examples/ auth/ authorizationHeader.ts fasterHmacSign.ts WebSockets/ subscriptions/ README.md ws-futures-private.ts ws-futures-public.ts ws-spot-private.ts ws-spot-public.ts ws-api-client.ts ws-api-raw-promises.ts kucoin-FUTURES-examples-nodejs.md kucoin-SPOT-examples-nodejs.md rest-futures-orders-guide.ts rest-futures-private-trade.ts rest-futures-public.ts rest-spot-private-trade.ts rest-spot-public.ts tsconfig.examples.json src/ lib/ websocket/ logger.ts websocket-util.ts WsStore.ts WsStore.types.ts BaseRestClient.ts BaseWSClient.ts misc-util.ts requestUtils.ts webCryptoAPI.ts types/ request/ broker.types.ts futures.types.ts spot-account.ts spot-affiliate.ts spot-convert.ts spot-earn.ts spot-funding.ts spot-margin-trading.ts spot-misc.ts spot-trading.ts uta-types.ts response/ broker.types.ts futures.types.ts shared.types.ts spot-account.ts spot-affiliate.ts spot-convert.ts spot-earn.ts spot-funding.ts spot-margin-trading.ts spot-misc.ts spot-trading.ts spot-vip.ts uta-types.ts ws.ts websockets/ ws-api.ts ws-events.ts ws-general.ts BrokerClient.ts FuturesClient.ts index.ts SpotClient.ts UnifiedAPIClient.ts WebsocketAPIClient.ts WebsocketClient.ts .eslintrc.cjs .gitignore .nvmrc .prettierrc jest.config.ts LICENSE.md package.json postBuild.sh README.md tea.yaml tsconfig.cjs.json tsconfig.esm.json tsconfig.json tsconfig.linting.json ================================================================ Files ================================================================ ================ File: examples/kucoin-FUTURES-examples-nodejs.md ================ # **KuCoin FUTURES API Examples** - Node.js, JavaScript & Typescript SDK for Kucoin REST APIs & WebSockets <p align="center"> <a href="https://www.npmjs.com/package/kucoin-api"> <picture> <source media="(prefers-color-scheme: dark)" srcset="https://github.com/tiagosiebler/kucoin-api/blob/master/docs/images/logoDarkMode2.svg?raw=true#gh-dark-mode-only"> <img alt="SDK Logo" src="https://github.com/tiagosiebler/kucoin-api/blob/master/docs/images/logoBrightMode2.svg?raw=true#gh-light-mode-only"> </picture> </a> </p> 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 <p align="center"> <a href="https://www.npmjs.com/package/kucoin-api"> <picture> <source media="(prefers-color-scheme: dark)" srcset="https://github.com/tiagosiebler/kucoin-api/blob/master/docs/images/logoDarkMode2.svg?raw=true#gh-dark-mode-only"> <img alt="SDK Logo" src="https://github.com/tiagosiebler/kucoin-api/blob/master/docs/images/logoBrightMode2.svg?raw=true#gh-light-mode-only"> </picture> </a> </p> This document provides comprehensive examples for using the KuCoin SPOT API with Node.js and JavaScript. It covers various functionalities including account management, fund transfers, trade execution, order management, and market data retrieval. The examples are designed to help developers quickly integrate KuCoin Spot API into their NodeJS, Javascript and Typscript applications. If you are here, it means you will be great addition to our [Node.js Traders](https://t.me/nodetraders) community on Telegram where we discuss trading ideas, provide support regarding SDKs and share valuable resources! - [KuCoin Documentation](https://www.kucoin.com/docs/beginners/introduction) - official Kucoin API docs - [Node.js & JavaScript SDK for Kucoin](https://github.com/tiagosiebler/kucoin-api) - Github repo of our SDK Current file contains only certain most used examples. If you can't find what you need, you can search through [SpotClient.ts](https://github.com/tiagosiebler/kucoin-api/blob/master/src/SpotClient.ts) - all of the endpoints and functions will be there! Otherwise, just ask in [Node.js Traders](https://t.me/nodetraders) Telegram group. Do you need help with Futures? Check out [Futures Quickstart guide](https://github.com/tiagosiebler/kucoin-api/blob/master/examples/kucoin-FUTURES-examples-nodejs.md) **Table of contents:** - [Installation](#installation) - [Usage](#usage) - [REST API](#rest-api) - [Account and balance](#account-examples) - [Account overview](#account-overview) - [Transactions](#transactions) - [Deposit and Withdrawal](#deposit-and-withdrawal) - [Subaccount](#subaccount) - [Subaccount management](#subaccount-management) - [Subaccount API management](#subaccount-api-management) - [Market Data](#market-data) - [Symbol and exchange info](#symbol-and-exchange-info) - [Order Book data](#order-book-data) - [Kline/Candles](#klinecandles) - [Trade Execution](#trade) - [General info](#general-info) - [Market short](#market-short) - [Market long](#market-long) - [Limit short](#limit-short) - [Limit long](#limit-long) - [Place multiple orders](#place-multiple-orders) - [Trade/Order/Positions Management](#tradeorderpositions-management) - [Fetching orders](#fetching-orders) - [Cancel order](#cancel-order) - [Cancel all orders for specific symbol](#cancel-all-orders-for-specific-symbol) - [Fills](#fills) - [Spot HF trade](#spot-hf-trade) - [Margin trade](#margin-trade--margin-hf-trade) - [WebSocket](#websocket) - [Community group](#community-group) ## Installation: ```js // Install by npm npm install kucoin-api // Install by yarn yarn add kucoin-api ``` ## Usage #### Create API credentials - [Kucoin API Key Management](https://www.kucoin.com/account/api) #### Import SDK to your project ```js // require const { SpotClient } = require('kucoin-api'); // import import { SpotClient } from 'kucoin-api'; // initialise Spot Client const spotClient = new SpotClient({ // insert your api key, secret and passphrase - use env vars, if not just fill the string values apiKey: process.env.KUCOIN_API_KEY || 'insert-your-api-key', apiSecret: process.env.KUCOIN_API_SECRET || 'insert-your-api-secret', apiPassphrase: process.env.KUCOIN_API_PASSPHRASE || 'insert-your-api-passphrase', }); ``` ## REST API ### Account examples #### Account Overview ```js // Get Account Summary spotClient.getAccountSummary(); // Get all Account Balances spotClient.getBalances(); // Get specific Account or Currency Balance spotClient.getBalance({ currency: 'USDT', type: 'main', // 'trade' | 'margin' | 'trade_hf' }); // Example call to get account details by ID spotClient.getAccountDetails({ accountId: '5bd6e9286d99522a52e458de' }); // Margin endpoints for balances spotClient.getMarginBalances(); spotClient.getMarginBalance(); spotClient.getIsolatedMarginBalance(); ``` #### Transactions ```js // Example call to get account ledgers with specified parameters spotClient.getTransactions({ currency: 'BTC', startAt: 1601395200000 }); // Example call to get high-frequency account ledgers with specified parameters spotClient.getHFTransactions({ bizType: 'TRADE_EXCHANGE', currency: 'YOP,DAI', startAt: 1601395200000, }); // Example call to get high-frequency margin account ledgers with specified parameters spotClient.getHFMarginTransactions({ bizType: 'MARGIN_EXCHANGE', currency: 'YOP,DAI', startAt: 1601395200000, }); ``` #### Deposit and Withdrawal ```js // Example call to create a deposit address spotClient.createDepositAddress({ currency: 'BTC', // Optional parameter chain: 'BTC', }); // Example call to get deposit addresses with specified parameters spotClient.getDepositAddressesV2({ currency: 'BTC', }); // Example call to get deposits spotClient.getDeposits(); // Example call to get withdrawals with specified parameters spotClient.getWithdrawals({ currency: 'BTC', // Optional parameter }); // Example call to submit a withdrawal spotClient.submitWithdraw({ currency: 'BTC', address: '1A1zP1eP5QGefi2DMPTfTL5SLmv7DivfNa', amount: 0.01, // Optional parameters memo: 'exampleMemo', chain: 'BTC', }); // Example call to cancel a withdrawal by ID spotClient.cancelWithdrawal({ withdrawalId: '5bffb63303aa675e8bbe18f9', }); ``` ### Subaccount #### Subaccount Management ```js // Get all subaccounts spotClient.getSubAccountsV2({}); // Example call to create a sub-account spotClient.createSubAccount({ // Fill in the required parameters for creating a sub-account subName: 'exampleSubAccount', password: 'examplePassword', access: 'trade', }); // Example call to get sub-account balance with specified parameters spotClient.getSubAccountBalance({ subUserId: '5caefba7d9575a0688f83c45', includeBaseAmount: false, }); // Example call to get sub-account balances spotClient.getSubAccountBalancesV2(); // Example call to get transferable funds spotClient.getTransferable({ currency: 'BTC', type: 'MAIN', }); // Example call to submit a transfer from master to sub-account spotClient.submitTransferMasterSub({ clientOid: client.generateNewOrderID(), // or use your custom UUID amount: 0.01, currency: 'USDT', direction: 'OUT', // 'IN' for transfer to master, 'OUT' for transfer to sub subUserId: 'enter_sub_user_id_here', }); // Example call to submit an inner transfer within same account spotClient.submitInnerTransfer({ clientOid: client.generateNewOrderID(), // or use your custom UUID amount: 0.01, currency: 'USDT', from: 'main', // Source account type to: 'trade', // Destination account type }); ``` #### Subaccount API management ```js // Get all subaccount APIs spotClient.getSubAPIs({ subName: 'my_sub_name', }); // Create APIs for Sub-Account spotClient.createSubAPI({ subName: 'my_sub_name', passphrase: 'my_passphrase', remark: 'my_remark', }); // Modify Sub-Account APIs spotClient.updateSubAPI({ subName: 'my_sub_name', passphrase: 'my_passphrase', apiKey: 'my_api_key', }); // Delete Sub-Account APIs spotClient.deleteSubAPI({ subName: 'my_sub_name', passphrase: 'my_passphrase', apiKey: 'my_api_key', }); ``` ### Market Data #### Symbol and exchange info ```js // Get All Currencies List spotClient.getCurrencies(); // Get info for a specific currency spotClient.getCurrency({ currency: 'BTC', }); // Get all Symbols spotClient.getSymbols(); // Example call to get ticker information for a specific symbol spotClient.getTicker({ symbol: 'BTC-USDT', }); // All tickers spotClient.getTickers(); // Get 24h stats for a specific symbol spotClient.get24hrStats({ symbol: 'BTC-USDT', }); ``` #### Order Book data ```js // get partial orderbook spotClient.getOrderBookLevel20({ symbol: 'BTC-USDT' }); // get partial orderbook spotClient.getOrderBookLevel100({ symbol: 'BTC-USDT' }); // get full orderbook spotClient.getFullOrderBook({ symbol: 'BTC-USDT' }); ``` #### Kline/Candles ```js // Example call to get Klines (candlestick data) with specified parameters spotClient.getKlines({ type: '1min', symbol: 'BTC-USDT', startAt: 1566703297, endAt: 1566789757, }); ``` --- ### Trade #### General info Please, read official [Kucoin API docs](https://www.kucoin.com/docs/rest/spot-trading/orders/place-order) to understand how to place orders, cancel orders, etc. and what is needed for each endpoint. These are just low-end examples to understand how to use it with SDK. #### Market Short ```js // Market short order const marketShort = spotClient.submitOrder({ clientOid: client.generateNewOrderID(), // or use your custom UUID side: 'sell', symbol: 'ETH-BTC', type: 'market', size: '0.5', // Specify the quantity to sell }); ``` #### Market Long ```js // Market long order const marketLong = spotClient.submitOrder({ clientOid: client.generateNewOrderID(), // or use your custom UUID side: 'buy', symbol: 'ETH-BTC', type: 'market', size: '0.5', // Specify the quantity to buy }); ``` #### Limit Short ```js // Limit short order const limitShort = spotClient.submitOrder({ clientOid: client.generateNewOrderID(), // or use your custom UUID side: 'sell', symbol: 'ETH-BTC', type: 'limit', price: '0.03', // Specify the price to sell size: '0.5', // Specify the quantity to sell timeInForce: 'GTC', // Good Till Canceled }); ``` #### Limit Long ```js // Limit long order const limitLong = spotClient.submitOrder({ clientOid: client.generateNewOrderID(), // or use your custom UUID side: 'buy', symbol: 'ETH-BTC', type: 'limit', price: '0.03', // Specify the price to buy size: '0.5', // Specify the quantity to buy timeInForce: 'GTC', // Good Till Canceled }); ``` ##### Place Multiple Orders ```js //request const multipleOrders = [ { clientOid: '3d07008668054da6b3cb12e432c2b13a', side: 'buy', type: 'limit', price: '0.01', size: '0.01', }, { clientOid: '37245dbe6e134b5c97732bfb36cd4a9d', side: 'buy', type: 'limit', price: '0.01', size: '0.01', }, ]; spotClient.submitMultipleOrders({ symbol: 'KCS-USDT', orderList: multipleOrders, }); ``` ### Trade/Order/Positions Management #### Fetching orders ```js // Get open orders spotClient.getOrders({ status: 'active' }); // Get closed orders spotClient.getOrders({ status: 'done' }); // Get List of Orders Completed in 24h spotClient.getRecentOrders(); // Get Details of a Single Order by ClientOrderId spotClient.getOrderByClientOid({ clientOid: 'clientOid' }); // Or By OrderId spotClient.getOrderByOrderId({ orderId: 'orderId' }); ``` #### Cancel Order ```js spotClient.cancelOrderById({ orderId: 'orderId' }); spotClient.cancelOrderByClientOid({ clientOid: 'clientOid' }); ``` #### Cancel all orders for specific symbol ```js //cancel all orders for symbol spotClient.cancelAllOrders({ symbol: 'XBTUSDTM' }); // cancel all orders for all symbols spotClient.cancelAllOrders(); ``` #### Fills ```js // Get Specific Fills spotClient.getFills({ type: 'market' }); // or search for all spotClient.getFills(); // Recent Fills from last 24 hours spotClient.getRecentFills(); ``` ### Spot HF trade All of the examples are 99% same as regular spot, but you can follow the [official HF Trade API documentation](https://www.kucoin.com/docs/rest/spot-trading/spot-hf-trade-pro-account/place-hf-order) and list of functions in [SpotClient.ts](https://github.com/tiagosiebler/kucoin-api/blob/master/src/SpotClient.ts) to find what you need! ### Margin trade & Margin HF trade All of the examples are 99% same as regular spot, but you can follow the [official Margin Trade API documentation](https://www.kucoin.com/docs/rest/margin-trading/market-data) and list of functions in [SpotClient.ts](https://github.com/tiagosiebler/kucoin-api/blob/master/src/SpotClient.ts) to find what you need! --- ## Websocket For Websocket examples, please refer to these links: - [Spot Public Websocket](https://github.com/tiagosiebler/kucoin-api/blob/master/examples/ws-spot-public.ts) - [Spot Private Websocket](https://github.com/tiagosiebler/kucoin-api/blob/master/examples/ws-spot-private.ts) - [Futures Public Websocket](https://github.com/tiagosiebler/kucoin-api/blob/master/examples/ws-futures-public.ts) - [Futures Private Websocket](https://github.com/tiagosiebler/kucoin-api/blob/master/examples/ws-futures-private.ts) ## Community group If you need help, something is wrong/missing or you have suggestions, please join our [Node.js Traders](https://t.me/nodetraders) community group on Telegram and let us know! ================ File: examples/rest-futures-orders-guide.ts ================ import { FuturesClient } from '../src/index.ts'; // import { FuturesClient } from 'kucoin-api'; // normally you should install this module via npm: `npm install kucoin-api` ⋮---- async function start() ⋮---- /** * ======= * Credits for this guide go to user: @DKTradingClient / Code Nerd from the Kucoin API Telegram group! * ======= /** * Futures are contracts, not currencies. In the futures symbols list you will see a "multiplier" field for each of the symbols. * Each contract equals to Multiplier x Size * For example: https://api-futures.kucoin.com/api/v1/contracts/XRPUSDTM - see the "multiplier" value. * */ ⋮---- /** * E.g. if multiplier is 10(what you can see from the endpoint), that means each SIZE is 10 XRP. So if XRP is currently at $0.5, * then each 1 contract (size 10) is going to cost $5.00 * size = (Funds x leverage) / (price x multiplier) */ ⋮---- /** * The trade amount indicates the amount of contract to buy or sell, and contract uses the base currency or lot as the trading unit. * The trade amount must be no less than 1 lot for the contract and no larger than the maxOrderQty. * It should be a multiple number of the lot, or the system will report an error when you place the order. * E.g. 1 lot of XBTUSDTM is 0.001 Bitcoin, while 1 lot of XBTUSDM is 1 USD. * or check the XRPUSDTM example above. * * Here are function examples using the Futures Create Order endpoint: */ ⋮---- // A MARKET SHORT of 2 contracts of XBT using leverage of 5: ⋮---- // A MARKET LONG of 2 contracts of XBT using leverage of 5: ⋮---- // A LIMIT SHORT of 2 contracts of XBT using leverage of 5: ⋮---- // A LIMIT LONG of 2 contracts of XBT using leverage of 5: ⋮---- // On any "close position" action, if you specify a SIZE=0 or leave off the SIZE parameter, // then it will close the whole position, regardless of the size. // If you specify a SIZE, it will close only the number of contracts you specify. ⋮---- // If closeOrder is set to TRUE, // the system will close the position and the position size will become 0. // Side, Size and Leverage fields can be left empty and the system will determine the side and size automatically. ⋮---- // A MARKET CLOSE POSITION example: ⋮---- // A LIMIT CLOSE of a LONG example: ⋮---- // A LIMIT CLOSE of a SHORT example: ⋮---- // A STOP LOSS example for a LONG position: ⋮---- // A STOP LOSS example for a SHORT position: ================ File: examples/rest-futures-private-trade.ts ================ import { FuturesClient } from '../src/index.ts'; // import { FuturesClient } from 'kucoin-api'; // normally you should install this module via npm: `npm install kucoin-api` ⋮---- async function start() ⋮---- /** * The trade amount indicates the amount of contract to buy or sell, and contract uses the base currency or lot as the trading unit. * The trade amount must be no less than 1 lot for the contract and no larger than the maxOrderQty. * It should be a multiple number of the lot, or the system will report an error when you place the order. * E.g. 1 lot of XBTUSDTM is 0.001 Bitcoin, while 1 lot of XBTUSDM is 1 USD. */ ⋮---- // Submit a futures entry order for 1 lot of XBTUSDTM (0.001 bitcoin) ================ File: examples/rest-futures-public.ts ================ import { FuturesClient } from '../src/index.ts'; // import { FuturesClient } from 'kucoin-api'; // normally you should install this module via npm: `npm install kucoin-api` ⋮---- async function start() ⋮---- // Fetch all symbols ⋮---- // Fetch ticker for a specific symbol ⋮---- // Fetch klines for a specific symbol ================ File: examples/rest-spot-private-trade.ts ================ import { SpotClient } from '../src/index.ts'; // import { SpotClient } from 'kucoin-api'; // normally you should install this module via npm: `npm install kucoin-api` ⋮---- async function start() ================ File: examples/rest-spot-public.ts ================ import { SpotClient } from '../src/index.ts'; // import { SpotClient } from 'kucoin-api'; // normally you should install this module via npm: `npm install kucoin-api` ⋮---- async function start() ⋮---- // Fetch all symbols ⋮---- // Fetch ticker for a specific symbol ⋮---- // Fetch klines for a specific symbol ================ File: examples/tsconfig.examples.json ================ { "extends": "../tsconfig.json", "compilerOptions": { "module": "commonjs", "outDir": "dist/cjs", "target": "esnext", "rootDir": "../" }, "include": ["../src/**/*.*", "../examples/**/*.*"] } ================ File: src/lib/misc-util.ts ================ export function neverGuard(x: never, msg: string): Error ================ File: src/types/request/broker.types.ts ================ export interface GetBrokerInfoRequest { begin: string; end: string; tradeType: '1' | '2'; } ⋮---- export interface GetBrokerSubAccountsRequest { uid: string; currentPage?: number; pageSize?: number; } ⋮---- export type BrokerSubAccountPermission = 'general' | 'spot' | 'futures'; ⋮---- export interface CreateBrokerSubAccountApiRequest { uid: string; passphrase: string; ipWhitelist: string[]; permissions: BrokerSubAccountPermission[]; label: string; } ⋮---- export interface GetBrokerSubAccountApisRequest { uid: string; apiKey?: string; } ⋮---- export interface UpdateBrokerSubAccountApiRequest { uid: string; apiKey: string; ipWhitelist: string[]; permissions: BrokerSubAccountPermission[]; label: string; } ⋮---- export interface DeleteBrokerSubAccountApiRequest { uid: string; apiKey: string; } ⋮---- export type BrokerTransferDirection = 'OUT' | 'IN'; export type BrokerAccountType = 'MAIN' | 'TRADE'; ⋮---- export interface BrokerTransferRequest { currency: string; amount: string; clientOid: string; direction: BrokerTransferDirection; accountType: BrokerAccountType; specialUid: string; specialAccountType: BrokerAccountType; } ⋮---- export interface GetBrokerDepositListRequest { currency?: string; status?: 'PROCESSING' | 'SUCCESS' | 'FAILURE'; hash?: string; startTimestamp?: number; endTimestamp?: number; limit?: number; } ================ File: src/types/request/spot-account.ts ================ export interface GetBalancesRequest { currency?: string; type?: 'main' | 'trade'; } ⋮---- export interface GetSpotTransactionsRequest { currency?: string; direction?: 'in' | 'out'; bizType?: | 'DEPOSIT' | 'WITHDRAW' | 'TRANSFER' | 'SUB_TRANSFER' | 'TRADE_EXCHANGE' | 'MARGIN_EXCHANGE' | 'KUCOIN_BONUS' | 'BROKER_TRANSFER' | 'REBATE'; startAt?: number; endAt?: number; currentPage?: number; pageSize?: number; } ⋮---- export interface AccountHFTransactionsRequest { currency?: string; direction?: 'in' | 'out'; bizType?: | 'TRANSFER' | 'TRADE_EXCHANGE' | 'RETURNED_FEES' | 'DEDUCTION_FEES' | 'OTHER'; lastId?: number; limit?: number; startAt?: number; endAt?: number; } ⋮---- export interface AccountHFMarginTransactionsRequest { currency?: string; direction?: 'in' | 'out'; bizType?: | 'TRANSFER' | 'MARGIN_EXCHANGE' | 'ISOLATED_EXCHANGE' | 'LIQUIDATION' | 'ASSERT_RETURN'; lastId?: number; limit?: number; startAt?: number; endAt?: number; } ⋮---- export interface CreateSubAccountRequest { password: string; remarks?: string; subName: string; access: string; } ⋮---- export interface CreateSubAccountAPIRequest { subName: string; passphrase: string; remark: string; permission?: string; ipWhitelist?: string; expire?: string; } ⋮---- export interface UpdateSubAccountAPIRequest { subName: string; apiKey: string; passphrase: string; permission?: string; ipWhitelist?: string; expire?: string; } ⋮---- export interface DeleteSubAccountAPIRequest { apiKey: string; passphrase: string; subName: string; } ================ File: src/types/request/spot-funding.ts ================ /** * *********** * Funding *********** * */ ⋮---- export interface CreateDepositAddressV3Request { currency: string; chain?: string; to?: 'main' | 'trade'; amount?: string; } ⋮---- export interface GetMarginBalanceRequest { quoteCurrency?: string; queryType?: 'MARGIN' | 'MARGIN_V2' | 'ALL'; } ⋮---- export interface GetIsolatedMarginBalanceRequest { symbol?: string; quoteCurrency?: string; queryType?: 'ISOLATED' | 'ISOLATED_V2' | 'ALL'; } ⋮---- /** * * Deposit * */ ⋮---- export interface GetDepositsRequest { currency?: string; startAt?: number; endAt?: number; status?: 'PROCESSING' | 'SUCCESS' | 'FAILURE'; currentPage?: number; pageSize?: number; } ⋮---- /** * * Withdrawals * */ ⋮---- export interface GetWithdrawalsRequest { currency?: string; status?: 'PROCESSING' | 'WALLET_PROCESSING' | 'SUCCESS' | 'FAILURE'; startAt?: number; endAt?: number; currentPage?: number; pageSize?: number; } ⋮---- export interface ApplyWithdrawRequest { currency: string; address: string; amount: number; memo?: string; isInner?: boolean; remark?: string; chain?: string; feeDeductType?: 'INTERNAL' | 'EXTERNAL'; } ⋮---- export interface SubmitWithdrawV3Request { currency: string; toAddress: string; amount: number; memo?: string; isInner?: boolean; remark?: string; chain?: string; feeDeductType?: 'INTERNAL' | 'EXTERNAL'; withdrawType: 'ADDRESS' | 'UID' | 'MAIL' | 'PHONE'; } ⋮---- /** * * Transfer * */ ⋮---- export interface GetTransferableRequest { currency: string; type: | 'MAIN' | 'TRADE' | 'TRADE_HF' | 'MARGIN' | 'ISOLATED' | 'OPTION' | 'MARGIN_V2' | 'ISOLATED_V2'; tag?: string; } ⋮---- export interface FlexTransferRequest { clientOid: string; currency?: string; amount: string; fromUserId?: string; fromAccountType: | 'MAIN' | 'TRADE' | 'CONTRACT' | 'MARGIN' | 'ISOLATED' | 'TRADE_HF' | 'MARGIN_V2' | 'ISOLATED_V2' | 'OPTION'; fromAccountTag?: string; type: 'INTERNAL' | 'PARENT_TO_SUB' | 'SUB_TO_PARENT'; toUserId?: string; toAccountType: | 'MAIN' | 'TRADE' | 'CONTRACT' | 'MARGIN' | 'ISOLATED' | 'TRADE_HF' | 'MARGIN_V2' | 'ISOLATED_V2' | 'OPTION'; toAccountTag?: string; } ⋮---- export interface submitTransferMasterSubRequest { clientOid: string; currency: string; amount: string; direction: 'OUT' | 'IN'; accountType?: | 'MAIN' | 'TRADE' | 'TRADE_HF' | 'MARGIN' | 'CONTRACT' | 'OPTION'; subAccountType?: | 'MAIN' | 'TRADE' | 'TRADE_HF' | 'MARGIN' | 'CONTRACT' | 'OPTION'; subUserId: string; } ⋮---- export interface InnerTransferRequest { clientOid: string; currency: string; from: | 'main' | 'trade' | 'trade_hf' | 'margin' | 'isolated' | 'margin_v2' | 'isolated_v2' | 'contract' | 'option'; to: | 'main' | 'trade' | 'trade_hf' | 'margin' | 'isolated' | 'margin_v2' | 'isolated_v2' | 'contract' | 'option'; amount: string; fromTag?: string; toTag?: string; } ================ File: src/types/request/spot-misc.ts ================ export interface GetAnnouncementsRequest { currentPage?: number; pageSize?: number; annType?: string; lang?: string; startTime?: number; endTime?: number; } ================ File: src/types/response/broker.types.ts ================ export interface BrokerInfo { accountSize: number; maxAccountSize: number | null; level: number; } ⋮---- export interface CreateBrokerSubAccountResponse { accountName: string; uid: string; createdAt: number; level: number; } ⋮---- export interface BrokerSubAccount { accountName: string; uid: string; createdAt: number; level: number; } ⋮---- export interface GetBrokerSubAccountsResponse { currentPage: number; pageSize: number; totalNum: number; totalPage: number; items: BrokerSubAccount[]; } ⋮---- export interface CreateBrokerSubAccountApiResponse { uid: string; label: string; apiKey: string; secretKey: string; apiVersion: number; permissions: string[]; ipWhitelist: string[]; createdAt: number; } ⋮---- export interface BrokerSubAccountApi { uid: string; label: string; apiKey: string; apiVersion: number; permissions: ('General' | 'Spot' | 'Futures')[]; ipWhitelist: string[]; createdAt: number; } ⋮---- export type BrokerTransferAccountType = | 'MAIN' | 'TRADE' | 'CONTRACT' | 'MARGIN' | 'ISOLATED'; export type BrokerTransferStatus = 'PROCESSING' | 'SUCCESS' | 'FAILURE'; ⋮---- export interface BrokerTransferHistory { orderId: string; currency: string; amount: string; fromUid: number; fromAccountType: BrokerTransferAccountType; fromAccountTag: string; toUid: number; toAccountType: BrokerTransferAccountType; toAccountTag: string; status: BrokerTransferStatus; reason: string | null; createdAt: number; } ⋮---- export interface BrokerDepositRecord { uid: number; hash: string; address: string; memo: string; amount: string; fee: string; currency: string; isInner: boolean; walletTxId: string; status: BrokerTransferStatus; remark: string; chain: string; createdAt: number; updatedAt: number; } ⋮---- export type BrokerWithdrawalStatus = | 'PROCESSING' | 'WALLET_PROCESSING' | 'REVIEW' | 'SUCCESS' | 'FAILURE'; ⋮---- export interface BrokerWithdrawalRecord { id: string; chain: string; walletTxId: string; uid: number; amount: string; memo: string; fee: string; address: string; remark: string; isInner: boolean; currency: string; status: BrokerWithdrawalStatus; createdAt: number; updatedAt: number; } ================ File: src/types/response/shared.types.ts ================ export interface APISuccessResponse<TData> { code: '200000'; data: TData; } ⋮---- export interface APIErrorResponse { msg: string; code: string; } ⋮---- export type APIResponse<TData> = APISuccessResponse<TData> | APIErrorResponse; ⋮---- export interface ServiceStatus { msg: string; status: 'cancelonly' | 'close' | 'open'; } ================ File: src/types/response/spot-misc.ts ================ export interface Announcement { annId: number; annTitle: string; annType: string[]; annDesc: string; cTime: number; language: string; annUrl: string; } ⋮---- export interface Announcements { totalNum: number; currentPage: number; pageSize: number; totalPage: number; items: Announcement[]; } ================ File: src/types/response/spot-vip.ts ================ /** * *********** * VIP LENDING *********** * */ ⋮---- export interface DiscountRateConfig { currency: string; usdtLevels: { left: number; right: number; discountRate: string; }[]; } ⋮---- export interface OtcLoan { parentUid: string; orders: { orderId: string; currency: string; principal: string; interest: string; }[]; ltv: { transferLtv: string; onlyClosePosLtv: string; delayedLiquidationLtv: string; instantLiquidationLtv: string; currentLtv: string; }; totalMarginAmount: string; transferMarginAmount: string; margins: { marginCcy: string; marginQty: string; marginFactor: string; }[]; } ⋮---- export interface OtcLoanAccount { uid: string; marginCcy: string; marginQty: string; marginFactor: string; accountType: 'TRADE' | 'TRADE_HF' | 'CONTRACT'; isParent: boolean; } ================ File: src/types/response/ws.ts ================ export interface WsServerInfo { endpoint: string; encrypt: boolean; protocol: string; pingInterval: number; pingTimeout: number; } ⋮---- export interface WsConnectionInfo { token: string; instanceServers: WsServerInfo[]; } ================ File: src/BrokerClient.ts ================ import { BaseRestClient } from './lib/BaseRestClient.js'; import { REST_CLIENT_TYPE_ENUM, RestClientType } from './lib/requestUtils.js'; import { BrokerTransferRequest, CreateBrokerSubAccountApiRequest, DeleteBrokerSubAccountApiRequest, GetBrokerDepositListRequest, GetBrokerInfoRequest, GetBrokerSubAccountApisRequest, GetBrokerSubAccountsRequest, UpdateBrokerSubAccountApiRequest, } from './types/request/broker.types.js'; import { BrokerDepositRecord, BrokerInfo, BrokerSubAccountApi, BrokerTransferHistory, BrokerWithdrawalRecord, CreateBrokerSubAccountApiResponse, CreateBrokerSubAccountResponse, GetBrokerSubAccountsResponse, } from './types/response/broker.types.js'; import { APISuccessResponse } from './types/response/shared.types.js'; ⋮---- /** * */ export class BrokerClient extends BaseRestClient ⋮---- getClientType(): RestClientType ⋮---- /** * Get Broker Info * * This endpoint supports querying the basic information of the current Broker */ getBrokerInfo( params: GetBrokerInfoRequest, ): Promise<APISuccessResponse<BrokerInfo>> ⋮---- /** * 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<APISuccessResponse<CreateBrokerSubAccountResponse>> ⋮---- /** * 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<APISuccessResponse<GetBrokerSubAccountsResponse>> ⋮---- /** * 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. * L