kucoin-api
Version:
Complete & robust Node.js SDK for Kucoin's REST APIs and WebSockets, with TypeScript & strong end to end tests.
1,769 lines (1,499 loc) • 314 kB
Plain Text
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
<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-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<TSuccess = any, TError = any> {
resolve?: (value: TSuccess) => TSuccess;
reject?: (value: TError) => TError;
promise?: Promise<TSuccess>;
}
⋮----
export interface WSConnectedResult {
wsKey: string;
}
⋮----
export interface WsStoredState<TWSTopicSubscribeEvent extends string | object> {
/** 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<typeof setTimeout> | undefined;
/** A timer tracking that an upstream heartbeat was sent, expecting a reply before it expires */
activePongTimer?: ReturnType<typeof setTimeout> | undefined;
/** If a reconnection is in progress, this will have the timer for the delayed reconnect */
activeReconnectTimer?: ReturnType<typeof setTimeout> | 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<string, DeferredPromise>;
/**
* 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<TWSTopicSubscribeEvent>;
/** 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<string>
⋮----
/**
* Sign a message, with a secret, using the Web Crypto API
*/
export async function signMessage(
message: string,
secret: string,
method: SignEncodeMethod,
algorithm: SignAlgorithm,
): Promise<string>
⋮----
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;