gateio-api
Version:
Complete & Robust Node.js SDK for Gate.com's REST APIs, WebSockets & WebSocket APIs, with TypeScript declarations.
1,380 lines • 116 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.RestClient = void 0;
const BaseRestClient_js_1 = require("./lib/BaseRestClient.js");
/**
* Unified REST API client for all of Gate's REST APIs
*/
class RestClient extends BaseRestClient_js_1.BaseRestClient {
constructor(restClientOptions = {}, requestOptions = {}) {
super(restClientOptions, requestOptions);
return this;
}
/**
*
* Custom SDK functions
*
*/
/**
* This method is used to get the latency and time sync between the client and the server.
* This is not official API endpoint and is only used for internal testing purposes.
* Use this method to check the latency and time sync between the client and the server.
* Final values might vary slightly, but it should be within few ms difference.
* If you have any suggestions or improvements to this measurement, please create an issue or pull request on GitHub.
*/
async fetchLatencySummary() {
const clientTimeReqStart = Date.now();
const serverTime = await this.getServerTime();
const clientTimeReqEnd = Date.now();
console.log('serverTime', serverTime);
const serverTimeMs = serverTime.server_time;
const roundTripTime = clientTimeReqEnd - clientTimeReqStart;
const estimatedOneWayLatency = Math.floor(roundTripTime / 2);
// Adjust server time by adding estimated one-way latency
const adjustedServerTime = serverTimeMs + estimatedOneWayLatency;
// Calculate time difference between adjusted server time and local time
const timeDifference = adjustedServerTime - clientTimeReqEnd;
const result = {
localTime: clientTimeReqEnd,
serverTime: serverTimeMs,
roundTripTime,
estimatedOneWayLatency,
adjustedServerTime,
timeDifference,
};
console.log('Time synchronization results:');
console.log(result);
console.log(`Your approximate latency to exchange server:
One way: ${estimatedOneWayLatency}ms.
Round trip: ${roundTripTime}ms.
`);
if (timeDifference > 500) {
console.warn(`WARNING! Time difference between server and client clock is greater than 500ms. It is currently ${timeDifference}ms.
Consider adjusting your system clock to avoid unwanted clock sync errors!
Visit https://github.com/tiagosiebler/awesome-crypto-examples/wiki/Timestamp-for-this-request-is-outside-of-the-recvWindow for more information`);
}
else {
console.log(`Time difference between server and client clock is within acceptable range of 500ms. It is currently ${timeDifference}ms.`);
}
return result;
}
/**
*
* Gate.io misc endpoints
*
*/
getClientType() {
return BaseRestClient_js_1.REST_CLIENT_TYPE_ENUM.main;
}
getSystemMaintenanceStatus() {
return this.get('/v1/public/system_info');
}
/**================================================================================================================================
* WITHDRAW
* ==========================================================================================================================
*/
/**
* Withdraw
*
* Withdrawals to Gate addresses do not incur transaction fees.
*
* @param params Withdrawal parameters
* @returns Promise<Withdraw>
*/
submitWithdrawal(params) {
return this.postPrivate('/withdrawals', { body: params });
}
/**
* Transfer between spot main accounts
*
* Both parties cannot be sub-accounts.
*
* @param params Transfer parameters
* @returns Promise<{
* id: number;
* }>
*/
submitSpotMainAccountTransfer(params) {
return this.postPrivate('/withdrawals/push', { body: params });
}
/**
* Cancel withdrawal with specified ID
*
* @param params Parameters containing the withdrawal ID
* @returns Promise<Withdraw>
*/
cancelWithdrawal(params) {
return this.deletePrivate(`/withdrawals/${params.withdrawal_id}`);
}
/**==========================================================================================================================
* WALLET
* ==========================================================================================================================
*/
/**
* List chains supported for specified currency
*
* @param params Parameters containing the currency name
* @returns Promise< GetCurrencyChainsResp[][]>
*/
getCurrencyChains(params) {
return this.get('/wallet/currency_chains', params);
}
/**
* Generate currency deposit address
*
* @param params Parameters containing the currency name
* @returns Promise<CreateDepositAddressResp>
*/
createDepositAddress(params) {
return this.getPrivate('/wallet/deposit_address', params);
}
/**
* Retrieve withdrawal records
*
* Record time range cannot exceed 30 days
*
* @param params Parameters for filtering withdrawal records
* @returns Promise<Withdraw[]>
*/
getWithdrawalRecords(params) {
return this.getPrivate('/wallet/withdrawals', params);
}
/**
* Retrieve deposit records
*
* Record time range cannot exceed 30 days
*
* @param params Parameters for filtering deposit records
* @returns Promise<Withdraw[]>
*/
getDepositRecords(params) {
return this.getPrivate('/wallet/deposits', params);
}
/**
* Transfer between trading accounts
*
* Transfer between different accounts. Currently support transfers between the following:
* - spot - margin
* - spot - futures(perpetual)
* - spot - delivery
* - spot - cross margin
* - spot - options
*
* @param params Transfer parameters
* @returns Promise<TransferResponse>
*/
submitTransfer(params) {
return this.postPrivate('/wallet/transfers', { body: params });
}
/**
* Transfer between main and sub accounts
*
* Support transferring with sub user's spot or futures account. Note that only main user's spot account is used no matter which sub user's account is operated.
*
* @param params Transfer parameters
* @returns Promise<any>
*/
submitMainSubTransfer(params) {
return this.postPrivate('/wallet/sub_account_transfers', { body: params });
}
/**
* Retrieve transfer records between main and sub accounts
*
* Record time range cannot exceed 30 days
*
* Note: only records after 2020-04-10 can be retrieved
*
* @param params Parameters for filtering transfer records
* @returns Promise<SubAccountTransferRecordResp[]>
*/
getMainSubTransfers(params) {
return this.getPrivate('/wallet/sub_account_transfers', params);
}
/**
* Sub-account transfers to sub-account
*
* It is possible to perform balance transfers between two sub-accounts under the same main account. You can use either the API Key of the main account or the API Key of the sub-account to initiate the transfer.
*
* @param params Transfer parameters
* @returns Promise<any>
*/
submitSubToSubTransfer(params) {
return this.postPrivate('/wallet/sub_account_to_sub_account', {
body: params,
});
}
/**
* Query transfer status based on client_order_id or tx_id
*
* @param params Parameters for querying transfer status
* @returns Promise<{
* tx_id: string;
* status: 'PENDING' | 'SUCCESS' | 'FAIL' | 'PARTIAL_SUCCESS';
* }>
*/
getTransferStatus(params) {
return this.getPrivate('/wallet/order_status', params);
}
/**
* Retrieve withdrawal status
*
* @param params Parameters for retrieving withdrawal status
* @returns Promise<GetWithdrawalStatusResp[]>
*/
getWithdrawalStatus(params) {
return this.getPrivate('/wallet/withdraw_status', params);
}
/**
* Retrieve sub account balances
*
* @param params Parameters for retrieving sub account balances
* @returns Promise<{
uid: string;
available: { [key: string]: string };
}[]>
*/
getSubBalance(params) {
return this.getPrivate('/wallet/sub_account_balances', params);
}
/**
* Query sub accounts' margin balances
*
* @param params Parameters for querying sub accounts' margin balances
* @returns Promise<SubAccountMarginBalancesResp[]>
*/
getSubMarginBalances(params) {
return this.getPrivate('/wallet/sub_account_margin_balances', params);
}
/**
* Query sub accounts' futures account balances
*
* @param params Parameters for querying sub accounts' futures account balances
* @returns Promise<SubAccountFuturesBalancesResp[]>
*/
getSubFuturesBalances(params) {
return this.getPrivate('/wallet/sub_account_futures_balances', params);
}
/**
* Query subaccount's cross_margin account info
*
* @param params Parameters for querying subaccount's cross_margin account info
* @returns Promise<SubAccountCrossMarginBalancesResp[]>
*/
getSubCrossMarginBalances(params) {
return this.getPrivate('/wallet/sub_account_cross_margin_balances', params);
}
/**
* Query saved addresses
*
* @param params Parameters for querying saved address
* @returns Promise<GetSavedAddressResp[]>
*/
getSavedAddresses(params) {
return this.getPrivate('/wallet/saved_address', params);
}
/**
* Retrieve personal trading fee
*
* @param params Parameters for retrieving personal trading fee
* @returns Promise<GetTradingFeesResp>
*/
getTradingFees(params) {
return this.getPrivate('/wallet/fee', params);
}
/**
* Retrieve user's total balances
*
* This endpoint returns an approximate sum of exchanged amount from all currencies to input currency for each account.
* The exchange rate and account balance could have been cached for at most 1 minute. It is not recommended to use its result for any trading calculation.
*
* For trading calculation, use the corresponding account query endpoint for each account type. For example:
* - GET /spot/accounts to query spot account balance
* - GET /margin/accounts to query margin account balance
* - GET /futures/{settle}/accounts to query futures account balance
*
* @param params Parameters for retrieving total balances
* @returns Promise<GetBalancesResp>
*/
getBalances(params) {
return this.getPrivate('/wallet/total_balance', params);
}
/**
* List small balance
*
* @returns Promise<GetSmallBalancesResp>
*/
getSmallBalances() {
return this.getPrivate('/wallet/small_balance');
}
/**
* Convert small balance
*
* @param params Parameters for converting small balance
* @returns Promise<any>
*/
convertSmallBalance(params) {
return this.postPrivate('/wallet/small_balance', { body: params });
}
/**
* List small balance history
*
* @param params Parameters for listing small balance history
* @returns Promise<GetSmallBalanceHistoryResp[]>
*/
getSmallBalanceHistory(params) {
return this.getPrivate('/wallet/small_balance_history', params);
}
/**
* List push orders
*
* @param params Parameters for listing push orders
* @returns Promise<PushOrder[]>
*/
getPushOrders(params) {
return this.getPrivate('/wallet/push', params);
}
/**==========================================================================================================================
* SUBACCOUNT
* ==========================================================================================================================
*/
/**
* Create a new sub-account
*
* @param params Parameters for creating a new sub-account
* @returns Promise<CreateSubAccountResp>
*/
createSubAccount(params) {
return this.postPrivate('/sub_accounts', { body: params });
}
/**
* List sub-accounts
*
* @param params Parameters for listing sub-accounts
* @returns Promise<GetSubAccountsResp[]>
*/
getSubAccounts(params) {
return this.getPrivate('/sub_accounts', params);
}
/**
* Get the sub-account
*
* @param params Parameters containing the sub-account user ID
* @returns Promise<SubAccountResp>
*/
getSubAccount(params) {
return this.getPrivate(`/sub_accounts/${params.user_id}`);
}
/**
* Create API Key of the sub-account
*
* @param params Parameters for creating API Key of the sub-account
* @returns Promise<CreateSubAccountApiKeyResp>
*/
createSubAccountApiKey(params) {
const { user_id, ...body } = params;
return this.postPrivate(`/sub_accounts/${user_id}/keys`, { body: body });
}
/**
* List all API Key of the sub-account
*
* @param params Parameters containing the sub-account user ID
* @returns Promise<SubAccountKey[]>
*/
getSubAccountApiKeys(params) {
return this.getPrivate(`/sub_accounts/${params.user_id}/keys`);
}
/**
* Update API key of the sub-account
*
* @param params Parameters for updating API key of the sub-account
* @returns Promise<any>
*/
updateSubAccountApiKey(params) {
const { user_id, key, ...body } = params;
return this.putPrivate(`/sub_accounts/${user_id}/keys/${key}`, { body });
}
/**
* Delete API key of the sub-account
*
* @param params Parameters for deleting API key of the sub-account
* @returns Promise<any>
*/
deleteSubAccountApiKey(params) {
return this.deletePrivate(`/sub_accounts/${params.user_id}/keys/${params.key}`);
}
/**
* Get the API Key of the sub-account
*
* @param params Parameters containing the sub-account user ID and API key
* @returns Promise<SubAccountKey>
*/
getSubAccountApiKey(params) {
return this.getPrivate(`/sub_accounts/${params.user_id}/keys/${params.key}`);
}
/**
* Lock the sub-account
*
* @param params Parameters containing the sub-account user ID
* @returns Promise<any>
*/
lockSubAccount(params) {
return this.postPrivate(`/sub_accounts/${params.user_id}/lock`);
}
/**
* Unlock the sub-account
*
* @param params Parameters containing the sub-account user ID
* @returns Promise<any>
*/
unlockSubAccount(params) {
return this.postPrivate(`/sub_accounts/${params.user_id}/unlock`);
}
/**
* Get sub-account mode
*
* Unified account mode:
* - classic: Classic account mode
* - multi_currency: Multi-currency margin mode
* - portfolio: Portfolio margin mode
*
* @returns Promise<SubAccountMode>
*/
getSubAccountMode() {
return this.getPrivate('/sub_accounts/unified_mode');
}
/**==========================================================================================================================
* UNIFIED
* ==========================================================================================================================
*/
/**
* Get unified account information
*
* The assets of each currency in the account will be adjusted according to their liquidity, defined by corresponding adjustment coefficients, and then uniformly converted to USD to calculate the total asset value and position value of the account.
*
* @param params Parameters for retrieving unified account information
* @returns Promise<GetUnifiedAccountInfoResp>
*/
getUnifiedAccountInfo(params) {
return this.getPrivate('/unified/accounts', params);
}
/**
* Query about the maximum borrowing for the unified account
*
* @param params Parameters for querying the maximum borrowing for the unified account
* @returns Promise<{
* currency: string;
* amount: string;
* }>
*/
getUnifiedMaxBorrow(params) {
return this.getPrivate('/unified/borrowable', params);
}
/**
* Query about the maximum transferable for the unified account
*
* @param params Parameters for querying the maximum transferable for the unified account
* @returns Promise<{
* currency: string;
* amount: string;
* }>
*/
getUnifiedMaxTransferable(params) {
return this.getPrivate('/unified/transferable', params);
}
/**
* Batch query maximum transferable amounts for unified accounts
*
* After withdrawing currency, the transferable amount will change.
*
* @param params Parameters containing currencies to query (up to 100 at once)
* @returns Promise with array of currency and maximum transferable amount
*/
getUnifiedMaxTransferables(params) {
return this.getPrivate('/unified/transferables', params);
}
getUnifiedBatchMaxBorrowable(params) {
return this.getPrivate('/unified/batch_borrowable', {
currencies: params.currencies.join(','),
});
}
/**
* Borrow or repay
*
* When borrowing, it is essential to ensure that the borrowed amount is not below the minimum borrowing threshold for the specific cryptocurrency and does not exceed the maximum borrowing limit set by the platform and the user.
*
* The interest on the loan will be automatically deducted from the account at regular intervals. It is the user's responsibility to manage the repayment of the borrowed amount.
*
* For repayment, the option to repay the entire borrowed amount is available by setting the parameter repaid_all=true
*
* @param params Parameters for borrowing or repaying
* @returns Promise<any>
*/
submitUnifiedBorrowOrRepay(params) {
return this.postPrivate('/unified/loans', { body: params });
}
/**
* List loans
*
* @param params Parameters for listing loans
* @returns Promise<GetUnifiedLoansResp[]>
*/
getUnifiedLoans(params) {
return this.getPrivate('/unified/loans', params);
}
/**
* Get loan records
*
* @param params Parameters for getting loan records
* @returns Promise<GetUnifiedLoanRecordsResp[]>
*/
getUnifiedLoanRecords(params) {
return this.getPrivate('/unified/loan_records', params);
}
/**
* List interest records
*
* @param params Parameters for listing interest records
* @returns Promise<GetUnifiedInterestRecordsResp[]>
*/
getUnifiedInterestRecords(params) {
return this.getPrivate('/unified/interest_records', params);
}
/**
* Retrieve user risk unit details, only valid in portfolio margin mode
*
* @returns Promise<GetUnifiedRiskUnitDetailsResp>
*/
getUnifiedRiskUnitDetails() {
return this.getPrivate('/unified/risk_units');
}
/**
* Set mode of the unified account
*
* Switching between different account modes requires only passing the parameters corresponding to the target account mode. It also supports opening or closing configuration switches for the corresponding account mode when switching.
*
* @param params Parameters for setting the mode of the unified account
* @returns Promise<any>
*/
setUnifiedAccountMode(params) {
return this.putPrivate('/unified/unified_mode', { body: params });
}
/**
* Query mode of the unified account
*
* @returns Promise<SetUnifiedAccountModeReq>
*/
getUnifiedAccountMode() {
return this.getPrivate('/unified/unified_mode');
}
/**
* Get unified estimate rate
*
* Due to fluctuations in lending depth, hourly interest rates may vary, and thus, I cannot provide exact rates. When a currency is not supported, the interest rate returned will be an empty string.
*
* @param params Parameters for querying estimate rates
* @returns Promise<{ [key: string]: string }>
*/
getUnifiedEstimateRate(params) {
return this.getPrivate('/unified/estimate_rate', params);
}
/**
* List currency discount tiers
*
* @returns Promise<GetUnifiedCurrencyDiscountTiersResp[]>
*/
getUnifiedCurrencyDiscountTiers() {
return this.get('/unified/currency_discount_tiers');
}
/**
* List loan margin tiers
*
* @returns Promise<{
* currency: string;
* margin_tiers: MarginTier[];
* }[]>
*/
getLoanMarginTiers() {
return this.get('/unified/loan_margin_tiers');
}
/**
* Portfolio margin calculator
*
* Portfolio Margin Calculator When inputting a simulated position portfolio, each position includes the position name and quantity held, supporting markets within the range of BTC and ETH perpetual contracts, options, and spot markets. When inputting simulated orders, each order includes the market identifier, order price, and order quantity, supporting markets within the range of BTC and ETH perpetual contracts, options, and spot markets. Market orders are not included.
*
* @param params Parameters for portfolio margin calculator
* @returns Promise<PortfolioMarginCalculatorResp>
*/
portfolioMarginCalculate(params) {
return this.post('/unified/portfolio_calculator', { body: params });
}
/**
* Query user currency leverage configuration
*
* Get the maximum and minimum leverage multiples that users can set for a currency type
*
* @param params Parameters containing the currency
* @returns Promise<UserCurrencyLeverageConfig>
*/
getUserCurrencyLeverageConfig(params) {
return this.getPrivate('/unified/leverage/user_currency_config', params);
}
/**
* Get the user's currency leverage
*
* If currency is not passed, query all currencies.
*
* @param params Optional parameters containing the currency
* @returns Promise<UserCurrencyLeverageSetting[]>
*/
getUserCurrencyLeverageSettings(params) {
return this.getPrivate('/unified/leverage/user_currency_setting', params);
}
/**
* Set the currency leverage ratio
*
* @param params Parameters for setting currency leverage ratio
* @returns Promise<any> Returns nothing on success (204 No Content)
*/
updateUserCurrencyLeverage(params) {
return this.postPrivate('/unified/leverage/user_currency_setting', {
body: params,
});
}
/**
* List loan currencies supported by unified account
*
* @param params Optional parameters for filtering
* @returns Promise with array of loan currencies
*/
getUnifiedLoanCurrencies(params) {
return this.getPrivate('/unified/currencies', params);
}
/**
* Get historical lending rates
*
* @param params Parameters for retrieving historical lending rates
* @returns Promise<UnifiedHistoryLendingRate>
*/
getHistoricalLendingRates(params) {
return this.getPrivate('/unified/history_loan_rate', params);
}
submitUnifiedLoanRepay(params) {
return this.postPrivate('/unified/loans/repay', { body: params });
}
/**==========================================================================================================================
* SPOT
* ==========================================================================================================================
*/
/**
* List all currencies' details
*
* Currency has two forms:
* - Only currency name, e.g., BTC, USDT
* - <currency>_<chain>, e.g., HT_ETH
*
* The latter one occurs when one currency has multiple chains. Currency detail contains a chain field whatever the form is. To retrieve all chains of one currency, you can use all the details which have the name of the currency or name starting with <currency>_.
*
* @returns Promise<GetSpotCurrenciesResp[]>
*/
getSpotCurrencies() {
return this.get('/spot/currencies');
}
/**
* Get details of a specific currency
*
* @param params Parameters for retrieving details of a specific currency
* @returns Promise<GetSpotCurrenciesResp>
*/
getSpotCurrency(params) {
return this.get(`/spot/currencies/${params.currency}`);
}
/**
* List all currency pairs supported
*
* @returns Promise<CurrencyPair[]>
*/
getSpotCurrencyPairs() {
return this.get('/spot/currency_pairs');
}
/**
* Get details of a specific currency pair
*
* @param params Parameters for retrieving details of a specific currency pair
* @returns Promise<CurrencyPair>
*/
getSpotCurrencyPair(params) {
return this.get(`/spot/currency_pairs/${params.currency_pair}`);
}
/**
* Retrieve ticker information
*
* Return only related data if currency_pair is specified; otherwise return all of them.
*
* @param params Parameters for retrieving ticker information
* @returns Promise<GetSpotTickerResp[]>
*/
getSpotTicker(params) {
return this.get('/spot/tickers', params);
}
/**
* Retrieve order book
*
* Order book will be sorted by price from high to low on bids; low to high on asks.
*
* @param params Parameters for retrieving order book
* @returns Promise<GetSpotOrderBookResp>
*/
getSpotOrderBook(params) {
return this.get('/spot/order_book', params);
}
/**
* Retrieve market trades
*
* You can use from and to to query by time range, or use last_id by scrolling page. The default behavior is by time range.
* Scrolling query using last_id is not recommended any more. If last_id is specified, time range query parameters will be ignored.
*
* @param params Parameters for retrieving market trades
* @returns Promise<GetSpotTradesResp[]>
*/
getSpotTrades(params) {
return this.get('/spot/trades', params);
}
/**
* Market Candles
*
* Maximum of 1000 points can be returned in a query. Be sure not to exceed the limit when specifying from, to and interval.
*
* @param params Parameters for retrieving market Candles
* @returns Promise<GetSpotCandlesResp>
*/
getSpotCandles(params) {
return this.get('/spot/candlesticks', params);
}
/**
* Query user trading fee rates
*
* This API is deprecated in favour of new fee retrieving API /wallet/fee.
*
* @param params Parameters for querying user trading fee rates
* @returns Promise<GetSpotFeeRatesResp>
*/
getSpotFeeRates(params) {
return this.getPrivate('/spot/fee', params);
}
/**
* Query a batch of user trading fee rates
*
* @param params Parameters for querying a batch of user trading fee rates
*/
getSpotBatchFeeRates(params) {
return this.getPrivate('/spot/batch_fee', params);
}
/**
* List spot accounts
*
* @param params Parameters for listing spot accounts
* @returns Promise<GetSpotAccountsResp[]>
*/
getSpotAccounts(params) {
return this.getPrivate('/spot/accounts', params);
}
/**
* Query account book
*
* Record time range cannot exceed 30 days.
*
* @param params Parameters for querying account book
* @returns Promise<GetSpotAccountBookResp[]>
*/
getSpotAccountBook(params) {
return this.getPrivate('/spot/account_book', params);
}
/**
* Create a batch of orders
*
* Batch orders requirements:
* - custom order field text is required
* - At most 4 currency pairs, maximum 10 orders each, are allowed in one request
* - No mixture of spot orders and margin orders, i.e. account must be identical for all orders
*
* NOTE: The "xGateExptime" parameter will translate to the "x-gate-exptime" header.
*
* @param params Parameters for creating a batch of orders
* @returns Promise<SubmitSpotBatchOrdersResp[]>
*/
submitSpotBatchOrders(body, params) {
const { xGateExptime } = params || {};
const headers = xGateExptime
? { 'x-gate-exptime': xGateExptime }
: undefined;
return this.postPrivate('/spot/batch_orders', {
headers: headers,
body: body,
});
}
/**
* List all open orders
*
* List open orders in all currency pairs.
* Note that pagination parameters affect record number in each currency pair's open order list. No pagination is applied to the number of currency pairs returned. All currency pairs with open orders will be returned.
* Spot, portfolio, and margin orders are returned by default. To list cross margin orders, account must be set to cross_margin.
*
* @param params Parameters for listing all open orders
* @returns Promise<GetSpotOpenOrdersResp[]>
*/
getSpotOpenOrders(params) {
return this.getPrivate('/spot/open_orders', params);
}
/**
* Close position when cross-currency is disabled
*
* Currently, only cross-margin accounts are supported to close position when cross currencies are disabled. Maximum buy quantity = (unpaid principal and interest - currency balance - the amount of the currency in the order book) / 0.998
*
* @param params Parameters for closing position when cross-currency is disabled
* @returns Promise<Order>
*/
submitSpotClosePosCrossDisabled(params) {
return this.postPrivate('/spot/cross_liquidate_orders', { body: params });
}
/**
* Create an order
*
* You can place orders with spot, portfolio, margin or cross margin account through setting the account field. It defaults to spot, which means spot account is used to place orders. If the user is using unified account, it defaults to the unified account.
*
* NOTE: The "xGateExptime" parameter will translate to the "x-gate-exptime" header.
*
* @param params Parameters for creating an order
* @returns Promise<Order>
*/
submitSpotOrder(params) {
const { xGateExptime, ...body } = params;
const headers = xGateExptime
? { 'x-gate-exptime': xGateExptime }
: undefined;
return this.postPrivate('/spot/orders', { headers: headers, body: body });
}
/**
* List orders
*
* Spot, portfolio and margin orders are returned by default. If cross margin orders are needed, account must be set to cross_margin.
*
* @param params Parameters for listing orders
* @returns Promise<Order[]>
*/
getSpotOrders(params) {
return this.getPrivate('/spot/orders', params);
}
/**
* Cancel all open orders in specified currency pair
*
* If account is not set, all open orders, including spot, portfolio, margin and cross margin ones, will be cancelled.
* You can set account to cancel only orders within the specified account.
*
* NOTE: The "xGateExptime" parameter will translate to the "x-gate-exptime" header.
*
* @param params Parameters for cancelling all open orders in specified currency pair
* @returns Promise<Order[]>
*/
cancelSpotOpenOrders(params) {
const { xGateExptime, ...query } = params;
const headers = xGateExptime
? { 'x-gate-exptime': xGateExptime }
: undefined;
return this.deletePrivate('/spot/orders', {
headers: headers,
query: query,
});
}
/**
* Cancel a batch of orders with an ID list
*
* Multiple currency pairs can be specified, but maximum 20 orders are allowed per request.
*
* NOTE: The "xGateExptime" parameter will translate to the "x-gate-exptime" header.
*
* @param params Parameters for cancelling a batch of orders
* @returns Promise<DeleteSpotBatchOrdersResp[]>
*/
batchCancelSpotOrders(body, params) {
const { xGateExptime } = params || {};
const headers = xGateExptime
? { 'x-gate-exptime': xGateExptime }
: undefined;
return this.postPrivate('/spot/cancel_batch_orders', {
headers: headers,
body: body,
});
}
/**
* Get a single order
*
* Spot, portfolio and margin orders are queried by default. If cross margin orders are needed or portfolio margin account are used, account must be set to cross_margin.
*
* @param params Parameters for getting a single order
* @returns Promise<Order>
*/
getSpotOrder(params) {
const { order_id, ...query } = params;
return this.getPrivate(`/spot/orders/${order_id}`, query);
}
/**
* Amend an order
*
* By default, the orders of spot, portfolio and margin account are updated. If you need to modify orders of the cross-margin account, you must specify account as cross_margin. For portfolio margin account, only cross_margin account is supported.
*
* Currently, only supports modification of price or amount fields.
*
* NOTE: The "xGateExptime" parameter will translate to the "x-gate-exptime" header.
*
* @param params Parameters for amending an order
* @returns Promise<Order>
*/
updateSpotOrder(params) {
const { xGateExptime, order_id, currency_pair, account, ...body } = params;
const headers = xGateExptime
? { 'x-gate-exptime': xGateExptime }
: undefined;
const query = {
currency_pair: currency_pair,
account: account,
};
return this.patchPrivate(`/spot/orders/${order_id}`, {
headers: headers,
query: query,
body: body,
});
}
/**
* Cancel a single order
*
* Spot, portfolio and margin orders are cancelled by default. If trying to cancel cross margin orders or portfolio margin account are used, account must be set to cross_margin.
*
* NOTE: The "xGateExptime" parameter will translate to the "x-gate-exptime" header.
*
* @param params Parameters for cancelling a single order
* @returns Promise<Order>
*/
cancelSpotOrder(params) {
const { xGateExptime, order_id, ...query } = params;
const headers = xGateExptime
? { 'x-gate-exptime': xGateExptime }
: undefined;
return this.deletePrivate(`/spot/orders/${order_id}`, {
headers: headers,
query: query,
});
}
/**
* List personal trading history
*
* Spot, portfolio and margin trades are queried by default. If cross margin trades are needed, account must be set to cross_margin.
*
* You can also set from and/or to to query by time range. If you don't specify from and/or to parameters, only the last 7 days of data will be returned. The range of from and to is not allowed to exceed 30 days. Time range parameters are handled as order finish time.
*
* @param params Parameters for listing personal trading history
* @returns Promise<GetSpotTradingHistoryResp[]>
*/
getSpotTradingHistory(params) {
return this.getPrivate('/spot/my_trades', params);
}
/**
* Get server current time
*
* @returns Promise<{
* server_time: number;
* }>
*/
getServerTime() {
return this.get('/spot/time');
}
/**
* Countdown cancel orders
*
* When the timeout set by the user is reached, if there is no cancel or set a new countdown, the related pending orders will be automatically cancelled. This endpoint can be called repeatedly to set a new countdown or cancel the countdown.
*
* @param params Parameters for setting countdown cancel orders
* @returns Promise<{
* triggerTime: number;
* }>
*/
submitSpotCountdownOrders(params) {
return this.postPrivate('/spot/countdown_cancel_all', { body: params });
}
/**
* Batch modification of orders
*
* Default modification of orders for spot, portfolio, and margin accounts. To modify orders for a cross margin account, the account parameter must be specified as cross_margin. For portfolio margin accounts, the account parameter can only be specified as cross_margin. Currently, only modifications to price or quantity (choose one) are supported.
*
* NOTE: The "xGateExptime" parameter will translate to the "x-gate-exptime" header.
*
* @param params Parameters for batch modification of orders
* @returns Promise<Order[]>
*/
batchUpdateSpotOrders(body, params) {
const { xGateExptime } = params || {};
const headers = xGateExptime
? { 'x-gate-exptime': xGateExptime }
: undefined;
return this.postPrivate('/spot/amend_batch_orders', {
headers: headers,
body: body,
});
}
/**
* Query spot insurance fund historical data
*
* @param params Parameters for querying spot insurance fund history
* @returns Promise<{
* currency: string;
* balance: string;
* time: number;
* }[]>
*/
getSpotInsuranceHistory(params) {
return this.getPrivate('/spot/insurance_history', params);
}
/**
* Create a price-triggered order
*
* @param params Parameters for creating a price-triggered order
* @returns Promise<{
* id: number;
* }>
*/
submitSpotPriceTriggerOrder(params) {
return this.postPrivate('/spot/price_orders', { body: params });
}
/**
* Retrieve running auto order list
*
* @param params Parameters for retrieving running auto order list
* @returns Promise<SpotPriceTriggeredOrder[]>
*/
getSpotAutoOrders(params) {
return this.getPrivate('/spot/price_orders', params);
}
/**
* Cancel all open orders
*
* @param params Parameters for cancelling all open orders
* @returns Promise<SpotPriceTriggeredOrder[]>
*/
cancelAllOpenSpotOrders(params) {
return this.deletePrivate('/spot/price_orders', { query: params });
}
/**
* Get a price-triggered order
*
* @param params Parameters for getting a price-triggered order
* @returns Promise<SpotPriceTriggeredOrder>
*/
getPriceTriggeredOrder(params) {
return this.getPrivate(`/spot/price_orders/${params.order_id}`);
}
/**
* Cancel a price-triggered order
*
* @param params Parameters for cancelling a price-triggered order
* @returns Promise<SpotPriceTriggeredOrder>
*/
cancelSpotTriggeredOrder(params) {
return this.deletePrivate(`/spot/price_orders/${params.order_id}`);
}
/**
* Set collateral currency
*
* @param params Parameters for setting collateral currency
* @returns Promise<{
* is_success: boolean;
* }>
*/
setCollateralCurrency(params) {
return this.postPrivate('/unified/collateral_currencies', { body: params });
}
/**==========================================================================================================================
* MARGIN
* ==========================================================================================================================
*/
/**
* Margin account list
*
* @param params Parameters for listing margin accounts
* @returns Promise<GetMarginAccountsResp[]>
*/
getMarginAccounts(params) {
return this.getPrivate('/margin/accounts', params);
}
/**
* List margin account balance change history
*
* Only transferals from and to margin account are provided for now. Time range allows 30 days at most.
*
* @param params Parameters for listing margin account balance change history
* @returns Promise<GetMarginBalanceHistoryResp[]>
*/
getMarginBalanceHistory(params) {
return this.getPrivate('/margin/account_book', params);
}
/**
* Funding account list
*
* @param params Parameters for listing funding accounts
* @returns Promise<{
* currency: string;
* available: string;
* locked: string;
* lent: string;
* total_lent: string;
* }[]>
*/
getFundingAccounts(params) {
return this.getPrivate('/margin/funding_accounts', params);
}
/**
* Update user's auto repayment setting
*
* @param params Parameters for updating auto repayment setting
* @returns Promise<{ status: 'on' | 'off' }>
*/
updateAutoRepaymentSetting(params) {
return this.postPrivate('/margin/auto_repay', { query: params });
}
/**
* Retrieve user auto repayment setting
*
* @returns Promise<{ status: 'on' | 'off' }>
*/
getAutoRepaymentSetting() {
return this.getPrivate('/margin/auto_repay');
}
/**
* Get the max transferable amount for a specific margin currency
*
* @param params Parameters for retrieving the max transferable amount
* @returns Promise<{
* currency: string;
* currency_pair?: string;
* amount: string;
* }>
*/
getMarginTransferableAmount(params) {
return this.getPrivate('/margin/transferable', params);
}
/**
* @deprecated as of 2025-02-10
* Currencies supported by cross margin
*
* @returns Promise<GetCrossMarginCurrenciesResp[]>
*/
getCrossMarginCurrencies() {
return this.get('/margin/cross/currencies');
}
/**
* @deprecated as of 2025-02-10
* Retrieve detail of one single currency supported by cross margin
*
* @param params Parameters containing the currency name
* @returns Promise<GetCrossMarginCurrenciesResp>
*/
getCrossMarginCurrency(params) {
return this.get(`/margin/cross/currencies/${params.currency}`);
}
/**
* @deprecated as of 2025-02-10
* Retrieve cross margin account
*
* @returns Promise<GetCrossMarginAccountResp>
*/
getCrossMarginAccount() {
return this.getPrivate('/margin/cross/accounts');
}
/**
* @deprecated as of 2025-02-10
* Retrieve cross margin account change history
*
* Record time range cannot exceed 30 days.
*
* @param params Parameters for retrieving cross margin account change history
* @returns Promise<GetCrossMarginAccountHistoryResp[]>
*/
getCrossMarginAccountHistory(params) {
return this.getPrivate('/margin/cross/account_book', params);
}
/**
*
* @deprecated as of 2025-02-10
* Create a cross margin borrow loan
*
* Borrow amount cannot be less than currency minimum borrow amount.
*
* @param params Parameters for creating a cross margin borrow loan
* @returns Promise<SubmitCrossMarginBorrowLoanResp>
*
*/
submitCrossMarginBorrowLoan(params) {
return this.postPrivate('/margin/cross/loans', { body: params });
}
/**
*
* List cross margin borrow history
*
* Sort by creation time in descending order by default. Set reverse=false to return ascending results.
*
* @param params Parameters for listing cross margin borrow history
* @returns Promise<SubmitCrossMarginBorrowLoanResp[]>
*/
getCrossMarginBorrowHistory(params) {
return this.getPrivate('/margin/cross/loans', params);
}
/**
* @deprecated as of 2025-02-10
* Retrieve single borrow loan detail
*
* @param params Parameters containing the borrow loan ID
* @returns Promise<SubmitCrossMarginBorrowLoanResp>
*/
getCrossMarginBorrowLoan(params) {
return this.getPrivate(`/margin/cross/loans/${params.loan_id}`);
}
/**
* @deprecated as of 2025-02-10
* Cross margin repayments
*
* When the liquidity of the currency is insufficient and the transaction risk is high, the currency will be disabled, and funds cannot be transferred. When the available balance of cross-margin is insufficient, the balance of the spot account can be used for repayment. Please ensure that the balance of the spot account is sufficient, and system uses cross-margin account for repayment first.
*
* @param params Parameters for cross margin repayments
* @returns Promise<SubmitCrossMarginBorrowLoanResp[]>
*/
submitCrossMarginRepayment(params) {
return this.postPrivate('/margin/cross/repayments', { body: params });
}
/**
* @deprecated as of 2025-02-10
* Retrieve cross margin repayments
*
* Sort by creation time in descending order by default. Set reverse=false to return ascending results.
*
* @param params Parameters for retrieving cross margin repayments
* @returns Promise<GetCrossMarginRepaymentsResp[]>
*/
getCrossMarginRepayments(params) {
return this.getPrivate('/margin/cross/repayments', params);
}
/**
* @deprecated as of 2025-02-10
* Interest records for the cross margin account
*
* @param params Parameters for retrieving interest records
* @returns Promise<GetCrossMarginInterestRecordsResp[]>
*/
getCrossMarginInterestRecords(params) {
return this.getPrivate('/margin/cross/interest_records', params);
}
/**
* @deprecated as of 2025-02-10
* Get the max transferable amount for a specific cross margin currency
*
* @param params Parameters for retrieving the max transferable amount
* @returns Promise<{
* currency: string;
* amount: string;
* }>
*/
getCrossMarginTransferableAmount(params) {
return this.getPrivate('/margin/cross/transferable', params);
}
/**
* @deprecated as of 2025-02-10
* Estimated interest rates
*
* Please note that the interest rates are subject to change based on the borrowing and lending demand, and therefore, the provided rates may not be entirely accurate.
*
* @param params Parameters for retrieving estimated interest rates
* @returns Promise<any>
*/
getEstimatedInterestRates(params) {
return this.getPrivate('/margin/cross/estimate_rate', params);
}
/**
* @deprecated as of 2025-02-10
* Get the max borrowable amount for a specific cross margin currency
*
* @param params Parameters for retrieving the max borrowable amount
* @returns Promise<{
* currency: string;
* amount: string;
* }>
*/
getCrossMarginBorrowableAmount(params) {
return this.getPrivate('/margin/cross/borrowable', params);
}
/**
* Check the user's own leverage lending gradient in the current market
*
* @param params Parameters containing currency pair to query
* @returns Promise with array of market gradient information
*/
getMarginUserLoanTiers(params) {
return this.getPrivate('/margin/user/loan_margin_tiers', params);
}
/**
* Query the current market leverage lending gradient
*
* @param params Parameters containing currency pair to query
* @returns Promise with array of market gradient information
*/
getMarginPublicLoanTiers(params) {
return this.get('/margin/loan_margin_tiers', params);
}
/**
* Set the user market leverage multiple
*
* @param params Parameters containing currency pair and leverage value
* @returns Promise<void> - Returns nothing on success (204 No Content)
*/
setMarginUserLeverage(params) {
return this.postPrivate('/margin/leverage/user_market_setting', {
body: params,
});
}
/**
* Query the user's leverage account list
*
* Supports querying risk rate per position account and margin rate per position account
*
* @param params Optional parameters for filtering by currency pair
* @returns Promise with array of margin account details
*/
getMarginUserAccounts(params) {
return this.getPrivate('/margin/user/account', params);
}
/**==========================================================================================================================
* MARGIN UNI
* ==========================================================================================================================
*/
/**
* List lending markets
*
* @returns Promise<GetLendingMarketsResp[]>
*/
getLendingMarkets() {
return this.get('/margin/uni/currency_pairs');
}
/**
* Get detail of lending market
*
* @param params Parameters containing the currency pair
* @returns Promise<{
* currency_pair: string;
* base_min_borrow_amount: string;
* quote_min_borrow_amount: string;
* leverage: string;
* }>
*/
getLendingMarket(params) {
return this.get(`/margin/uni/currency_pairs/${params.currency_pair}`);
}
/**
* Estimate interest rate
*
* Please note that the interes