diff --git a/docs/endpointFunctionList.md b/docs/endpointFunctionList.md index efece8f..57378d2 100644 --- a/docs/endpointFunctionList.md +++ b/docs/endpointFunctionList.md @@ -49,454 +49,454 @@ This table includes all endpoints from the official Exchange API docs and corres | Function | AUTH | HTTP Method | Endpoint | | -------- | :------: | :------: | -------- | -| [getSystemMaintenanceStatus()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L711) | | GET | `/v1/public/system_info` | -| [listAnnouncementArticles()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L715) | | POST | `/ann/list_article` | -| [submitWithdrawal()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L734) | :closed_lock_with_key: | POST | `/withdrawals` | -| [submitSpotMainAccountTransfer()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L748) | :closed_lock_with_key: | POST | `/withdrawals/push` | -| [cancelWithdrawal()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L764) | :closed_lock_with_key: | DELETE | `/withdrawals/{withdrawal_id}` | -| [getCurrencyChains()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L781) | | GET | `/wallet/currency_chains` | -| [createDepositAddress()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L791) | :closed_lock_with_key: | GET | `/wallet/deposit_address` | -| [getWithdrawalRecords()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L805) | :closed_lock_with_key: | GET | `/wallet/withdrawals` | -| [getDepositRecords()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L819) | :closed_lock_with_key: | GET | `/wallet/deposits` | -| [submitTransfer()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L838) | :closed_lock_with_key: | POST | `/wallet/transfers` | -| [getTransfer()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L850) | :closed_lock_with_key: | GET | `/wallet/transfers` | -| [submitMainSubTransfer()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L862) | :closed_lock_with_key: | POST | `/wallet/sub_account_transfers` | -| [getMainSubTransfers()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L876) | :closed_lock_with_key: | GET | `/wallet/sub_account_transfers` | -| [submitSubToSubTransfer()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L890) | :closed_lock_with_key: | POST | `/wallet/sub_account_to_sub_account` | -| [getTransferStatus()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L905) | :closed_lock_with_key: | GET | `/wallet/order_status` | -| [getWithdrawalStatus()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L921) | :closed_lock_with_key: | GET | `/wallet/withdraw_status` | -| [getSubBalance()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L933) | :closed_lock_with_key: | GET | `/wallet/sub_account_balances` | -| [getSubMarginBalances()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L945) | :closed_lock_with_key: | GET | `/wallet/sub_account_margin_balances` | -| [getSubFuturesBalances()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L957) | :closed_lock_with_key: | GET | `/wallet/sub_account_futures_balances` | -| [getSubCrossMarginBalances()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L970) | :closed_lock_with_key: | GET | `/wallet/sub_account_cross_margin_balances` | -| [getSavedAddresses()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L982) | :closed_lock_with_key: | GET | `/wallet/saved_address` | -| [getTradingFees()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L992) | :closed_lock_with_key: | GET | `/wallet/fee` | -| [getBalances()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1013) | :closed_lock_with_key: | GET | `/wallet/total_balance` | -| [getSmallBalances()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1022) | :closed_lock_with_key: | GET | `/wallet/small_balance` | -| [convertSmallBalance()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1032) | :closed_lock_with_key: | POST | `/wallet/small_balance` | -| [getSmallBalanceHistory()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1045) | :closed_lock_with_key: | GET | `/wallet/small_balance_history` | -| [getPushOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1057) | :closed_lock_with_key: | GET | `/wallet/push` | -| [getLowCapExchangeList()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1066) | :closed_lock_with_key: | GET | `/wallet/getLowCapExchangeList` | -| [createSubAccount()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1081) | :closed_lock_with_key: | POST | `/sub_accounts` | -| [getSubAccounts()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1092) | :closed_lock_with_key: | GET | `/sub_accounts` | -| [getSubAccount()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1102) | :closed_lock_with_key: | GET | `/sub_accounts/{user_id}` | -| [createSubAccountApiKey()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1112) | :closed_lock_with_key: | POST | `/sub_accounts/{user_id}/keys` | -| [getSubAccountApiKeys()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1125) | :closed_lock_with_key: | GET | `/sub_accounts/{user_id}/keys` | -| [updateSubAccountApiKey()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1139) | :closed_lock_with_key: | PUT | `/sub_accounts/{user_id}/keys/{key}` | -| [deleteSubAccountApiKey()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1150) | :closed_lock_with_key: | DELETE | `/sub_accounts/{user_id}/keys/{key}` | -| [getSubAccountApiKey()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1165) | :closed_lock_with_key: | GET | `/sub_accounts/{user_id}/keys/{key}` | -| [lockSubAccount()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1180) | :closed_lock_with_key: | POST | `/sub_accounts/{user_id}/lock` | -| [unlockSubAccount()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1190) | :closed_lock_with_key: | POST | `/sub_accounts/{user_id}/unlock` | -| [getSubAccountMode()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1204) | :closed_lock_with_key: | GET | `/sub_accounts/unified_mode` | -| [getUnifiedAccountInfo()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1223) | :closed_lock_with_key: | GET | `/unified/accounts` | -| [getUnifiedMaxBorrow()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1239) | :closed_lock_with_key: | GET | `/unified/borrowable` | -| [getUnifiedMaxTransferable()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1255) | :closed_lock_with_key: | GET | `/unified/transferable` | -| [getUnifiedMaxTransferables()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1270) | :closed_lock_with_key: | GET | `/unified/transferables` | -| [getUnifiedBatchMaxBorrowable()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1279) | :closed_lock_with_key: | GET | `/unified/batch_borrowable` | -| [submitUnifiedBorrowOrRepay()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1297) | :closed_lock_with_key: | POST | `/unified/loans` | -| [getUnifiedLoans()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1309) | :closed_lock_with_key: | GET | `/unified/loans` | -| [getUnifiedLoanRecords()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1319) | :closed_lock_with_key: | GET | `/unified/loan_records` | -| [getUnifiedInterestRecords()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1331) | :closed_lock_with_key: | GET | `/unified/interest_records` | -| [getUnifiedRiskUnitDetails()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1342) | :closed_lock_with_key: | GET | `/unified/risk_units` | -| [setUnifiedAccountMode()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1354) | :closed_lock_with_key: | PUT | `/unified/unified_mode` | -| [getUnifiedAccountMode()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1363) | :closed_lock_with_key: | GET | `/unified/unified_mode` | -| [getUnifiedEstimateRate()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1375) | :closed_lock_with_key: | GET | `/unified/estimate_rate` | -| [getUnifiedCurrencyDiscountTiers()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1386) | | GET | `/unified/currency_discount_tiers` | -| [getLoanMarginTiers()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1398) | | GET | `/unified/loan_margin_tiers` | -| [portfolioMarginCalculate()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1415) | | POST | `/unified/portfolio_calculator` | -| [setUserLeverage()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1429) | :closed_lock_with_key: | POST | `/unified/leverage/user_setting` | -| [getUserCurrencyLeverageConfig()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1443) | :closed_lock_with_key: | GET | `/unified/leverage/user_currency_config` | -| [getUserCurrencyLeverageSettings()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1457) | :closed_lock_with_key: | GET | `/unified/leverage/user_currency_setting` | -| [updateUserCurrencyLeverage()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1472) | :closed_lock_with_key: | POST | `/unified/leverage/user_currency_setting` | -| [getUnifiedLoanCurrencies()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1487) | :closed_lock_with_key: | GET | `/unified/currencies` | -| [getHistoricalLendingRates()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1499) | :closed_lock_with_key: | GET | `/unified/history_loan_rate` | -| [submitUnifiedLoanRepay()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1505) | :closed_lock_with_key: | POST | `/unified/loans/repay` | -| [getEstimatedQuickRepayment()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1512) | :closed_lock_with_key: | GET | `/unified/estimated_quick_repayment` | -| [createQuickRepayment()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1519) | :closed_lock_with_key: | POST | `/unified/quick_repayment` | -| [setUnifiedDeltaNeutral()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1530) | :closed_lock_with_key: | POST | `/unified/delta_neutral` | -| [getUnifiedDeltaNeutral()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1539) | :closed_lock_with_key: | GET | `/unified/delta_neutral` | -| [getSpotCurrencies()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1559) | | GET | `/spot/currencies` | -| [getSpotCurrency()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1569) | | GET | `/spot/currencies/{currency}` | -| [getSpotCurrencyPairs()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1578) | | GET | `/spot/currency_pairs` | -| [getSpotCurrencyPair()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1588) | | GET | `/spot/currency_pairs/{currency_pair}` | -| [getSpotTicker()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1602) | | GET | `/spot/tickers` | -| [getSpotOrderBook()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1617) | | GET | `/spot/order_book` | -| [getSpotTrades()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1630) | | GET | `/spot/trades` | -| [getSpotCandles()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1642) | | GET | `/spot/candlesticks` | -| [getSpotFeeRates()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1654) | :closed_lock_with_key: | GET | `/spot/fee` | -| [getSpotBatchFeeRates()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1663) | :closed_lock_with_key: | GET | `/spot/batch_fee` | -| [getSpotAccounts()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1675) | :closed_lock_with_key: | GET | `/spot/accounts` | -| [getSpotAccountBook()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1687) | :closed_lock_with_key: | GET | `/spot/account_book` | -| [submitSpotBatchOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1706) | :closed_lock_with_key: | POST | `/spot/batch_orders` | -| [getSpotOpenOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1733) | :closed_lock_with_key: | GET | `/spot/open_orders` | -| [submitSpotClosePosCrossDisabled()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1749) | :closed_lock_with_key: | POST | `/spot/cross_liquidate_orders` | -| [submitSpotOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1765) | :closed_lock_with_key: | POST | `/spot/orders` | -| [getSpotOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1782) | :closed_lock_with_key: | GET | `/spot/orders` | -| [cancelSpotOpenOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1797) | :closed_lock_with_key: | DELETE | `/spot/orders` | -| [batchCancelSpotOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1826) | :closed_lock_with_key: | POST | `/spot/cancel_batch_orders` | -| [getSpotOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1851) | :closed_lock_with_key: | GET | `/spot/orders/{order_id}` | -| [updateSpotOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1868) | :closed_lock_with_key: | PATCH | `/spot/orders/{order_id}` | -| [cancelSpotOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1896) | :closed_lock_with_key: | DELETE | `/spot/orders/{order_id}` | -| [getSpotTradingHistory()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1925) | :closed_lock_with_key: | GET | `/spot/my_trades` | -| [submitSpotCountdownOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1954) | :closed_lock_with_key: | POST | `/spot/countdown_cancel_all` | -| [batchUpdateSpotOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1973) | :closed_lock_with_key: | POST | `/spot/amend_batch_orders` | -| [getSpotInsuranceHistory()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2000) | :closed_lock_with_key: | GET | `/spot/insurance_history` | -| [submitSpotPriceTriggerOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2014) | :closed_lock_with_key: | POST | `/spot/price_orders` | -| [getSpotAutoOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2026) | :closed_lock_with_key: | GET | `/spot/price_orders` | -| [cancelAllOpenSpotOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2038) | :closed_lock_with_key: | DELETE | `/spot/price_orders` | -| [getPriceTriggeredOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2051) | :closed_lock_with_key: | GET | `/spot/price_orders/{order_id}` | -| [cancelSpotTriggeredOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2063) | :closed_lock_with_key: | DELETE | `/spot/price_orders/{order_id}` | -| [getSpotPovOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2077) | :closed_lock_with_key: | GET | `/spot/pov_orders` | -| [createSpotPovOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2089) | :closed_lock_with_key: | POST | `/spot/pov_orders` | -| [cancelSpotPovOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2101) | :closed_lock_with_key: | DELETE | `/spot/pov_orders` | -| [getSpotPovOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2115) | :closed_lock_with_key: | GET | `/spot/pov_orders/{order_id}` | -| [cancelSpotPovOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2127) | :closed_lock_with_key: | DELETE | `/spot/pov_orders/{order_id}` | -| [setCollateralCurrency()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2139) | :closed_lock_with_key: | POST | `/unified/collateral_currencies` | -| [getMarginAccounts()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2160) | :closed_lock_with_key: | GET | `/margin/accounts` | -| [getMarginBalanceHistory()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2174) | :closed_lock_with_key: | GET | `/margin/account_book` | -| [getFundingAccounts()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2192) | :closed_lock_with_key: | GET | `/margin/funding_accounts` | -| [updateAutoRepaymentSetting()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2210) | :closed_lock_with_key: | POST | `/margin/auto_repay` | -| [getAutoRepaymentSetting()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2221) | :closed_lock_with_key: | GET | `/margin/auto_repay` | -| [getMarginTransferableAmount()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2235) | :closed_lock_with_key: | GET | `/margin/transferable` | -| [getCrossMarginCurrencies()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2252) | | GET | `/margin/cross/currencies` | -| [getCrossMarginCurrency()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2263) | | GET | `/margin/cross/currencies/{currency}` | -| [getCrossMarginAccount()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2275) | :closed_lock_with_key: | GET | `/margin/cross/accounts` | -| [getCrossMarginAccountHistory()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2288) | :closed_lock_with_key: | GET | `/margin/cross/account_book` | -| [submitCrossMarginBorrowLoan()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2305) | :closed_lock_with_key: | POST | `/margin/cross/loans` | -| [getCrossMarginBorrowHistory()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2320) | :closed_lock_with_key: | GET | `/margin/cross/loans` | -| [getCrossMarginBorrowLoan()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2333) | :closed_lock_with_key: | GET | `/margin/cross/loans/{loan_id}` | -| [submitCrossMarginRepayment()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2348) | :closed_lock_with_key: | POST | `/margin/cross/repayments` | -| [getCrossMarginRepayments()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2364) | :closed_lock_with_key: | GET | `/margin/cross/repayments` | -| [getCrossMarginInterestRecords()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2377) | :closed_lock_with_key: | GET | `/margin/cross/interest_records` | -| [getCrossMarginTransferableAmount()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2393) | :closed_lock_with_key: | GET | `/margin/cross/transferable` | -| [getEstimatedInterestRates()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2409) | :closed_lock_with_key: | GET | `/margin/cross/estimate_rate` | -| [getCrossMarginBorrowableAmount()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2423) | :closed_lock_with_key: | GET | `/margin/cross/borrowable` | -| [getMarginUserLoanTiers()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2436) | :closed_lock_with_key: | GET | `/margin/user/loan_margin_tiers` | -| [getMarginPublicLoanTiers()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2452) | | GET | `/margin/loan_margin_tiers` | -| [setMarginUserLeverage()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2468) | :closed_lock_with_key: | POST | `/margin/leverage/user_market_setting` | -| [getMarginUserAccounts()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2485) | :closed_lock_with_key: | GET | `/margin/user/account` | -| [getLendingMarkets()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2500) | | GET | `/margin/uni/currency_pairs` | -| [getLendingMarket()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2515) | | GET | `/margin/uni/currency_pairs/{currency_pair}` | -| [getEstimatedInterestRate()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2527) | :closed_lock_with_key: | GET | `/margin/uni/estimate_rate` | -| [submitMarginUNIBorrowOrRepay()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2537) | :closed_lock_with_key: | POST | `/margin/uni/loans` | -| [getMarginUNILoans()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2553) | :closed_lock_with_key: | GET | `/margin/uni/loans` | -| [getMarginUNILoanRecords()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2563) | :closed_lock_with_key: | GET | `/margin/uni/loan_records` | -| [getMarginUNIInterestRecords()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2575) | :closed_lock_with_key: | GET | `/margin/uni/interest_records` | -| [getMarginUNIMaxBorrow()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2587) | :closed_lock_with_key: | GET | `/margin/uni/borrowable` | -| [getFlashSwapCurrencyPairs()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2603) | | GET | `/flash_swap/currency_pairs` | -| [submitFlashSwapOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2619) | :closed_lock_with_key: | POST | `/flash_swap/orders` | -| [getFlashSwapOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2631) | :closed_lock_with_key: | GET | `/flash_swap/orders` | -| [getFlashSwapOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2643) | :closed_lock_with_key: | GET | `/flash_swap/orders/{order_id}` | -| [submitFlashSwapOrderPreview()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2653) | :closed_lock_with_key: | POST | `/flash_swap/orders/preview` | -| [getFuturesContracts()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2670) | | GET | `/futures/{settle}/contracts` | -| [getFuturesContract()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2685) | | GET | `/futures/{settle}/contracts/{contract}` | -| [listFuturesADLRiskStates()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2692) | | GET | `/futures/{settle}/adl_risk_states` | -| [getFuturesOrderBook()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2706) | | GET | `/futures/{settle}/order_book` | -| [getFuturesTrades()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2719) | | GET | `/futures/{settle}/trades` | -| [getFuturesCandles()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2734) | | GET | `/futures/{settle}/candlesticks` | -| [getPremiumIndexKLines()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2747) | | GET | `/futures/{settle}/premium_index` | -| [getFuturesTickers()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2760) | | GET | `/futures/{settle}/tickers` | -| [getFundingRates()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2777) | | GET | `/futures/{settle}/funding_rate` | -| [getBatchFundingRates()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2793) | | POST | `/futures/{settle}/funding_rates` | -| [getFuturesInsuranceBalanceHistory()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2811) | | GET | `/futures/{settle}/insurance` | -| [getFuturesStats()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2830) | | GET | `/futures/{settle}/contract_stats` | -| [getIndexConstituents()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2841) | | GET | `/futures/{settle}/index_constituents/{index}` | -| [getLiquidationHistory()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2858) | | GET | `/futures/{settle}/liq_orders` | -| [getRiskLimitTiers()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2875) | | GET | `/futures/{settle}/risk_limit_tiers` | -| [getFuturesAccount()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2888) | :closed_lock_with_key: | GET | `/futures/{settle}/accounts` | -| [getFuturesAccountBook()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2902) | :closed_lock_with_key: | GET | `/futures/{settle}/account_book` | -| [getFuturesPositions()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2915) | :closed_lock_with_key: | GET | `/futures/{settle}/positions` | -| [getFuturesPosition()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2930) | :closed_lock_with_key: | GET | `/futures/{settle}/positions/{contract}` | -| [updateFuturesMargin()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2947) | :closed_lock_with_key: | POST | `/futures/{settle}/positions/{contract}/margin` | -| [updateFuturesLeverage()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2975) | :closed_lock_with_key: | POST | `/futures/{settle}/positions/{contract}/leverage` | -| [getFuturesContractLeverage()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2995) | :closed_lock_with_key: | GET | `/futures/{settle}/get_leverage/{contract}` | -| [updateFuturesPositionMode()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3011) | :closed_lock_with_key: | POST | `/futures/{settle}/positions/cross_mode` | -| [updatePositionRiskLimit()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3028) | :closed_lock_with_key: | POST | `/futures/{settle}/positions/{contract}/risk_limit` | -| [updateFuturesDualMode()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3048) | :closed_lock_with_key: | POST | `/futures/{settle}/dual_mode` | -| [getDualModePosition()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3064) | :closed_lock_with_key: | GET | `/futures/{settle}/dual_comp/positions/{contract}` | -| [updateDualModePositionMargin()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3079) | :closed_lock_with_key: | POST | `/futures/{settle}/dual_comp/positions/{contract}/margin` | -| [updateDualModePositionLeverage()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3095) | :closed_lock_with_key: | POST | `/futures/{settle}/dual_comp/positions/{contract}/leverage` | -| [updateDualModePositionRiskLimit()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3119) | :closed_lock_with_key: | POST | `/futures/{settle}/dual_comp/positions/{contract}/risk_limit` | -| [submitFuturesOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3146) | :closed_lock_with_key: | POST | `/futures/{settle}/orders` | -| [getFuturesOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3167) | :closed_lock_with_key: | GET | `/futures/{settle}/orders` | -| [cancelAllFuturesOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3182) | :closed_lock_with_key: | DELETE | `/futures/{settle}/orders` | -| [getFuturesOrdersByTimeRange()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3202) | :closed_lock_with_key: | GET | `/futures/{settle}/orders_timerange` | -| [submitFuturesBatchOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3225) | :closed_lock_with_key: | POST | `/futures/{settle}/batch_orders` | -| [getFuturesOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3250) | :closed_lock_with_key: | GET | `/futures/{settle}/orders/{order_id}` | -| [cancelFuturesOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3267) | :closed_lock_with_key: | DELETE | `/futures/{settle}/orders/{order_id}` | -| [updateFuturesOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3292) | :closed_lock_with_key: | PUT | `/futures/{settle}/orders/{order_id}` | -| [getFuturesTradingHistory()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3313) | :closed_lock_with_key: | GET | `/futures/{settle}/my_trades` | -| [getFuturesTradingHistoryByTimeRange()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3328) | :closed_lock_with_key: | GET | `/futures/{settle}/my_trades_timerange` | -| [getFuturesPositionHistory()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3341) | :closed_lock_with_key: | GET | `/futures/{settle}/position_close` | -| [getFuturesLiquidationHistory()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3354) | :closed_lock_with_key: | GET | `/futures/{settle}/liquidates` | -| [getFuturesAutoDeleveragingHistory()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3367) | :closed_lock_with_key: | GET | `/futures/{settle}/auto_deleverages` | -| [setFuturesOrderCancelCountdown()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3384) | :closed_lock_with_key: | POST | `/futures/{settle}/countdown_cancel_all` | -| [getFuturesUserTradingFees()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3401) | :closed_lock_with_key: | GET | `/futures/{settle}/fee` | -| [batchCancelFuturesOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3419) | :closed_lock_with_key: | POST | `/futures/{settle}/batch_cancel_orders` | -| [batchUpdateFuturesOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3446) | :closed_lock_with_key: | POST | `/futures/{settle}/batch_amend_orders` | -| [getRiskLimitTable()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3468) | | GET | `/futures/{settle}/risk_limit_table` | -| [submitFuturesPriceTriggeredOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3481) | :closed_lock_with_key: | POST | `/futures/{settle}/price_orders` | -| [getFuturesAutoOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3494) | :closed_lock_with_key: | GET | `/futures/{settle}/price_orders` | -| [cancelAllOpenFuturesOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3507) | :closed_lock_with_key: | DELETE | `/futures/{settle}/price_orders` | -| [getFuturesPriceTriggeredOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3523) | :closed_lock_with_key: | GET | `/futures/{settle}/price_orders/{order_id}` | -| [cancelFuturesPriceTriggeredOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3538) | :closed_lock_with_key: | DELETE | `/futures/{settle}/price_orders/{order_id}` | -| [updateFuturesPriceTriggeredOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3553) | :closed_lock_with_key: | PUT | `/futures/{settle}/price_orders/amend` | -| [createTrailOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3568) | :closed_lock_with_key: | POST | `/futures/{settle}/autoorder/v1/trail/create` | -| [terminateTrailOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3586) | :closed_lock_with_key: | POST | `/futures/{settle}/autoorder/v1/trail/stop` | -| [batchTerminateTrailOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3599) | :closed_lock_with_key: | POST | `/futures/{settle}/autoorder/v1/trail/stop_all` | -| [getTrailOrderList()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3614) | :closed_lock_with_key: | GET | `/futures/{settle}/autoorder/v1/trail/list` | -| [getTrailOrderDetail()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3627) | :closed_lock_with_key: | GET | `/futures/{settle}/autoorder/v1/trail/detail` | -| [updateTrailOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3645) | :closed_lock_with_key: | POST | `/futures/{settle}/autoorder/v1/trail/update` | -| [getTrailOrderChangeLog()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3658) | :closed_lock_with_key: | GET | `/futures/{settle}/autoorder/v1/trail/change_log` | -| [createChaseOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3671) | :closed_lock_with_key: | POST | `/futures/{settle}/autoorder/v1/chase/create` | -| [stopChaseOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3681) | :closed_lock_with_key: | POST | `/futures/{settle}/autoorder/v1/chase/stop` | -| [stopAllChaseOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3691) | :closed_lock_with_key: | POST | `/futures/{settle}/autoorder/v1/chase/stop_all` | -| [getChaseOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3703) | :closed_lock_with_key: | GET | `/futures/{settle}/autoorder/v1/chase/list` | -| [getChaseOrderDetail()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3711) | :closed_lock_with_key: | GET | `/futures/{settle}/autoorder/v1/chase/detail` | -| [getFuturesPositionCloseHistory()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3720) | :closed_lock_with_key: | GET | `/futures/{settle}/position_close_history` | -| [getFuturesInsuranceHistory()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3729) | :closed_lock_with_key: | GET | `/futures/{settle}/insurance` | -| [getAllDeliveryContracts()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3746) | | GET | `/delivery/{settle}/contracts` | -| [getDeliveryContract()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3758) | | GET | `/delivery/{settle}/contracts/{contract}` | -| [getDeliveryOrderBook()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3773) | | GET | `/delivery/{settle}/order_book` | -| [getDeliveryTrades()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3786) | | GET | `/delivery/{settle}/trades` | -| [getDeliveryCandles()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3800) | | GET | `/delivery/{settle}/candlesticks` | -| [getDeliveryTickers()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3811) | | GET | `/delivery/{settle}/tickers` | -| [getDeliveryInsuranceBalanceHistory()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3828) | | GET | `/delivery/{settle}/insurance` | -| [getDeliveryAccount()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3847) | :closed_lock_with_key: | GET | `/delivery/{settle}/accounts` | -| [getDeliveryBook()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3858) | :closed_lock_with_key: | GET | `/delivery/{settle}/account_book` | -| [getDeliveryPositions()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3869) | :closed_lock_with_key: | GET | `/delivery/{settle}/positions` | -| [getDeliveryPosition()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3879) | :closed_lock_with_key: | GET | `/delivery/{settle}/positions/{contract}` | -| [updateDeliveryMargin()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3894) | :closed_lock_with_key: | POST | `/delivery/{settle}/positions/{contract}/margin` | -| [updateDeliveryLeverage()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3912) | :closed_lock_with_key: | POST | `/delivery/{settle}/positions/{contract}/leverage` | -| [updateDeliveryRiskLimit()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3930) | :closed_lock_with_key: | POST | `/delivery/{settle}/positions/{contract}/risk_limit` | -| [submitDeliveryOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3950) | :closed_lock_with_key: | POST | `/delivery/{settle}/orders` | -| [getDeliveryOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3965) | :closed_lock_with_key: | GET | `/delivery/{settle}/orders` | -| [cancelAllDeliveryOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3978) | :closed_lock_with_key: | DELETE | `/delivery/{settle}/orders` | -| [getDeliveryOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3997) | :closed_lock_with_key: | GET | `/delivery/{settle}/orders/{order_id}` | -| [cancelDeliveryOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4012) | :closed_lock_with_key: | DELETE | `/delivery/{settle}/orders/{order_id}` | -| [getDeliveryTradingHistory()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4027) | :closed_lock_with_key: | GET | `/delivery/{settle}/my_trades` | -| [getDeliveryClosedPositions()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4040) | :closed_lock_with_key: | GET | `/delivery/{settle}/position_close` | -| [getDeliveryLiquidationHistory()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4053) | :closed_lock_with_key: | GET | `/delivery/{settle}/liquidates` | -| [getDeliverySettlementHistory()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4066) | :closed_lock_with_key: | GET | `/delivery/{settle}/settlements` | -| [submitDeliveryTriggeredOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4079) | :closed_lock_with_key: | POST | `/delivery/{settle}/price_orders` | -| [getDeliveryAutoOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4094) | :closed_lock_with_key: | GET | `/delivery/{settle}/price_orders` | -| [cancelAllOpenDeliveryOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4107) | :closed_lock_with_key: | DELETE | `/delivery/{settle}/price_orders` | -| [getDeliveryTriggeredOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4123) | :closed_lock_with_key: | GET | `/delivery/{settle}/price_orders/{order_id}` | -| [cancelTriggeredDeliveryOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4138) | :closed_lock_with_key: | DELETE | `/delivery/{settle}/price_orders/{order_id}` | -| [getOptionsUnderlyings()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4157) | | GET | `/options/underlyings` | -| [getOptionsExpirationTimes()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4167) | | GET | `/options/expirations` | -| [getOptionsContracts()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4177) | | GET | `/options/contracts` | -| [getOptionsContract()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4190) | | GET | `/options/contracts/{contract}` | -| [getOptionsSettlementHistory()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4200) | | GET | `/options/settlements` | -| [getOptionsContractSettlement()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4212) | | GET | `/options/settlements/{contract}` | -| [getOptionsMySettlements()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4227) | :closed_lock_with_key: | GET | `/options/my_settlements` | -| [getOptionsOrderBook()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4241) | | GET | `/options/order_book` | -| [getOptionsTickers()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4253) | | GET | `/options/tickers` | -| [getOptionsUnderlyingTicker()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4267) | | GET | `/options/underlying/tickers/{underlying}` | -| [getOptionsCandles()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4281) | | GET | `/options/candlesticks` | -| [getOptionsUnderlyingCandles()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4291) | | GET | `/options/underlying/candlesticks` | -| [getOptionsTrades()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4303) | | GET | `/options/trades` | -| [getOptionsAccount()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4314) | :closed_lock_with_key: | GET | `/options/accounts` | -| [getOptionsAccountChange()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4324) | :closed_lock_with_key: | GET | `/options/account_book` | -| [getOptionsPositionsUnderlying()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4336) | :closed_lock_with_key: | GET | `/options/positions` | -| [getOptionsPositionContract()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4348) | :closed_lock_with_key: | GET | `/options/positions/{contract}` | -| [getOptionsLiquidation()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4360) | :closed_lock_with_key: | GET | `/options/position_close` | -| [submitOptionsOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4373) | :closed_lock_with_key: | POST | `/options/orders` | -| [getOptionsOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4385) | :closed_lock_with_key: | GET | `/options/orders` | -| [cancelAllOpenOptionsOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4397) | :closed_lock_with_key: | DELETE | `/options/orders` | -| [getOptionsOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4411) | :closed_lock_with_key: | GET | `/options/orders/{order_id}` | -| [amendOptionsOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4423) | :closed_lock_with_key: | PUT | `/options/orders/{order_id}` | -| [cancelOptionsOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4438) | :closed_lock_with_key: | DELETE | `/options/orders/{order_id}` | -| [submitOptionsCountdownCancel()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4457) | :closed_lock_with_key: | POST | `/options/countdown_cancel_all` | -| [getOptionsPersonalHistory()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4473) | :closed_lock_with_key: | GET | `/options/my_trades` | -| [setOptionsMMPSettings()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4485) | :closed_lock_with_key: | POST | `/options/mmp` | -| [getOptionsMMPSettings()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4497) | :closed_lock_with_key: | GET | `/options/mmp` | -| [resetOptionsMMPSettings()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4509) | :closed_lock_with_key: | POST | `/options/mmp/reset` | -| [getLendingCurrencies()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4525) | | GET | `/earn/uni/currencies` | -| [getLendingCurrency()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4535) | | GET | `/earn/uni/currencies/{currency}` | -| [submitLendOrRedeemOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4545) | :closed_lock_with_key: | POST | `/earn/uni/lends` | -| [getLendingOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4555) | :closed_lock_with_key: | GET | `/earn/uni/lends` | -| [updateLendingOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4567) | :closed_lock_with_key: | PATCH | `/earn/uni/lends` | -| [getLendingRecords()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4580) | :closed_lock_with_key: | GET | `/earn/uni/lend_records` | -| [getLendingTotalInterest()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4593) | :closed_lock_with_key: | GET | `/earn/uni/interests/{currency}` | -| [getLendingInterestRecords()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4606) | :closed_lock_with_key: | GET | `/earn/uni/interest_records` | -| [updateInterestReinvestment()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4619) | :closed_lock_with_key: | PUT | `/earn/uni/interest_reinvest` | -| [getLendingInterestStatus()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4635) | :closed_lock_with_key: | GET | `/earn/uni/interest_status/{currency}` | -| [getLendingAnnualizedTrendChart()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4650) | :closed_lock_with_key: | GET | `/earn/uni/chart` | -| [getLendingEstimatedRates()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4658) | :closed_lock_with_key: | GET | `/earn/uni/rate` | -| [submitMultiLoanOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4675) | :closed_lock_with_key: | POST | `/loan/multi_collateral/orders` | -| [getMultiLoanOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4687) | :closed_lock_with_key: | GET | `/loan/multi_collateral/orders` | -| [getMultiLoanOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4699) | :closed_lock_with_key: | GET | `/loan/multi_collateral/orders/{order_id}` | -| [repayMultiLoan()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4709) | :closed_lock_with_key: | POST | `/loan/multi_collateral/repay` | -| [getMultiLoanRepayRecords()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4719) | :closed_lock_with_key: | GET | `/loan/multi_collateral/repay` | -| [updateMultiLoan()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4731) | :closed_lock_with_key: | POST | `/loan/multi_collateral/mortgage` | -| [getMultiLoanAdjustmentRecords()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4743) | :closed_lock_with_key: | GET | `/loan/multi_collateral/mortgage` | -| [getMultiLoanCurrencyQuota()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4755) | :closed_lock_with_key: | GET | `/loan/multi_collateral/currency_quota` | -| [getMultiLoanSupportedCurrencies()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4767) | | GET | `/loan/multi_collateral/currencies` | -| [getMultiLoanRatio()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4776) | | GET | `/loan/multi_collateral/ltv` | -| [getMultiLoanFixedRates()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4785) | | GET | `/loan/multi_collateral/fixed_rate` | -| [getMultiLoanCurrentRates()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4798) | | GET | `/loan/multi_collateral/current_rate` | -| [getDualInvestmentProducts()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4820) | | GET | `/earn/dual/investment_plan` | -| [getDualInvestmentOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4831) | :closed_lock_with_key: | GET | `/earn/dual/orders` | -| [submitDualInvestmentOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4843) | :closed_lock_with_key: | POST | `/earn/dual/orders` | -| [getDualOrderRefundPreview()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4852) | :closed_lock_with_key: | GET | `/earn/dual/order-refund-preview` | -| [submitDualOrderRefund()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4861) | :closed_lock_with_key: | POST | `/earn/dual/order-refund` | -| [updateDualOrderReinvest()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4870) | :closed_lock_with_key: | POST | `/earn/dual/modify-order-reinvest` | -| [getDualProjectRecommend()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4881) | :closed_lock_with_key: | GET | `/earn/dual/project-recommend` | -| [getEarnFixedTermProducts()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4890) | | GET | `/earn/fixed-term/product` | -| [getEarnFixedTermProductsByAsset()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4899) | | GET | `/earn/fixed-term/product/{asset}/list` | -| [createEarnFixedTermLend()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4909) | :closed_lock_with_key: | POST | `/earn/fixed-term/user/lend` | -| [getEarnFixedTermLends()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4918) | :closed_lock_with_key: | GET | `/earn/fixed-term/user/lend` | -| [createEarnFixedTermPreRedeem()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4927) | :closed_lock_with_key: | POST | `/earn/fixed-term/user/pre-redeem` | -| [getEarnFixedTermHistory()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4938) | :closed_lock_with_key: | GET | `/earn/fixed-term/user/history` | -| [createAutoInvestPlan()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4947) | :closed_lock_with_key: | POST | `/earn/autoinvest/plans/create` | -| [updateAutoInvestPlan()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4956) | :closed_lock_with_key: | POST | `/earn/autoinvest/plans/update` | -| [stopAutoInvestPlan()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4963) | :closed_lock_with_key: | POST | `/earn/autoinvest/plans/stop` | -| [addAutoInvestPlanPosition()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4970) | :closed_lock_with_key: | POST | `/earn/autoinvest/plans/add_position` | -| [getAutoInvestCoins()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4981) | :closed_lock_with_key: | GET | `/earn/autoinvest/coins` | -| [getAutoInvestMinAmount()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4990) | :closed_lock_with_key: | POST | `/earn/autoinvest/min_invest_amount` | -| [getAutoInvestPlanRecords()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5001) | :closed_lock_with_key: | GET | `/earn/autoinvest/plans/records` | -| [getAutoInvestOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5010) | :closed_lock_with_key: | GET | `/earn/autoinvest/orders` | -| [getAutoInvestConfig()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5019) | :closed_lock_with_key: | GET | `/earn/autoinvest/config` | -| [getAutoInvestPlanDetail()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5026) | :closed_lock_with_key: | GET | `/earn/autoinvest/plans/detail` | -| [getAutoInvestPlans()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5035) | :closed_lock_with_key: | GET | `/earn/autoinvest/plans/list_info` | -| [getStakingCoins()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5047) | :closed_lock_with_key: | GET | `/earn/staking/coins` | -| [submitStakingSwap()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5060) | :closed_lock_with_key: | POST | `/earn/staking/swap` | -| [getAccountDetail()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5079) | :closed_lock_with_key: | GET | `/account/detail` | -| [getAccountRateLimit()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5088) | :closed_lock_with_key: | GET | `/account/rate_limit` | -| [createStpGroup()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5098) | :closed_lock_with_key: | POST | `/account/stp_groups` | -| [getStpGroups()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5108) | :closed_lock_with_key: | GET | `/account/stp_groups` | -| [getStpGroupUsers()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5118) | :closed_lock_with_key: | GET | `/account/stp_groups/{stp_id}/users` | -| [addUsersToStpGroup()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5128) | :closed_lock_with_key: | POST | `/account/stp_groups/{stp_id}/users` | -| [deleteUserFromStpGroup()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5144) | :closed_lock_with_key: | DELETE | `/account/stp_groups/{stp_id}/users` | -| [setGTDeduction()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5162) | :closed_lock_with_key: | POST | `/account/debit_fee` | -| [getGTDeduction()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5173) | :closed_lock_with_key: | GET | `/account/debit_fee` | -| [getAccountMainKeys()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5182) | :closed_lock_with_key: | GET | `/account/main_keys` | -| [getAgencyTransactionHistory()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5198) | :closed_lock_with_key: | GET | `/rebate/agency/transaction_history` | -| [getAgencyCommissionHistory()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5211) | :closed_lock_with_key: | GET | `/rebate/agency/commission_history` | -| [getPartnerTransactionHistory()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5225) | :closed_lock_with_key: | GET | `/rebate/partner/transaction_history` | -| [getPartnerCommissionHistory()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5240) | :closed_lock_with_key: | GET | `/rebate/partner/commission_history` | -| [getPartnerSubordinateList()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5263) | :closed_lock_with_key: | GET | `/rebate/partner/sub_list` | -| [getPartnerAgentDataAggregated()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5273) | :closed_lock_with_key: | GET | `/rebate/partner/data/aggregated` | -| [getBrokerCommissionHistory()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5286) | :closed_lock_with_key: | GET | `/rebate/broker/commission_history` | -| [getBrokerTransactionHistory()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5299) | :closed_lock_with_key: | GET | `/rebate/broker/transaction_history` | -| [getUserRebateInfo()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5308) | :closed_lock_with_key: | GET | `/rebate/user/info` | -| [createOTCQuote()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5343) | :closed_lock_with_key: | POST | `/otc/quote` | -| [createOTCFiatOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5355) | :closed_lock_with_key: | POST | `/otc/order/create` | -| [createOTCStablecoinOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5369) | :closed_lock_with_key: | POST | `/otc/stable_coin/order/create` | -| [getOTCBankList()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5378) | :closed_lock_with_key: | GET | `/otc/bank/list` | -| [getOTCBankListLegacy()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5385) | :closed_lock_with_key: | GET | `/otc/bank_list` | -| [createOTCUploadPreUpload()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5389) | :closed_lock_with_key: | POST | `/otc/upload/pre_upload` | -| [createOTCBank()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5398) | :closed_lock_with_key: | POST | `/otc/bank/create` | -| [deleteOTCBank()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5412) | :closed_lock_with_key: | POST | `/otc/bank/delete` | -| [setDefaultOTCBank()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5419) | :closed_lock_with_key: | POST | `/otc/bank/set_default` | -| [getOTCBankSupplementChecklist()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5426) | :closed_lock_with_key: | GET | `/otc/bank/bank_supplement_checklist` | -| [submitOTCBankPersonalSupplement()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5435) | :closed_lock_with_key: | POST | `/otc/order/paid` | -| [submitOTCBankEnterpriseSupplement()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5454) | :closed_lock_with_key: | POST | `/otc/order/paid` | -| [markOTCOrderAsPaid()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5490) | :closed_lock_with_key: | POST | `/otc/order/paid` | -| [cancelOTCOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5504) | :closed_lock_with_key: | POST | `/otc/order/cancel` | -| [getOTCFiatOrderList()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5516) | :closed_lock_with_key: | GET | `/otc/order/list` | -| [getOTCStablecoinOrderList()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5530) | :closed_lock_with_key: | GET | `/otc/stable_coin/order/list` | -| [getOTCFiatOrderDetail()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5544) | :closed_lock_with_key: | GET | `/otc/order/detail` | -| [getP2PMerchantUserInfo()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5558) | :closed_lock_with_key: | POST | `/p2p/merchant/account/get_user_info` | -| [getP2PMerchantCounterpartyUserInfo()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5567) | :closed_lock_with_key: | POST | `/p2p/merchant/account/get_counterparty_user_info` | -| [getP2PMerchantMyselfPayment()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5579) | :closed_lock_with_key: | POST | `/p2p/merchant/account/get_myself_payment` | -| [getP2PMerchantSpotBalance()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5592) | :closed_lock_with_key: | POST | `/p2p/merchant/account/set_merchant_work_hours` | -| [setP2PMerchantWorkHours()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5601) | :closed_lock_with_key: | POST | `/p2p/merchant/account/set_merchant_work_hours` | -| [getP2PMerchantPendingTransactionList()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5612) | :closed_lock_with_key: | POST | `/p2p/merchant/transaction/get_pending_transaction_list` | -| [getP2PMerchantCompletedTransactionList()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5624) | :closed_lock_with_key: | POST | `/p2p/merchant/transaction/get_completed_transaction_list` | -| [getP2PMerchantTransactionDetails()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5636) | :closed_lock_with_key: | POST | `/p2p/merchant/transaction/get_transaction_details` | -| [confirmP2PMerchantPayment()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5648) | :closed_lock_with_key: | POST | `/p2p/merchant/transaction/confirm-payment` | -| [confirmP2PMerchantReceipt()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5659) | :closed_lock_with_key: | POST | `/p2p/merchant/transaction/confirm-receipt` | -| [cancelP2PMerchantTransaction()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5670) | :closed_lock_with_key: | POST | `/p2p/merchant/transaction/cancel` | -| [placeP2PMerchantBizPushOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5681) | :closed_lock_with_key: | POST | `/p2p/merchant/books/place_biz_push_order` | -| [updateP2PMerchantAdsStatus()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5692) | :closed_lock_with_key: | POST | `/p2p/merchant/books/ads_update_status` | -| [getP2PMerchantAdsDetail()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5705) | :closed_lock_with_key: | POST | `/p2p/merchant/books/ads_detail` | -| [getP2PMerchantMyAdsList()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5714) | :closed_lock_with_key: | POST | `/p2p/merchant/books/my_ads_list` | -| [getP2PMerchantAdsList()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5725) | :closed_lock_with_key: | POST | `/p2p/merchant/books/ads_list` | -| [getP2PMerchantChatsList()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5734) | :closed_lock_with_key: | POST | `/p2p/merchant/chat/get_chats_list` | -| [sendP2PMerchantChatMessage()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5745) | :closed_lock_with_key: | POST | `/p2p/merchant/chat/send_chat_message` | -| [uploadP2PMerchantChatFile()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5756) | :closed_lock_with_key: | POST | `/p2p/merchant/chat/upload_chat_file` | -| [getCrossExSymbols()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5777) | | GET | `/crossex/rule/symbols` | -| [getCrossExRiskLimits()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5789) | | GET | `/crossex/rule/risk_limits` | -| [getCrossExTransferCoins()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5803) | | GET | `/crossex/transfers/coin` | -| [createCrossExTransfer()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5817) | :closed_lock_with_key: | POST | `/crossex/transfers` | -| [getCrossExTransferHistory()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5831) | :closed_lock_with_key: | GET | `/crossex/transfers` | -| [createCrossExOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5845) | :closed_lock_with_key: | POST | `/crossex/orders` | -| [cancelBatchCrossExOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5859) | :closed_lock_with_key: | POST | `/crossex/batch_cancel_orders` | -| [cancelCrossExOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5873) | :closed_lock_with_key: | DELETE | `/crossex/orders/{order_id}` | -| [modifyCrossExOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5886) | :closed_lock_with_key: | PUT | `/crossex/orders/{order_id}` | -| [getCrossExOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5901) | :closed_lock_with_key: | GET | `/crossex/orders/{order_id}` | -| [createCrossExConvertQuote()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5913) | :closed_lock_with_key: | POST | `/crossex/convert/quote` | -| [createCrossExConvertOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5927) | :closed_lock_with_key: | POST | `/crossex/convert/orders` | -| [updateCrossExAccount()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5941) | :closed_lock_with_key: | PUT | `/crossex/accounts` | -| [getCrossExAccounts()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5955) | :closed_lock_with_key: | GET | `/crossex/accounts` | -| [setCrossExPositionLeverage()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5967) | :closed_lock_with_key: | POST | `/crossex/positions/leverage` | -| [getCrossExPositionLeverage()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5981) | :closed_lock_with_key: | GET | `/crossex/positions/leverage` | -| [setCrossExMarginPositionLeverage()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5995) | :closed_lock_with_key: | POST | `/crossex/margin_positions/leverage` | -| [getCrossExMarginPositionLeverage()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6011) | :closed_lock_with_key: | GET | `/crossex/margin_positions/leverage` | -| [closeCrossExPosition()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6025) | :closed_lock_with_key: | POST | `/crossex/position` | -| [updateCrossExPositionsMargin()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6031) | :closed_lock_with_key: | POST | `/crossex/positions/margin` | -| [getCrossExInterestRate()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6045) | :closed_lock_with_key: | GET | `/crossex/interest_rate` | -| [getCrossExFeeRate()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6058) | :closed_lock_with_key: | GET | `/crossex/fee` | -| [getCrossExPositions()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6070) | :closed_lock_with_key: | GET | `/crossex/positions` | -| [getCrossExMarginPositions()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6084) | :closed_lock_with_key: | GET | `/crossex/margin_positions` | -| [getCrossExAdlRank()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6098) | :closed_lock_with_key: | GET | `/crossex/adl_rank` | -| [getCrossExOpenOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6110) | :closed_lock_with_key: | GET | `/crossex/open_orders` | -| [getCrossExHistoryOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6124) | :closed_lock_with_key: | GET | `/crossex/history_orders` | -| [getCrossExHistoryPositions()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6138) | :closed_lock_with_key: | GET | `/crossex/history_positions` | -| [getCrossExHistoryMarginPositions()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6152) | :closed_lock_with_key: | GET | `/crossex/history_margin_positions` | -| [getCrossExHistoryMarginInterests()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6166) | :closed_lock_with_key: | GET | `/crossex/history_margin_interests` | -| [getCrossExHistoryTrades()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6180) | :closed_lock_with_key: | GET | `/crossex/history_trades` | -| [getCrossExAccountBook()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6194) | :closed_lock_with_key: | GET | `/crossex/account_book` | -| [getCrossExCoinDiscountRate()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6208) | :closed_lock_with_key: | GET | `/crossex/coin_discount_rate` | -| [getCrossExMarketTickers()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6222) | | GET | `/crossex/market/tickers` | -| [getCrossExMarketFundingInfo()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6236) | | GET | `/crossex/market/funding_info` | -| [getAlphaAccounts()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6254) | :closed_lock_with_key: | GET | `/alpha/accounts` | -| [getAlphaAccountBook()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6266) | :closed_lock_with_key: | GET | `/alpha/account_book` | -| [createAlphaQuote()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6280) | :closed_lock_with_key: | POST | `/alpha/quote` | -| [createAlphaOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6292) | :closed_lock_with_key: | POST | `/alpha/orders` | -| [getAlphaOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6304) | :closed_lock_with_key: | GET | `/alpha/orders` | -| [getAlphaOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6316) | :closed_lock_with_key: | GET | `/alpha/order` | -| [getAlphaCurrencies()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6328) | | GET | `/alpha/currencies` | -| [getAlphaTickers()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6340) | | GET | `/alpha/tickers` | -| [getTradFiMT5Account()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6346) | :closed_lock_with_key: | GET | `/tradfi/users/mt5-account` | -| [getTradFiSymbolCategories()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6350) | | GET | `/tradfi/symbols/categories` | -| [getTradFiSymbols()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6356) | | GET | `/tradfi/symbols` | -| [getTradFiSymbolCommissions()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6368) | :closed_lock_with_key: | GET | `/tradfi/symbols/commissions` | -| [getTradFiSymbolDetail()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6374) | :closed_lock_with_key: | GET | `/tradfi/symbols/detail` | -| [getTradFiKlines()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6380) | | GET | `/tradfi/symbols/{symbol}/klines` | -| [getTradFiTicker()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6387) | | GET | `/tradfi/symbols/{symbol}/tickers` | -| [createTradFiUser()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6391) | :closed_lock_with_key: | POST | `/tradfi/users` | -| [getTradFiAssets()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6395) | :closed_lock_with_key: | GET | `/tradfi/users/assets` | -| [createTradFiTransaction()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6399) | :closed_lock_with_key: | POST | `/tradfi/transactions` | -| [getTradFiTransactions()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6405) | :closed_lock_with_key: | GET | `/tradfi/transactions` | -| [createTradFiOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6411) | :closed_lock_with_key: | POST | `/tradfi/orders` | -| [getTradFiOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6417) | :closed_lock_with_key: | GET | `/tradfi/orders` | -| [modifyTradFiOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6421) | :closed_lock_with_key: | PUT | `/tradfi/orders/{orderId}` | -| [cancelTradFiOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6428) | :closed_lock_with_key: | DELETE | `/tradfi/orders/{orderId}` | -| [getTradFiOrderHistory()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6432) | :closed_lock_with_key: | GET | `/tradfi/orders/history` | -| [getTradFiPositions()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6438) | :closed_lock_with_key: | GET | `/tradfi/positions` | -| [modifyTradFiPosition()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6444) | :closed_lock_with_key: | PUT | `/tradfi/positions/{positionId}` | -| [closeTradFiPosition()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6453) | :closed_lock_with_key: | POST | `/tradfi/positions/{positionId}/close` | -| [getTradFiPositionHistory()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6462) | :closed_lock_with_key: | GET | `/tradfi/positions/history` | -| [getTradFiOrderLog()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6471) | :closed_lock_with_key: | GET | `/tradfi/orders/log/{log_id}` | -| [getStockUserAssets()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6485) | :closed_lock_with_key: | GET | `/stock/users/assets` | -| [getStockSymbols()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6497) | | GET | `/stock/symbols` | -| [getStockSymbolDetail()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6509) | :closed_lock_with_key: | GET | `/stock/symbols/detail` | -| [getStockOrderBook()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6521) | | GET | `/stock/market/{symbol}/orderbook` | -| [getStockOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6531) | :closed_lock_with_key: | GET | `/stock/orders` | -| [createStockOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6545) | :closed_lock_with_key: | POST | `/stock/orders` | -| [cancelAllStockOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6556) | :closed_lock_with_key: | DELETE | `/stock/orders` | -| [getStockOrderHistory()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6566) | :closed_lock_with_key: | GET | `/stock/orders/history` | -| [updateStockOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6579) | :closed_lock_with_key: | PUT | `/stock/orders/{orderId}` | -| [cancelStockOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6592) | :closed_lock_with_key: | DELETE | `/stock/orders/{orderId}` | -| [getStockPositions()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6604) | :closed_lock_with_key: | GET | `/stock/positions` | -| [closeStockPosition()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6616) | :closed_lock_with_key: | POST | `/stock/positions/close` | -| [getStockTransactions()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6628) | :closed_lock_with_key: | GET | `/stock/transactions` | -| [createStockTransaction()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6642) | :closed_lock_with_key: | POST | `/stock/transactions` | -| [getStockExchanges()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6653) | | GET | `/stock/exchanges` | -| [getStockFeeRate()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6664) | | GET | `/stock/fee-rate` | +| [getSystemMaintenanceStatus()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L712) | | GET | `/v1/public/system_info` | +| [listAnnouncementArticles()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L716) | | POST | `/ann/list_article` | +| [submitWithdrawal()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L735) | :closed_lock_with_key: | POST | `/withdrawals` | +| [submitSpotMainAccountTransfer()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L749) | :closed_lock_with_key: | POST | `/withdrawals/push` | +| [cancelWithdrawal()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L765) | :closed_lock_with_key: | DELETE | `/withdrawals/{withdrawal_id}` | +| [getCurrencyChains()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L782) | | GET | `/wallet/currency_chains` | +| [createDepositAddress()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L792) | :closed_lock_with_key: | GET | `/wallet/deposit_address` | +| [getWithdrawalRecords()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L806) | :closed_lock_with_key: | GET | `/wallet/withdrawals` | +| [getDepositRecords()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L820) | :closed_lock_with_key: | GET | `/wallet/deposits` | +| [submitTransfer()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L839) | :closed_lock_with_key: | POST | `/wallet/transfers` | +| [getTransfer()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L851) | :closed_lock_with_key: | GET | `/wallet/transfers` | +| [submitMainSubTransfer()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L863) | :closed_lock_with_key: | POST | `/wallet/sub_account_transfers` | +| [getMainSubTransfers()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L877) | :closed_lock_with_key: | GET | `/wallet/sub_account_transfers` | +| [submitSubToSubTransfer()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L891) | :closed_lock_with_key: | POST | `/wallet/sub_account_to_sub_account` | +| [getTransferStatus()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L906) | :closed_lock_with_key: | GET | `/wallet/order_status` | +| [getWithdrawalStatus()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L922) | :closed_lock_with_key: | GET | `/wallet/withdraw_status` | +| [getSubBalance()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L934) | :closed_lock_with_key: | GET | `/wallet/sub_account_balances` | +| [getSubMarginBalances()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L946) | :closed_lock_with_key: | GET | `/wallet/sub_account_margin_balances` | +| [getSubFuturesBalances()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L958) | :closed_lock_with_key: | GET | `/wallet/sub_account_futures_balances` | +| [getSubCrossMarginBalances()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L971) | :closed_lock_with_key: | GET | `/wallet/sub_account_cross_margin_balances` | +| [getSavedAddresses()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L983) | :closed_lock_with_key: | GET | `/wallet/saved_address` | +| [getTradingFees()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L993) | :closed_lock_with_key: | GET | `/wallet/fee` | +| [getBalances()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1014) | :closed_lock_with_key: | GET | `/wallet/total_balance` | +| [getSmallBalances()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1023) | :closed_lock_with_key: | GET | `/wallet/small_balance` | +| [convertSmallBalance()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1033) | :closed_lock_with_key: | POST | `/wallet/small_balance` | +| [getSmallBalanceHistory()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1046) | :closed_lock_with_key: | GET | `/wallet/small_balance_history` | +| [getPushOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1058) | :closed_lock_with_key: | GET | `/wallet/push` | +| [getLowCapExchangeList()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1067) | :closed_lock_with_key: | GET | `/wallet/getLowCapExchangeList` | +| [createSubAccount()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1082) | :closed_lock_with_key: | POST | `/sub_accounts` | +| [getSubAccounts()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1093) | :closed_lock_with_key: | GET | `/sub_accounts` | +| [getSubAccount()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1103) | :closed_lock_with_key: | GET | `/sub_accounts/{user_id}` | +| [createSubAccountApiKey()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1113) | :closed_lock_with_key: | POST | `/sub_accounts/{user_id}/keys` | +| [getSubAccountApiKeys()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1126) | :closed_lock_with_key: | GET | `/sub_accounts/{user_id}/keys` | +| [updateSubAccountApiKey()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1140) | :closed_lock_with_key: | PUT | `/sub_accounts/{user_id}/keys/{key}` | +| [deleteSubAccountApiKey()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1151) | :closed_lock_with_key: | DELETE | `/sub_accounts/{user_id}/keys/{key}` | +| [getSubAccountApiKey()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1166) | :closed_lock_with_key: | GET | `/sub_accounts/{user_id}/keys/{key}` | +| [lockSubAccount()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1181) | :closed_lock_with_key: | POST | `/sub_accounts/{user_id}/lock` | +| [unlockSubAccount()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1191) | :closed_lock_with_key: | POST | `/sub_accounts/{user_id}/unlock` | +| [getSubAccountMode()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1205) | :closed_lock_with_key: | GET | `/sub_accounts/unified_mode` | +| [getUnifiedAccountInfo()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1224) | :closed_lock_with_key: | GET | `/unified/accounts` | +| [getUnifiedMaxBorrow()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1240) | :closed_lock_with_key: | GET | `/unified/borrowable` | +| [getUnifiedMaxTransferable()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1256) | :closed_lock_with_key: | GET | `/unified/transferable` | +| [getUnifiedMaxTransferables()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1271) | :closed_lock_with_key: | GET | `/unified/transferables` | +| [getUnifiedBatchMaxBorrowable()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1280) | :closed_lock_with_key: | GET | `/unified/batch_borrowable` | +| [submitUnifiedBorrowOrRepay()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1298) | :closed_lock_with_key: | POST | `/unified/loans` | +| [getUnifiedLoans()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1310) | :closed_lock_with_key: | GET | `/unified/loans` | +| [getUnifiedLoanRecords()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1320) | :closed_lock_with_key: | GET | `/unified/loan_records` | +| [getUnifiedInterestRecords()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1332) | :closed_lock_with_key: | GET | `/unified/interest_records` | +| [getUnifiedRiskUnitDetails()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1343) | :closed_lock_with_key: | GET | `/unified/risk_units` | +| [setUnifiedAccountMode()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1355) | :closed_lock_with_key: | PUT | `/unified/unified_mode` | +| [getUnifiedAccountMode()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1364) | :closed_lock_with_key: | GET | `/unified/unified_mode` | +| [getUnifiedEstimateRate()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1376) | :closed_lock_with_key: | GET | `/unified/estimate_rate` | +| [getUnifiedCurrencyDiscountTiers()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1387) | | GET | `/unified/currency_discount_tiers` | +| [getLoanMarginTiers()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1399) | | GET | `/unified/loan_margin_tiers` | +| [portfolioMarginCalculate()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1416) | | POST | `/unified/portfolio_calculator` | +| [setUserLeverage()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1430) | :closed_lock_with_key: | POST | `/unified/leverage/user_setting` | +| [getUserCurrencyLeverageConfig()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1444) | :closed_lock_with_key: | GET | `/unified/leverage/user_currency_config` | +| [getUserCurrencyLeverageSettings()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1458) | :closed_lock_with_key: | GET | `/unified/leverage/user_currency_setting` | +| [updateUserCurrencyLeverage()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1473) | :closed_lock_with_key: | POST | `/unified/leverage/user_currency_setting` | +| [getUnifiedLoanCurrencies()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1488) | :closed_lock_with_key: | GET | `/unified/currencies` | +| [getHistoricalLendingRates()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1500) | :closed_lock_with_key: | GET | `/unified/history_loan_rate` | +| [submitUnifiedLoanRepay()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1506) | :closed_lock_with_key: | POST | `/unified/loans/repay` | +| [getEstimatedQuickRepayment()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1513) | :closed_lock_with_key: | GET | `/unified/estimated_quick_repayment` | +| [createQuickRepayment()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1520) | :closed_lock_with_key: | POST | `/unified/quick_repayment` | +| [setUnifiedDeltaNeutral()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1531) | :closed_lock_with_key: | POST | `/unified/delta_neutral` | +| [getUnifiedDeltaNeutral()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1540) | :closed_lock_with_key: | GET | `/unified/delta_neutral` | +| [getSpotCurrencies()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1560) | | GET | `/spot/currencies` | +| [getSpotCurrency()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1570) | | GET | `/spot/currencies/{currency}` | +| [getSpotCurrencyPairs()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1579) | | GET | `/spot/currency_pairs` | +| [getSpotCurrencyPair()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1589) | | GET | `/spot/currency_pairs/{currency_pair}` | +| [getSpotTicker()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1603) | | GET | `/spot/tickers` | +| [getSpotOrderBook()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1618) | | GET | `/spot/order_book` | +| [getSpotTrades()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1631) | | GET | `/spot/trades` | +| [getSpotCandles()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1643) | | GET | `/spot/candlesticks` | +| [getSpotFeeRates()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1655) | :closed_lock_with_key: | GET | `/spot/fee` | +| [getSpotBatchFeeRates()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1664) | :closed_lock_with_key: | GET | `/spot/batch_fee` | +| [getSpotAccounts()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1676) | :closed_lock_with_key: | GET | `/spot/accounts` | +| [getSpotAccountBook()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1688) | :closed_lock_with_key: | GET | `/spot/account_book` | +| [submitSpotBatchOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1707) | :closed_lock_with_key: | POST | `/spot/batch_orders` | +| [getSpotOpenOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1734) | :closed_lock_with_key: | GET | `/spot/open_orders` | +| [submitSpotClosePosCrossDisabled()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1750) | :closed_lock_with_key: | POST | `/spot/cross_liquidate_orders` | +| [submitSpotOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1766) | :closed_lock_with_key: | POST | `/spot/orders` | +| [getSpotOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1783) | :closed_lock_with_key: | GET | `/spot/orders` | +| [cancelSpotOpenOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1798) | :closed_lock_with_key: | DELETE | `/spot/orders` | +| [batchCancelSpotOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1827) | :closed_lock_with_key: | POST | `/spot/cancel_batch_orders` | +| [getSpotOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1852) | :closed_lock_with_key: | GET | `/spot/orders/{order_id}` | +| [updateSpotOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1869) | :closed_lock_with_key: | PATCH | `/spot/orders/{order_id}` | +| [cancelSpotOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1897) | :closed_lock_with_key: | DELETE | `/spot/orders/{order_id}` | +| [getSpotTradingHistory()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1926) | :closed_lock_with_key: | GET | `/spot/my_trades` | +| [submitSpotCountdownOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1955) | :closed_lock_with_key: | POST | `/spot/countdown_cancel_all` | +| [batchUpdateSpotOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L1974) | :closed_lock_with_key: | POST | `/spot/amend_batch_orders` | +| [getSpotInsuranceHistory()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2001) | :closed_lock_with_key: | GET | `/spot/insurance_history` | +| [submitSpotPriceTriggerOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2015) | :closed_lock_with_key: | POST | `/spot/price_orders` | +| [getSpotAutoOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2027) | :closed_lock_with_key: | GET | `/spot/price_orders` | +| [cancelAllOpenSpotOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2039) | :closed_lock_with_key: | DELETE | `/spot/price_orders` | +| [getPriceTriggeredOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2052) | :closed_lock_with_key: | GET | `/spot/price_orders/{order_id}` | +| [cancelSpotTriggeredOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2064) | :closed_lock_with_key: | DELETE | `/spot/price_orders/{order_id}` | +| [getSpotPovOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2078) | :closed_lock_with_key: | GET | `/spot/pov_orders` | +| [createSpotPovOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2090) | :closed_lock_with_key: | POST | `/spot/pov_orders` | +| [cancelSpotPovOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2102) | :closed_lock_with_key: | DELETE | `/spot/pov_orders` | +| [getSpotPovOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2116) | :closed_lock_with_key: | GET | `/spot/pov_orders/{order_id}` | +| [cancelSpotPovOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2128) | :closed_lock_with_key: | DELETE | `/spot/pov_orders/{order_id}` | +| [setCollateralCurrency()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2140) | :closed_lock_with_key: | POST | `/unified/collateral_currencies` | +| [getMarginAccounts()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2161) | :closed_lock_with_key: | GET | `/margin/accounts` | +| [getMarginBalanceHistory()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2175) | :closed_lock_with_key: | GET | `/margin/account_book` | +| [getFundingAccounts()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2193) | :closed_lock_with_key: | GET | `/margin/funding_accounts` | +| [updateAutoRepaymentSetting()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2211) | :closed_lock_with_key: | POST | `/margin/auto_repay` | +| [getAutoRepaymentSetting()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2222) | :closed_lock_with_key: | GET | `/margin/auto_repay` | +| [getMarginTransferableAmount()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2236) | :closed_lock_with_key: | GET | `/margin/transferable` | +| [getCrossMarginCurrencies()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2253) | | GET | `/margin/cross/currencies` | +| [getCrossMarginCurrency()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2264) | | GET | `/margin/cross/currencies/{currency}` | +| [getCrossMarginAccount()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2276) | :closed_lock_with_key: | GET | `/margin/cross/accounts` | +| [getCrossMarginAccountHistory()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2289) | :closed_lock_with_key: | GET | `/margin/cross/account_book` | +| [submitCrossMarginBorrowLoan()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2306) | :closed_lock_with_key: | POST | `/margin/cross/loans` | +| [getCrossMarginBorrowHistory()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2321) | :closed_lock_with_key: | GET | `/margin/cross/loans` | +| [getCrossMarginBorrowLoan()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2334) | :closed_lock_with_key: | GET | `/margin/cross/loans/{loan_id}` | +| [submitCrossMarginRepayment()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2349) | :closed_lock_with_key: | POST | `/margin/cross/repayments` | +| [getCrossMarginRepayments()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2365) | :closed_lock_with_key: | GET | `/margin/cross/repayments` | +| [getCrossMarginInterestRecords()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2378) | :closed_lock_with_key: | GET | `/margin/cross/interest_records` | +| [getCrossMarginTransferableAmount()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2394) | :closed_lock_with_key: | GET | `/margin/cross/transferable` | +| [getEstimatedInterestRates()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2410) | :closed_lock_with_key: | GET | `/margin/cross/estimate_rate` | +| [getCrossMarginBorrowableAmount()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2424) | :closed_lock_with_key: | GET | `/margin/cross/borrowable` | +| [getMarginUserLoanTiers()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2437) | :closed_lock_with_key: | GET | `/margin/user/loan_margin_tiers` | +| [getMarginPublicLoanTiers()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2453) | | GET | `/margin/loan_margin_tiers` | +| [setMarginUserLeverage()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2469) | :closed_lock_with_key: | POST | `/margin/leverage/user_market_setting` | +| [getMarginUserAccounts()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2486) | :closed_lock_with_key: | GET | `/margin/user/account` | +| [getLendingMarkets()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2501) | | GET | `/margin/uni/currency_pairs` | +| [getLendingMarket()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2516) | | GET | `/margin/uni/currency_pairs/{currency_pair}` | +| [getEstimatedInterestRate()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2528) | :closed_lock_with_key: | GET | `/margin/uni/estimate_rate` | +| [submitMarginUNIBorrowOrRepay()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2538) | :closed_lock_with_key: | POST | `/margin/uni/loans` | +| [getMarginUNILoans()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2554) | :closed_lock_with_key: | GET | `/margin/uni/loans` | +| [getMarginUNILoanRecords()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2564) | :closed_lock_with_key: | GET | `/margin/uni/loan_records` | +| [getMarginUNIInterestRecords()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2576) | :closed_lock_with_key: | GET | `/margin/uni/interest_records` | +| [getMarginUNIMaxBorrow()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2588) | :closed_lock_with_key: | GET | `/margin/uni/borrowable` | +| [getFlashSwapCurrencyPairs()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2604) | | GET | `/flash_swap/currency_pairs` | +| [submitFlashSwapOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2620) | :closed_lock_with_key: | POST | `/flash_swap/orders` | +| [getFlashSwapOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2632) | :closed_lock_with_key: | GET | `/flash_swap/orders` | +| [getFlashSwapOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2644) | :closed_lock_with_key: | GET | `/flash_swap/orders/{order_id}` | +| [submitFlashSwapOrderPreview()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2654) | :closed_lock_with_key: | POST | `/flash_swap/orders/preview` | +| [getFuturesContracts()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2671) | | GET | `/futures/{settle}/contracts` | +| [getFuturesContract()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2686) | | GET | `/futures/{settle}/contracts/{contract}` | +| [listFuturesADLRiskStates()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2693) | | GET | `/futures/{settle}/adl_risk_states` | +| [getFuturesOrderBook()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2707) | | GET | `/futures/{settle}/order_book` | +| [getFuturesTrades()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2720) | | GET | `/futures/{settle}/trades` | +| [getFuturesCandles()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2735) | | GET | `/futures/{settle}/candlesticks` | +| [getPremiumIndexKLines()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2748) | | GET | `/futures/{settle}/premium_index` | +| [getFuturesTickers()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2761) | | GET | `/futures/{settle}/tickers` | +| [getFundingRates()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2778) | | GET | `/futures/{settle}/funding_rate` | +| [getBatchFundingRates()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2794) | | POST | `/futures/{settle}/funding_rates` | +| [getFuturesInsuranceBalanceHistory()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2812) | | GET | `/futures/{settle}/insurance` | +| [getFuturesStats()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2831) | | GET | `/futures/{settle}/contract_stats` | +| [getIndexConstituents()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2842) | | GET | `/futures/{settle}/index_constituents/{index}` | +| [getLiquidationHistory()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2859) | | GET | `/futures/{settle}/liq_orders` | +| [getRiskLimitTiers()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2876) | | GET | `/futures/{settle}/risk_limit_tiers` | +| [getFuturesAccount()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2889) | :closed_lock_with_key: | GET | `/futures/{settle}/accounts` | +| [getFuturesAccountBook()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2903) | :closed_lock_with_key: | GET | `/futures/{settle}/account_book` | +| [getFuturesPositions()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2916) | :closed_lock_with_key: | GET | `/futures/{settle}/positions` | +| [getFuturesPosition()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2931) | :closed_lock_with_key: | GET | `/futures/{settle}/positions/{contract}` | +| [updateFuturesMargin()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2948) | :closed_lock_with_key: | POST | `/futures/{settle}/positions/{contract}/margin` | +| [updateFuturesLeverage()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2976) | :closed_lock_with_key: | POST | `/futures/{settle}/positions/{contract}/leverage` | +| [getFuturesContractLeverage()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L2996) | :closed_lock_with_key: | GET | `/futures/{settle}/get_leverage/{contract}` | +| [updateFuturesPositionMode()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3012) | :closed_lock_with_key: | POST | `/futures/{settle}/positions/cross_mode` | +| [updatePositionRiskLimit()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3029) | :closed_lock_with_key: | POST | `/futures/{settle}/positions/{contract}/risk_limit` | +| [updateFuturesDualMode()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3049) | :closed_lock_with_key: | POST | `/futures/{settle}/dual_mode` | +| [getDualModePosition()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3065) | :closed_lock_with_key: | GET | `/futures/{settle}/dual_comp/positions/{contract}` | +| [updateDualModePositionMargin()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3080) | :closed_lock_with_key: | POST | `/futures/{settle}/dual_comp/positions/{contract}/margin` | +| [updateDualModePositionLeverage()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3096) | :closed_lock_with_key: | POST | `/futures/{settle}/dual_comp/positions/{contract}/leverage` | +| [updateDualModePositionRiskLimit()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3120) | :closed_lock_with_key: | POST | `/futures/{settle}/dual_comp/positions/{contract}/risk_limit` | +| [submitFuturesOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3147) | :closed_lock_with_key: | POST | `/futures/{settle}/orders` | +| [getFuturesOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3168) | :closed_lock_with_key: | GET | `/futures/{settle}/orders` | +| [cancelAllFuturesOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3183) | :closed_lock_with_key: | DELETE | `/futures/{settle}/orders` | +| [getFuturesOrdersByTimeRange()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3203) | :closed_lock_with_key: | GET | `/futures/{settle}/orders_timerange` | +| [submitFuturesBatchOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3226) | :closed_lock_with_key: | POST | `/futures/{settle}/batch_orders` | +| [getFuturesOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3251) | :closed_lock_with_key: | GET | `/futures/{settle}/orders/{order_id}` | +| [cancelFuturesOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3268) | :closed_lock_with_key: | DELETE | `/futures/{settle}/orders/{order_id}` | +| [updateFuturesOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3293) | :closed_lock_with_key: | PUT | `/futures/{settle}/orders/{order_id}` | +| [getFuturesTradingHistory()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3314) | :closed_lock_with_key: | GET | `/futures/{settle}/my_trades` | +| [getFuturesTradingHistoryByTimeRange()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3329) | :closed_lock_with_key: | GET | `/futures/{settle}/my_trades_timerange` | +| [getFuturesPositionHistory()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3342) | :closed_lock_with_key: | GET | `/futures/{settle}/position_close` | +| [getFuturesLiquidationHistory()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3355) | :closed_lock_with_key: | GET | `/futures/{settle}/liquidates` | +| [getFuturesAutoDeleveragingHistory()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3368) | :closed_lock_with_key: | GET | `/futures/{settle}/auto_deleverages` | +| [setFuturesOrderCancelCountdown()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3385) | :closed_lock_with_key: | POST | `/futures/{settle}/countdown_cancel_all` | +| [getFuturesUserTradingFees()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3402) | :closed_lock_with_key: | GET | `/futures/{settle}/fee` | +| [batchCancelFuturesOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3420) | :closed_lock_with_key: | POST | `/futures/{settle}/batch_cancel_orders` | +| [batchUpdateFuturesOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3447) | :closed_lock_with_key: | POST | `/futures/{settle}/batch_amend_orders` | +| [getRiskLimitTable()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3469) | | GET | `/futures/{settle}/risk_limit_table` | +| [submitFuturesPriceTriggeredOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3482) | :closed_lock_with_key: | POST | `/futures/{settle}/price_orders` | +| [getFuturesAutoOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3495) | :closed_lock_with_key: | GET | `/futures/{settle}/price_orders` | +| [cancelAllOpenFuturesOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3508) | :closed_lock_with_key: | DELETE | `/futures/{settle}/price_orders` | +| [getFuturesPriceTriggeredOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3524) | :closed_lock_with_key: | GET | `/futures/{settle}/price_orders/{order_id}` | +| [cancelFuturesPriceTriggeredOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3539) | :closed_lock_with_key: | DELETE | `/futures/{settle}/price_orders/{order_id}` | +| [updateFuturesPriceTriggeredOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3554) | :closed_lock_with_key: | PUT | `/futures/{settle}/price_orders/amend` | +| [createTrailOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3569) | :closed_lock_with_key: | POST | `/futures/{settle}/autoorder/v1/trail/create` | +| [terminateTrailOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3587) | :closed_lock_with_key: | POST | `/futures/{settle}/autoorder/v1/trail/stop` | +| [batchTerminateTrailOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3600) | :closed_lock_with_key: | POST | `/futures/{settle}/autoorder/v1/trail/stop_all` | +| [getTrailOrderList()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3615) | :closed_lock_with_key: | GET | `/futures/{settle}/autoorder/v1/trail/list` | +| [getTrailOrderDetail()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3628) | :closed_lock_with_key: | GET | `/futures/{settle}/autoorder/v1/trail/detail` | +| [updateTrailOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3646) | :closed_lock_with_key: | POST | `/futures/{settle}/autoorder/v1/trail/update` | +| [getTrailOrderChangeLog()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3659) | :closed_lock_with_key: | GET | `/futures/{settle}/autoorder/v1/trail/change_log` | +| [createChaseOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3672) | :closed_lock_with_key: | POST | `/futures/{settle}/autoorder/v1/chase/create` | +| [stopChaseOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3682) | :closed_lock_with_key: | POST | `/futures/{settle}/autoorder/v1/chase/stop` | +| [stopAllChaseOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3692) | :closed_lock_with_key: | POST | `/futures/{settle}/autoorder/v1/chase/stop_all` | +| [getChaseOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3704) | :closed_lock_with_key: | GET | `/futures/{settle}/autoorder/v1/chase/list` | +| [getChaseOrderDetail()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3712) | :closed_lock_with_key: | GET | `/futures/{settle}/autoorder/v1/chase/detail` | +| [getFuturesPositionCloseHistory()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3721) | :closed_lock_with_key: | GET | `/futures/{settle}/position_close_history` | +| [getFuturesInsuranceHistory()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3730) | :closed_lock_with_key: | GET | `/futures/{settle}/insurance` | +| [getAllDeliveryContracts()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3747) | | GET | `/delivery/{settle}/contracts` | +| [getDeliveryContract()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3759) | | GET | `/delivery/{settle}/contracts/{contract}` | +| [getDeliveryOrderBook()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3774) | | GET | `/delivery/{settle}/order_book` | +| [getDeliveryTrades()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3787) | | GET | `/delivery/{settle}/trades` | +| [getDeliveryCandles()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3801) | | GET | `/delivery/{settle}/candlesticks` | +| [getDeliveryTickers()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3812) | | GET | `/delivery/{settle}/tickers` | +| [getDeliveryInsuranceBalanceHistory()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3829) | | GET | `/delivery/{settle}/insurance` | +| [getDeliveryAccount()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3848) | :closed_lock_with_key: | GET | `/delivery/{settle}/accounts` | +| [getDeliveryBook()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3859) | :closed_lock_with_key: | GET | `/delivery/{settle}/account_book` | +| [getDeliveryPositions()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3870) | :closed_lock_with_key: | GET | `/delivery/{settle}/positions` | +| [getDeliveryPosition()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3880) | :closed_lock_with_key: | GET | `/delivery/{settle}/positions/{contract}` | +| [updateDeliveryMargin()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3895) | :closed_lock_with_key: | POST | `/delivery/{settle}/positions/{contract}/margin` | +| [updateDeliveryLeverage()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3913) | :closed_lock_with_key: | POST | `/delivery/{settle}/positions/{contract}/leverage` | +| [updateDeliveryRiskLimit()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3931) | :closed_lock_with_key: | POST | `/delivery/{settle}/positions/{contract}/risk_limit` | +| [submitDeliveryOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3951) | :closed_lock_with_key: | POST | `/delivery/{settle}/orders` | +| [getDeliveryOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3966) | :closed_lock_with_key: | GET | `/delivery/{settle}/orders` | +| [cancelAllDeliveryOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3979) | :closed_lock_with_key: | DELETE | `/delivery/{settle}/orders` | +| [getDeliveryOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3998) | :closed_lock_with_key: | GET | `/delivery/{settle}/orders/{order_id}` | +| [cancelDeliveryOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4013) | :closed_lock_with_key: | DELETE | `/delivery/{settle}/orders/{order_id}` | +| [getDeliveryTradingHistory()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4028) | :closed_lock_with_key: | GET | `/delivery/{settle}/my_trades` | +| [getDeliveryClosedPositions()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4041) | :closed_lock_with_key: | GET | `/delivery/{settle}/position_close` | +| [getDeliveryLiquidationHistory()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4054) | :closed_lock_with_key: | GET | `/delivery/{settle}/liquidates` | +| [getDeliverySettlementHistory()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4067) | :closed_lock_with_key: | GET | `/delivery/{settle}/settlements` | +| [submitDeliveryTriggeredOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4080) | :closed_lock_with_key: | POST | `/delivery/{settle}/price_orders` | +| [getDeliveryAutoOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4095) | :closed_lock_with_key: | GET | `/delivery/{settle}/price_orders` | +| [cancelAllOpenDeliveryOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4108) | :closed_lock_with_key: | DELETE | `/delivery/{settle}/price_orders` | +| [getDeliveryTriggeredOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4124) | :closed_lock_with_key: | GET | `/delivery/{settle}/price_orders/{order_id}` | +| [cancelTriggeredDeliveryOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4139) | :closed_lock_with_key: | DELETE | `/delivery/{settle}/price_orders/{order_id}` | +| [getOptionsUnderlyings()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4158) | | GET | `/options/underlyings` | +| [getOptionsExpirationTimes()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4168) | | GET | `/options/expirations` | +| [getOptionsContracts()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4178) | | GET | `/options/contracts` | +| [getOptionsContract()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4191) | | GET | `/options/contracts/{contract}` | +| [getOptionsSettlementHistory()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4201) | | GET | `/options/settlements` | +| [getOptionsContractSettlement()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4213) | | GET | `/options/settlements/{contract}` | +| [getOptionsMySettlements()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4228) | :closed_lock_with_key: | GET | `/options/my_settlements` | +| [getOptionsOrderBook()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4242) | | GET | `/options/order_book` | +| [getOptionsTickers()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4254) | | GET | `/options/tickers` | +| [getOptionsUnderlyingTicker()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4268) | | GET | `/options/underlying/tickers/{underlying}` | +| [getOptionsCandles()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4282) | | GET | `/options/candlesticks` | +| [getOptionsUnderlyingCandles()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4292) | | GET | `/options/underlying/candlesticks` | +| [getOptionsTrades()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4304) | | GET | `/options/trades` | +| [getOptionsAccount()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4315) | :closed_lock_with_key: | GET | `/options/accounts` | +| [getOptionsAccountChange()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4325) | :closed_lock_with_key: | GET | `/options/account_book` | +| [getOptionsPositionsUnderlying()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4337) | :closed_lock_with_key: | GET | `/options/positions` | +| [getOptionsPositionContract()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4349) | :closed_lock_with_key: | GET | `/options/positions/{contract}` | +| [getOptionsLiquidation()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4361) | :closed_lock_with_key: | GET | `/options/position_close` | +| [submitOptionsOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4374) | :closed_lock_with_key: | POST | `/options/orders` | +| [getOptionsOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4386) | :closed_lock_with_key: | GET | `/options/orders` | +| [cancelAllOpenOptionsOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4398) | :closed_lock_with_key: | DELETE | `/options/orders` | +| [getOptionsOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4412) | :closed_lock_with_key: | GET | `/options/orders/{order_id}` | +| [amendOptionsOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4424) | :closed_lock_with_key: | PUT | `/options/orders/{order_id}` | +| [cancelOptionsOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4439) | :closed_lock_with_key: | DELETE | `/options/orders/{order_id}` | +| [submitOptionsCountdownCancel()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4458) | :closed_lock_with_key: | POST | `/options/countdown_cancel_all` | +| [getOptionsPersonalHistory()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4474) | :closed_lock_with_key: | GET | `/options/my_trades` | +| [setOptionsMMPSettings()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4486) | :closed_lock_with_key: | POST | `/options/mmp` | +| [getOptionsMMPSettings()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4498) | :closed_lock_with_key: | GET | `/options/mmp` | +| [resetOptionsMMPSettings()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4510) | :closed_lock_with_key: | POST | `/options/mmp/reset` | +| [getLendingCurrencies()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4526) | | GET | `/earn/uni/currencies` | +| [getLendingCurrency()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4536) | | GET | `/earn/uni/currencies/{currency}` | +| [submitLendOrRedeemOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4546) | :closed_lock_with_key: | POST | `/earn/uni/lends` | +| [getLendingOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4556) | :closed_lock_with_key: | GET | `/earn/uni/lends` | +| [updateLendingOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4568) | :closed_lock_with_key: | PATCH | `/earn/uni/lends` | +| [getLendingRecords()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4581) | :closed_lock_with_key: | GET | `/earn/uni/lend_records` | +| [getLendingTotalInterest()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4594) | :closed_lock_with_key: | GET | `/earn/uni/interests/{currency}` | +| [getLendingInterestRecords()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4607) | :closed_lock_with_key: | GET | `/earn/uni/interest_records` | +| [updateInterestReinvestment()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4620) | :closed_lock_with_key: | PUT | `/earn/uni/interest_reinvest` | +| [getLendingInterestStatus()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4636) | :closed_lock_with_key: | GET | `/earn/uni/interest_status/{currency}` | +| [getLendingAnnualizedTrendChart()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4651) | :closed_lock_with_key: | GET | `/earn/uni/chart` | +| [getLendingEstimatedRates()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4659) | :closed_lock_with_key: | GET | `/earn/uni/rate` | +| [submitMultiLoanOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4676) | :closed_lock_with_key: | POST | `/loan/multi_collateral/orders` | +| [getMultiLoanOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4688) | :closed_lock_with_key: | GET | `/loan/multi_collateral/orders` | +| [getMultiLoanOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4700) | :closed_lock_with_key: | GET | `/loan/multi_collateral/orders/{order_id}` | +| [repayMultiLoan()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4710) | :closed_lock_with_key: | POST | `/loan/multi_collateral/repay` | +| [getMultiLoanRepayRecords()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4720) | :closed_lock_with_key: | GET | `/loan/multi_collateral/repay` | +| [updateMultiLoan()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4732) | :closed_lock_with_key: | POST | `/loan/multi_collateral/mortgage` | +| [getMultiLoanAdjustmentRecords()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4744) | :closed_lock_with_key: | GET | `/loan/multi_collateral/mortgage` | +| [getMultiLoanCurrencyQuota()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4756) | :closed_lock_with_key: | GET | `/loan/multi_collateral/currency_quota` | +| [getMultiLoanSupportedCurrencies()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4768) | | GET | `/loan/multi_collateral/currencies` | +| [getMultiLoanRatio()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4777) | | GET | `/loan/multi_collateral/ltv` | +| [getMultiLoanFixedRates()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4786) | | GET | `/loan/multi_collateral/fixed_rate` | +| [getMultiLoanCurrentRates()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4799) | | GET | `/loan/multi_collateral/current_rate` | +| [getDualInvestmentProducts()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4821) | | GET | `/earn/dual/investment_plan` | +| [getDualInvestmentOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4832) | :closed_lock_with_key: | GET | `/earn/dual/orders` | +| [submitDualInvestmentOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4844) | :closed_lock_with_key: | POST | `/earn/dual/orders` | +| [getDualOrderRefundPreview()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4853) | :closed_lock_with_key: | GET | `/earn/dual/order-refund-preview` | +| [submitDualOrderRefund()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4862) | :closed_lock_with_key: | POST | `/earn/dual/order-refund` | +| [updateDualOrderReinvest()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4871) | :closed_lock_with_key: | POST | `/earn/dual/modify-order-reinvest` | +| [getDualProjectRecommend()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4882) | :closed_lock_with_key: | GET | `/earn/dual/project-recommend` | +| [getEarnFixedTermProducts()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4891) | | GET | `/earn/fixed-term/product` | +| [getEarnFixedTermProductsByAsset()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4900) | | GET | `/earn/fixed-term/product/{asset}/list` | +| [createEarnFixedTermLend()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4910) | :closed_lock_with_key: | POST | `/earn/fixed-term/user/lend` | +| [getEarnFixedTermLends()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4919) | :closed_lock_with_key: | GET | `/earn/fixed-term/user/lend` | +| [createEarnFixedTermPreRedeem()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4928) | :closed_lock_with_key: | POST | `/earn/fixed-term/user/pre-redeem` | +| [getEarnFixedTermHistory()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4939) | :closed_lock_with_key: | GET | `/earn/fixed-term/user/history` | +| [createAutoInvestPlan()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4948) | :closed_lock_with_key: | POST | `/earn/autoinvest/plans/create` | +| [updateAutoInvestPlan()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4957) | :closed_lock_with_key: | POST | `/earn/autoinvest/plans/update` | +| [stopAutoInvestPlan()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4964) | :closed_lock_with_key: | POST | `/earn/autoinvest/plans/stop` | +| [addAutoInvestPlanPosition()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4971) | :closed_lock_with_key: | POST | `/earn/autoinvest/plans/add_position` | +| [getAutoInvestCoins()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4982) | :closed_lock_with_key: | GET | `/earn/autoinvest/coins` | +| [getAutoInvestMinAmount()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4991) | :closed_lock_with_key: | POST | `/earn/autoinvest/min_invest_amount` | +| [getAutoInvestPlanRecords()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5002) | :closed_lock_with_key: | GET | `/earn/autoinvest/plans/records` | +| [getAutoInvestOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5011) | :closed_lock_with_key: | GET | `/earn/autoinvest/orders` | +| [getAutoInvestConfig()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5020) | :closed_lock_with_key: | GET | `/earn/autoinvest/config` | +| [getAutoInvestPlanDetail()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5027) | :closed_lock_with_key: | GET | `/earn/autoinvest/plans/detail` | +| [getAutoInvestPlans()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5036) | :closed_lock_with_key: | GET | `/earn/autoinvest/plans/list_info` | +| [getStakingCoins()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5048) | :closed_lock_with_key: | GET | `/earn/staking/coins` | +| [submitStakingSwap()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5061) | :closed_lock_with_key: | POST | `/earn/staking/swap` | +| [getAccountDetail()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5080) | :closed_lock_with_key: | GET | `/account/detail` | +| [getAccountRateLimit()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5089) | :closed_lock_with_key: | GET | `/account/rate_limit` | +| [createStpGroup()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5099) | :closed_lock_with_key: | POST | `/account/stp_groups` | +| [getStpGroups()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5109) | :closed_lock_with_key: | GET | `/account/stp_groups` | +| [getStpGroupUsers()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5119) | :closed_lock_with_key: | GET | `/account/stp_groups/{stp_id}/users` | +| [addUsersToStpGroup()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5129) | :closed_lock_with_key: | POST | `/account/stp_groups/{stp_id}/users` | +| [deleteUserFromStpGroup()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5145) | :closed_lock_with_key: | DELETE | `/account/stp_groups/{stp_id}/users` | +| [setGTDeduction()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5163) | :closed_lock_with_key: | POST | `/account/debit_fee` | +| [getGTDeduction()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5174) | :closed_lock_with_key: | GET | `/account/debit_fee` | +| [getAccountMainKeys()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5183) | :closed_lock_with_key: | GET | `/account/main_keys` | +| [getAgencyTransactionHistory()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5199) | :closed_lock_with_key: | GET | `/rebate/agency/transaction_history` | +| [getAgencyCommissionHistory()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5212) | :closed_lock_with_key: | GET | `/rebate/agency/commission_history` | +| [getPartnerTransactionHistory()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5226) | :closed_lock_with_key: | GET | `/rebate/partner/transaction_history` | +| [getPartnerCommissionHistory()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5241) | :closed_lock_with_key: | GET | `/rebate/partner/commission_history` | +| [getPartnerSubordinateList()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5264) | :closed_lock_with_key: | GET | `/rebate/partner/sub_list` | +| [getPartnerAgentDataAggregated()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5274) | :closed_lock_with_key: | GET | `/rebate/partner/data/aggregated` | +| [getBrokerCommissionHistory()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5287) | :closed_lock_with_key: | GET | `/rebate/broker/commission_history` | +| [getBrokerTransactionHistory()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5300) | :closed_lock_with_key: | GET | `/rebate/broker/transaction_history` | +| [getUserRebateInfo()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5309) | :closed_lock_with_key: | GET | `/rebate/user/info` | +| [createOTCQuote()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5344) | :closed_lock_with_key: | POST | `/otc/quote` | +| [createOTCFiatOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5356) | :closed_lock_with_key: | POST | `/otc/order/create` | +| [createOTCStablecoinOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5370) | :closed_lock_with_key: | POST | `/otc/stable_coin/order/create` | +| [getOTCBankList()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5379) | :closed_lock_with_key: | GET | `/otc/bank/list` | +| [getOTCBankListLegacy()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5386) | :closed_lock_with_key: | GET | `/otc/bank_list` | +| [createOTCUploadPreUpload()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5390) | :closed_lock_with_key: | POST | `/otc/upload/pre_upload` | +| [createOTCBank()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5399) | :closed_lock_with_key: | POST | `/otc/bank/create` | +| [deleteOTCBank()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5413) | :closed_lock_with_key: | POST | `/otc/bank/delete` | +| [setDefaultOTCBank()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5420) | :closed_lock_with_key: | POST | `/otc/bank/set_default` | +| [getOTCBankSupplementChecklist()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5427) | :closed_lock_with_key: | GET | `/otc/bank/bank_supplement_checklist` | +| [submitOTCBankPersonalSupplement()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5436) | :closed_lock_with_key: | POST | `/otc/order/paid` | +| [submitOTCBankEnterpriseSupplement()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5455) | :closed_lock_with_key: | POST | `/otc/order/paid` | +| [markOTCOrderAsPaid()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5491) | :closed_lock_with_key: | POST | `/otc/order/paid` | +| [cancelOTCOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5505) | :closed_lock_with_key: | POST | `/otc/order/cancel` | +| [getOTCFiatOrderList()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5517) | :closed_lock_with_key: | GET | `/otc/order/list` | +| [getOTCStablecoinOrderList()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5531) | :closed_lock_with_key: | GET | `/otc/stable_coin/order/list` | +| [getOTCFiatOrderDetail()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5545) | :closed_lock_with_key: | GET | `/otc/order/detail` | +| [getP2PMerchantUserInfo()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5559) | :closed_lock_with_key: | POST | `/p2p/merchant/account/get_user_info` | +| [getP2PMerchantCounterpartyUserInfo()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5568) | :closed_lock_with_key: | POST | `/p2p/merchant/account/get_counterparty_user_info` | +| [getP2PMerchantMyselfPayment()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5580) | :closed_lock_with_key: | POST | `/p2p/merchant/account/get_myself_payment` | +| [getP2PMerchantSpotBalance()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5593) | :closed_lock_with_key: | POST | `/p2p/merchant/account/set_merchant_work_hours` | +| [setP2PMerchantWorkHours()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5602) | :closed_lock_with_key: | POST | `/p2p/merchant/account/set_merchant_work_hours` | +| [getP2PMerchantPendingTransactionList()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5613) | :closed_lock_with_key: | POST | `/p2p/merchant/transaction/get_pending_transaction_list` | +| [getP2PMerchantCompletedTransactionList()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5625) | :closed_lock_with_key: | POST | `/p2p/merchant/transaction/get_completed_transaction_list` | +| [getP2PMerchantTransactionDetails()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5637) | :closed_lock_with_key: | POST | `/p2p/merchant/transaction/get_transaction_details` | +| [confirmP2PMerchantPayment()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5649) | :closed_lock_with_key: | POST | `/p2p/merchant/transaction/confirm-payment` | +| [confirmP2PMerchantReceipt()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5660) | :closed_lock_with_key: | POST | `/p2p/merchant/transaction/confirm-receipt` | +| [cancelP2PMerchantTransaction()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5671) | :closed_lock_with_key: | POST | `/p2p/merchant/transaction/cancel` | +| [placeP2PMerchantBizPushOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5682) | :closed_lock_with_key: | POST | `/p2p/merchant/books/place_biz_push_order` | +| [updateP2PMerchantAdsStatus()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5693) | :closed_lock_with_key: | POST | `/p2p/merchant/books/ads_update_status` | +| [getP2PMerchantAdsDetail()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5706) | :closed_lock_with_key: | POST | `/p2p/merchant/books/ads_detail` | +| [getP2PMerchantMyAdsList()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5715) | :closed_lock_with_key: | POST | `/p2p/merchant/books/my_ads_list` | +| [getP2PMerchantAdsList()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5726) | :closed_lock_with_key: | POST | `/p2p/merchant/books/ads_list` | +| [getP2PMerchantChatsList()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5735) | :closed_lock_with_key: | POST | `/p2p/merchant/chat/get_chats_list` | +| [sendP2PMerchantChatMessage()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5746) | :closed_lock_with_key: | POST | `/p2p/merchant/chat/send_chat_message` | +| [uploadP2PMerchantChatFile()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5757) | :closed_lock_with_key: | POST | `/p2p/merchant/chat/upload_chat_file` | +| [getCrossExSymbols()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5778) | | GET | `/crossex/rule/symbols` | +| [getCrossExRiskLimits()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5790) | | GET | `/crossex/rule/risk_limits` | +| [getCrossExTransferCoins()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5804) | | GET | `/crossex/transfers/coin` | +| [createCrossExTransfer()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5818) | :closed_lock_with_key: | POST | `/crossex/transfers` | +| [getCrossExTransferHistory()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5832) | :closed_lock_with_key: | GET | `/crossex/transfers` | +| [createCrossExOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5846) | :closed_lock_with_key: | POST | `/crossex/orders` | +| [cancelBatchCrossExOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5860) | :closed_lock_with_key: | POST | `/crossex/batch_cancel_orders` | +| [cancelCrossExOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5874) | :closed_lock_with_key: | DELETE | `/crossex/orders/{order_id}` | +| [modifyCrossExOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5887) | :closed_lock_with_key: | PUT | `/crossex/orders/{order_id}` | +| [getCrossExOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5902) | :closed_lock_with_key: | GET | `/crossex/orders/{order_id}` | +| [createCrossExConvertQuote()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5914) | :closed_lock_with_key: | POST | `/crossex/convert/quote` | +| [createCrossExConvertOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5928) | :closed_lock_with_key: | POST | `/crossex/convert/orders` | +| [updateCrossExAccount()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5942) | :closed_lock_with_key: | PUT | `/crossex/accounts` | +| [getCrossExAccounts()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5956) | :closed_lock_with_key: | GET | `/crossex/accounts` | +| [setCrossExPositionLeverage()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5968) | :closed_lock_with_key: | POST | `/crossex/positions/leverage` | +| [getCrossExPositionLeverage()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5982) | :closed_lock_with_key: | GET | `/crossex/positions/leverage` | +| [setCrossExMarginPositionLeverage()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5996) | :closed_lock_with_key: | POST | `/crossex/margin_positions/leverage` | +| [getCrossExMarginPositionLeverage()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6012) | :closed_lock_with_key: | GET | `/crossex/margin_positions/leverage` | +| [closeCrossExPosition()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6026) | :closed_lock_with_key: | POST | `/crossex/position` | +| [updateCrossExPositionsMargin()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6032) | :closed_lock_with_key: | POST | `/crossex/positions/margin` | +| [getCrossExInterestRate()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6046) | :closed_lock_with_key: | GET | `/crossex/interest_rate` | +| [getCrossExFeeRate()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6059) | :closed_lock_with_key: | GET | `/crossex/fee` | +| [getCrossExPositions()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6071) | :closed_lock_with_key: | GET | `/crossex/positions` | +| [getCrossExMarginPositions()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6085) | :closed_lock_with_key: | GET | `/crossex/margin_positions` | +| [getCrossExAdlRank()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6099) | :closed_lock_with_key: | GET | `/crossex/adl_rank` | +| [getCrossExOpenOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6111) | :closed_lock_with_key: | GET | `/crossex/open_orders` | +| [getCrossExHistoryOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6125) | :closed_lock_with_key: | GET | `/crossex/history_orders` | +| [getCrossExHistoryPositions()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6139) | :closed_lock_with_key: | GET | `/crossex/history_positions` | +| [getCrossExHistoryMarginPositions()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6153) | :closed_lock_with_key: | GET | `/crossex/history_margin_positions` | +| [getCrossExHistoryMarginInterests()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6167) | :closed_lock_with_key: | GET | `/crossex/history_margin_interests` | +| [getCrossExHistoryTrades()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6181) | :closed_lock_with_key: | GET | `/crossex/history_trades` | +| [getCrossExAccountBook()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6195) | :closed_lock_with_key: | GET | `/crossex/account_book` | +| [getCrossExCoinDiscountRate()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6209) | :closed_lock_with_key: | GET | `/crossex/coin_discount_rate` | +| [getCrossExMarketTickers()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6223) | | GET | `/crossex/market/tickers` | +| [getCrossExMarketFundingInfo()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6237) | | GET | `/crossex/market/funding_info` | +| [getAlphaAccounts()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6255) | :closed_lock_with_key: | GET | `/alpha/accounts` | +| [getAlphaAccountBook()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6267) | :closed_lock_with_key: | GET | `/alpha/account_book` | +| [createAlphaQuote()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6281) | :closed_lock_with_key: | POST | `/alpha/quote` | +| [createAlphaOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6293) | :closed_lock_with_key: | POST | `/alpha/orders` | +| [getAlphaOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6305) | :closed_lock_with_key: | GET | `/alpha/orders` | +| [getAlphaOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6317) | :closed_lock_with_key: | GET | `/alpha/order` | +| [getAlphaCurrencies()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6329) | | GET | `/alpha/currencies` | +| [getAlphaTickers()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6341) | | GET | `/alpha/tickers` | +| [getTradFiMT5Account()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6347) | :closed_lock_with_key: | GET | `/tradfi/users/mt5-account` | +| [getTradFiSymbolCategories()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6351) | | GET | `/tradfi/symbols/categories` | +| [getTradFiSymbols()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6357) | | GET | `/tradfi/symbols` | +| [getTradFiSymbolCommissions()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6369) | :closed_lock_with_key: | GET | `/tradfi/symbols/commissions` | +| [getTradFiSymbolDetail()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6375) | :closed_lock_with_key: | GET | `/tradfi/symbols/detail` | +| [getTradFiKlines()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6381) | | GET | `/tradfi/symbols/{symbol}/klines` | +| [getTradFiTicker()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6388) | | GET | `/tradfi/symbols/{symbol}/tickers` | +| [createTradFiUser()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6392) | :closed_lock_with_key: | POST | `/tradfi/users` | +| [getTradFiAssets()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6396) | :closed_lock_with_key: | GET | `/tradfi/users/assets` | +| [createTradFiTransaction()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6400) | :closed_lock_with_key: | POST | `/tradfi/transactions` | +| [getTradFiTransactions()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6406) | :closed_lock_with_key: | GET | `/tradfi/transactions` | +| [createTradFiOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6412) | :closed_lock_with_key: | POST | `/tradfi/orders` | +| [getTradFiOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6418) | :closed_lock_with_key: | GET | `/tradfi/orders` | +| [modifyTradFiOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6422) | :closed_lock_with_key: | PUT | `/tradfi/orders/{orderId}` | +| [cancelTradFiOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6429) | :closed_lock_with_key: | DELETE | `/tradfi/orders/{orderId}` | +| [getTradFiOrderHistory()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6433) | :closed_lock_with_key: | GET | `/tradfi/orders/history` | +| [getTradFiPositions()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6439) | :closed_lock_with_key: | GET | `/tradfi/positions` | +| [modifyTradFiPosition()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6445) | :closed_lock_with_key: | PUT | `/tradfi/positions/{positionId}` | +| [closeTradFiPosition()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6454) | :closed_lock_with_key: | POST | `/tradfi/positions/{positionId}/close` | +| [getTradFiPositionHistory()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6463) | :closed_lock_with_key: | GET | `/tradfi/positions/history` | +| [getTradFiOrderLog()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6472) | :closed_lock_with_key: | GET | `/tradfi/orders/log/{log_id}` | +| [getStockUserAssets()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6486) | :closed_lock_with_key: | GET | `/stock/users/assets` | +| [getStockSymbols()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6498) | | GET | `/stock/symbols` | +| [getStockSymbolDetail()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6510) | :closed_lock_with_key: | GET | `/stock/symbols/detail` | +| [getStockOrderBook()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6522) | | GET | `/stock/market/{symbol}/orderbook` | +| [getStockOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6532) | :closed_lock_with_key: | GET | `/stock/orders` | +| [createStockOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6546) | :closed_lock_with_key: | POST | `/stock/orders` | +| [cancelAllStockOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6557) | :closed_lock_with_key: | DELETE | `/stock/orders` | +| [getStockOrderHistory()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6567) | :closed_lock_with_key: | GET | `/stock/orders/history` | +| [updateStockOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6580) | :closed_lock_with_key: | PUT | `/stock/orders/{orderId}` | +| [cancelStockOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6593) | :closed_lock_with_key: | DELETE | `/stock/orders/{orderId}` | +| [getStockPositions()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6605) | :closed_lock_with_key: | GET | `/stock/positions` | +| [closeStockPosition()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6617) | :closed_lock_with_key: | POST | `/stock/positions/close` | +| [getStockTransactions()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6629) | :closed_lock_with_key: | GET | `/stock/transactions` | +| [createStockTransaction()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6643) | :closed_lock_with_key: | POST | `/stock/transactions` | +| [getStockExchanges()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6654) | | GET | `/stock/exchanges` | +| [getStockFeeRate()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6665) | | GET | `/stock/fee-rate` | # WebsocketAPIClient.ts diff --git a/llms.txt b/llms.txt index a13ad5e..8a2d03c 100644 --- a/llms.txt +++ b/llms.txt @@ -441,118 +441,6 @@ File: src/lib/misc-util.ts ================ export function neverGuard(x: never, msg: string): Error -================ -File: src/lib/requestUtils.ts -================ -import WebSocket from 'isomorphic-ws'; -⋮---- -import { GateBaseUrlKey } from '../types/shared.js'; -⋮---- -export interface RestClientOptions { - /** Your API key */ - apiKey?: string; - - /** Your API secret */ - apiSecret?: string; - - /** - * Override the default/global max size of the request window (in ms) for signed api calls. - * If you don't include a recv window when making an API call, this value will be used as default - */ - recvWindow?: number; - - /** Default: false. If true, we'll throw errors if any params are undefined */ - strictParamValidation?: boolean; - - /** - * Optionally override API protocol + domain - * e.g baseUrl: 'https://api.gate.io' - **/ - baseUrl?: string; - - // manually override with one of the known base URLs in the library - baseUrlKey?: GateBaseUrlKey; - - /** Default: true. whether to try and post-process request exceptions (and throw them). */ - parseExceptions?: boolean; - - /** - * Enable keep alive for REST API requests (via axios). - * See: https://github.com/tiagosiebler/bybit-api/issues/368 - */ - keepAlive?: boolean; - - /** - * When using HTTP KeepAlive, how often to send TCP KeepAlive packets over sockets being kept alive. Default = 1000. - * Only relevant if keepAlive is set to true. - * Default: 1000 (defaults comes from https agent) - */ - keepAliveMsecs?: number; - - /** - * Allows you to provide a custom "signMessage" function, e.g. to use node's much faster createHmac method - * - * Look in the examples folder for a demonstration on using node's createHmac instead. - */ - customSignMessageFn?: (message: string, secret: string) => Promise; -} -⋮---- -/** Your API key */ -⋮---- -/** Your API secret */ -⋮---- -/** - * Override the default/global max size of the request window (in ms) for signed api calls. - * If you don't include a recv window when making an API call, this value will be used as default - */ -⋮---- -/** Default: false. If true, we'll throw errors if any params are undefined */ -⋮---- -/** - * Optionally override API protocol + domain - * e.g baseUrl: 'https://api.gate.io' - **/ -⋮---- -// manually override with one of the known base URLs in the library -⋮---- -/** Default: true. whether to try and post-process request exceptions (and throw them). */ -⋮---- -/** - * Enable keep alive for REST API requests (via axios). - * See: https://github.com/tiagosiebler/bybit-api/issues/368 - */ -⋮---- -/** - * When using HTTP KeepAlive, how often to send TCP KeepAlive packets over sockets being kept alive. Default = 1000. - * Only relevant if keepAlive is set to true. - * Default: 1000 (defaults comes from https agent) - */ -⋮---- -/** - * Allows you to provide a custom "signMessage" function, e.g. to use node's much faster createHmac method - * - * Look in the examples folder for a demonstration on using node's createHmac instead. - */ -⋮---- -export function serializeParams | undefined = {}>( - params: T, - strict_validation: boolean | undefined, - encodeValues: boolean, - prefixWith: string, -): string -⋮---- -// Only prefix if there's a value -⋮---- -export function getRestBaseUrl(restClientOptions: RestClientOptions): string -⋮---- -export interface MessageEventLike { - target: WebSocket; - type: 'message'; - data: string; -} -⋮---- -export function isMessageEvent(msg: unknown): msg is MessageEventLike - ================ File: src/lib/webCryptoAPI.ts ================ @@ -599,26 +487,6 @@ export interface CreateStpGroupReq { create_time?: number; } -================ -File: src/types/request/announcement.ts -================ -/** POST /ann/list_article */ -⋮---- -export interface ListAnnouncementArticlesReq { - title_query?: string; - page?: string; - size?: string; - tags?: string; - timer?: string; - cate_name?: string; - cate_level?: string; - sub_website_id?: string; - pinned?: number; - update_after?: number; - lang?: string; - filter_empty_content?: number; -} - ================ File: src/types/request/collateralLoan.ts ================ @@ -668,205 +536,77 @@ export interface GetLoanCollateralRecordsReq { } ================ -File: src/types/request/delivery.ts +File: src/types/request/earnuni.ts ================ /**========================================================================================================================== - * DELIVERY + * EARN UNI * ========================================================================================================================== */ ⋮---- -export interface GetDeliveryOrderBookReq { - settle: 'usdt'; - contract: string; - interval?: '0' | '0.1' | '0.01'; - limit?: number; - with_id?: boolean; +export interface SubmitLendOrRedeemReq { + currency: string; + amount: string; + type: 'lend' | 'redeem'; + min_rate?: string; } ⋮---- -export interface GetDeliveryTradesReq { - settle: 'usdt'; - contract: string; +export interface GetLendingOrdersReq { + currency?: string; + page?: number; limit?: number; - last_id?: string; - from?: number; - to?: number; } ⋮---- -export interface GetDeliveryCandlesReq { - settle: 'usdt'; - contract: string; +export interface GetLendingRecordsReq { + currency?: string; + page?: number; + limit?: number; from?: number; to?: number; - limit?: number; - interval?: - | '10s' - | '30s' - | '1m' - | '5m' - | '15m' - | '30m' - | '1h' - | '2h' - | '4h' - | '6h' - | '8h' - | '12h' - | '1d' - | '7d' - | '1w' - | '30d'; + type?: 'lend' | 'redeem'; } ⋮---- -export interface GetDeliveryBookReq { - settle: 'usdt'; +export interface GetLendingInterestRecordsReq { + currency?: string; + page?: number; limit?: number; from?: number; to?: number; - type?: - | 'dnw' - | 'pnl' - | 'fee' - | 'refr' - | 'fund' - | 'point_dnw' - | 'point_fee' - | 'point_refr' - | 'bonus_offset'; } + +================ +File: src/types/request/flashswap.ts +================ +/**========================================================================================================================== + * FLASH SWAP + * ========================================================================================================================== + */ ⋮---- -export interface SubmitDeliveryFuturesOrderReq { - settle: 'usdt'; - contract: string; - size: number; - iceberg?: number; - price?: string; - close?: boolean; - reduce_only?: boolean; - tif?: string; - text?: string; - auto_size?: string; - stp_act?: string; +export interface SubmitFlashSwapOrderReq { + preview_id: string; + sell_currency: string; + sell_amount: string; + buy_currency: string; + buy_amount: string; } ⋮---- -export interface GetDeliveryOrdersReq { - settle: 'usdt'; - contract?: string; - status: 'open' | 'finished'; +export interface GetFlashSwapOrdersReq { + status?: number; + sell_currency?: string; + buy_currency?: string; + reverse?: boolean; limit?: number; - offset?: number; - last_id?: string; - count_total?: 0 | 1; + page?: number; } ⋮---- -export interface GetDeliveryTradingHistoryReq { - settle: 'usdt'; - contract?: string; - order?: number; - limit?: number; - offset?: number; - last_id?: string; - count_total?: 0 | 1; +export interface GetFlashSwapOrderReq { + order_id: number; } ⋮---- -export interface GetDeliveryClosedPositionsReq { - settle: 'usdt'; - contract?: string; - limit?: number; -} -⋮---- -export interface GetDeliveryLiquidationHistoryReq { - settle: 'usdt'; - contract?: string; - limit?: number; - at?: number; -} -⋮---- -export interface GetDeliverySettlementHistoryReq { - settle: 'usdt'; - contract?: string; - limit?: number; - at?: number; -} -export interface GetDeliveryAutoOrdersReq { - settle: 'usdt'; - status: 'open' | 'finished'; - contract?: string; - limit?: number; - offset?: number; -} - -================ -File: src/types/request/earnuni.ts -================ -/**========================================================================================================================== - * EARN UNI - * ========================================================================================================================== - */ -⋮---- -export interface SubmitLendOrRedeemReq { - currency: string; - amount: string; - type: 'lend' | 'redeem'; - min_rate?: string; -} -⋮---- -export interface GetLendingOrdersReq { - currency?: string; - page?: number; - limit?: number; -} -⋮---- -export interface GetLendingRecordsReq { - currency?: string; - page?: number; - limit?: number; - from?: number; - to?: number; - type?: 'lend' | 'redeem'; -} -⋮---- -export interface GetLendingInterestRecordsReq { - currency?: string; - page?: number; - limit?: number; - from?: number; - to?: number; -} - -================ -File: src/types/request/flashswap.ts -================ -/**========================================================================================================================== - * FLASH SWAP - * ========================================================================================================================== - */ -⋮---- -export interface SubmitFlashSwapOrderReq { - preview_id: string; - sell_currency: string; - sell_amount: string; - buy_currency: string; - buy_amount: string; -} -⋮---- -export interface GetFlashSwapOrdersReq { - status?: number; - sell_currency?: string; - buy_currency?: string; - reverse?: boolean; - limit?: number; - page?: number; -} -⋮---- -export interface GetFlashSwapOrderReq { - order_id: number; -} -⋮---- -export interface SubmitFlashSwapOrderPreviewReq { - sell_currency: string; - sell_amount?: string; - buy_currency: string; - buy_amount?: string; +export interface SubmitFlashSwapOrderPreviewReq { + sell_currency: string; + sell_amount?: string; + buy_currency: string; + buy_amount?: string; } ================ @@ -1146,44 +886,6 @@ export interface AccountMainKey { state: number; // 1 - Normal, 2 - Locked, 3 - Frozen mode: number; // 1 - Classic, 2 - Legacy Unified -================ -File: src/types/response/announcement.ts -================ -export interface AnnouncementArticleLanguage { - code?: string; - name?: string; -} -⋮---- -export interface AnnouncementArticle { - id?: number; - title?: string; - brief?: string; - created?: string; - updated?: string; - release_time?: string; - views?: number; - author?: string; - author_id?: number; - tags?: string; - cate?: string; - is_top?: number; - cate_id?: number; - source?: string; - content_lang_list?: AnnouncementArticleLanguage[]; -} -⋮---- -export interface AnnouncementArticleListData { - list?: AnnouncementArticle[]; - total?: number; -} -⋮---- -export interface AnnouncementArticleListResponse { - code?: number; - data?: AnnouncementArticleListData; - message?: string; - version?: string; -} - ================ File: src/types/response/collateralloan.ts ================ @@ -1417,1535 +1119,1000 @@ export interface WsDataEvent { } ================ -File: src/types/websockets/requests.ts +File: src/WebsocketAPIClient.ts ================ -import { CHANNEL_ID } from '../../lib/requestUtils.js'; -import { WSAPITopic } from './wsAPI.js'; -⋮---- -export type WsOperation = 'subscribe' | 'unsubscribe' | 'auth'; +import { DefaultLogger } from './lib/logger.js'; +import { WS_KEY_MAP } from './lib/websocket/websocket-util.js'; +import { WSClientConfigurableOptions } from './types/websockets/client.js'; +import { + WSAPIFuturesOrder, + WSAPIFuturesOrderAmendReq, + WSAPIFuturesOrderBatchPlaceRespItem, + WSAPIFuturesOrderCancelCPReq, + WSAPIFuturesOrderCancelIdsRespItem, + WSAPIFuturesOrderCancelReq, + WSAPIFuturesOrderListReq, + WSAPIFuturesOrderPlaceReq, + WSAPIFuturesOrderStatusReq, + WSAPIResponse, + WSAPISpotOrder, + WSAPISpotOrderAmendReq, + WSAPISpotOrderCancelCPReq, + WSAPISpotOrderCancelIdsReq, + WSAPISpotOrderCancelIdsRespItem, + WSAPISpotOrderCancelReq, + WSAPISpotOrderListReq, + WSAPISpotOrderPlaceReq, + WSAPISpotOrderStatusReq, + WSAPIWsKey, +} from './types/websockets/wsAPI.js'; +import { WebsocketClient } from './WebsocketClient.js'; ⋮---- -export interface WsRequestAuthGate { - method: 'api_key'; - KEY: string; - SIGN: string; +/** + * Configurable options specific to only the REST-like WebsocketAPIClient + */ +export interface WSAPIClientConfigurableOptions { + /** + * Default: true + * + * Attach default event listeners, which will console log any high level + * events (opened/reconnecting/reconnected/etc). + * + * If you disable this, you should set your own event listeners + * on the embedded WS Client `wsApiClient.getWSClient().on(....)`. + */ + attachEventListeners: boolean; } ⋮---- -export interface WsRequestPing { - time: number; - channel: 'spot.ping' | 'futures.ping' | 'options.ping' | 'announcement.ping'; -} +/** + * Default: true + * + * Attach default event listeners, which will console log any high level + * events (opened/reconnecting/reconnected/etc). + * + * If you disable this, you should set your own event listeners + * on the embedded WS Client `wsApiClient.getWSClient().on(....)`. + */ ⋮---- -export interface WsRequestOperationGate< - TWSTopic extends string, - TWSPayload = any, -> { - time: number; - id?: number; - channel: TWSTopic; - auth?: WsRequestAuthGate; - event?: WsOperation; - payload?: TWSPayload; -} +/** + * This is a minimal Websocket API wrapper around the WebsocketClient. + * + * Some methods support passing in a custom "wsKey". This is a reference to which WS connection should + * be used to transmit that message. This is only useful if you wish to use an alternative wss + * domain that is supported by the SDK. + * + * Note: To use testnet, don't set the wsKey - use `testnet: true` in + * the constructor instead. + * + * Note: You can also directly use the sendWSAPIRequest() method to make WS API calls, but some + * may find the below methods slightly more intuitive. + * + * Refer to the WS API promises example for a more detailed example on using sendWSAPIRequest() directly: + * https://github.com/tiagosiebler/gateio-api/blob/master/examples/ws-private-spot-wsapi.ts#L119 + */ +export class WebsocketAPIClient ⋮---- -export interface WSAPIRequest< - TRequestParams = any, - TWSChannel extends WSAPITopic = any, -> { - time: number; - id?: number; - channel: TWSChannel; - event: 'api'; - payload: { - req_id: string; - req_param?: TRequestParams | string; - req_header: { - 'X-Gate-Channel-Id': typeof CHANNEL_ID; - }; - api_key?: string; - signature?: string; - timestamp?: string; - }; -} - -================ -File: src/types/websockets/wsAPI.ts -================ -import { WsKey } from '../../lib/websocket/websocket-util.js'; +constructor( + options?: WSClientConfigurableOptions & + Partial, + logger?: DefaultLogger, +) ⋮---- -export type SpotWSAPITopic = - | 'spot.login' - | 'spot.order_place' - | 'spot.order_cancel' - | 'spot.order_cancel_ids' - | 'spot.order_cancel_cp' - | 'spot.order_amend' - | 'spot.order_status' - | 'spot.order_list'; -⋮---- -export type FuturesWSAPITopic = - | 'futures.login' - | 'futures.order_place' - | 'futures.order_batch_place' - | 'futures.order_cancel' - | 'futures.order_cancel_cp' - | 'futures.order_amend' - | 'futures.order_list' - | 'futures.order_status' - | 'futures.order_cancel_ids'; +public getWSClient(): WebsocketClient ⋮---- -export interface WsAPIWsKeyTopicMap { - spotV4: SpotWSAPITopic; - perpFuturesUSDTV4: FuturesWSAPITopic; - perpFuturesBTCV4: FuturesWSAPITopic; - deliveryFuturesUSDTV4: FuturesWSAPITopic; - deliveryFuturesBTCV4: FuturesWSAPITopic; - // optionsV4: never; - // announcementsV4: never; -} +public setTimeOffsetMs(newOffset: number): void ⋮---- -// optionsV4: never; -// announcementsV4: never; +/* + * + * SPOT - Trading requests + * + */ ⋮---- -export type WSAPITopic = SpotWSAPITopic | FuturesWSAPITopic; -export type WSAPIWsKey = keyof WsAPIWsKeyTopicMap; +/** + * Submit a spot order + */ +submitNewSpotOrder( + params: WSAPISpotOrderPlaceReq, + wsKey?: WSAPIWsKey, +): Promise> ⋮---- -// ==================================== -// Spot WebSocket API Request Types -// ==================================== +/** + * Cancel a spot order + */ +cancelSpotOrder( + params: WSAPISpotOrderCancelReq, + wsKey?: WSAPIWsKey, +): Promise> ⋮---- -export interface WSAPISpotOrderPlaceReq { - text?: string; - currency_pair: string; - type?: 'limit' | 'market'; - account?: 'spot' | 'margin' | 'unified' | 'cross_margin'; - side: 'buy' | 'sell'; - amount: string; - price?: string; - time_in_force?: 'gtc' | 'ioc' | 'poc' | 'fok'; - iceberg?: string; - auto_borrow?: boolean; - auto_repay?: boolean; - stp_act?: 'cn' | 'co' | 'cb'; - action_mode?: 'ACK' | 'RESULT' | 'FULL'; -} +/** + * Cancel all spot orders with the given id list + */ +cancelSpotOrderById( + params: WSAPISpotOrderCancelIdsReq[], + wsKey?: WSAPIWsKey, +): Promise> ⋮---- -export interface WSAPISpotOrderCancelReq { - order_id: string; - currency_pair: string; - account?: string; -} +/** + * Cancel a spot order for a given symbol + */ +cancelSpotOrderForSymbol( + params: WSAPISpotOrderCancelCPReq, + wsKey?: WSAPIWsKey, +): Promise> ⋮---- -export interface WSAPISpotOrderCancelIdsReq { - currency_pair: string; - id: string; - account?: string; -} +/** + * Update a spot order + */ +updateSpotOrder( + params: WSAPISpotOrderAmendReq, + wsKey?: WSAPIWsKey, +): Promise> ⋮---- -export interface WSAPISpotOrderCancelCPReq { - currency_pair: string; - side?: 'buy' | 'sell'; - account?: string; -} +/** + * Get the status of a spot order + */ +getSpotOrderStatus( + params: WSAPISpotOrderStatusReq, + wsKey?: WSAPIWsKey, +): Promise> ⋮---- -export interface WSAPISpotOrderAmendReq { - amount?: string; - price?: string; - amend_text?: string; - order_id: string; - currency_pair: string; - account?: string; -} +/** + * Get all spot orders + */ +getSpotOrders( + params: WSAPISpotOrderListReq, + wsKey?: WSAPIWsKey, +): Promise> ⋮---- -export interface WSAPISpotOrderStatusReq { - order_id: string; - currency_pair: string; - account?: string; -} +/* + * + * Futures - Trading requests + * + */ ⋮---- -export interface WSAPISpotOrderListReq { - currency_pair: string; - status: 'open' | 'finished'; - page?: number; - limit?: number; - account?: string; - from?: number; - to?: number; - side?: 'buy' | 'sell'; -} +/** + * Submit a futures order. + * + * Note: without a wsKey, this defaults to the perpFuturesUSDTV4 connection + */ +submitNewFuturesOrder( + params: WSAPIFuturesOrderPlaceReq, + wsKey?: WSAPIWsKey, +): Promise> ⋮---- -// ==================================== -// Futures WebSocket API Request Types -// ==================================== +/** + * Submit a batch of futures orders + * + * Note: without a wsKey, this defaults to the perpFuturesUSDTV4 connection + */ +submitNewFuturesBatchOrder( + params: WSAPIFuturesOrderPlaceReq[], + wsKey?: WSAPIWsKey, +): Promise> ⋮---- -export interface WSAPIFuturesOrderPlaceReq { - contract: string; - size: number; - iceberg?: number; - price?: string; - close?: boolean; - reduce_only?: boolean; - tif?: 'gtc' | 'ioc' | 'poc' | 'fok'; - text?: string; - auto_size?: 'close_long' | 'close_short'; - stp_act?: 'cn' | 'co' | 'cb'; -} +/** + * Cancel a futures order + * + * Note: without a wsKey, this defaults to the perpFuturesUSDTV4 connection + */ +cancelFuturesOrder( + params: WSAPIFuturesOrderCancelReq, + wsKey?: WSAPIWsKey, +): Promise> ⋮---- -export interface WSAPIFuturesOrderCancelReq { - order_id: string; -} +/** + * Cancel futures orders by id list + * + * Note: without a wsKey, this defaults to the perpFuturesUSDTV4 connection + */ +cancelFuturesOrderById( + params: string[], + wsKey?: WSAPIWsKey, +): Promise> ⋮---- -export interface WSAPIFuturesOrderCancelCPReq { - contract: string; - side?: 'bid' | 'ask'; -} +/** + * Cancel all open futures orders + * + * Note: without a wsKey, this defaults to the perpFuturesUSDTV4 connection + */ +cancelFuturesAllOpenOrders( + params: WSAPIFuturesOrderCancelCPReq, + wsKey?: WSAPIWsKey, +): Promise> ⋮---- -export interface WSAPIFuturesOrderAmendReq { - order_id: string; - price?: string; - size?: number; - amend_text?: string; -} +/** + * Update a futures order + * + * Note: without a wsKey, this defaults to the perpFuturesUSDTV4 connection + */ +updateFuturesOrder( + params: WSAPIFuturesOrderAmendReq, + wsKey?: WSAPIWsKey, +): Promise> ⋮---- -export interface WSAPIFuturesOrderListReq { - contract: string; - status: 'open' | 'finished'; - limit?: number; - offset?: number; - last_id?: string; - count_total?: number; -} +/** + * Get all futures orders + * + * Note: without a wsKey, this defaults to the perpFuturesUSDTV4 connection + */ +getFuturesOrders( + params: WSAPIFuturesOrderListReq, + wsKey?: WSAPIWsKey, +): Promise> ⋮---- -export interface WSAPIFuturesOrderStatusReq { - order_id: string; -} +/** + * Get futures order status + * + * Note: without a wsKey, this defaults to the perpFuturesUSDTV4 connection + */ +getFuturesOrderStatus( + params: WSAPIFuturesOrderStatusReq, + wsKey?: WSAPIWsKey, +): Promise> ⋮---- -// ==================================== -// Spot WebSocket API Response Types -// ==================================== +/** + * + * + * + * + * + * + * + * Private methods for handling some of the convenience/automation provided by the WS API Client + * + * + * + * + * + * + * + */ ⋮---- -export interface WSAPISpotOrder { - id: string; - text: string; - amend_text: string; - create_time: string; - update_time: string; - create_time_ms: number; - update_time_ms: number; - status: string; - currency_pair: string; - type: string; - account: string; - side: string; - amount: string; - price: string; - time_in_force: string; - iceberg: string; - left: string; - fill_price?: string; - filled_amount?: string; - filled_total: string; - avg_deal_price?: string; - fee: string; - fee_currency: string; - point_fee: string; - gt_fee: string; - gt_maker_fee?: string; - gt_taker_fee?: string; - gt_discount?: boolean; - rebated_fee: string; - rebated_fee_currency: string; - stp_id?: number; - stp_act?: string; - finish_as: string; -} +private setupDefaultEventListeners() ⋮---- -export interface WSAPISpotOrderCancelIdsRespItem { - currency_pair: string; - id: string; - succeeded: boolean; -} +/** + * General event handlers for monitoring the WebsocketClient + */ ⋮---- -// ==================================== -// Futures WebSocket API Response Types -// ==================================== +// Blind JSON.stringify can fail on circular references ⋮---- -export interface WSAPIFuturesOrder { - id: number; - user: number; - create_time: number; - finish_time?: number; - update_time?: number; - finish_as?: string; - status: string; - contract: string; - size: number; - price: string; - tif: string; - left?: number; - fill_price: string; - text: string; - tkfr: string; - mkfr: string; - stp_id?: number; - stp_act?: string; - amend_text?: string; +// JSON.stringify({ ...data, target: 'WebSocket' }), + +================ +File: .eslintrc.cjs +================ +// 'no-unused-vars': ['warn'], + +================ +File: .prettierrc +================ +{ + "tabWidth": 2, + "singleQuote": true, + "trailingComma": "all" } + +================ +File: jest.config.ts +================ +/** + * For a detailed explanation regarding each configuration property, visit: + * https://jestjs.io/docs/configuration + */ ⋮---- -export interface WSAPIFuturesOrderBatchPlaceRespItem extends WSAPIFuturesOrder { - succeeded: boolean; -} +import type { Config } from 'jest'; ⋮---- -export interface WSAPIFuturesOrderCancelIdsRespItem { - id: string; - user_id: number; - succeeded?: boolean; - message?: string; -} +// All imported modules in your tests should be mocked automatically +// automock: false, ⋮---- -// ==================================== -// Request Parameter Mapping -// ==================================== +// Stop running tests after `n` failures +// bail: 0, +bail: false, // enable to stop test when an error occur, ⋮---- -export interface WsAPITopicRequestParamMap { - 'spot.login': undefined; - 'futures.login': undefined; - - 'spot.order_place': WSAPISpotOrderPlaceReq; - 'spot.order_cancel': WSAPISpotOrderCancelReq; - 'spot.order_cancel_ids': WSAPISpotOrderCancelIdsReq[]; - 'spot.order_cancel_cp': WSAPISpotOrderCancelCPReq; - 'spot.order_amend': WSAPISpotOrderAmendReq; - 'spot.order_status': WSAPISpotOrderStatusReq; - 'spot.order_list': WSAPISpotOrderListReq; - - 'futures.order_place': WSAPIFuturesOrderPlaceReq; - 'futures.order_batch_place': WSAPIFuturesOrderPlaceReq[]; - 'futures.order_cancel': WSAPIFuturesOrderCancelReq; - 'futures.order_cancel_ids': string[]; - 'futures.order_cancel_cp': WSAPIFuturesOrderCancelCPReq; - 'futures.order_amend': WSAPIFuturesOrderAmendReq; - 'futures.order_list': WSAPIFuturesOrderListReq; - 'futures.order_status': WSAPIFuturesOrderStatusReq; -} +// The directory where Jest should store its cached dependency information +// cacheDirectory: "/private/var/folders/kf/2k3sz4px6c9cbyzj1h_b192h0000gn/T/jest_dx", ⋮---- -export type WsAPITopicRequestParams = - WsAPITopicRequestParamMap[keyof WsAPITopicRequestParamMap]; +// Automatically clear mock calls, instances, contexts and results before every test ⋮---- -// ==================================== -// Response Headers and Base Response -// ==================================== +// Indicates whether the coverage information should be collected while executing the test ⋮---- -export interface WSAPIResponseHeader { - /** String timestamp as ms */ - response_time: string; - /** Status of WS API call. "200" if successful, else exception is thrown */ - status: '200' | string; - channel: TChannel; - event: 'api'; - client_id: string; -} +// An array of glob patterns indicating a set of files for which coverage information should be collected ⋮---- -/** String timestamp as ms */ +// The directory where Jest should output its coverage files ⋮---- -/** Status of WS API call. "200" if successful, else exception is thrown */ +// An array of regexp pattern strings used to skip coverage collection +// coveragePathIgnorePatterns: [ +// "/node_modules/" +// ], ⋮---- -export interface WSAPILoginResponse { - api_key: string; - uid: string; -} +// Indicates which provider should be used to instrument code for coverage ⋮---- -export interface WSAPIOrderStatusResponse { - left: string; - update_time: string; - amount: string; - create_time: string; - price: string; - finish_as: string; - time_in_force: string; - currency_pair: string; - type: string; - account: string; - side: string; - amend_text: string; - text: string; - status: string; - iceberg: string; - avg_deal_price: string; - filled_total: string; - id: string; - fill_price: string; - update_time_ms: number; - create_time_ms: number; -} +// A list of reporter names that Jest uses when writing coverage reports +// coverageReporters: [ +// "json", +// "text", +// "lcov", +// "clover" +// ], ⋮---- -export type WSAPIResponseData = WSAPILoginResponse | WSAPIOrderStatusResponse; +// An object that configures minimum threshold enforcement for coverage results +// coverageThreshold: undefined, ⋮---- -export interface WSAPIResponse< - TResponseData extends object = WSAPIResponseData | object, - TChannel extends WSAPITopic = WSAPITopic, -> { - wsKey: WsKey; - header: WSAPIResponseHeader; - data: { - result: TResponseData; - }; - /** Auto-generated */ - request_id: string; -} +// A path to a custom dependency extractor +// dependencyExtractor: undefined, ⋮---- -/** Auto-generated */ +// Make calling deprecated APIs throw helpful error messages +// errorOnDeprecated: false, ⋮---- -// ==================================== -// Response Type Mapping -// ==================================== +// The default configuration for fake timers +// fakeTimers: { +// "enableGlobally": false +// }, ⋮---- -export interface WsAPITopicResponseMap { - 'spot.login': WSAPIResponse; - 'futures.login': WSAPIResponse; - - 'spot.order_place': WSAPIResponse; - 'spot.order_cancel': WSAPIResponse; - 'spot.order_cancel_ids': WSAPIResponse< - WSAPISpotOrderCancelIdsRespItem[], - 'spot.order_cancel_ids' - >; - 'spot.order_cancel_cp': WSAPIResponse< - WSAPISpotOrder[], - 'spot.order_cancel_cp' - >; - 'spot.order_amend': WSAPIResponse; - 'spot.order_status': WSAPIResponse; - 'spot.order_list': WSAPIResponse; - - 'futures.order_place': WSAPIResponse< - WSAPIFuturesOrder, - 'futures.order_place' - >; - 'futures.order_batch_place': WSAPIResponse< - WSAPIFuturesOrderBatchPlaceRespItem[], - 'futures.order_batch_place' - >; - 'futures.order_cancel': WSAPIResponse< - WSAPIFuturesOrder, - 'futures.order_cancel' - >; - 'futures.order_cancel_ids': WSAPIResponse< - WSAPIFuturesOrderCancelIdsRespItem[], - 'futures.order_cancel_ids' - >; - 'futures.order_cancel_cp': WSAPIResponse< - WSAPIFuturesOrder[], - 'futures.order_cancel_cp' - >; - 'futures.order_amend': WSAPIResponse< - WSAPIFuturesOrder, - 'futures.order_amend' - >; - 'futures.order_list': WSAPIResponse< - WSAPIFuturesOrder[], - 'futures.order_list' - >; - 'futures.order_status': WSAPIResponse< - WSAPIFuturesOrder, - 'futures.order_status' - >; -} +// Force coverage collection from ignored files using an array of glob patterns +// forceCoverageMatch: [], ⋮---- -// export interface WsAPIResponseMap { -// 'spot.login': WSAPIResponse; -// 'futures.login': WSAPIResponse; -// string: object; -// } - -================ -File: src/WebsocketAPIClient.ts -================ -import { DefaultLogger } from './lib/logger.js'; -import { WS_KEY_MAP } from './lib/websocket/websocket-util.js'; -import { WSClientConfigurableOptions } from './types/websockets/client.js'; -import { - WSAPIFuturesOrder, - WSAPIFuturesOrderAmendReq, - WSAPIFuturesOrderBatchPlaceRespItem, - WSAPIFuturesOrderCancelCPReq, - WSAPIFuturesOrderCancelIdsRespItem, - WSAPIFuturesOrderCancelReq, - WSAPIFuturesOrderListReq, - WSAPIFuturesOrderPlaceReq, - WSAPIFuturesOrderStatusReq, - WSAPIResponse, - WSAPISpotOrder, - WSAPISpotOrderAmendReq, - WSAPISpotOrderCancelCPReq, - WSAPISpotOrderCancelIdsReq, - WSAPISpotOrderCancelIdsRespItem, - WSAPISpotOrderCancelReq, - WSAPISpotOrderListReq, - WSAPISpotOrderPlaceReq, - WSAPISpotOrderStatusReq, - WSAPIWsKey, -} from './types/websockets/wsAPI.js'; -import { WebsocketClient } from './WebsocketClient.js'; +// A path to a module which exports an async function that is triggered once before all test suites +// globalSetup: undefined, ⋮---- -/** - * Configurable options specific to only the REST-like WebsocketAPIClient - */ -export interface WSAPIClientConfigurableOptions { - /** - * Default: true - * - * Attach default event listeners, which will console log any high level - * events (opened/reconnecting/reconnected/etc). - * - * If you disable this, you should set your own event listeners - * on the embedded WS Client `wsApiClient.getWSClient().on(....)`. - */ - attachEventListeners: boolean; -} +// A path to a module which exports an async function that is triggered once after all test suites +// globalTeardown: undefined, ⋮---- -/** - * Default: true - * - * Attach default event listeners, which will console log any high level - * events (opened/reconnecting/reconnected/etc). - * - * If you disable this, you should set your own event listeners - * on the embedded WS Client `wsApiClient.getWSClient().on(....)`. - */ +// A set of global variables that need to be available in all test environments +// globals: {}, ⋮---- -/** - * This is a minimal Websocket API wrapper around the WebsocketClient. - * - * Some methods support passing in a custom "wsKey". This is a reference to which WS connection should - * be used to transmit that message. This is only useful if you wish to use an alternative wss - * domain that is supported by the SDK. - * - * Note: To use testnet, don't set the wsKey - use `testnet: true` in - * the constructor instead. - * - * Note: You can also directly use the sendWSAPIRequest() method to make WS API calls, but some - * may find the below methods slightly more intuitive. - * - * Refer to the WS API promises example for a more detailed example on using sendWSAPIRequest() directly: - * https://github.com/tiagosiebler/gateio-api/blob/master/examples/ws-private-spot-wsapi.ts#L119 - */ -export class WebsocketAPIClient +// The maximum amount of workers used to run your tests. Can be specified as % or a number. E.g. maxWorkers: 10% will use 10% of your CPU amount + 1 as the maximum worker number. maxWorkers: 2 will use a maximum of 2 workers. +// maxWorkers: "50%", ⋮---- -constructor( - options?: WSClientConfigurableOptions & - Partial, - logger?: DefaultLogger, -) +// An array of directory names to be searched recursively up from the requiring module's location +// moduleDirectories: [ +// "node_modules" +// ], ⋮---- -public getWSClient(): WebsocketClient +// An array of file extensions your modules use ⋮---- -public setTimeOffsetMs(newOffset: number): void +// modulePaths: ['src'], ⋮---- -/* - * - * SPOT - Trading requests - * - */ +// A map from regular expressions to module names or to arrays of module names that allow to stub out resources with a single module +// moduleNameMapper: {}, ⋮---- -/** - * Submit a spot order - */ -submitNewSpotOrder( - params: WSAPISpotOrderPlaceReq, - wsKey?: WSAPIWsKey, -): Promise> +// An array of regexp pattern strings, matched against all module paths before considered 'visible' to the module loader +// modulePathIgnorePatterns: [], ⋮---- -/** - * Cancel a spot order - */ -cancelSpotOrder( - params: WSAPISpotOrderCancelReq, - wsKey?: WSAPIWsKey, -): Promise> +// Activates notifications for test results +// notify: false, ⋮---- -/** - * Cancel all spot orders with the given id list - */ -cancelSpotOrderById( - params: WSAPISpotOrderCancelIdsReq[], - wsKey?: WSAPIWsKey, -): Promise> +// An enum that specifies notification mode. Requires { notify: true } +// notifyMode: "failure-change", ⋮---- -/** - * Cancel a spot order for a given symbol - */ -cancelSpotOrderForSymbol( - params: WSAPISpotOrderCancelCPReq, - wsKey?: WSAPIWsKey, -): Promise> +// A preset that is used as a base for Jest's configuration +// preset: undefined, ⋮---- -/** - * Update a spot order - */ -updateSpotOrder( - params: WSAPISpotOrderAmendReq, - wsKey?: WSAPIWsKey, -): Promise> +// Run tests from one or more projects +// projects: undefined, ⋮---- -/** - * Get the status of a spot order - */ -getSpotOrderStatus( - params: WSAPISpotOrderStatusReq, - wsKey?: WSAPIWsKey, -): Promise> +// Use this configuration option to add custom reporters to Jest +// reporters: undefined, ⋮---- -/** - * Get all spot orders - */ -getSpotOrders( - params: WSAPISpotOrderListReq, - wsKey?: WSAPIWsKey, -): Promise> +// Automatically reset mock state before every test +// resetMocks: false, ⋮---- -/* - * - * Futures - Trading requests - * - */ +// Reset the module registry before running each individual test +// resetModules: false, ⋮---- -/** - * Submit a futures order. - * - * Note: without a wsKey, this defaults to the perpFuturesUSDTV4 connection - */ -submitNewFuturesOrder( - params: WSAPIFuturesOrderPlaceReq, - wsKey?: WSAPIWsKey, -): Promise> +// A path to a custom resolver +// resolver: undefined, ⋮---- -/** - * Submit a batch of futures orders - * - * Note: without a wsKey, this defaults to the perpFuturesUSDTV4 connection - */ -submitNewFuturesBatchOrder( - params: WSAPIFuturesOrderPlaceReq[], - wsKey?: WSAPIWsKey, -): Promise> +// Automatically restore mock state and implementation before every test +// restoreMocks: false, ⋮---- -/** - * Cancel a futures order - * - * Note: without a wsKey, this defaults to the perpFuturesUSDTV4 connection - */ -cancelFuturesOrder( - params: WSAPIFuturesOrderCancelReq, - wsKey?: WSAPIWsKey, -): Promise> +// The root directory that Jest should scan for tests and modules within +// rootDir: undefined, ⋮---- -/** - * Cancel futures orders by id list - * - * Note: without a wsKey, this defaults to the perpFuturesUSDTV4 connection - */ -cancelFuturesOrderById( - params: string[], - wsKey?: WSAPIWsKey, -): Promise> +// A list of paths to directories that Jest should use to search for files in +// roots: [ +// "" +// ], ⋮---- -/** - * Cancel all open futures orders - * - * Note: without a wsKey, this defaults to the perpFuturesUSDTV4 connection - */ -cancelFuturesAllOpenOrders( - params: WSAPIFuturesOrderCancelCPReq, - wsKey?: WSAPIWsKey, -): Promise> -⋮---- -/** - * Update a futures order - * - * Note: without a wsKey, this defaults to the perpFuturesUSDTV4 connection - */ -updateFuturesOrder( - params: WSAPIFuturesOrderAmendReq, - wsKey?: WSAPIWsKey, -): Promise> -⋮---- -/** - * Get all futures orders - * - * Note: without a wsKey, this defaults to the perpFuturesUSDTV4 connection - */ -getFuturesOrders( - params: WSAPIFuturesOrderListReq, - wsKey?: WSAPIWsKey, -): Promise> -⋮---- -/** - * Get futures order status - * - * Note: without a wsKey, this defaults to the perpFuturesUSDTV4 connection - */ -getFuturesOrderStatus( - params: WSAPIFuturesOrderStatusReq, - wsKey?: WSAPIWsKey, -): Promise> -⋮---- -/** - * - * - * - * - * - * - * - * Private methods for handling some of the convenience/automation provided by the WS API Client - * - * - * - * - * - * - * - */ -⋮---- -private setupDefaultEventListeners() -⋮---- -/** - * General event handlers for monitoring the WebsocketClient - */ -⋮---- -// Blind JSON.stringify can fail on circular references +// Allows you to use a custom runner instead of Jest's default test runner +// runner: "jest-runner", ⋮---- -// JSON.stringify({ ...data, target: 'WebSocket' }), - -================ -File: src/WebsocketClient.ts -================ -import { BaseWebsocketClient, EmittableEvent } from './lib/BaseWSClient.js'; -import { neverGuard } from './lib/misc-util.js'; -import { CHANNEL_ID, MessageEventLike } from './lib/requestUtils.js'; -import { - SignAlgorithm, - SignEncodeMethod, - signMessage, -} from './lib/webCryptoAPI.js'; -import { - getPrivateFuturesTopics, - getPrivateOptionsTopics, - getPrivateSpotTopics, - getPromiseRefForWSAPIRequest, - WS_BASE_URL_MAP, - WS_KEY_MAP, - WsKey, - WsMarket, - WsTopicRequest, -} from './lib/websocket/websocket-util.js'; -import { WSConnectedResult } from './lib/websocket/WsStore.types.js'; -import { - WSAPIRequest, - WsOperation, - WsRequestOperationGate, - WsRequestPing, -} from './types/websockets/requests.js'; -import { - WsAPITopicRequestParamMap, - WsAPITopicResponseMap, - WSAPIWsKey, - WsAPIWsKeyTopicMap, -} from './types/websockets/wsAPI.js'; +// The paths to modules that run some code to configure or set up the testing environment before each test +// setupFiles: [], ⋮---- -export interface WSAPIRequestFlags { - /** If true, will skip auth requirement for WS API connection */ - authIsOptional?: boolean | undefined; -} +// A list of paths to modules that run some code to configure or set up the testing framework before each test +// setupFilesAfterEnv: [], ⋮---- -/** If true, will skip auth requirement for WS API connection */ +// The number of seconds after which a test is considered as slow and reported as such in the results. +// slowTestThreshold: 5, ⋮---- -/** - * WS topics are always a string for gate. Some exchanges use complex objects - */ -export type WsTopic = string; +// A list of paths to snapshot serializer modules Jest should use for snapshot testing +// snapshotSerializers: [], ⋮---- -export class WebsocketClient extends BaseWebsocketClient +// The test environment that will be used for testing +// testEnvironment: "jest-environment-node", ⋮---- -/** - * Request connection of all dependent (public & private) websockets, instead of waiting for automatic connection by library. - * - * Returns array of promises that individually resolve when each connection is successfully opened. - */ -public connectAll(): Promise[] +// Options that will be passed to the testEnvironment +// testEnvironmentOptions: {}, ⋮---- -/** - * Ensures the WS API connection is active and ready. - * - * You do not need to call this, but if you call this before making any WS API requests, - * it can accelerate the first request (by preparing the connection in advance). - */ -public connectWSAPI(wsKey: WSAPIWsKey, skipAuth?: boolean): Promise +// Adds a location field to test results +// testLocationInResults: false, ⋮---- -/** This call automatically ensures the connection is active AND authenticated before resolving */ +// The glob patterns Jest uses to detect test files ⋮---- -/** - * Request subscription to one or more topics. Pass topics as either an array of strings, or array of objects (if the topic has parameters). - * Objects should be formatted as {topic: string, params: object}. - * - * - Subscriptions are automatically routed to the correct websocket connection. - * - Authentication/connection is automatic. - * - Resubscribe after network issues is automatic. - * - * Call `unsubscribe(topics)` to remove topics - */ -public subscribe( - requests: - | (WsTopicRequest | WsTopic) - | (WsTopicRequest | WsTopic)[], - wsKey: WsKey, -) +// "**/__tests__/**/*.[jt]s?(x)", ⋮---- -/** - * Unsubscribe from one or more topics. Similar to subscribe() but in reverse. - * - * - Requests are automatically routed to the correct websocket connection. - * - These topics will be removed from the topic cache, so they won't be subscribed to again. - */ -public unsubscribe( - requests: - | (WsTopicRequest | WsTopic) - | (WsTopicRequest | WsTopic)[], - wsKey: WsKey, -) +// An array of regexp pattern strings that are matched against all test paths, matched tests are skipped +// testPathIgnorePatterns: [ +// "/node_modules/" +// ], ⋮---- -/** - * WS API Methods - similar to the REST API, but via WebSockets - */ +// The regexp pattern or array of patterns that Jest uses to detect test files +// testRegex: [], ⋮---- -/** - * Send a Websocket API event on a connection. Returns a promise that resolves on reply. - * - * Returned promise is rejected if an exception is detected in the reply OR the connection disconnects for any reason (even if automatic reconnect will happen). - * - * After a fresh connection, you should always send a login request first. - * - * If you authenticated once and you're reconnected later (e.g. connection temporarily lost), the SDK will by default automatically: - * - Detect you were authenticated to the WS API before - * - Try to re-authenticate (up to 5 times, in case something (bad timestamp) goes wrong) - * - If it succeeds, it will emit the 'authenticated' event. - * - If it fails and gives up, it will emit an 'exception' event (type: 'wsapi.auth', reason: detailed text). - * - * You can turn off the automatic re-auth WS API logic using `reauthWSAPIOnReconnect: false` in the WSClient config. - * - * @param wsKey - The connection this event is for (e.g. "spotV4" | "perpFuturesUSDTV4" | "perpFuturesBTCV4" | "deliveryFuturesUSDTV4" | "deliveryFuturesBTCV4" | "optionsV4") - * @param channel - The channel this event is for (e.g. "spot.login" to authenticate) - * @param params - Any request parameters for the payload (contents of req_param in the docs). Signature generation is automatic, only send parameters such as order ID as per the docs. - * @returns Promise - tries to resolve with async WS API response. Rejects if disconnected or exception is seen in async WS API response - */ +// This option allows the use of a custom results processor +// testResultsProcessor: undefined, ⋮---- -// This overload allows the caller to omit the 3rd param, if it isn't required (e.g. for the login call) -async sendWSAPIRequest< - TWSKey extends keyof WsAPIWsKeyTopicMap, - TWSChannel extends WsAPIWsKeyTopicMap[TWSKey] = WsAPIWsKeyTopicMap[TWSKey], - TWSParams extends - WsAPITopicRequestParamMap[TWSChannel] = WsAPITopicRequestParamMap[TWSChannel], - TWSAPIResponse extends - | WsAPITopicResponseMap[TWSChannel] - | object = WsAPITopicResponseMap[TWSChannel], - >( - wsKey: TWSKey, - channel: TWSChannel, - params?: TWSParams extends void | never ? undefined : TWSParams, - requestFlags?: WSAPIRequestFlags, - ): Promise; +// This option allows use of a custom test runner +// testRunner: "jest-circus/runner", ⋮---- -async sendWSAPIRequest< - TWSKey extends keyof WsAPIWsKeyTopicMap = keyof WsAPIWsKeyTopicMap, - TWSChannel extends WsAPIWsKeyTopicMap[TWSKey] = WsAPIWsKeyTopicMap[TWSKey], - TWSParams extends - WsAPITopicRequestParamMap[TWSChannel] = WsAPITopicRequestParamMap[TWSChannel], - TWSAPIResponse = object, - >( - wsKey: TWSKey, - channel: TWSChannel, - params: TWSParams & { signRequest?: boolean }, - requestFlags?: WSAPIRequestFlags, -): Promise +// A map from regular expressions to paths to transformers +// transform: undefined, ⋮---- -// Some commands don't require authentication. +// An array of regexp pattern strings that are matched against all source file paths, matched files will skip transformation +// transformIgnorePatterns: [ +// "/node_modules/", +// "\\.pnp\\.[^\\/]+$" +// ], ⋮---- -// this.logger.trace('sendWSAPIRequest(): assertIsAuthenticated(${wsKey})...'); +// Prevents import esm module error from v1 axios release, issue #5026 ⋮---- -// this.logger.trace('sendWSAPIRequest(): assertIsAuthenticated(${wsKey}) ok'); +// An array of regexp pattern strings that are matched against all modules before the module loader will automatically return a mock for them +// unmockedModulePathPatterns: undefined, ⋮---- -// id: timeInSeconds, +// Indicates whether each individual test should be reported during the run +// verbose: undefined, +verbose: true, // report individual test ⋮---- -/** - * Some WS API requests require a timestamp to be included. assertIsConnected and assertIsAuthenticated - * can introduce a small delay before the actual request is sent, if not connected before that request is - * made. This can lead to a curious race condition, where the request timestamp is before - * the "authorizedSince" timestamp - as such, binance does not recognise the session as already authenticated. - * - * The below mechanism measures any delay introduced from the assert calls, and if the request includes a timestamp, - * it offsets that timestamp by the delay. - */ +// An array of regexp patterns that are matched against all source file paths before re-running tests in watch mode +// watchPathIgnorePatterns: [], ⋮---- -// Sign request +// Whether to use watchman for file crawling +// watchman: true, + +================ +File: LICENSE.md +================ +Copyright 2022 Tiago Siebler + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +================ +File: postBuild.sh +================ +#!/bin/bash +# +# Add package.json files to cjs/mjs subtrees +# + +cat >dist/cjs/package.json <dist/mjs/package.json <, - wsKey: WsKey, -): boolean +// Submit a market order with 50% of the balance ⋮---- -// No private announcements channels +settle: 'usdt', // Specify the settlement currency +contract: 'BTC_USDT', // Specify the contract +size: orderAmount, // Order size: positive for long, negative for short, in USDT +price: '0', // Market order, so price is set to '0' +tif: 'ioc', // Time in force: 'ioc' (Immediate Or Cancel) ⋮---- -/** - * Not in use for gate.io - */ +// for more detailed ws connection, you can use a lot more listeners like below: ⋮---- -// eslint-disable-next-line @typescript-eslint/no-unused-vars -protected getWsMarketForWsKey(_wsKey: WsKey): WsMarket +// Something happened, attempting to reconnect ⋮---- -/** - * Not in use for gate.io - */ -protected getPrivateWSKeys(): WsKey[] +// Reconnect successful ⋮---- -protected isAuthOnConnectWsKey(wsKey: WsKey): boolean +// Connection closed. If unexpected, expect reconnect -> reconnected. ⋮---- -/** Force subscription requests to be sent in smaller batches, if a number is returned */ -// eslint-disable-next-line @typescript-eslint/no-unused-vars -protected getMaxTopicsPerSubscribeEvent(_wsKey: WsKey): number | null +// Reply to a request, e.g. "subscribe"/"unsubscribe"/"authenticate" + +================ +File: examples/Rest/futures/getBalances.ts +================ +import { RestClient } from '../../../src/index.js'; // For an easy demonstration, import from the src dir. Normally though, see below to import from the npm installed version instead. +// import { RestClient } from 'gateio-api'; // Import the RestClient from the published version of this SDK, installed via NPM (npm install gateio-api) ⋮---- -/** - * Map one or more topics into fully prepared "subscribe request" events (already stringified and ready to send) - */ -protected async getWsOperationEventsForTopics( - topics: WsTopicRequest[], - wsKey: WsKey, - operation: WsOperation, -): Promise +// Define the account object with API key and secret ⋮---- -// console.log(new Date(), `called getWsSubscribeEventsForTopics()`, topics); -// console.trace(); +key: process.env.API_KEY || 'yourApiHere', // Replace 'yourApiHere' with your actual API key +secret: process.env.API_SECRET || 'yourSecretHere', // Replace 'yourSecretHere' with your actual API secret ⋮---- -// Events that are ready to send (usually stringified JSON) +// Initialize the RestClient with the API credentials ⋮---- -/** - * @returns one or more correctly structured request events for performing a operations over WS. This can vary per exchange spec. - */ -private async getWsRequestEvents( - market: WsMarket, - operation: WsOperation, - requests: WsTopicRequest[], - wsKey: WsKey, -): Promise[]> +async function getFuturesBalances() ⋮---- -// If private topic request, build auth part for request +// Fetch the futures account balance for USDT settlement ⋮---- -// No key or secret, push event as failed -⋮---- -private async signMessage( - paramsStr: string, - secret: string, - method: 'hex' | 'base64', - algorithm: SignAlgorithm, -): Promise -⋮---- -protected async getWsAuthRequestEvent(wsKey: WsKey): Promise +console.log('Response: ', result); // Log the response to the console ⋮---- -// id: timeInSeconds, +console.error('Error in execution: ', e); // Log any errors that occur ⋮---- -/** - * - * @param requestEvent - * @returns A signed updated WS API request object, ready to be sent - */ -private async signWSAPIRequest( - requestEvent: WSAPIRequest, -): Promise> - -================ -File: .eslintrc.cjs -================ -// 'no-unused-vars': ['warn'], - -================ -File: .prettierrc -================ -{ - "tabWidth": 2, - "singleQuote": true, - "trailingComma": "all" -} +// Execute the function to get futures balances ================ -File: jest.config.ts +File: examples/Rest/futures/getContractSize.ts ================ /** - * For a detailed explanation regarding each configuration property, visit: - * https://jestjs.io/docs/configuration + * Example: Get futures contract size (quanto_multiplier) and convert between + * notional (e.g. USDT) and order size in contracts. + * + * Gate.io futures orders use `size` = number of CONTRACTS, not currency amount. + * The contract details endpoint returns `quanto_multiplier`: the amount of + * underlying (e.g. BTC) that 1 contract represents. So: + * notional_in_settle = size * quanto_multiplier * price + * size = notional_in_settle / (quanto_multiplier * price) + * + * This example: + * 1) Fetches contract with getFuturesContract + * 2) Reads quanto_multiplier and derives "contract size" in quote currency + * 3) Converts a desired notional (e.g. 1000 USDT) to order size in contracts */ ⋮---- -import type { Config } from 'jest'; -⋮---- -// All imported modules in your tests should be mocked automatically -// automock: false, +import { RestClient } from '../../../src/index.js'; +// import { RestClient } from 'gateio-api'; ⋮---- -// Stop running tests after `n` failures -// bail: 0, -bail: false, // enable to stop test when an error occur, +async function getContractSizeExample() ⋮---- -// The directory where Jest should store its cached dependency information -// cacheDirectory: "/private/var/folders/kf/2k3sz4px6c9cbyzj1h_b192h0000gn/T/jest_dx", +// 1) Get single contract (public, no auth required) ⋮---- -// Automatically clear mock calls, instances, contexts and results before every test +// 2) Contract size in quote (settle) currency: 1 contract = q * p ⋮---- -// Indicates whether the coverage information should be collected while executing the test +// 3) Convert desired notional (e.g. 1000 USDT) to size in contracts ⋮---- -// An array of glob patterns indicating a set of files for which coverage information should be collected +// Example: you would pass this size to submitFuturesOrder +// await client.submitFuturesOrder({ +// settle: SETTLE, +// contract: CONTRACT, +// size: size, // in contracts; positive = long, negative = short +// price: markPrice, +// tif: 'gtc', +// }); + +================ +File: examples/Rest/futures/getContractSizeExample.ts +================ +/** + * Example: Get futures contract size (quanto_multiplier) and convert between + * notional (e.g. USDT) and order size in contracts. + * + * Gate.io futures orders use `size` = number of CONTRACTS, not currency amount. + * The contract details endpoint returns `quanto_multiplier`: the amount of + * underlying (e.g. BTC) that 1 contract represents. So: + * notional_in_settle = size * quanto_multiplier * price + * size = notional_in_settle / (quanto_multiplier * price) + * + * This example: + * 1) Fetches contract with getFuturesContract + * 2) Reads quanto_multiplier and derives "contract size" in quote currency + * 3) Converts a desired notional (e.g. 1000 USDT) to order size in contracts + */ ⋮---- -// The directory where Jest should output its coverage files +import { RestClient } from '../../../src/index.js'; +// import { RestClient } from 'gateio-api'; ⋮---- -// An array of regexp pattern strings used to skip coverage collection -// coveragePathIgnorePatterns: [ -// "/node_modules/" -// ], +async function getContractSizeExample() ⋮---- -// Indicates which provider should be used to instrument code for coverage +// 1) Get single contract (public, no auth required) ⋮---- -// A list of reporter names that Jest uses when writing coverage reports -// coverageReporters: [ -// "json", -// "text", -// "lcov", -// "clover" -// ], +// 2) Contract size in quote (settle) currency: 1 contract = q * p ⋮---- -// An object that configures minimum threshold enforcement for coverage results -// coverageThreshold: undefined, +// 3) Convert desired notional (e.g. 1000 USDT) to size in contracts ⋮---- -// A path to a custom dependency extractor -// dependencyExtractor: undefined, +// Example: you would pass this size to submitFuturesOrder +// await client.submitFuturesOrder({ +// settle: SETTLE, +// contract: CONTRACT, +// size: size, // in contracts; positive = long, negative = short +// price: markPrice, +// tif: 'gtc', +// }); + +================ +File: examples/Rest/futures/getOrders.ts +================ +import { RestClient } from '../../../src/index.js'; // For an easy demonstration, import from the src dir. Normally though, see below to import from the npm installed version instead. +// import { RestClient } from 'gateio-api'; // Import the RestClient from the published version of this SDK, installed via NPM (npm install gateio-api) ⋮---- -// Make calling deprecated APIs throw helpful error messages -// errorOnDeprecated: false, +// Define the account object with API key and secret ⋮---- -// The default configuration for fake timers -// fakeTimers: { -// "enableGlobally": false -// }, +key: process.env.API_KEY || 'yourApiHere', // Replace 'yourApiHere' with your actual API key or use environment variables +secret: process.env.API_SECRET || 'yourSecretHere', // Replace 'yourSecretHere' with your actual API secret or use environment variables ⋮---- -// Force coverage collection from ignored files using an array of glob patterns -// forceCoverageMatch: [], +// Initialize the RestClient with the API credentials ⋮---- -// A path to a module which exports an async function that is triggered once before all test suites -// globalSetup: undefined, +async function getFuturesOrders() ⋮---- -// A path to a module which exports an async function that is triggered once after all test suites -// globalTeardown: undefined, +// Fetch open futures orders with USDT settlement ⋮---- -// A set of global variables that need to be available in all test environments -// globals: {}, +settle: 'usdt', // Specify the settlement currency +status: 'open', // Specify the status of the orders to fetch ⋮---- -// The maximum amount of workers used to run your tests. Can be specified as % or a number. E.g. maxWorkers: 10% will use 10% of your CPU amount + 1 as the maximum worker number. maxWorkers: 2 will use a maximum of 2 workers. -// maxWorkers: "50%", +console.log('openOrders: ', openOrders); // Log the response to the console ⋮---- -// An array of directory names to be searched recursively up from the requiring module's location -// moduleDirectories: [ -// "node_modules" -// ], +// Fetch finished futures orders with USDT settlement ⋮---- -// An array of file extensions your modules use +settle: 'usdt', // Specify the settlement currency +status: 'finished', // Specify the status of the orders to fetch ⋮---- -// modulePaths: ['src'], +console.log('finishedOrders: ', finishedOrders); // Log the response to the console ⋮---- -// A map from regular expressions to module names or to arrays of module names that allow to stub out resources with a single module -// moduleNameMapper: {}, +console.error('Error in execution: ', e); // Log any errors that occur ⋮---- -// An array of regexp pattern strings, matched against all module paths before considered 'visible' to the module loader -// modulePathIgnorePatterns: [], +// Execute the function to get futures orders + +================ +File: examples/Rest/futures/getTickers.ts +================ +import { RestClient } from '../../../src/index.js'; // For an easy demonstration, import from the src dir. Normally though, see below to import from the npm installed version instead. +// import { RestClient } from 'gateio-api'; // Import the RestClient from the published version of this SDK, installed via NPM (npm install gateio-api) ⋮---- -// Activates notifications for test results -// notify: false, +// Define the account object with API key and secret ⋮---- -// An enum that specifies notification mode. Requires { notify: true } -// notifyMode: "failure-change", +key: process.env.API_KEY || 'yourApiHere', // Replace 'yourApiHere' with your actual API key +secret: process.env.API_SECRET || 'yourSecretHere', // Replace 'yourSecretHere' with your actual API secret ⋮---- -// A preset that is used as a base for Jest's configuration -// preset: undefined, +// Initialize the RestClient with the API credentials ⋮---- -// Run tests from one or more projects -// projects: undefined, +async function getFuturesTicker() ⋮---- -// Use this configuration option to add custom reporters to Jest -// reporters: undefined, +// Fetch all futures tickers with USDT settlement ⋮---- -// Automatically reset mock state before every test -// resetMocks: false, +settle: 'usdt', // Specify the settlement currency ⋮---- -// Reset the module registry before running each individual test -// resetModules: false, +console.log('allTickers: ', allTickers); // Log the response to the console ⋮---- -// A path to a custom resolver -// resolver: undefined, +// Fetch a specific futures ticker with USDT settlement ⋮---- -// Automatically restore mock state and implementation before every test -// restoreMocks: false, +settle: 'usdt', // Specify the settlement currency +contract: 'BTC_USDT', // Specify the contract ⋮---- -// The root directory that Jest should scan for tests and modules within -// rootDir: undefined, +console.log('ticker: ', ticker); // Log the response to the console ⋮---- -// A list of paths to directories that Jest should use to search for files in -// roots: [ -// "" -// ], +console.error('Error in execution: ', e); // Log any errors that occur ⋮---- -// Allows you to use a custom runner instead of Jest's default test runner -// runner: "jest-runner", +// Execute the function to get futures tickers + +================ +File: examples/Rest/futures/submitLimitOrder.ts +================ +import { RestClient } from '../../../src/index.js'; // For an easy demonstration, import from the src dir. Normally though, see below to import from the npm installed version instead. +// import { RestClient } from 'gateio-api'; // Import the RestClient from the published version of this SDK, installed via NPM (npm install gateio-api) ⋮---- -// The paths to modules that run some code to configure or set up the testing environment before each test -// setupFiles: [], +// Define the account object with API key and secret ⋮---- -// A list of paths to modules that run some code to configure or set up the testing framework before each test -// setupFilesAfterEnv: [], +key: process.env.API_KEY || 'yourApiHere', // Replace 'yourApiHere' with your actual API key +secret: process.env.API_SECRET || 'yourSecretHere', // Replace 'yourSecretHere' with your actual API secret ⋮---- -// The number of seconds after which a test is considered as slow and reported as such in the results. -// slowTestThreshold: 5, +// Initialize the RestClient with the API credentials ⋮---- -// A list of paths to snapshot serializer modules Jest should use for snapshot testing -// snapshotSerializers: [], +async function submitFuturesOrder() ⋮---- -// The test environment that will be used for testing -// testEnvironment: "jest-environment-node", +// Submit a limit order for futures trading ⋮---- -// Options that will be passed to the testEnvironment -// testEnvironmentOptions: {}, +settle: 'usdt', // Specify the settlement currency +contract: 'BTC_USDT', // Specify the contract +size: 10, // Order size: positive for long, negative for short +price: '45000', // Limit price for the order +tif: 'gtc', // Time in force: 'gtc' (Good Till Cancelled) ⋮---- -// Adds a location field to test results -// testLocationInResults: false, +console.log('Response: ', result); // Log the response to the console ⋮---- -// The glob patterns Jest uses to detect test files +console.error('Error in execution: ', e); // Log any errors that occur ⋮---- -// "**/__tests__/**/*.[jt]s?(x)", -⋮---- -// An array of regexp pattern strings that are matched against all test paths, matched tests are skipped -// testPathIgnorePatterns: [ -// "/node_modules/" -// ], -⋮---- -// The regexp pattern or array of patterns that Jest uses to detect test files -// testRegex: [], +// Execute the function to submit a futures order + +================ +File: examples/Rest/futures/submitMarketOrder.ts +================ +import { RestClient } from '../../../src/index.js'; // For an easy demonstration, import from the src dir. Normally though, see below to import from the npm installed version instead. +// import { RestClient } from 'gateio-api'; // Import the RestClient from the published version of this SDK, installed via NPM (npm install gateio-api) ⋮---- -// This option allows the use of a custom results processor -// testResultsProcessor: undefined, +// Define the account object with API key and secret ⋮---- -// This option allows use of a custom test runner -// testRunner: "jest-circus/runner", +key: process.env.API_KEY || 'yourApiHere', // Replace 'yourApiHere' with your actual API key +secret: process.env.API_SECRET || 'yourSecretHere', // Replace 'yourSecretHere' with your actual API secret ⋮---- -// A map from regular expressions to paths to transformers -// transform: undefined, +// Initialize the RestClient with the API credentials ⋮---- -// An array of regexp pattern strings that are matched against all source file paths, matched files will skip transformation -// transformIgnorePatterns: [ -// "/node_modules/", -// "\\.pnp\\.[^\\/]+$" -// ], +async function submitFuturesOrder() ⋮---- -// Prevents import esm module error from v1 axios release, issue #5026 +// Submit a market order for futures trading ⋮---- -// An array of regexp pattern strings that are matched against all modules before the module loader will automatically return a mock for them -// unmockedModulePathPatterns: undefined, +settle: 'usdt', // Specify the settlement currency +contract: 'BTC_USDT', // Specify the contract +size: 20, // Order size: positive for long, negative for short +price: '0', // Market order, so price is set to '0' +tif: 'ioc', // Time in force: 'ioc' (Immediate Or Cancel) ⋮---- -// Indicates whether each individual test should be reported during the run -// verbose: undefined, -verbose: true, // report individual test +console.log('Response: ', result); // Log the response to the console ⋮---- -// An array of regexp patterns that are matched against all source file paths before re-running tests in watch mode -// watchPathIgnorePatterns: [], +console.error('Error in execution: ', e); // Log any errors that occur ⋮---- -// Whether to use watchman for file crawling -// watchman: true, - -================ -File: LICENSE.md -================ -Copyright 2022 Tiago Siebler - -Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - -================ -File: postBuild.sh -================ -#!/bin/bash -# -# Add package.json files to cjs/mjs subtrees -# - -cat >dist/cjs/package.json <dist/mjs/package.json < reconnected. +console.error('Error in execution: ', e); // Log any errors that occur ⋮---- -// Reply to a request, e.g. "subscribe"/"unsubscribe"/"authenticate" +// Execute the function to submit a futures order ================ -File: examples/Rest/futures/getBalances.ts +File: examples/Rest/otc/createOTCBank.ts ================ +import { readFileSync } from 'fs'; +⋮---- import { RestClient } from '../../../src/index.js'; // For an easy demonstration, import from the src dir. Normally though, see below to import from the npm installed version instead. // import { RestClient } from 'gateio-api'; // Import the RestClient from the published version of this SDK, installed via NPM (npm install gateio-api) ⋮---- -// Define the account object with API key and secret +async function createOTCBankExample() ⋮---- -key: process.env.API_KEY || 'yourApiHere', // Replace 'yourApiHere' with your actual API key -secret: process.env.API_SECRET || 'yourSecretHere', // Replace 'yourSecretHere' with your actual API secret -⋮---- -// Initialize the RestClient with the API credentials -⋮---- -async function getFuturesBalances() -⋮---- -// Fetch the futures account balance for USDT settlement -⋮---- -console.log('Response: ', result); // Log the response to the console -⋮---- -console.error('Error in execution: ', e); // Log any errors that occur -⋮---- -// Execute the function to get futures balances +// Path to account-opening proof (jpg/jpeg/png/pdf, max 4MB per Gate docs) ================ -File: examples/Rest/futures/getContractSize.ts +File: examples/Rest/otc/getOTCBankList.ts ================ -/** - * Example: Get futures contract size (quanto_multiplier) and convert between - * notional (e.g. USDT) and order size in contracts. - * - * Gate.io futures orders use `size` = number of CONTRACTS, not currency amount. - * The contract details endpoint returns `quanto_multiplier`: the amount of - * underlying (e.g. BTC) that 1 contract represents. So: - * notional_in_settle = size * quanto_multiplier * price - * size = notional_in_settle / (quanto_multiplier * price) - * - * This example: - * 1) Fetches contract with getFuturesContract - * 2) Reads quanto_multiplier and derives "contract size" in quote currency - * 3) Converts a desired notional (e.g. 1000 USDT) to order size in contracts - */ -⋮---- import { RestClient } from '../../../src/index.js'; // import { RestClient } from 'gateio-api'; ⋮---- -async function getContractSizeExample() -⋮---- -// 1) Get single contract (public, no auth required) -⋮---- -// 2) Contract size in quote (settle) currency: 1 contract = q * p -⋮---- -// 3) Convert desired notional (e.g. 1000 USDT) to size in contracts -⋮---- -// Example: you would pass this size to submitFuturesOrder -// await client.submitFuturesOrder({ -// settle: SETTLE, -// contract: CONTRACT, -// size: size, // in contracts; positive = long, negative = short -// price: markPrice, -// tif: 'gtc', -// }); +async function getOTCBankListExample() ================ -File: examples/Rest/futures/getContractSizeExample.ts +File: examples/Rest/spot/getBalances.ts ================ -/** - * Example: Get futures contract size (quanto_multiplier) and convert between - * notional (e.g. USDT) and order size in contracts. - * - * Gate.io futures orders use `size` = number of CONTRACTS, not currency amount. - * The contract details endpoint returns `quanto_multiplier`: the amount of - * underlying (e.g. BTC) that 1 contract represents. So: - * notional_in_settle = size * quanto_multiplier * price - * size = notional_in_settle / (quanto_multiplier * price) - * - * This example: - * 1) Fetches contract with getFuturesContract - * 2) Reads quanto_multiplier and derives "contract size" in quote currency - * 3) Converts a desired notional (e.g. 1000 USDT) to order size in contracts - */ +import { RestClient } from '../../../src/index.js'; // For an easy demonstration, import from the src dir. Normally though, see below to import from the npm installed version instead. +// import { RestClient } from 'gateio-api'; // Import the RestClient from the published version of this SDK, installed via NPM (npm install gateio-api) ⋮---- -import { RestClient } from '../../../src/index.js'; -// import { RestClient } from 'gateio-api'; +// Define the account object with API key and secret ⋮---- -async function getContractSizeExample() +key: process.env.API_KEY || 'yourApiHere', // Replace 'yourApiHere' with your actual API key +secret: process.env.API_SECRET || 'yourSecretHere', // Replace 'yourSecretHere' with your actual API secret ⋮---- -// 1) Get single contract (public, no auth required) +// Initialize the RestClient with the API credentials ⋮---- -// 2) Contract size in quote (settle) currency: 1 contract = q * p +async function getSpotBalances() ⋮---- -// 3) Convert desired notional (e.g. 1000 USDT) to size in contracts +// Fetch the spot account balances ⋮---- -// Example: you would pass this size to submitFuturesOrder -// await client.submitFuturesOrder({ -// settle: SETTLE, -// contract: CONTRACT, -// size: size, // in contracts; positive = long, negative = short -// price: markPrice, -// tif: 'gtc', -// }); +console.log('Response: ', balances); // Log the response to the console +⋮---- +console.error('Error in execution: ', e); // Log any errors that occur +⋮---- +// Execute the function to get spot balances ================ -File: examples/Rest/futures/getOrders.ts +File: examples/Rest/spot/getCandles.ts ================ import { RestClient } from '../../../src/index.js'; // For an easy demonstration, import from the src dir. Normally though, see below to import from the npm installed version instead. // import { RestClient } from 'gateio-api'; // Import the RestClient from the published version of this SDK, installed via NPM (npm install gateio-api) ⋮---- // Define the account object with API key and secret ⋮---- -key: process.env.API_KEY || 'yourApiHere', // Replace 'yourApiHere' with your actual API key or use environment variables -secret: process.env.API_SECRET || 'yourSecretHere', // Replace 'yourSecretHere' with your actual API secret or use environment variables +key: process.env.API_KEY || 'yourApiHere', // Replace 'yourApiHere' with your actual API key +secret: process.env.API_SECRET || 'yourSecretHere', // Replace 'yourSecretHere' with your actual API secret ⋮---- // Initialize the RestClient with the API credentials ⋮---- -async function getFuturesOrders() -⋮---- -// Fetch open futures orders with USDT settlement -⋮---- -settle: 'usdt', // Specify the settlement currency -status: 'open', // Specify the status of the orders to fetch -⋮---- -console.log('openOrders: ', openOrders); // Log the response to the console -⋮---- -// Fetch finished futures orders with USDT settlement +async function getSpotCandles() ⋮---- -settle: 'usdt', // Specify the settlement currency -status: 'finished', // Specify the status of the orders to fetch +// Fetch the spot account balances ⋮---- -console.log('finishedOrders: ', finishedOrders); // Log the response to the console +console.log('Response: ', balances); // Log the response to the console ⋮---- console.error('Error in execution: ', e); // Log any errors that occur ⋮---- -// Execute the function to get futures orders +// Execute the function to get spot balances ================ -File: examples/Rest/futures/getTickers.ts +File: examples/Rest/spot/getOrders.ts ================ import { RestClient } from '../../../src/index.js'; // For an easy demonstration, import from the src dir. Normally though, see below to import from the npm installed version instead. // import { RestClient } from 'gateio-api'; // Import the RestClient from the published version of this SDK, installed via NPM (npm install gateio-api) @@ -2957,27 +2124,28 @@ secret: process.env.API_SECRET || 'yourSecretHere', // Replace 'yourSecretHere' ⋮---- // Initialize the RestClient with the API credentials ⋮---- -async function getFuturesTicker() +async function getSpotOrders() ⋮---- -// Fetch all futures tickers with USDT settlement +// Fetch open spot orders for the BTC_USDT currency pair ⋮---- -settle: 'usdt', // Specify the settlement currency +currency_pair: 'BTC_USDT', // Specify the currency pair +status: 'open', // Specify the status of the orders to fetch ⋮---- -console.log('allTickers: ', allTickers); // Log the response to the console +console.log('openOrders: ', openOrders); // Log the response to the console ⋮---- -// Fetch a specific futures ticker with USDT settlement +// Fetch finished spot orders for the BTC_USDT currency pair ⋮---- -settle: 'usdt', // Specify the settlement currency -contract: 'BTC_USDT', // Specify the contract +currency_pair: 'BTC_USDT', // Specify the currency pair +status: 'finished', // Specify the status of the orders to fetch ⋮---- -console.log('ticker: ', ticker); // Log the response to the console +console.log('finishedOrders: ', finishedOrders); // Log the response to the console ⋮---- console.error('Error in execution: ', e); // Log any errors that occur ⋮---- -// Execute the function to get futures tickers +// Execute the function to get spot orders ================ -File: examples/Rest/futures/submitLimitOrder.ts +File: examples/Rest/spot/getTickers.ts ================ import { RestClient } from '../../../src/index.js'; // For an easy demonstration, import from the src dir. Normally though, see below to import from the npm installed version instead. // import { RestClient } from 'gateio-api'; // Import the RestClient from the published version of this SDK, installed via NPM (npm install gateio-api) @@ -2989,24 +2157,24 @@ secret: process.env.API_SECRET || 'yourSecretHere', // Replace 'yourSecretHere' ⋮---- // Initialize the RestClient with the API credentials ⋮---- -async function submitFuturesOrder() +async function getSpotTicker() ⋮---- -// Submit a limit order for futures trading +// Fetch the ticker for a specific currency pair (BTC_USDT) ⋮---- -settle: 'usdt', // Specify the settlement currency -contract: 'BTC_USDT', // Specify the contract -size: 10, // Order size: positive for long, negative for short -price: '45000', // Limit price for the order -tif: 'gtc', // Time in force: 'gtc' (Good Till Cancelled) +currency_pair: 'BTC_USDT', // Specify the currency pair ⋮---- -console.log('Response: ', result); // Log the response to the console +console.log('Response: ', ticker); // Log the response to the console +⋮---- +// Fetch all tickers +⋮---- +console.log('Response: ', allTickers); // Log the response to the console ⋮---- console.error('Error in execution: ', e); // Log any errors that occur ⋮---- -// Execute the function to submit a futures order +// Execute the function to get spot tickers ================ -File: examples/Rest/futures/submitMarketOrder.ts +File: examples/Rest/spot/submitLimitOrder.ts ================ import { RestClient } from '../../../src/index.js'; // For an easy demonstration, import from the src dir. Normally though, see below to import from the npm installed version instead. // import { RestClient } from 'gateio-api'; // Import the RestClient from the published version of this SDK, installed via NPM (npm install gateio-api) @@ -3018,24 +2186,25 @@ secret: process.env.API_SECRET || 'yourSecretHere', // Replace 'yourSecretHere' ⋮---- // Initialize the RestClient with the API credentials ⋮---- -async function submitFuturesOrder() +async function submitSpotOrder() ⋮---- -// Submit a market order for futures trading +// Submit a limit order for spot trading ⋮---- -settle: 'usdt', // Specify the settlement currency -contract: 'BTC_USDT', // Specify the contract -size: 20, // Order size: positive for long, negative for short -price: '0', // Market order, so price is set to '0' -tif: 'ioc', // Time in force: 'ioc' (Immediate Or Cancel) +currency_pair: 'BTC_USDT', // Specify the currency pair +side: 'buy', // Specify the order side: 'buy' or 'sell' +type: 'limit', // Specify the order type: 'limit' +amount: '0.001', // Specify the amount to buy +price: '45000', // Specify the limit price +time_in_force: 'gtc', // Time in force: 'gtc' (Good Till Cancelled) ⋮---- console.log('Response: ', result); // Log the response to the console ⋮---- console.error('Error in execution: ', e); // Log any errors that occur ⋮---- -// Execute the function to submit a futures order +// Execute the function to submit a spot order ================ -File: examples/Rest/futures/testnet.ts +File: examples/Rest/spot/submitMarketOrder.ts ================ import { RestClient } from '../../../src/index.js'; // For an easy demonstration, import from the src dir. Normally though, see below to import from the npm installed version instead. // import { RestClient } from 'gateio-api'; // Import the RestClient from the published version of this SDK, installed via NPM (npm install gateio-api) @@ -3047,256 +2216,51 @@ secret: process.env.API_SECRET || 'yourSecretHere', // Replace 'yourSecretHere' ⋮---- // Initialize the RestClient with the API credentials ⋮---- -/** - * To use a different base URL, use the baseUrl key. The SDK uses the live environment by default: - * baseUrlKey: 'live', - *'https://api.gateio.ws/api/v4' - * But you can force it to use any of the available environments. Examples below. - */ -⋮---- -/* - * Futures TestNet trading: - * 'https://fx-api-testnet.gateio.ws/api/v4' - */ -⋮---- -/** - * Futures live trading alternative (futures only): - * 'https://fx-api.gateio.ws/api/v4' - */ -// baseUrlKey: 'futuresLiveAlternative' -⋮---- -async function submitFuturesOrder() +async function submitSpotOrder() ⋮---- -// Submit a market order for futures trading +// Submit a market order for spot trading ⋮---- -settle: 'usdt', // Specify the settlement currency -contract: 'BTC_USDT', // Specify the contract -size: 20, // Order size: positive for long, negative for short -price: '0', // Market order, so price is set to '0' -tif: 'ioc', // Time in force: 'ioc' (Immediate Or Cancel) +currency_pair: 'BTC_USDT', // Specify the currency pair +side: 'buy', // Specify the order side: 'buy' or 'sell' +type: 'market', // Specify the order type: 'market' +amount: '10', // Specify the amount to buy +time_in_force: 'ioc', // Time in force: 'ioc' (Immediate Or Cancel) ⋮---- console.log('Response: ', result); // Log the response to the console ⋮---- console.error('Error in execution: ', e); // Log any errors that occur ⋮---- -// Execute the function to submit a futures order +// Execute the function to submit a spot order ================ -File: examples/Rest/otc/createOTCBank.ts +File: examples/Websocket/WS-API/ws-api-client.ts ================ -import { readFileSync } from 'fs'; +import { WebsocketAPIClient, WS_KEY_MAP } from '../../../src/index.js'; +// import { LogParams, WebsocketClient } from 'gateio-api'; // normally you should install this module via npm: `npm install gateio-api` ⋮---- -import { RestClient } from '../../../src/index.js'; // For an easy demonstration, import from the src dir. Normally though, see below to import from the npm installed version instead. -// import { RestClient } from 'gateio-api'; // Import the RestClient from the published version of this SDK, installed via NPM (npm install gateio-api) +async function start() ⋮---- -async function createOTCBankExample() +/** + * Optional: authenticate in advance. This will prepare and authenticate a connection. + * Useful to save time for the first request but completely optional. It will also happen automatically when you make your first request. + */ +// console.log(new Date(), 'Authenticating in advance...'); +// await client.getWSClient().connectWSAPI('spotV4'); +// console.log(new Date(), 'Authenticating in advance...OK!'); ⋮---- -// Path to account-opening proof (jpg/jpeg/png/pdf, max 4MB per Gate docs) - -================ -File: examples/Rest/otc/getOTCBankList.ts -================ -import { RestClient } from '../../../src/index.js'; -// import { RestClient } from 'gateio-api'; +/* ============ SPOT TRADING EXAMPLES ============ */ ⋮---- -async function getOTCBankListExample() - -================ -File: examples/Rest/spot/getBalances.ts -================ -import { RestClient } from '../../../src/index.js'; // For an easy demonstration, import from the src dir. Normally though, see below to import from the npm installed version instead. -// import { RestClient } from 'gateio-api'; // Import the RestClient from the published version of this SDK, installed via NPM (npm install gateio-api) +// SPOT ORDER PLACE - Submit a new spot order ⋮---- -// Define the account object with API key and secret +// SPOT ORDER CANCEL - Cancel a specific spot order ⋮---- -key: process.env.API_KEY || 'yourApiHere', // Replace 'yourApiHere' with your actual API key -secret: process.env.API_SECRET || 'yourSecretHere', // Replace 'yourSecretHere' with your actual API secret +// SPOT ORDER CANCEL BY IDS - Cancel orders by ID list ⋮---- -// Initialize the RestClient with the API credentials +// SPOT ORDER CANCEL BY CURRENCY PAIR - Cancel all orders for a currency pair ⋮---- -async function getSpotBalances() +// SPOT ORDER AMEND - Update an existing spot order ⋮---- -// Fetch the spot account balances -⋮---- -console.log('Response: ', balances); // Log the response to the console -⋮---- -console.error('Error in execution: ', e); // Log any errors that occur -⋮---- -// Execute the function to get spot balances - -================ -File: examples/Rest/spot/getCandles.ts -================ -import { RestClient } from '../../../src/index.js'; // For an easy demonstration, import from the src dir. Normally though, see below to import from the npm installed version instead. -// import { RestClient } from 'gateio-api'; // Import the RestClient from the published version of this SDK, installed via NPM (npm install gateio-api) -⋮---- -// Define the account object with API key and secret -⋮---- -key: process.env.API_KEY || 'yourApiHere', // Replace 'yourApiHere' with your actual API key -secret: process.env.API_SECRET || 'yourSecretHere', // Replace 'yourSecretHere' with your actual API secret -⋮---- -// Initialize the RestClient with the API credentials -⋮---- -async function getSpotCandles() -⋮---- -// Fetch the spot account balances -⋮---- -console.log('Response: ', balances); // Log the response to the console -⋮---- -console.error('Error in execution: ', e); // Log any errors that occur -⋮---- -// Execute the function to get spot balances - -================ -File: examples/Rest/spot/getOrders.ts -================ -import { RestClient } from '../../../src/index.js'; // For an easy demonstration, import from the src dir. Normally though, see below to import from the npm installed version instead. -// import { RestClient } from 'gateio-api'; // Import the RestClient from the published version of this SDK, installed via NPM (npm install gateio-api) -⋮---- -// Define the account object with API key and secret -⋮---- -key: process.env.API_KEY || 'yourApiHere', // Replace 'yourApiHere' with your actual API key -secret: process.env.API_SECRET || 'yourSecretHere', // Replace 'yourSecretHere' with your actual API secret -⋮---- -// Initialize the RestClient with the API credentials -⋮---- -async function getSpotOrders() -⋮---- -// Fetch open spot orders for the BTC_USDT currency pair -⋮---- -currency_pair: 'BTC_USDT', // Specify the currency pair -status: 'open', // Specify the status of the orders to fetch -⋮---- -console.log('openOrders: ', openOrders); // Log the response to the console -⋮---- -// Fetch finished spot orders for the BTC_USDT currency pair -⋮---- -currency_pair: 'BTC_USDT', // Specify the currency pair -status: 'finished', // Specify the status of the orders to fetch -⋮---- -console.log('finishedOrders: ', finishedOrders); // Log the response to the console -⋮---- -console.error('Error in execution: ', e); // Log any errors that occur -⋮---- -// Execute the function to get spot orders - -================ -File: examples/Rest/spot/getTickers.ts -================ -import { RestClient } from '../../../src/index.js'; // For an easy demonstration, import from the src dir. Normally though, see below to import from the npm installed version instead. -// import { RestClient } from 'gateio-api'; // Import the RestClient from the published version of this SDK, installed via NPM (npm install gateio-api) -⋮---- -// Define the account object with API key and secret -⋮---- -key: process.env.API_KEY || 'yourApiHere', // Replace 'yourApiHere' with your actual API key -secret: process.env.API_SECRET || 'yourSecretHere', // Replace 'yourSecretHere' with your actual API secret -⋮---- -// Initialize the RestClient with the API credentials -⋮---- -async function getSpotTicker() -⋮---- -// Fetch the ticker for a specific currency pair (BTC_USDT) -⋮---- -currency_pair: 'BTC_USDT', // Specify the currency pair -⋮---- -console.log('Response: ', ticker); // Log the response to the console -⋮---- -// Fetch all tickers -⋮---- -console.log('Response: ', allTickers); // Log the response to the console -⋮---- -console.error('Error in execution: ', e); // Log any errors that occur -⋮---- -// Execute the function to get spot tickers - -================ -File: examples/Rest/spot/submitLimitOrder.ts -================ -import { RestClient } from '../../../src/index.js'; // For an easy demonstration, import from the src dir. Normally though, see below to import from the npm installed version instead. -// import { RestClient } from 'gateio-api'; // Import the RestClient from the published version of this SDK, installed via NPM (npm install gateio-api) -⋮---- -// Define the account object with API key and secret -⋮---- -key: process.env.API_KEY || 'yourApiHere', // Replace 'yourApiHere' with your actual API key -secret: process.env.API_SECRET || 'yourSecretHere', // Replace 'yourSecretHere' with your actual API secret -⋮---- -// Initialize the RestClient with the API credentials -⋮---- -async function submitSpotOrder() -⋮---- -// Submit a limit order for spot trading -⋮---- -currency_pair: 'BTC_USDT', // Specify the currency pair -side: 'buy', // Specify the order side: 'buy' or 'sell' -type: 'limit', // Specify the order type: 'limit' -amount: '0.001', // Specify the amount to buy -price: '45000', // Specify the limit price -time_in_force: 'gtc', // Time in force: 'gtc' (Good Till Cancelled) -⋮---- -console.log('Response: ', result); // Log the response to the console -⋮---- -console.error('Error in execution: ', e); // Log any errors that occur -⋮---- -// Execute the function to submit a spot order - -================ -File: examples/Rest/spot/submitMarketOrder.ts -================ -import { RestClient } from '../../../src/index.js'; // For an easy demonstration, import from the src dir. Normally though, see below to import from the npm installed version instead. -// import { RestClient } from 'gateio-api'; // Import the RestClient from the published version of this SDK, installed via NPM (npm install gateio-api) -⋮---- -// Define the account object with API key and secret -⋮---- -key: process.env.API_KEY || 'yourApiHere', // Replace 'yourApiHere' with your actual API key -secret: process.env.API_SECRET || 'yourSecretHere', // Replace 'yourSecretHere' with your actual API secret -⋮---- -// Initialize the RestClient with the API credentials -⋮---- -async function submitSpotOrder() -⋮---- -// Submit a market order for spot trading -⋮---- -currency_pair: 'BTC_USDT', // Specify the currency pair -side: 'buy', // Specify the order side: 'buy' or 'sell' -type: 'market', // Specify the order type: 'market' -amount: '10', // Specify the amount to buy -time_in_force: 'ioc', // Time in force: 'ioc' (Immediate Or Cancel) -⋮---- -console.log('Response: ', result); // Log the response to the console -⋮---- -console.error('Error in execution: ', e); // Log any errors that occur -⋮---- -// Execute the function to submit a spot order - -================ -File: examples/Websocket/WS-API/ws-api-client.ts -================ -import { WebsocketAPIClient, WS_KEY_MAP } from '../../../src/index.js'; -// import { LogParams, WebsocketClient } from 'gateio-api'; // normally you should install this module via npm: `npm install gateio-api` -⋮---- -async function start() -⋮---- -/** - * Optional: authenticate in advance. This will prepare and authenticate a connection. - * Useful to save time for the first request but completely optional. It will also happen automatically when you make your first request. - */ -// console.log(new Date(), 'Authenticating in advance...'); -// await client.getWSClient().connectWSAPI('spotV4'); -// console.log(new Date(), 'Authenticating in advance...OK!'); -⋮---- -/* ============ SPOT TRADING EXAMPLES ============ */ -⋮---- -// SPOT ORDER PLACE - Submit a new spot order -⋮---- -// SPOT ORDER CANCEL - Cancel a specific spot order -⋮---- -// SPOT ORDER CANCEL BY IDS - Cancel orders by ID list -⋮---- -// SPOT ORDER CANCEL BY CURRENCY PAIR - Cancel all orders for a currency pair -⋮---- -// SPOT ORDER AMEND - Update an existing spot order -⋮---- -// SPOT ORDER STATUS - Get status of a specific spot order +// SPOT ORDER STATUS - Get status of a specific spot order ⋮---- // SPOT ORDER LIST - Get list of spot orders ⋮---- @@ -3889,2300 +2853,2782 @@ deleteTopic(key: WsKey, topic: TWSTopicSubscribeEventArgs) // Check if we're subscribed to a topic like this ================ -File: src/lib/BaseWSClient.ts +File: src/lib/multipartUtil.ts ================ -import EventEmitter from 'events'; -import WebSocket from 'isomorphic-ws'; -⋮---- -import { - WebsocketClientOptions, - WSClientConfigurableOptions, -} from '../types/websockets/client.js'; -import { WsOperation } from '../types/websockets/requests.js'; -import { WS_LOGGER_CATEGORY } from '../WebsocketClient.js'; -import { DefaultLogger } from './logger.js'; -import { isMessageEvent, MessageEventLike } from './requestUtils.js'; -import { checkWebCryptoAPISupported } from './webCryptoAPI.js'; -import { - safeTerminateWs, - WsTopicRequest, - WsTopicRequestOrStringTopic, -} from './websocket/websocket-util.js'; -import { WsStore } from './websocket/WsStore.js'; -import { - WSConnectedResult, - WsConnectionStateEnum, -} from './websocket/WsStore.types.js'; -⋮---- -interface WSClientEventMap { - /** Connection opened. If this connection was previously opened and reconnected, expect the reconnected event instead */ - open: (evt: { - wsKey: WsKey; - event: any; - wsUrl: string; - ws: WebSocket; - }) => void /** Reconnecting a dropped connection */; - reconnect: (evt: { wsKey: WsKey; event: any }) => void; - /** Successfully reconnected a connection that dropped */ - reconnected: (evt: { - wsKey: WsKey; - event: any; - wsUrl: string; - ws: WebSocket; - }) => void; - /** Connection closed */ - close: (evt: { wsKey: WsKey; event: any }) => void; - /** Received reply to websocket command (e.g. after subscribing to topics) */ - response: (response: any & { wsKey: WsKey }) => void; - /** Received data for topic */ - update: (response: any & { wsKey: WsKey }) => void; - /** Exception from ws client OR custom listeners (e.g. if you throw inside your event handler) */ - exception: (response: any & { wsKey: WsKey }) => void; - error: (response: any & { wsKey: WsKey }) => void; - /** Confirmation that a connection successfully authenticated */ - authenticated: (event: { wsKey: WsKey; event: any }) => void; -} +/** File payload for Gate multipart/form-data OTC endpoints */ +export type GateMultipartFile = + | Blob + | Buffer + | { filename?: string; content: Blob | Buffer }; ⋮---- -/** Connection opened. If this connection was previously opened and reconnected, expect the reconnected event instead */ +export function appendGateMultipartFile( + form: FormData, + fieldName: string, + file: GateMultipartFile, +): void ⋮---- -}) => void /** Reconnecting a dropped connection */; +export function appendGateMultipartFields( + form: FormData, + fields: Record, +): void + +================ +File: src/lib/requestUtils.ts +================ +import WebSocket from 'isomorphic-ws'; ⋮---- -/** Successfully reconnected a connection that dropped */ +import { GateBaseUrlKey } from '../types/shared.js'; ⋮---- -/** Connection closed */ -⋮---- -/** Received reply to websocket command (e.g. after subscribing to topics) */ +export interface RestClientOptions { + /** Your API key */ + apiKey?: string; + + /** Your API secret */ + apiSecret?: string; + + /** + * Override the default/global max size of the request window (in ms) for signed api calls. + * If you don't include a recv window when making an API call, this value will be used as default + */ + recvWindow?: number; + + /** Default: false. If true, we'll throw errors if any params are undefined */ + strictParamValidation?: boolean; + + /** + * Optionally override API protocol + domain + * e.g baseUrl: 'https://api.gate.io' + **/ + baseUrl?: string; + + // manually override with one of the known base URLs in the library + baseUrlKey?: GateBaseUrlKey; + + /** Default: true. whether to try and post-process request exceptions (and throw them). */ + parseExceptions?: boolean; + + /** + * Enable keep alive for REST API requests (via axios). + * See: https://github.com/tiagosiebler/bybit-api/issues/368 + */ + keepAlive?: boolean; + + /** + * When using HTTP KeepAlive, how often to send TCP KeepAlive packets over sockets being kept alive. Default = 1000. + * Only relevant if keepAlive is set to true. + * Default: 1000 (defaults comes from https agent) + */ + keepAliveMsecs?: number; + + /** + * Allows you to provide a custom "signMessage" function, e.g. to use node's much faster createHmac method + * + * Look in the examples folder for a demonstration on using node's createHmac instead. + */ + customSignMessageFn?: (message: string, secret: string) => Promise; + + /** + * When true, sends `X-Gate-Size-Decimal: 1` on futures/delivery REST and WebSocket traffic so size-related fields are returned as decimal strings instead of integers rounded down. + * @default false + */ + futuresSizeDecimal?: boolean; +} ⋮---- -/** Received data for topic */ +/** Your API key */ ⋮---- -/** Exception from ws client OR custom listeners (e.g. if you throw inside your event handler) */ +/** Your API secret */ ⋮---- -/** Confirmation that a connection successfully authenticated */ +/** + * Override the default/global max size of the request window (in ms) for signed api calls. + * If you don't include a recv window when making an API call, this value will be used as default + */ ⋮---- -export interface EmittableEvent { - eventType: 'response' | 'update' | 'exception' | 'authenticated'; - event: TEvent; -} +/** Default: false. If true, we'll throw errors if any params are undefined */ ⋮---- -// Type safety for on and emit handlers: https://stackoverflow.com/a/61609010/880837 -export interface BaseWebsocketClient { - on>( - event: U, - listener: WSClientEventMap[U], - ): this; - - emit>( - event: U, - ...args: Parameters[U]> - ): boolean; -} +/** + * Optionally override API protocol + domain + * e.g baseUrl: 'https://api.gate.io' + **/ ⋮---- -on>( - event: U, - listener: WSClientEventMap[U], - ): this; +// manually override with one of the known base URLs in the library ⋮---- -emit>( - event: U, - ...args: Parameters[U]> - ): boolean; +/** Default: true. whether to try and post-process request exceptions (and throw them). */ ⋮---- /** - * Users can conveniently pass topics as strings or objects (object has topic name + optional params). - * - * This method normalises topics into objects (object has topic name + optional params). - */ -function getNormalisedTopicRequests( - wsTopicRequests: WsTopicRequestOrStringTopic[], -): WsTopicRequest[] -⋮---- -// passed as string, convert to object -⋮---- -// already a normalised object, thanks to user + * Enable keep alive for REST API requests (via axios). + * See: https://github.com/tiagosiebler/bybit-api/issues/368 + */ ⋮---- /** - * Base WebSocket abstraction layer. Handles connections, tracking each connection as a unique "WS Key" - */ -// eslint-disable-next-line @typescript-eslint/no-unsafe-declaration-merging -export abstract class BaseWebsocketClient< + * When using HTTP KeepAlive, how often to send TCP KeepAlive packets over sockets being kept alive. Default = 1000. + * Only relevant if keepAlive is set to true. + * Default: 1000 (defaults comes from https agent) + */ ⋮---- /** - * The WS connections supported by the client, each identified by a unique primary key + * Allows you to provide a custom "signMessage" function, e.g. to use node's much faster createHmac method + * + * Look in the examples folder for a demonstration on using node's createHmac instead. */ ⋮---- /** - * State store to track a list of topics (topic requests) we are expected to be subscribed to if reconnected + * When true, sends `X-Gate-Size-Decimal: 1` on futures/delivery REST and WebSocket traffic so size-related fields are returned as decimal strings instead of integers rounded down. + * @default false */ ⋮---- -constructor( - options?: WSClientConfigurableOptions, - logger?: typeof DefaultLogger, -) +export function isFuturesMarketRestEndpoint(endpoint: string): boolean ⋮---- -// Some defaults: +export function isFuturesMarketWsKey(wsKey: string): boolean ⋮---- -// Gate.io only has one connection (for both public & private). Auth works with every sub, not on connect, so this is turned off. +/** Request headers for REST or WS when `futuresSizeDecimal` is enabled. */ +export function getFuturesSizeDecimalHeaders( + futuresSizeDecimal?: boolean, +): Record ⋮---- -// Gate.io requires auth to be added to every request, when subscribing to private topics. This is handled automatically. +export function serializeParams | undefined = {}>( + params: T, + strict_validation: boolean | undefined, + encodeValues: boolean, + prefixWith: string, +): string ⋮---- -// Automatically re-auth WS API, if we were auth'd before and get reconnected +// Only prefix if there's a value ⋮---- -// Check Web Crypto API support when credentials are provided and no custom sign function is used +export function getRestBaseUrl(restClientOptions: RestClientOptions): string ⋮---- -protected abstract isAuthOnConnectWsKey(wsKey: TWSKey): boolean; +export interface MessageEventLike { + target: WebSocket; + type: 'message'; + data: string; +} ⋮---- -protected abstract sendPingEvent(wsKey: TWSKey, ws: WebSocket): void; +export function isMessageEvent(msg: unknown): msg is MessageEventLike + +================ +File: src/types/request/announcement.ts +================ +/** POST /ann/list_article */ ⋮---- -protected abstract sendPongEvent(wsKey: TWSKey, ws: WebSocket): void; +export interface ListAnnouncementArticlesReq { + title_query?: string; + page?: string; + size?: string; + tags?: string; + timer?: string; + cate_name?: string; + cate_level?: string; + sub_website_id?: string; + pinned?: number; + update_after?: number; + lang?: string; + filter_empty_content?: number; +} + +================ +File: src/types/request/delivery.ts +================ +import { FuturesContractSize } from '../shared.js'; ⋮---- -protected abstract isWsPing(data: any): boolean; +/**========================================================================================================================== + * DELIVERY + * ========================================================================================================================== + */ ⋮---- -protected abstract isWsPong(data: any): boolean; +export interface GetDeliveryOrderBookReq { + settle: 'usdt'; + contract: string; + interval?: '0' | '0.1' | '0.01'; + limit?: number; + with_id?: boolean; +} ⋮---- -protected abstract getWsAuthRequestEvent(wsKey: TWSKey): Promise; +export interface GetDeliveryTradesReq { + settle: 'usdt'; + contract: string; + limit?: number; + last_id?: string; + from?: number; + to?: number; +} ⋮---- -protected abstract isPrivateTopicRequest( - request: WsTopicRequest, - wsKey: TWSKey, - ): boolean; +export interface GetDeliveryCandlesReq { + settle: 'usdt'; + contract: string; + from?: number; + to?: number; + limit?: number; + interval?: + | '10s' + | '30s' + | '1m' + | '5m' + | '15m' + | '30m' + | '1h' + | '2h' + | '4h' + | '6h' + | '8h' + | '12h' + | '1d' + | '7d' + | '1w' + | '30d'; +} ⋮---- -protected abstract getPrivateWSKeys(): TWSKey[]; +export interface GetDeliveryBookReq { + settle: 'usdt'; + limit?: number; + from?: number; + to?: number; + type?: + | 'dnw' + | 'pnl' + | 'fee' + | 'refr' + | 'fund' + | 'point_dnw' + | 'point_fee' + | 'point_refr' + | 'bonus_offset'; +} ⋮---- -protected abstract getWsUrl(wsKey: TWSKey): string; +export interface SubmitDeliveryFuturesOrderReq { + settle: 'usdt'; + contract: string; + /** String when `futuresSizeDecimal` is enabled on the client. */ + size: FuturesContractSize; + /** String when `futuresSizeDecimal` is enabled on the client. */ + iceberg?: FuturesContractSize; + price?: string; + close?: boolean; + reduce_only?: boolean; + tif?: string; + text?: string; + auto_size?: string; + stp_act?: string; +} ⋮---- -protected abstract getMaxTopicsPerSubscribeEvent( - wsKey: TWSKey, - ): number | null; +/** String when `futuresSizeDecimal` is enabled on the client. */ ⋮---- -/** - * Returns a list of string events that can be individually sent upstream to complete subscribing/unsubscribing/etc to these topics - */ -protected abstract getWsOperationEventsForTopics( - topics: WsTopicRequest[], - wsKey: TWSKey, - operation: WsOperation, - ): Promise; -⋮---- -/** - * Abstraction called to sort ws events into emittable event types (response to a request, data update, etc) - */ -protected abstract resolveEmittableEvents( - wsKey: TWSKey, - event: MessageEventLike, - ): EmittableEvent[]; -⋮---- -/** - * Request connection of all dependent (public & private) websockets, instead of waiting for automatic connection by library - */ -protected abstract connectAll(): Promise[]; +/** String when `futuresSizeDecimal` is enabled on the client. */ ⋮---- -protected isPrivateWsKey(wsKey: TWSKey): boolean +export interface GetDeliveryOrdersReq { + settle: 'usdt'; + contract?: string; + status: 'open' | 'finished'; + limit?: number; + offset?: number; + last_id?: string; + count_total?: 0 | 1; +} ⋮---- -/** Returns auto-incrementing request ID, used to track promise references for async requests */ -protected getNewRequestId(): string +export interface GetDeliveryTradingHistoryReq { + settle: 'usdt'; + contract?: string; + order?: number; + limit?: number; + offset?: number; + last_id?: string; + count_total?: 0 | 1; +} ⋮---- -protected abstract sendWSAPIRequest( - wsKey: TWSKey, - channel: string, - params?: any, - ): Promise; +export interface GetDeliveryClosedPositionsReq { + settle: 'usdt'; + contract?: string; + limit?: number; +} ⋮---- -protected abstract sendWSAPIRequest( - wsKey: TWSKey, - channel: string, - params: any, - ): Promise; +export interface GetDeliveryLiquidationHistoryReq { + settle: 'usdt'; + contract?: string; + limit?: number; + at?: number; +} ⋮---- -public getTimeOffsetMs() +export interface GetDeliverySettlementHistoryReq { + settle: 'usdt'; + contract?: string; + limit?: number; + at?: number; +} +export interface GetDeliveryAutoOrdersReq { + settle: 'usdt'; + status: 'open' | 'finished'; + contract?: string; + limit?: number; + offset?: number; +} + +================ +File: src/types/request/options.ts +================ +/**========================================================================================================================== + * OPTIONS + * ========================================================================================================================== + */ +export interface GetOptionsSettlementHistoryReq { + underlying: string; + limit?: number; + offset?: number; + from?: number; + to?: number; +} +export interface GetOptionsMySettlementsReq { + underlying: string; + contract?: string; + limit?: number; + offset?: number; + from?: number; + to?: number; +} ⋮---- -// TODO: not implemented -public setTimeOffsetMs(newOffset: number) +export interface GetOptionsOrderBookReq { + contract: string; + interval?: '0' | '0.1' | '0.01'; + limit?: number; + with_id?: boolean; +} ⋮---- -/** - * Don't call directly! Use subscribe() instead! - * - * Subscribe to one or more topics on a WS connection (identified by WS Key). - * - * - Topics are automatically cached - * - Connections are automatically opened, if not yet connected - * - Authentication is automatically handled - * - Topics are automatically resubscribed to, if something happens to the connection, unless you call unsubsribeTopicsForWsKey(topics, key). - * - * @param wsRequests array of topics to subscribe to - * @param wsKey ws key referring to the ws connection these topics should be subscribed on - */ -protected subscribeTopicsForWsKey( - wsTopicRequests: WsTopicRequestOrStringTopic[], - wsKey: TWSKey, -) +export interface GetOptionsCandlesReq { + contract: string; + limit?: number; + from?: number; + to?: number; + interval?: '1m' | '5m' | '15m' | '30m' | '1h'; +} ⋮---- -// Store topics, so future automation (post-auth, post-reconnect) has everything needed to resubscribe automatically +export interface GetOptionsUnderlyingCandlesReq { + underlying: string; + limit?: number; + from?: number; + to?: number; + interval?: '1m' | '5m' | '15m' | '30m' | '1h'; +} ⋮---- -// start connection process if it hasn't yet begun. Topics are automatically subscribed to on-connect +export interface GetOptionsTradesReq { + contract?: string; + type?: 'C' | 'P'; + limit?: number; + offset?: number; + from?: number; + to?: number; +} ⋮---- -// Subscribe should happen automatically once connected, nothing to do here after topics are added to wsStore. +export interface GetOptionsAccountChangeReq { + limit?: number; + offset?: number; + from?: number; + to?: number; + type?: 'dnw' | 'prem' | 'fee' | 'refr' | 'set'; +} ⋮---- -/** - * Are we in the process of connection? Nothing to send yet. - */ +export interface SubmitOptionsOrderReq { + contract: string; + size: number; + iceberg?: number; + price?: string; + close?: boolean; + reduce_only?: boolean; + tif?: 'gtc' | 'ioc' | 'poc'; + text?: string; +} ⋮---- -// We're connected. Check if auth is needed and if already authenticated +export interface AmendOptionsOrderReq { + contract: string; // Options contract name + price: string; // Order price + size: number; // Order size +} ⋮---- -/** - * If not authenticated yet and auth is required, don't request topics yet. - * - * Auth should already automatically be in progress, so no action needed from here. Topics will automatically subscribe post-auth success. - */ +contract: string; // Options contract name +price: string; // Order price +size: number; // Order size ⋮---- -// Finally, request subscription to topics if the connection is healthy and ready +export interface GetOptionsOrdersReq { + contract?: string; + underlying?: string; + status: 'open' | 'finished'; + limit?: number; + offset?: number; + from?: number; + to?: number; +} ⋮---- -protected unsubscribeTopicsForWsKey( - wsTopicRequests: WsTopicRequestOrStringTopic[], - wsKey: TWSKey, -) +export interface GetOptionsPersonalHistoryReq { + underlying: string; + contract?: string; + limit?: number; + offset?: number; + from?: number; + to?: number; +} ⋮---- -// Store topics, so future automation (post-auth, post-reconnect) has everything needed to resubscribe automatically +export interface OptionsMMPSettingsReq { + underlying: string; + window: number; // Time window in milliseconds, between 1-5000, 0 to disable MMP + frozen_period: number; // Frozen period in milliseconds, 0 to freeze indefinitely until reset API is called + qty_limit: string; // Maximum transaction volume (positive number, up to 2 decimal places) + delta_limit: string; // Maximum net delta value (positive number, up to 2 decimal places) +} ⋮---- -// If not connected, don't need to do anything. -// Removing the topic from the store is enough to stop it from being resubscribed to on reconnect. +window: number; // Time window in milliseconds, between 1-5000, 0 to disable MMP +frozen_period: number; // Frozen period in milliseconds, 0 to freeze indefinitely until reset API is called +qty_limit: string; // Maximum transaction volume (positive number, up to 2 decimal places) +delta_limit: string; // Maximum net delta value (positive number, up to 2 decimal places) + +================ +File: src/types/request/rebate.ts +================ +export interface GetAgencyTransactionHistoryReq { + currency_pair?: string; + user_id?: number; + from?: number; + to?: number; + limit?: number; + offset?: number; +} ⋮---- -// We're connected. Check if auth is needed and if already authenticated +export interface GetAgencyCommissionHistoryReq { + currency?: string; + user_id?: number; + from?: number; + to?: number; + limit?: number; + offset?: number; +} ⋮---- -/** - * If not authenticated yet and auth is required, don't need to do anything. - * We don't subscribe to topics until auth is complete anyway. - */ +export interface GetPartnerSubordinateListReq { + user_id?: number; + limit?: number; + offset?: number; +} ⋮---- -// Finally, request subscription to topics if the connection is healthy and ready +export interface GetBrokerCommissionHistoryReq { + limit?: number; + offset?: number; + user_id?: number; + from?: number; + to?: number; +} ⋮---- -/** - * Splits topic requests into two groups, public & private topic requests - */ -private sortTopicRequestsIntoPublicPrivate( - wsTopicRequests: WsTopicRequest[], - wsKey: TWSKey, -): +export interface GetBrokerTransactionHistoryReq { + limit?: number; + offset?: number; + user_id?: number; + from?: number; + to?: number; +} ⋮---- -/** Get the WsStore that tracks websockets & topics */ -public getWsStore(): WsStore> +// Interfaces for request and response +export interface PartnerTransactionReq { + currency_pair?: string; + user_id?: number; + from?: number; + to?: number; + limit?: number; + offset?: number; +} ⋮---- -public close(wsKey: TWSKey, force?: boolean) +/** GET /rebate/partner/data/aggregated */ +export interface GetPartnerAgentDataAggregatedReq { + /** `yyyy-mm-dd hh:ii:ss` (UTC+8); default start of last 7 days */ + start_date?: string; + /** `yyyy-mm-dd hh:ii:ss` (UTC+8); default end of last 7 days */ + end_date?: string; + /** + * 0 All (default), 1 Spot, 2 Futures, 3 Alpha, 4 Web3, 5 Perps (DEX), + * 6 Exchange All, 7 Web3 All, 8 TradFi. `trading_user_count` only when 0. + */ + business_type?: number; +} ⋮---- -public closeAll(force?: boolean) +/** `yyyy-mm-dd hh:ii:ss` (UTC+8); default start of last 7 days */ ⋮---- -public isConnected(wsKey: TWSKey): boolean +/** `yyyy-mm-dd hh:ii:ss` (UTC+8); default end of last 7 days */ ⋮---- /** - * Request connection to a specific websocket, instead of waiting for automatic connection. + * 0 All (default), 1 Spot, 2 Futures, 3 Alpha, 4 Web3, 5 Perps (DEX), + * 6 Exchange All, 7 Web3 All, 8 TradFi. `trading_user_count` only when 0. */ -protected async connect( - wsKey: TWSKey, -): Promise + +================ +File: src/types/response/alpha.ts +================ +/**========================================================================================================================== + * ALPHA + * ========================================================================================================================== + */ ⋮---- -private connectToWsUrl(url: string, wsKey: TWSKey): WebSocket +export interface AlphaAccount { + currency: string; // Currency name + available: string; // Available Balance + locked: string; // Locked balance + token_address: string; // Token address + chain: string; // Blockchain name +} ⋮---- -private parseWsError(context: string, error: any, wsKey: TWSKey) +currency: string; // Currency name +available: string; // Available Balance +locked: string; // Locked balance +token_address: string; // Token address +chain: string; // Blockchain name ⋮---- -/** Get a signature, build the auth request and send it */ -private async sendAuthRequest(wsKey: TWSKey): Promise +export interface AlphaAccountBook { + id: number; // Order ID + time: number; // Operation timestamp + currency: string; // Currency name + change: string; // Change amount + balance: string; // Balance after change +} ⋮---- -// console.log('ws auth req', request); +id: number; // Order ID +time: number; // Operation timestamp +currency: string; // Currency name +change: string; // Change amount +balance: string; // Balance after change ⋮---- -private reconnectWithDelay(wsKey: TWSKey, connectionDelayMs: number) +export interface CreateAlphaQuoteResp { + quote_id: string; // Quote ID for order placement, valid for 1 minute + min_amount: string; // Minimum order size + max_amount: string; // Maximum order size + price: string; // Token Price (USDT-based) + slippage: string; // Slippage + estimate_gas_fee_amount_usdt: string; // Estimated Gas Fee (USDT-based) + order_fee: string; // Slippage tolerance (10 means 10% tolerance) + target_token_min_amount: string; // Minimum received amount + target_token_max_amount: string; // Maximum received amount + error_type: number; // Failure Type (0: Success, 1: Exceeds maximum value, 2: Below minimum value) +} ⋮---- -private ping(wsKey: TWSKey) +quote_id: string; // Quote ID for order placement, valid for 1 minute +min_amount: string; // Minimum order size +max_amount: string; // Maximum order size +price: string; // Token Price (USDT-based) +slippage: string; // Slippage +estimate_gas_fee_amount_usdt: string; // Estimated Gas Fee (USDT-based) +order_fee: string; // Slippage tolerance (10 means 10% tolerance) +target_token_min_amount: string; // Minimum received amount +target_token_max_amount: string; // Maximum received amount +error_type: number; // Failure Type (0: Success, 1: Exceeds maximum value, 2: Below minimum value) ⋮---- -private clearTimers(wsKey: TWSKey) +export interface CreateAlphaOrderResp { + order_id: string; // Order ID + status: number; // Order Status (0: All, 1: Processing, 2: Successful, 3: Failed, 4: Cancelled, 5: Buy order placed but transfer not completed, 6: Order cancelled but transfer not completed) + side: string; // Buy or sell orders (buy/sell) + gas_mode: string; // Trading mode (speed: Smart mode, custom: Custom mode) + create_time: number; // Creation timestamp + amount: string; // Trade Quantity + token_address: string; // Token contract address + chain: string; // Blockchain name +} ⋮---- -// Send a ping at intervals -private clearPingTimer(wsKey: TWSKey) +order_id: string; // Order ID +status: number; // Order Status (0: All, 1: Processing, 2: Successful, 3: Failed, 4: Cancelled, 5: Buy order placed but transfer not completed, 6: Order cancelled but transfer not completed) +side: string; // Buy or sell orders (buy/sell) +gas_mode: string; // Trading mode (speed: Smart mode, custom: Custom mode) +create_time: number; // Creation timestamp +amount: string; // Trade Quantity +token_address: string; // Token contract address +chain: string; // Blockchain name ⋮---- -// Expect a pong within a time limit -private clearPongTimer(wsKey: TWSKey) +export interface AlphaOrder { + order_id: string; // Order ID + tx_hash: string; // Transaction Hash + side: string; // Buy or sell orders (buy/sell) + usdt_amount: string; // Amount (USDT) + currency: string; // Token + currency_amount: string; // Token amount + status: number; // Order Status (0: All, 1: Processing, 2: Successful, 3: Failed, 4: Cancelled, 5: Buy order placed but transfer not completed, 6: Order cancelled but transfer not completed) + gas_mode: string; // Trading mode (speed: Smart mode, custom: Custom mode) + chain: string; // Blockchain + gas_fee: string; // Gas Fee (USDT-based) + transaction_fee: string; // Trading Fee (USDT-based) + failed_reason: string; // Failure reason (if applicable) + create_time: number; // Creation timestamp +} ⋮---- -// this.logger.trace(`Cleared pong timeout for "${wsKey}"`); +order_id: string; // Order ID +tx_hash: string; // Transaction Hash +side: string; // Buy or sell orders (buy/sell) +usdt_amount: string; // Amount (USDT) +currency: string; // Token +currency_amount: string; // Token amount +status: number; // Order Status (0: All, 1: Processing, 2: Successful, 3: Failed, 4: Cancelled, 5: Buy order placed but transfer not completed, 6: Order cancelled but transfer not completed) +gas_mode: string; // Trading mode (speed: Smart mode, custom: Custom mode) +chain: string; // Blockchain +gas_fee: string; // Gas Fee (USDT-based) +transaction_fee: string; // Trading Fee (USDT-based) +failed_reason: string; // Failure reason (if applicable) +create_time: number; // Creation timestamp ⋮---- -// this.logger.trace(`No active pong timer for "${wsKey}"`); +export interface AlphaCurrency { + currency: string; // Currency symbol + name: string; // Currency name + chain: string; // The main chain corresponding to the coin + address: string; // Contract Address + amount_precision: number; // Amount scale + precision: number; // Price scale + status: number; // Currency Trading Status (1: Normal trading, 2: Suspended trading, 3: Delisted) +} ⋮---- -/** - * Simply builds and sends subscribe events for a list of topics for a ws key - * - * @private Use the `subscribe(topics)` or `subscribeTopicsForWsKey(topics, wsKey)` method to subscribe to topics. Send WS message to subscribe to topics. - */ -private async requestSubscribeTopics( - wsKey: TWSKey, - topics: WsTopicRequest[], -) +currency: string; // Currency symbol +name: string; // Currency name +chain: string; // The main chain corresponding to the coin +address: string; // Contract Address +amount_precision: number; // Amount scale +precision: number; // Price scale +status: number; // Currency Trading Status (1: Normal trading, 2: Suspended trading, 3: Delisted) ⋮---- -// Automatically splits requests into smaller batches, if needed +export interface AlphaTicker { + currency: string; // Currency symbol + last: string; // Last trading price + change: string; // 24h price change percentage (negative for decrease, e.g., -7.45) + volume: string; // 24h Trading Volume (USDT) + market_cap: string; // Current Token Market Cap +} ⋮---- -`Subscribing to ${topics.length} "${wsKey}" topics in ${subscribeWsMessages.length} batches.`, // Events: "${JSON.stringify(topics)}" +currency: string; // Currency symbol +last: string; // Last trading price +change: string; // 24h price change percentage (negative for decrease, e.g., -7.45) +volume: string; // 24h Trading Volume (USDT) +market_cap: string; // Current Token Market Cap + +================ +File: src/types/response/announcement.ts +================ +export interface AnnouncementArticleLanguage { + code?: string; + name?: string; +} ⋮---- -// console.log(`batches: `, JSON.stringify(subscribeWsMessages, null, 2)); +export interface AnnouncementArticle { + id?: number; + title?: string; + brief?: string; + created?: string; + updated?: string; + release_time?: string; + views?: number; + author?: string; + author_id?: number; + tags?: string; + cate?: string; + is_top?: number; + cate_id?: number; + source?: string; + content_lang_list?: AnnouncementArticleLanguage[]; +} ⋮---- -// this.logger.trace(`Sending batch via message: "${wsMessage}"`); +export interface AnnouncementArticleListData { + list?: AnnouncementArticle[]; + total?: number; +} ⋮---- -/** - * Simply builds and sends unsubscribe events for a list of topics for a ws key - * - * @private Use the `unsubscribe(topics)` method to unsubscribe from topics. Send WS message to unsubscribe from topics. - */ -private async requestUnsubscribeTopics( - wsKey: TWSKey, - wsTopicRequests: WsTopicRequest[], -) +export interface AnnouncementArticleListResponse { + code?: number; + data?: AnnouncementArticleListData; + message?: string; + version?: string; +} + +================ +File: src/types/response/autoinvest.ts +================ +/**========================================================================================================================== + * EARN AUTO INVEST + * ========================================================================================================================== + */ ⋮---- -/** - * Try sending a string event on a WS connection (identified by the WS Key) - */ -public tryWsSend( - wsKey: TWSKey, - wsMessage: string, - throwExceptions?: boolean, -) -⋮---- -private async onWsOpen( - event: any, - wsKey: TWSKey, - url: string, - ws: WebSocket, -) -⋮---- -// Resolve & cleanup deferred "connection attempt in progress" promise -⋮---- -// eslint-disable-next-line @typescript-eslint/no-unused-vars -⋮---- -// Remove before resolving, in case there's more requests queued -⋮---- -// Some websockets require an auth packet to be sent after opening the connection -⋮---- -// Reconnect to topics known before it connected -⋮---- -// Request sub to public topics, if any -⋮---- -// Request sub to private topics, if auth on connect isn't needed -⋮---- -// If enabled, automatically reauth WS API if reconnected -⋮---- -// eslint-disable-next-line @typescript-eslint/no-unused-vars -⋮---- -/** - * Handle subscription to private topics _after_ authentication successfully completes asynchronously. - * - * Only used for exchanges that require auth before sending private topic subscription requests - */ -private onWsAuthenticated( - wsKey: TWSKey, - event: { isWSAPI?: boolean; WSAPIAuthChannel?: string }, -) -⋮---- -// Resolve & cleanup deferred "auth attempt in progress" promise -⋮---- -// Remove before continuing, in case there's more requests queued -⋮---- -private onWsMessage(event: unknown, wsKey: TWSKey, ws: WebSocket) -⋮---- -// any message can clear the pong timer - wouldn't get a message if the ws wasn't working -⋮---- -// console.log(`raw event: `, { data, dataType, emittableEvents }); -⋮---- -private onWsClose(event: unknown, wsKey: TWSKey) -⋮---- -// unintentional close, attempt recovery -⋮---- -// clean up any pending promises for this connection -⋮---- -// intentional close - clean up -// clean up any pending promises for this connection -⋮---- -// clean up any pending promises for this connection -⋮---- -// This was an intentional close, delete all state for this connection, as if it never existed: -⋮---- -private getWs(wsKey: TWSKey) +/** POST /earn/autoinvest/plans/create — example response shape */ +export interface CreateAutoInvestPlanResp { + id: number; + amount: string; + money: string; + next_time: number; + period_type: string; + period_day: number; + period_hour: number; + fund_flow: string; + fund_source: string; +} ⋮---- -private setWsState(wsKey: TWSKey, state: WsConnectionStateEnum) +export interface AutoInvestCoinItem { + key: string; + value: string; + asset_icon_url: string; + sort: number; +} ⋮---- -/** - * Promise-driven method to assert that a ws has successfully connected (will await until connection is open) - */ -protected async assertIsConnected(wsKey: TWSKey): Promise +export interface AutoInvestMinAmountResp { + min_amount: string; +} ⋮---- -// Already in progress? Await shared promise and retry +export interface AutoInvestPlanExecutionRecord { + id: number; + type: string; + money: string; + user_id: number; + plan_id: number; + plan_version: number; + amount: string; + create_time: number; + update_time: number; + status: string; + status_type: number; + /** 2 = buy, other = sell */ + side: number; + status_message: string; + detail: string; + asset: string; +} ⋮---- -// Start connection, it should automatically store/return a promise. +/** 2 = buy, other = sell */ ⋮---- -/** - * Promise-driven method to assert that a ws has been successfully authenticated (will await until auth is confirmed) - */ -public async assertIsAuthenticated(wsKey: TWSKey): Promise +export interface AutoInvestPlanExecutionRecordsPaginated { + page: number; + page_size: number; + total_page: number; + total: number; + list: AutoInvestPlanExecutionRecord[]; +} ⋮---- -// Already in progress? Await shared promise and retry +export interface AutoInvestOrderItem { + id: number; + type: string; + amount: string; + plan_id: number; + side: number; + asset: string; + record_id: number; + total_money: string; + market: string; + price: string; + create_time: number; + total: string; + fund_flow: string; + error_code: number; + error_msg: string; + status: number; +} ⋮---- -// this.logger.trace('assertIsAuthenticated(): ok'); +export interface AutoInvestConfigItem { + coin: string; + max_limit: string; +} ⋮---- -// Start authentication, it should automatically store/return a promise. - -================ -File: src/lib/multipartUtil.ts -================ -/** File payload for Gate multipart/form-data OTC endpoints */ -export type GateMultipartFile = - | Blob - | Buffer - | { filename?: string; content: Blob | Buffer }; +export interface AutoInvestPlanPortfolioItem { + asset: string; + ratio: string; + cum_invest?: string; + cum_hold?: string; + cum_redeem?: string; + avg_price?: string; + redeem_status?: number; + lend_amount?: string; +} ⋮---- -export function appendGateMultipartFile( - form: FormData, - fieldName: string, - file: GateMultipartFile, -): void +export interface AutoInvestPlanDetail { + id: number; + version: number; + name: string; + create_time: number; + update_time: number; + user_id: number; + money: string; + amount: string; + period_type: string; + period_day: number; + period_hour: number; + portfolio: AutoInvestPlanPortfolioItem[]; + next_time?: number; + period?: number; + fund_source?: string; + fund_flow?: string; +} ⋮---- -export function appendGateMultipartFields( - form: FormData, - fields: Record, -): void +export interface AutoInvestPlansListResp { + page: number; + page_size: number; + page_count: number; + total_count: number; + list: AutoInvestPlanDetail[]; +} ================ -File: src/types/request/options.ts +File: src/types/response/margin.ts ================ /**========================================================================================================================== - * OPTIONS + * MARGIN * ========================================================================================================================== */ -export interface GetOptionsSettlementHistoryReq { - underlying: string; - limit?: number; - offset?: number; - from?: number; - to?: number; -} -export interface GetOptionsMySettlementsReq { - underlying: string; - contract?: string; - limit?: number; - offset?: number; - from?: number; - to?: number; +⋮---- +export interface MarginAccount { + currency_pair: string; + locked: boolean; + risk: string; + base: { + currency: string; + available: string; + locked: string; + borrowed: string; + interest: string; + }; + quote: { + currency: string; + available: string; + locked: string; + borrowed: string; + interest: string; + }; } ⋮---- -export interface GetOptionsOrderBookReq { - contract: string; - interval?: '0' | '0.1' | '0.01'; - limit?: number; - with_id?: boolean; +export interface MarginBalanceHistoryRecord { + id: string; + time: string; + time_ms: number; + currency: string; + currency_pair: string; + change: string; + balance: string; + type: string; } ⋮---- -export interface GetOptionsCandlesReq { - contract: string; - limit?: number; - from?: number; - to?: number; - interval?: '1m' | '5m' | '15m' | '30m' | '1h'; -} -⋮---- -export interface GetOptionsUnderlyingCandlesReq { - underlying: string; - limit?: number; - from?: number; - to?: number; - interval?: '1m' | '5m' | '15m' | '30m' | '1h'; +export interface CrossMarginCurrency { + name: string; + rate: string; + prec: string; + discount: string; + min_borrow_amount: string; + user_max_borrow_amount: string; + total_max_borrow_amount: string; + price: string; + loanable: boolean; + status: number; } ⋮---- -export interface GetOptionsTradesReq { - contract?: string; - type?: 'C' | 'P'; - limit?: number; - offset?: number; - from?: number; - to?: number; +export interface CrossMarginAccount { + user_id: number; + refresh_time: number; + locked: boolean; + balances: { + [currency: string]: { + available: string; + freeze: string; + borrowed: string; + interest: string; + negative_liab: string; + futures_pos_liab: string; + equity: string; + total_freeze: string; + total_liab: string; + }; + }; + total: string; + borrowed: string; + interest: string; + risk: string; + total_initial_margin: string; + total_margin_balance: string; + total_maintenance_margin: string; + total_initial_margin_rate: string; + total_maintenance_margin_rate: string; + total_available_margin: string; + portfolio_margin_total: string; + portfolio_margin_total_liab: string; + portfolio_margin_total_equity: string; } ⋮---- -export interface GetOptionsAccountChangeReq { - limit?: number; - offset?: number; - from?: number; - to?: number; - type?: 'dnw' | 'prem' | 'fee' | 'refr' | 'set'; +export interface CrossMarginAccountHistoryRecord { + id: string; + time: number; + currency: string; + change: string; + balance: string; + type: string; } ⋮---- -export interface SubmitOptionsOrderReq { - contract: string; - size: number; - iceberg?: number; - price?: string; - close?: boolean; - reduce_only?: boolean; - tif?: 'gtc' | 'ioc' | 'poc'; +export interface CrossMarginMorrowLoanRecord { + id: string; + create_time: number; + update_time: number; + currency: string; + amount: string; text?: string; + status: number; + repaid: string; + repaid_interest: string; + unpaid_interest: string; } ⋮---- -export interface AmendOptionsOrderReq { - contract: string; // Options contract name - price: string; // Order price - size: number; // Order size -} -⋮---- -contract: string; // Options contract name -price: string; // Order price -size: number; // Order size -⋮---- -export interface GetOptionsOrdersReq { - contract?: string; - underlying?: string; - status: 'open' | 'finished'; - limit?: number; - offset?: number; - from?: number; - to?: number; -} -⋮---- -export interface GetOptionsPersonalHistoryReq { - underlying: string; - contract?: string; - limit?: number; - offset?: number; - from?: number; - to?: number; +export interface MarginUserAccount { + currency_pair: string; + account_type: string; // Description updated to remove "risk" option + leverage: string; + locked: boolean; + risk?: string; // Deprecated + mmr?: string; // Refined description + base: { + currency: string; + available: string; + locked: string; + borrowed: string; + interest: string; + }; + quote: { + currency: string; + available: string; + locked: string; + borrowed: string; + interest: string; + }; } ⋮---- -export interface OptionsMMPSettingsReq { - underlying: string; - window: number; // Time window in milliseconds, between 1-5000, 0 to disable MMP - frozen_period: number; // Frozen period in milliseconds, 0 to freeze indefinitely until reset API is called - qty_limit: string; // Maximum transaction volume (positive number, up to 2 decimal places) - delta_limit: string; // Maximum net delta value (positive number, up to 2 decimal places) -} +account_type: string; // Description updated to remove "risk" option ⋮---- -window: number; // Time window in milliseconds, between 1-5000, 0 to disable MMP -frozen_period: number; // Frozen period in milliseconds, 0 to freeze indefinitely until reset API is called -qty_limit: string; // Maximum transaction volume (positive number, up to 2 decimal places) -delta_limit: string; // Maximum net delta value (positive number, up to 2 decimal places) +risk?: string; // Deprecated +mmr?: string; // Refined description ================ -File: src/types/request/rebate.ts +File: src/types/response/multicollateralLoan.ts ================ -export interface GetAgencyTransactionHistoryReq { - currency_pair?: string; - user_id?: number; - from?: number; - to?: number; - limit?: number; - offset?: number; -} -⋮---- -export interface GetAgencyCommissionHistoryReq { - currency?: string; - user_id?: number; - from?: number; - to?: number; - limit?: number; - offset?: number; -} -⋮---- -export interface GetPartnerSubordinateListReq { - user_id?: number; - limit?: number; - offset?: number; -} -⋮---- -export interface GetBrokerCommissionHistoryReq { - limit?: number; - offset?: number; - user_id?: number; - from?: number; - to?: number; -} -⋮---- -export interface GetBrokerTransactionHistoryReq { - limit?: number; - offset?: number; - user_id?: number; - from?: number; - to?: number; -} +/**========================================================================================================================== + * MULTI COLLATERAL LOAN + * ========================================================================================================================== + */ ⋮---- -// Interfaces for request and response -export interface PartnerTransactionReq { - currency_pair?: string; - user_id?: number; - from?: number; - to?: number; - limit?: number; - offset?: number; +export interface MultiLoanOrder { + order_id: string; + order_type: string; + fixed_type: string; + fixed_rate: string; + expire_time: number; + auto_renew: boolean; + auto_repay: boolean; + current_ltv: string; + status: string; + borrow_time: number; + total_left_repay_usdt: string; + total_left_collateral_usdt: string; + borrow_currencies: { + currency: string; + index_price: string; + left_repay_principal: string; + left_repay_interest: string; + left_repay_usdt: string; + }[]; + collateral_currencies: { + currency: string; + index_price: string; + left_collateral: string; + left_collateral_usdt: string; + }[]; } ⋮---- -/** GET /rebate/partner/data/aggregated */ -export interface GetPartnerAgentDataAggregatedReq { - /** `yyyy-mm-dd hh:ii:ss` (UTC+8); default start of last 7 days */ - start_date?: string; - /** `yyyy-mm-dd hh:ii:ss` (UTC+8); default end of last 7 days */ - end_date?: string; - /** - * 0 All (default), 1 Spot, 2 Futures, 3 Alpha, 4 Web3, 5 Perps (DEX), - * 6 Exchange All, 7 Web3 All, 8 TradFi. `trading_user_count` only when 0. - */ - business_type?: number; +export interface RepayMultiLoanResp { + order_id: number; + repaid_currencies: { + succeeded: boolean; + label?: string; + message?: string; + currency: string; + repaid_principal: string; + repaid_interest: string; + }[]; } ⋮---- -/** `yyyy-mm-dd hh:ii:ss` (UTC+8); default start of last 7 days */ -⋮---- -/** `yyyy-mm-dd hh:ii:ss` (UTC+8); default end of last 7 days */ -⋮---- -/** - * 0 All (default), 1 Spot, 2 Futures, 3 Alpha, 4 Web3, 5 Perps (DEX), - * 6 Exchange All, 7 Web3 All, 8 TradFi. `trading_user_count` only when 0. - */ - -================ -File: src/types/request/stock.ts -================ -/** Stock / TradFi Spot API request types */ -⋮---- -export interface GetStockUserAssetsReq { - pnl_calc_type?: number; - pnl_calc_price?: number; -} -⋮---- -export interface GetStockSymbolsReq { - symbols?: string; - exchange?: string; // us | hk | jp - with_desc_i18n?: boolean; - page?: number; - page_size?: number; -} -⋮---- -exchange?: string; // us | hk | jp -⋮---- -export interface GetStockSymbolDetailReq { - symbols?: string; - exchange?: string; // us | hk | jp - page?: number; - page_size?: number; -} -⋮---- -exchange?: string; // us | hk | jp -⋮---- -export interface GetStockOrdersReq { - symbol?: string; +export interface MultiLoanRepayRecord { + order_id: number; + record_id: number; + init_ltv: string; + before_ltv: string; + after_ltv: string; + borrow_time: number; + repay_time: number; + borrow_currencies: { + currency: string; + index_price: string; + before_amount: string; + before_amount_usdt: string; + after_amount: string; + after_amount_usdt: string; + }[]; + collateral_currencies: { + currency: string; + index_price: string; + before_amount: string; + before_amount_usdt: string; + after_amount: string; + after_amount_usdt: string; + }[]; + repaid_currencies: { + currency: string; + index_price: string; + repaid_amount: string; + repaid_principal: string; + repaid_interest: string; + repaid_amount_usdt: string; + }[]; + total_interest_list: { + currency: string; + index_price: string; + amount: string; + amount_usdt: string; + }[]; + left_repay_interest_list: { + currency: string; + index_price: string; + before_amount: string; + before_amount_usdt: string; + after_amount: string; + after_amount_usdt: string; + }[]; } ⋮---- -export interface CreateStockOrderReq { - volume: string; - symbol: string; - side: 1 | 2; - price_type: 'market' | 'limit'; - /** Limit: all only; market: regular only */ - trading_session: 'all' | 'regular'; - time_in_force: 'day'; - price?: string; - client_order_id?: string; +export interface UpdateMultiLoanResp { + order_id: number; + collateral_currencies: { + succeeded: boolean; + label?: string; + message?: string; + currency: string; + amount: string; + }[]; } ⋮---- -/** Limit: all only; market: regular only */ -⋮---- -export interface GetStockOrderHistoryReq { - symbol?: string; - order_ids?: string; - begin_time?: number; - end_time?: number; - side?: 1 | 2; - page?: number; - page_size?: number; +export interface MultiLoanAdjustmentRecord { + order_id: number; + record_id: number; + before_ltv: string; + after_ltv: string; + operate_time: number; + borrow_currencies: { + currency: string; + index_price: string; + before_amount: string; + before_amount_usdt: string; + after_amount: string; + after_amount_usdt: string; + }[]; + collateral_currencies: { + currency: string; + index_price: string; + before_amount: string; + before_amount_usdt: string; + after_amount: string; + after_amount_usdt: string; + }[]; } ⋮---- -export interface UpdateStockOrderReq { - volume: string; - price: string; +export interface MultiLoanCurrencyQuota { + currency: string; + index_price: string; + min_quota: string; + left_quota: string; + left_quote_usdt: string; + /** Remaining borrow/collateral limit for fixed-term currency */ + left_quota_fixed?: string; + /** Remaining currency limit for fixed-term converted to USDT */ + left_quote_usdt_fixed?: string; } ⋮---- -export interface GetStockPositionsReq { - pnl_calc_type?: number; - pnl_calc_price?: number; - symbol?: string; - exchange?: string; // us | hk | jp -} +/** Remaining borrow/collateral limit for fixed-term currency */ ⋮---- -exchange?: string; // us | hk | jp +/** Remaining currency limit for fixed-term converted to USDT */ ⋮---- -export interface CloseStockPositionReq { - symbol: string; - close_type: 1 | 2; - close_volume?: string; +export interface MultiLoanSupportedCurrencies { + loan_currencies: { + currency: string; + price: string; + }[]; + collateral_currencies: { + currency: string; + index_price: string; + discount: string; + }[]; } ⋮---- -export interface GetStockTransactionsReq { - begin_time?: number; - end_time?: number; - ref_id?: string; - type?: string; - page?: number; - page_size?: number; +export interface MultiLoanRatio { + init_ltv: string; + alert_ltv: string; + liquidate_ltv: string; } ⋮---- -export interface CreateStockTransactionReq { - asset: string; - change: string; - type: 'deposit' | 'withdraw'; - ref_id: string; +export interface MultiLoanFixedRate { + currency: string; + rate_7d: string; + rate_30d: string; + update_time: number; } ================ -File: src/types/response/alpha.ts +File: src/types/response/options.ts ================ /**========================================================================================================================== - * ALPHA + * OPTIONS * ========================================================================================================================== */ ⋮---- -export interface AlphaAccount { - currency: string; // Currency name - available: string; // Available Balance - locked: string; // Locked balance - token_address: string; // Token address - chain: string; // Blockchain name +export interface OptionsContract { + name: string; + tag: string; // Expiry period: day, week, month + create_time: number; + expiration_time: number; + is_call: boolean; + strike_price: string; + last_price: string; + mark_price: string; + orderbook_id: number; + trade_id?: number; // Deprecated + trade_size: number; + position_size: number; + underlying: string; + underlying_price: string; // Forward futures price for the delivery date + multiplier: string; // Option contract multiplier + order_price_round: string; + mark_price_round: string; // Minimum unit of mark price + maker_fee_rate: string; + taker_fee_rate: string; + price_limit_fee_rate: string; + ref_discount_rate: string; + ref_rebate_rate: string; + order_price_deviate?: string; // Deprecated + order_size_min: number; + order_size_max: number; + orders_limit: number; // Maximum number of orders per user in this market } ⋮---- -currency: string; // Currency name -available: string; // Available Balance -locked: string; // Locked balance -token_address: string; // Token address -chain: string; // Blockchain name +tag: string; // Expiry period: day, week, month ⋮---- -export interface AlphaAccountBook { - id: number; // Order ID - time: number; // Operation timestamp - currency: string; // Currency name - change: string; // Change amount - balance: string; // Balance after change -} +trade_id?: number; // Deprecated ⋮---- -id: number; // Order ID -time: number; // Operation timestamp -currency: string; // Currency name -change: string; // Change amount -balance: string; // Balance after change +underlying_price: string; // Forward futures price for the delivery date +multiplier: string; // Option contract multiplier ⋮---- -export interface CreateAlphaQuoteResp { - quote_id: string; // Quote ID for order placement, valid for 1 minute - min_amount: string; // Minimum order size - max_amount: string; // Maximum order size - price: string; // Token Price (USDT-based) - slippage: string; // Slippage - estimate_gas_fee_amount_usdt: string; // Estimated Gas Fee (USDT-based) - order_fee: string; // Slippage tolerance (10 means 10% tolerance) - target_token_min_amount: string; // Minimum received amount - target_token_max_amount: string; // Maximum received amount - error_type: number; // Failure Type (0: Success, 1: Exceeds maximum value, 2: Below minimum value) -} -⋮---- -quote_id: string; // Quote ID for order placement, valid for 1 minute -min_amount: string; // Minimum order size -max_amount: string; // Maximum order size -price: string; // Token Price (USDT-based) -slippage: string; // Slippage -estimate_gas_fee_amount_usdt: string; // Estimated Gas Fee (USDT-based) -order_fee: string; // Slippage tolerance (10 means 10% tolerance) -target_token_min_amount: string; // Minimum received amount -target_token_max_amount: string; // Maximum received amount -error_type: number; // Failure Type (0: Success, 1: Exceeds maximum value, 2: Below minimum value) +mark_price_round: string; // Minimum unit of mark price ⋮---- -export interface CreateAlphaOrderResp { - order_id: string; // Order ID - status: number; // Order Status (0: All, 1: Processing, 2: Successful, 3: Failed, 4: Cancelled, 5: Buy order placed but transfer not completed, 6: Order cancelled but transfer not completed) - side: string; // Buy or sell orders (buy/sell) - gas_mode: string; // Trading mode (speed: Smart mode, custom: Custom mode) - create_time: number; // Creation timestamp - amount: string; // Trade Quantity - token_address: string; // Token contract address - chain: string; // Blockchain name -} +order_price_deviate?: string; // Deprecated ⋮---- -order_id: string; // Order ID -status: number; // Order Status (0: All, 1: Processing, 2: Successful, 3: Failed, 4: Cancelled, 5: Buy order placed but transfer not completed, 6: Order cancelled but transfer not completed) -side: string; // Buy or sell orders (buy/sell) -gas_mode: string; // Trading mode (speed: Smart mode, custom: Custom mode) -create_time: number; // Creation timestamp -amount: string; // Trade Quantity -token_address: string; // Token contract address -chain: string; // Blockchain name +orders_limit: number; // Maximum number of orders per user in this market ⋮---- -export interface AlphaOrder { - order_id: string; // Order ID - tx_hash: string; // Transaction Hash - side: string; // Buy or sell orders (buy/sell) - usdt_amount: string; // Amount (USDT) - currency: string; // Token - currency_amount: string; // Token amount - status: number; // Order Status (0: All, 1: Processing, 2: Successful, 3: Failed, 4: Cancelled, 5: Buy order placed but transfer not completed, 6: Order cancelled but transfer not completed) - gas_mode: string; // Trading mode (speed: Smart mode, custom: Custom mode) - chain: string; // Blockchain - gas_fee: string; // Gas Fee (USDT-based) - transaction_fee: string; // Trading Fee (USDT-based) - failed_reason: string; // Failure reason (if applicable) - create_time: number; // Creation timestamp +export interface OptionsSettlementHistoryRecord { + time: number; + contract: string; + profit: string; + fee: string; + strike_price: string; + settle_price: string; } ⋮---- -order_id: string; // Order ID -tx_hash: string; // Transaction Hash -side: string; // Buy or sell orders (buy/sell) -usdt_amount: string; // Amount (USDT) -currency: string; // Token -currency_amount: string; // Token amount -status: number; // Order Status (0: All, 1: Processing, 2: Successful, 3: Failed, 4: Cancelled, 5: Buy order placed but transfer not completed, 6: Order cancelled but transfer not completed) -gas_mode: string; // Trading mode (speed: Smart mode, custom: Custom mode) -chain: string; // Blockchain -gas_fee: string; // Gas Fee (USDT-based) -transaction_fee: string; // Trading Fee (USDT-based) -failed_reason: string; // Failure reason (if applicable) -create_time: number; // Creation timestamp -⋮---- -export interface AlphaCurrency { - currency: string; // Currency symbol - name: string; // Currency name - chain: string; // The main chain corresponding to the coin - address: string; // Contract Address - amount_precision: number; // Amount scale - precision: number; // Price scale - status: number; // Currency Trading Status (1: Normal trading, 2: Suspended trading, 3: Delisted) +export interface OptionsUserSettlement { + time: number; + underlying: string; + contract: string; + strike_price: string; + settle_price: string; + size: number; + settle_profit: string; + fee: string; + realised_pnl: string; } ⋮---- -currency: string; // Currency symbol -name: string; // Currency name -chain: string; // The main chain corresponding to the coin -address: string; // Contract Address -amount_precision: number; // Amount scale -precision: number; // Price scale -status: number; // Currency Trading Status (1: Normal trading, 2: Suspended trading, 3: Delisted) -⋮---- -export interface AlphaTicker { - currency: string; // Currency symbol - last: string; // Last trading price - change: string; // 24h price change percentage (negative for decrease, e.g., -7.45) - volume: string; // 24h Trading Volume (USDT) - market_cap: string; // Current Token Market Cap +export interface OptionsOrderBook { + id?: number; + current: number; + update: number; + asks: { p: string; s: number }[]; + bids: { p: string; s: number }[]; } ⋮---- -currency: string; // Currency symbol -last: string; // Last trading price -change: string; // 24h price change percentage (negative for decrease, e.g., -7.45) -volume: string; // 24h Trading Volume (USDT) -market_cap: string; // Current Token Market Cap - -================ -File: src/types/response/autoinvest.ts -================ -/**========================================================================================================================== - * EARN AUTO INVEST - * ========================================================================================================================== - */ -⋮---- -/** POST /earn/autoinvest/plans/create — example response shape */ -export interface CreateAutoInvestPlanResp { - id: number; - amount: string; - money: string; - next_time: number; - period_type: string; - period_day: number; - period_hour: number; - fund_flow: string; - fund_source: string; +export interface OptionsTicker { + name: string; + last_price: string; + mark_price: string; + index_price: string; + ask1_size: number; + ask1_price: string; + bid1_size: number; + bid1_price: string; + position_size: number; + mark_iv: string; + bid_iv: string; + ask_iv: string; + leverage: string; // Leverage calculation formula updated with reference note + delta: string; + gamma: string; + vega: string; + theta: string; + rho: string; } ⋮---- -export interface AutoInvestCoinItem { - key: string; - value: string; - asset_icon_url: string; - sort: number; +leverage: string; // Leverage calculation formula updated with reference note +⋮---- +export interface OptionsCandle { + t: number; + v?: number; + c: string; + h: string; + l: string; + o: string; } ⋮---- -export interface AutoInvestMinAmountResp { - min_amount: string; +export interface OptionsUnderlyingCandle { + t: number; + v?: number; + c: string; + h: string; + l: string; + o: string; + sum: string; } ⋮---- -export interface AutoInvestPlanExecutionRecord { +export interface OptionsTrade { id: number; - type: string; - money: string; - user_id: number; - plan_id: number; - plan_version: number; - amount: string; create_time: number; - update_time: number; - status: string; - status_type: number; - /** 2 = buy, other = sell */ - side: number; - status_message: string; - detail: string; - asset: string; + create_time_ms: number; + contract: string; + size: number; + price: string; + is_internal?: boolean; // Deprecated } ⋮---- -/** 2 = buy, other = sell */ +is_internal?: boolean; // Deprecated ⋮---- -export interface AutoInvestPlanExecutionRecordsPaginated { - page: number; - page_size: number; - total_page: number; - total: number; - list: AutoInvestPlanExecutionRecord[]; +export interface OptionsAccount { + user: number; + total?: string; // Only applicable to classic options accounts (unified account limitation) + equity?: string; // Only applicable to classic options accounts (unified account limitation) + short_enabled: boolean; + unrealised_pnl: string; // Enhanced with calculation formula + init_margin: string; + maint_margin: string; + order_margin: string; + available: string; + point: string; + currency: string; + liq_triggered?: boolean; // Whether account is in liquidation status + margin_mode?: number; // 0: classic options account; 1: Multi-Currency Margin Mode; 2: Portfolio Margin Mode; 3: Single-Currency Margin Mode } ⋮---- -export interface AutoInvestOrderItem { - id: number; - type: string; - amount: string; - plan_id: number; - side: number; - asset: string; - record_id: number; - total_money: string; - market: string; - price: string; - create_time: number; - total: string; - fund_flow: string; - error_code: number; - error_msg: string; - status: number; -} +total?: string; // Only applicable to classic options accounts (unified account limitation) +equity?: string; // Only applicable to classic options accounts (unified account limitation) ⋮---- -export interface AutoInvestConfigItem { - coin: string; - max_limit: string; -} +unrealised_pnl: string; // Enhanced with calculation formula ⋮---- -export interface AutoInvestPlanPortfolioItem { - asset: string; - ratio: string; - cum_invest?: string; - cum_hold?: string; - cum_redeem?: string; - avg_price?: string; - redeem_status?: number; - lend_amount?: string; -} +liq_triggered?: boolean; // Whether account is in liquidation status +margin_mode?: number; // 0: classic options account; 1: Multi-Currency Margin Mode; 2: Portfolio Margin Mode; 3: Single-Currency Margin Mode ⋮---- -export interface AutoInvestPlanDetail { - id: number; - version: number; - name: string; - create_time: number; - update_time: number; - user_id: number; - money: string; - amount: string; - period_type: string; - period_day: number; - period_hour: number; - portfolio: AutoInvestPlanPortfolioItem[]; - next_time?: number; - period?: number; - fund_source?: string; - fund_flow?: string; -} -⋮---- -export interface AutoInvestPlansListResp { - page: number; - page_size: number; - page_count: number; - total_count: number; - list: AutoInvestPlanDetail[]; -} - -================ -File: src/types/response/delivery.ts -================ -/**========================================================================================================================== - * DELIVERY - * ========================================================================================================================== - */ -⋮---- -export interface DeliveryOrderBook { - id?: number; - current: number; - update: number; - asks: { p: string; s: number }[]; - bids: { p: string; s: number }[]; -} -⋮---- -export interface DeliveryTrade { - id: number; - create_time: number; - create_time_ms: number; - contract: string; - size: number; - price: string; - is_internal?: boolean; // Deprecated -} -⋮---- -is_internal?: boolean; // Deprecated -⋮---- -export interface DeliveryCandle { - t: number; - v?: number; - c: string; - h: string; - l: string; - o: string; -} -⋮---- -export interface DeliveryTicker { - contract: string; - last: string; - change_percentage: string; - total_size: string; - low_24h: string; - high_24h: string; - volume_24h: string; - volume_24h_btc?: string; - volume_24h_usd?: string; - volume_24h_base: string; - volume_24h_quote: string; - volume_24h_settle: string; - mark_price: string; - funding_rate: string; - funding_rate_indicative: string; - index_price: string; - quanto_base_rate?: string; // Deprecated - basis_rate: string; - basis_value: string; - lowest_ask: string; - highest_bid: string; -} -⋮---- -quanto_base_rate?: string; // Deprecated -⋮---- -export interface DeliveryAccount { - total: string; // Balance, only applicable to classic contract account - unrealised_pnl: string; - position_margin?: string; // Deprecated - order_margin: string; // Initial margin for all pending orders - available: string; - point: string; - currency: string; - in_dual_mode: boolean; - position_mode?: string; // Position mode: single - one-way, dual - dual-side, split - sub-positions (in_dual_mode is deprecated) - enable_credit: boolean; - position_initial_margin: string; - maintenance_margin: string; - bonus: string; - enable_evolved_classic?: boolean; // Deprecated - cross_order_margin: string; - cross_initial_margin: string; - cross_maintenance_margin: string; - cross_unrealised_pnl: string; - cross_available: string; - isolated_position_margin: string; - enable_new_dual_mode?: boolean; // Deprecated - margin_mode?: number; // 0: classic delivery account; 1: Multi-Currency Margin Mode; 2: Portfolio Margin Mode; 3: Single-Currency Margin Mode - history: { - dnw: string; - pnl: string; - fee: string; - refr: string; - fund: string; - point_dnw: string; - point_fee: string; - point_refr: string; - bonus_dnw: string; - bonus_offset: string; - }; - enable_tiered_mm: boolean; -} -⋮---- -total: string; // Balance, only applicable to classic contract account -⋮---- -position_margin?: string; // Deprecated -order_margin: string; // Initial margin for all pending orders -⋮---- -position_mode?: string; // Position mode: single - one-way, dual - dual-side, split - sub-positions (in_dual_mode is deprecated) -⋮---- -enable_evolved_classic?: boolean; // Deprecated -⋮---- -enable_new_dual_mode?: boolean; // Deprecated -margin_mode?: number; // 0: classic delivery account; 1: Multi-Currency Margin Mode; 2: Portfolio Margin Mode; 3: Single-Currency Margin Mode -⋮---- -export interface DeliveryBook { +export interface OptionsAccountChangeRecord { time: number; change: string; balance: string; - type: - | 'dnw' - | 'pnl' - | 'fee' - | 'refr' - | 'fund' - | 'point_dnw' - | 'point_fee' - | 'point_refr' - | 'bonus_offset'; + type: 'dnw' | 'prem' | 'fee' | 'refr' | 'set'; text: string; - contract?: string; - trade_id?: string; } ⋮---- -export interface DeliveryTradingHistoryRecord { - id: number; - create_time: number; +export interface OptionsPositionsUnderlying { + user: number; + underlying: string; + underlying_price: string; // Forward futures price for the delivery date contract: string; - order_id: string; size: number; - price: string; - role: 'taker' | 'maker'; - text: string; - fee: string; - point_fee: string; + entry_price: string; + mark_price: string; + mark_iv: string; + realised_pnl: string; + unrealised_pnl: string; + pending_orders: number; + close_order: { + id: number; + price: string; + is_liq: boolean; + } | null; + delta: string; + gamma: string; + vega: string; + theta: string; } ⋮---- -export interface DeliveryClosedPosition { +underlying_price: string; // Forward futures price for the delivery date +⋮---- +export interface GetOptionsLiquidationResp { time: number; contract: string; side: 'long' | 'short'; pnl: string; - pnl_pnl: string; - pnl_fund: string; - pnl_fee: string; text: string; - max_size: string; - first_open_time: number; - long_price: string; - short_price: string; + settle_size: string; } ⋮---- -export interface DeliveryLiquidationHistoryRecord { - time: number; +export interface SubmitOptionsOrderResp { + id: number; + user: number; + create_time: number; + finish_time: number; + finish_as: + | 'filled' + | 'cancelled' + | 'liquidated' + | 'ioc' + | 'auto_deleveraged' + | 'reduce_only' + | 'position_closed'; + status: 'open' | 'finished'; contract: string; - leverage?: string; size: number; - margin?: string; - entry_price?: string; - liq_price?: string; - mark_price?: string; - order_id?: number; - order_price: string; - fill_price: string; + iceberg: number; + price: string; + is_close: boolean; + is_reduce_only: boolean; + is_liq: boolean; + tif: 'gtc' | 'ioc' | 'poc'; left: number; + fill_price: string; + text: string; + tkfr: string; + mkfr: string; + refu: number; + refr: string; } ⋮---- -export interface DeliverySettlementHistoryRecord { - time: number; +export interface OptionsUserHistoryRecord { + id: number; + create_time: number; contract: string; - leverage: string; + order_id: number; size: number; - margin: string; - entry_price: string; - settle_price: string; - profit: string; - fee: string; + price: string; + underlying_price: string; // Forward futures price for the delivery date + role: 'taker' | 'maker'; } - -================ -File: src/types/response/margin.ts -================ -/**========================================================================================================================== - * MARGIN - * ========================================================================================================================== - */ ⋮---- -export interface MarginAccount { - currency_pair: string; - locked: boolean; - risk: string; - base: { - currency: string; - available: string; - locked: string; - borrowed: string; - interest: string; - }; - quote: { - currency: string; - available: string; - locked: string; - borrowed: string; - interest: string; - }; -} +underlying_price: string; // Forward futures price for the delivery date ⋮---- -export interface MarginBalanceHistoryRecord { - id: string; - time: string; - time_ms: number; - currency: string; - currency_pair: string; - change: string; - balance: string; - type: string; +export interface OptionsMMPSettings { + underlying: string; + window: number; + frozen_period: number; + qty_limit: string; + delta_limit: string; + trigger_time_ms: number; // Trigger freeze time in milliseconds, 0 means no freeze triggered + frozen_until_ms: number; // Unfreeze time in milliseconds, if no frozen period is configured, no unfreeze time after freeze is triggered } ⋮---- -export interface CrossMarginCurrency { - name: string; - rate: string; - prec: string; - discount: string; - min_borrow_amount: string; - user_max_borrow_amount: string; - total_max_borrow_amount: string; - price: string; - loanable: boolean; - status: number; +trigger_time_ms: number; // Trigger freeze time in milliseconds, 0 means no freeze triggered +frozen_until_ms: number; // Unfreeze time in milliseconds, if no frozen period is configured, no unfreeze time after freeze is triggered + +================ +File: src/types/response/rebate.ts +================ +export interface AgencyTransactionHistoryRecord { + transaction_time: number; + user_id: number; + group_name: string; + fee: string; + fee_asset: string; + currency_pair: string; + amount: string; + amount_asset: string; + source: string; } ⋮---- -export interface CrossMarginAccount { +export interface AgencyCommissionHistoryRecord { + commission_time: number; user_id: number; - refresh_time: number; - locked: boolean; - balances: { - [currency: string]: { - available: string; - freeze: string; - borrowed: string; - interest: string; - negative_liab: string; - futures_pos_liab: string; - equity: string; - total_freeze: string; - total_liab: string; - }; - }; - total: string; - borrowed: string; - interest: string; - risk: string; - total_initial_margin: string; - total_margin_balance: string; - total_maintenance_margin: string; - total_initial_margin_rate: string; - total_maintenance_margin_rate: string; - total_available_margin: string; - portfolio_margin_total: string; - portfolio_margin_total_liab: string; - portfolio_margin_total_equity: string; + group_name: string; + /** Rebate commission amount (not a generic trade notional). */ + commission_amount: string; + /** Asset of the rebate commission. */ + commission_asset: string; + source: string; } ⋮---- -export interface CrossMarginAccountHistoryRecord { - id: string; - time: number; - currency: string; - change: string; - balance: string; - type: string; -} +/** Rebate commission amount (not a generic trade notional). */ ⋮---- -export interface CrossMarginMorrowLoanRecord { - id: string; - create_time: number; - update_time: number; - currency: string; - amount: string; - text?: string; - status: number; - repaid: string; - repaid_interest: string; - unpaid_interest: string; +/** Asset of the rebate commission. */ +⋮---- +export interface PartnerSubordinate { + user_id: number; + user_join_time: number; + type: number; + desc: string; } ⋮---- -export interface MarginUserAccount { +export interface BrokerCommissionHistoryRecord { + commission_time: number; + user_id: number; + group_name: string; + amount: string; + fee: string; + fee_asset: string; + rebate_fee: string; + source: string; // Rebate source, e.g. Spot, Futures, Options, Alpha, TradFi currency_pair: string; - account_type: string; // Description updated to remove "risk" option - leverage: string; - locked: boolean; - risk?: string; // Deprecated - mmr?: string; // Refined description - base: { - currency: string; - available: string; - locked: string; - borrowed: string; - interest: string; - }; - quote: { - currency: string; - available: string; - locked: string; - borrowed: string; - interest: string; + sub_broker_info: { + user_id: number; + original_commission_rate: string; + relative_commission_rate: string; + commission_rate: string; }; } ⋮---- -account_type: string; // Description updated to remove "risk" option -⋮---- -risk?: string; // Deprecated -mmr?: string; // Refined description - -================ -File: src/types/response/marginuni.ts -================ -/**========================================================================================================================== - * MARGIN UNI - * ========================================================================================================================== - */ +source: string; // Rebate source, e.g. Spot, Futures, Options, Alpha, TradFi ⋮---- -export interface LendingMarket { +export interface BrokerTransactionHistoryRecord { + transaction_time: number; + user_id: number; + group_name: string; + fee: string; currency_pair: string; - base_min_borrow_amount: string; - quote_min_borrow_amount: string; - leverage: string; - status?: string | number; - delisted_time?: number; + amount: string; + fee_asset: string; + source: string; // Rebate source, e.g. Spot, Futures, Options, Alpha, TradFi + sub_broker_info: { + user_id: number; + original_commission_rate: string; + relative_commission_rate: string; + commission_rate: string; + }; } ⋮---- -export interface MarginUNILoan { - currency: string; - currency_pair: string; - amount: string; - type: string; // Lending type, margin indicates margin borrowing - create_time: number; - update_time: number; +source: string; // Rebate source, e.g. Spot, Futures, Options, Alpha, TradFi +⋮---- +export interface PartnerCommission { + commission_time: number; + user_id: number; + group_name: string; + /** Rebate commission amount (not a generic trade notional). */ + commission_amount: string; + /** Asset of the rebate commission. */ + commission_asset: string; + source: string; } ⋮---- -type: string; // Lending type, margin indicates margin borrowing +/** Rebate commission amount (not a generic trade notional). */ ⋮---- -export interface MarginUNILoanRecord { - type: string; +/** Asset of the rebate commission. */ +⋮---- +export interface PartnerTransaction { + transaction_time: number; + user_id: number; + group_name: string; + fee: string; + fee_asset: string; currency_pair: string; - currency: string; amount: string; - create_time: number; + amount_asset: string; + source: string; } ⋮---- -export interface MarginUNIInterestRecord { - currency: string; - currency_pair: string; - actual_rate: string; - interest: string; - status: number; - type: string; // Lending type, margin indicates margin borrowing - create_time: number; +/** `data` object for GET /rebate/partner/data/aggregated */ +export interface PartnerDataAggregated { + rebate_amount: string; + trade_volume: string; + net_fee: string; + customer_count: number; + /** Only when querying all business types (`business_type=0`); may be null */ + trading_user_count?: string | null; + time_range_desc: string; + business_type: number; + business_type_desc: string; } ⋮---- -type: string; // Lending type, margin indicates margin borrowing +/** Only when querying all business types (`business_type=0`); may be null */ ⋮---- -export interface MarginUNIMaxBorrowable { - currency: string; - currency_pair: string; - borrowable: string; +export interface PartnerDataAggregatedResponse { + code: number; + message: string; + data: PartnerDataAggregated; + timestamp: number; } ================ -File: src/types/response/multicollateralLoan.ts +File: src/types/response/withdrawal.ts ================ -/**========================================================================================================================== - * MULTI COLLATERAL LOAN - * ========================================================================================================================== - */ -⋮---- -export interface MultiLoanOrder { - order_id: string; - order_type: string; - fixed_type: string; - fixed_rate: string; - expire_time: number; - auto_renew: boolean; - auto_repay: boolean; - current_ltv: string; - status: string; - borrow_time: number; - total_left_repay_usdt: string; - total_left_collateral_usdt: string; - borrow_currencies: { - currency: string; - index_price: string; - left_repay_principal: string; - left_repay_interest: string; - left_repay_usdt: string; - }[]; - collateral_currencies: { - currency: string; - index_price: string; - left_collateral: string; - left_collateral_usdt: string; - }[]; -} -⋮---- -export interface RepayMultiLoanResp { - order_id: number; - repaid_currencies: { - succeeded: boolean; - label?: string; - message?: string; - currency: string; - repaid_principal: string; - repaid_interest: string; - }[]; +export interface WithdrawalRecord { + id: string; + txid: string; + block_number: string; + withdraw_order_id: string; + /** When `status` is DONE, withdrawal success time (not conditioned on `block_number`). */ + timestamp: string; + amount: string; + currency: string; + address: string; + memo?: string; + status: + | 'BCODE' // Deposit Code Operation + | 'CANCEL' // Cancelled + | 'CANCELPEND' // Withdrawal Cancellation Pending + | 'DMOVE' // Pending Manual Review + | 'DONE' // Completed + | 'EXTPEND' // Sent and Waiting for Confirmation + | 'FAIL' // On-Chain Failure Pending Confirmation + | 'FVERIFY' // Facial Verification in Progress + | 'INVALID' // Invalid Transaction + | 'LOCKED' // Wallet-Side Order Locked + | 'MANUAL' // Pending Manual Review + | 'PEND' // Processing + | 'PROCES' // Processing + | 'REJECT' // Rejected + | 'REQUEST' // Request in Progress + | 'REVIEW' // Under Review + | 'SPLITPEND' // Split Pending + | 'VERIFY'; // Verification in Progress + chain: string; } ⋮---- -export interface MultiLoanRepayRecord { - order_id: number; - record_id: number; - init_ltv: string; - before_ltv: string; - after_ltv: string; - borrow_time: number; - repay_time: number; - borrow_currencies: { - currency: string; - index_price: string; - before_amount: string; - before_amount_usdt: string; - after_amount: string; - after_amount_usdt: string; - }[]; - collateral_currencies: { - currency: string; - index_price: string; - before_amount: string; - before_amount_usdt: string; - after_amount: string; - after_amount_usdt: string; - }[]; - repaid_currencies: { - currency: string; - index_price: string; - repaid_amount: string; - repaid_principal: string; - repaid_interest: string; - repaid_amount_usdt: string; - }[]; - total_interest_list: { - currency: string; - index_price: string; - amount: string; - amount_usdt: string; - }[]; - left_repay_interest_list: { - currency: string; - index_price: string; - before_amount: string; - before_amount_usdt: string; - after_amount: string; - after_amount_usdt: string; - }[]; -} +/** When `status` is DONE, withdrawal success time (not conditioned on `block_number`). */ ⋮---- -export interface UpdateMultiLoanResp { - order_id: number; - collateral_currencies: { - succeeded: boolean; - label?: string; - message?: string; - currency: string; - amount: string; - }[]; -} +| 'BCODE' // Deposit Code Operation +| 'CANCEL' // Cancelled +| 'CANCELPEND' // Withdrawal Cancellation Pending +| 'DMOVE' // Pending Manual Review +| 'DONE' // Completed +| 'EXTPEND' // Sent and Waiting for Confirmation +| 'FAIL' // On-Chain Failure Pending Confirmation +| 'FVERIFY' // Facial Verification in Progress +| 'INVALID' // Invalid Transaction +| 'LOCKED' // Wallet-Side Order Locked +| 'MANUAL' // Pending Manual Review +| 'PEND' // Processing +| 'PROCES' // Processing +| 'REJECT' // Rejected +| 'REQUEST' // Request in Progress +| 'REVIEW' // Under Review +| 'SPLITPEND' // Split Pending +| 'VERIFY'; // Verification in Progress + +================ +File: src/types/websockets/requests.ts +================ +import { CHANNEL_ID } from '../../lib/requestUtils.js'; +import { WSAPITopic } from './wsAPI.js'; ⋮---- -export interface MultiLoanAdjustmentRecord { - order_id: number; - record_id: number; - before_ltv: string; - after_ltv: string; - operate_time: number; - borrow_currencies: { - currency: string; - index_price: string; - before_amount: string; - before_amount_usdt: string; - after_amount: string; - after_amount_usdt: string; - }[]; - collateral_currencies: { - currency: string; - index_price: string; - before_amount: string; - before_amount_usdt: string; - after_amount: string; - after_amount_usdt: string; - }[]; -} +export type WsOperation = 'subscribe' | 'unsubscribe' | 'auth'; ⋮---- -export interface MultiLoanCurrencyQuota { - currency: string; - index_price: string; - min_quota: string; - left_quota: string; - left_quote_usdt: string; - /** Remaining borrow/collateral limit for fixed-term currency */ - left_quota_fixed?: string; - /** Remaining currency limit for fixed-term converted to USDT */ - left_quote_usdt_fixed?: string; +export interface WsRequestAuthGate { + method: 'api_key'; + KEY: string; + SIGN: string; } ⋮---- -/** Remaining borrow/collateral limit for fixed-term currency */ -⋮---- -/** Remaining currency limit for fixed-term converted to USDT */ -⋮---- -export interface MultiLoanSupportedCurrencies { - loan_currencies: { - currency: string; - price: string; - }[]; - collateral_currencies: { - currency: string; - index_price: string; - discount: string; - }[]; +export interface WsRequestPing { + time: number; + channel: 'spot.ping' | 'futures.ping' | 'options.ping' | 'announcement.ping'; } ⋮---- -export interface MultiLoanRatio { - init_ltv: string; - alert_ltv: string; - liquidate_ltv: string; +export interface WsRequestOperationGate< + TWSTopic extends string, + TWSPayload = any, +> { + time: number; + id?: number; + channel: TWSTopic; + auth?: WsRequestAuthGate; + event?: WsOperation; + payload?: TWSPayload; } ⋮---- -export interface MultiLoanFixedRate { - currency: string; - rate_7d: string; - rate_30d: string; - update_time: number; +export interface WSAPIRequest< + TRequestParams = any, + TWSChannel extends WSAPITopic = any, +> { + time: number; + id?: number; + channel: TWSChannel; + event: 'api'; + payload: { + req_id: string; + req_param?: TRequestParams | string; + req_header: { + 'X-Gate-Channel-Id': typeof CHANNEL_ID; + 'X-Gate-Size-Decimal'?: '1'; + }; + api_key?: string; + signature?: string; + timestamp?: string; + }; } ================ -File: src/types/response/options.ts +File: src/types/websockets/wsAPI.ts ================ -/**========================================================================================================================== - * OPTIONS - * ========================================================================================================================== - */ +import { WsKey } from '../../lib/websocket/websocket-util.js'; +import { FuturesContractSize } from '../shared.js'; ⋮---- -export interface OptionsContract { - name: string; - tag: string; // Expiry period: day, week, month - create_time: number; - expiration_time: number; - is_call: boolean; - strike_price: string; - last_price: string; - mark_price: string; - orderbook_id: number; - trade_id?: number; // Deprecated - trade_size: number; - position_size: number; - underlying: string; - underlying_price: string; // Forward futures price for the delivery date - multiplier: string; // Option contract multiplier - order_price_round: string; - mark_price_round: string; // Minimum unit of mark price - maker_fee_rate: string; - taker_fee_rate: string; - price_limit_fee_rate: string; - ref_discount_rate: string; - ref_rebate_rate: string; - order_price_deviate?: string; // Deprecated - order_size_min: number; - order_size_max: number; - orders_limit: number; // Maximum number of orders per user in this market -} -⋮---- -tag: string; // Expiry period: day, week, month +export type SpotWSAPITopic = + | 'spot.login' + | 'spot.order_place' + | 'spot.order_cancel' + | 'spot.order_cancel_ids' + | 'spot.order_cancel_cp' + | 'spot.order_amend' + | 'spot.order_status' + | 'spot.order_list'; ⋮---- -trade_id?: number; // Deprecated +export type FuturesWSAPITopic = + | 'futures.login' + | 'futures.order_place' + | 'futures.order_batch_place' + | 'futures.order_cancel' + | 'futures.order_cancel_cp' + | 'futures.order_amend' + | 'futures.order_list' + | 'futures.order_status' + | 'futures.order_cancel_ids'; ⋮---- -underlying_price: string; // Forward futures price for the delivery date -multiplier: string; // Option contract multiplier +export interface WsAPIWsKeyTopicMap { + spotV4: SpotWSAPITopic; + perpFuturesUSDTV4: FuturesWSAPITopic; + perpFuturesBTCV4: FuturesWSAPITopic; + deliveryFuturesUSDTV4: FuturesWSAPITopic; + deliveryFuturesBTCV4: FuturesWSAPITopic; + // optionsV4: never; + // announcementsV4: never; +} ⋮---- -mark_price_round: string; // Minimum unit of mark price +// optionsV4: never; +// announcementsV4: never; ⋮---- -order_price_deviate?: string; // Deprecated +export type WSAPITopic = SpotWSAPITopic | FuturesWSAPITopic; +export type WSAPIWsKey = keyof WsAPIWsKeyTopicMap; ⋮---- -orders_limit: number; // Maximum number of orders per user in this market +// ==================================== +// Spot WebSocket API Request Types +// ==================================== ⋮---- -export interface OptionsSettlementHistoryRecord { - time: number; - contract: string; - profit: string; - fee: string; - strike_price: string; - settle_price: string; +export interface WSAPISpotOrderPlaceReq { + text?: string; + currency_pair: string; + type?: 'limit' | 'market'; + account?: 'spot' | 'margin' | 'unified' | 'cross_margin'; + side: 'buy' | 'sell'; + amount: string; + price?: string; + time_in_force?: 'gtc' | 'ioc' | 'poc' | 'fok'; + iceberg?: string; + auto_borrow?: boolean; + auto_repay?: boolean; + stp_act?: 'cn' | 'co' | 'cb'; + action_mode?: 'ACK' | 'RESULT' | 'FULL'; } ⋮---- -export interface OptionsUserSettlement { - time: number; - underlying: string; - contract: string; - strike_price: string; - settle_price: string; - size: number; - settle_profit: string; - fee: string; - realised_pnl: string; +export interface WSAPISpotOrderCancelReq { + order_id: string; + currency_pair: string; + account?: string; } ⋮---- -export interface OptionsOrderBook { - id?: number; - current: number; - update: number; - asks: { p: string; s: number }[]; - bids: { p: string; s: number }[]; +export interface WSAPISpotOrderCancelIdsReq { + currency_pair: string; + id: string; + account?: string; } ⋮---- -export interface OptionsTicker { - name: string; - last_price: string; - mark_price: string; - index_price: string; - ask1_size: number; - ask1_price: string; - bid1_size: number; - bid1_price: string; - position_size: number; - mark_iv: string; - bid_iv: string; - ask_iv: string; - leverage: string; // Leverage calculation formula updated with reference note - delta: string; - gamma: string; - vega: string; - theta: string; - rho: string; +export interface WSAPISpotOrderCancelCPReq { + currency_pair: string; + side?: 'buy' | 'sell'; + account?: string; } ⋮---- -leverage: string; // Leverage calculation formula updated with reference note -⋮---- -export interface OptionsCandle { - t: number; - v?: number; - c: string; - h: string; - l: string; - o: string; +export interface WSAPISpotOrderAmendReq { + amount?: string; + price?: string; + amend_text?: string; + order_id: string; + currency_pair: string; + account?: string; } ⋮---- -export interface OptionsUnderlyingCandle { - t: number; - v?: number; - c: string; - h: string; - l: string; - o: string; - sum: string; +export interface WSAPISpotOrderStatusReq { + order_id: string; + currency_pair: string; + account?: string; } ⋮---- -export interface OptionsTrade { - id: number; - create_time: number; - create_time_ms: number; - contract: string; - size: number; - price: string; - is_internal?: boolean; // Deprecated +export interface WSAPISpotOrderListReq { + currency_pair: string; + status: 'open' | 'finished'; + page?: number; + limit?: number; + account?: string; + from?: number; + to?: number; + side?: 'buy' | 'sell'; } ⋮---- -is_internal?: boolean; // Deprecated +// ==================================== +// Futures WebSocket API Request Types +// ==================================== ⋮---- -export interface OptionsAccount { - user: number; - total?: string; // Only applicable to classic options accounts (unified account limitation) - equity?: string; // Only applicable to classic options accounts (unified account limitation) - short_enabled: boolean; - unrealised_pnl: string; // Enhanced with calculation formula - init_margin: string; - maint_margin: string; - order_margin: string; - available: string; - point: string; - currency: string; - liq_triggered?: boolean; // Whether account is in liquidation status - margin_mode?: number; // 0: classic options account; 1: Multi-Currency Margin Mode; 2: Portfolio Margin Mode; 3: Single-Currency Margin Mode +export interface WSAPIFuturesOrderPlaceReq { + contract: string; + /** String when `futuresSizeDecimal` is enabled on the client. */ + size: FuturesContractSize; + /** String when `futuresSizeDecimal` is enabled on the client. */ + iceberg?: FuturesContractSize; + price?: string; + close?: boolean; + reduce_only?: boolean; + tif?: 'gtc' | 'ioc' | 'poc' | 'fok'; + text?: string; + auto_size?: 'close_long' | 'close_short'; + stp_act?: 'cn' | 'co' | 'cb'; } ⋮---- -total?: string; // Only applicable to classic options accounts (unified account limitation) -equity?: string; // Only applicable to classic options accounts (unified account limitation) -⋮---- -unrealised_pnl: string; // Enhanced with calculation formula +/** String when `futuresSizeDecimal` is enabled on the client. */ ⋮---- -liq_triggered?: boolean; // Whether account is in liquidation status -margin_mode?: number; // 0: classic options account; 1: Multi-Currency Margin Mode; 2: Portfolio Margin Mode; 3: Single-Currency Margin Mode +/** String when `futuresSizeDecimal` is enabled on the client. */ ⋮---- -export interface OptionsAccountChangeRecord { - time: number; - change: string; - balance: string; - type: 'dnw' | 'prem' | 'fee' | 'refr' | 'set'; - text: string; +export interface WSAPIFuturesOrderCancelReq { + order_id: string; } ⋮---- -export interface OptionsPositionsUnderlying { - user: number; - underlying: string; - underlying_price: string; // Forward futures price for the delivery date +export interface WSAPIFuturesOrderCancelCPReq { contract: string; - size: number; - entry_price: string; - mark_price: string; - mark_iv: string; - realised_pnl: string; - unrealised_pnl: string; - pending_orders: number; - close_order: { - id: number; - price: string; - is_liq: boolean; - } | null; - delta: string; - gamma: string; - vega: string; - theta: string; + side?: 'bid' | 'ask'; } ⋮---- -underlying_price: string; // Forward futures price for the delivery date +export interface WSAPIFuturesOrderAmendReq { + order_id: string; + price?: string; + /** String when `futuresSizeDecimal` is enabled on the client. */ + size?: FuturesContractSize; + amend_text?: string; +} ⋮---- -export interface GetOptionsLiquidationResp { - time: number; - contract: string; - side: 'long' | 'short'; - pnl: string; +/** String when `futuresSizeDecimal` is enabled on the client. */ +⋮---- +export interface WSAPIFuturesOrderListReq { + contract: string; + status: 'open' | 'finished'; + limit?: number; + offset?: number; + last_id?: string; + count_total?: number; +} +⋮---- +export interface WSAPIFuturesOrderStatusReq { + order_id: string; +} +⋮---- +// ==================================== +// Spot WebSocket API Response Types +// ==================================== +⋮---- +export interface WSAPISpotOrder { + id: string; text: string; - settle_size: string; + amend_text: string; + create_time: string; + update_time: string; + create_time_ms: number; + update_time_ms: number; + status: string; + currency_pair: string; + type: string; + account: string; + side: string; + amount: string; + price: string; + time_in_force: string; + iceberg: string; + left: string; + fill_price?: string; + filled_amount?: string; + filled_total: string; + avg_deal_price?: string; + fee: string; + fee_currency: string; + point_fee: string; + gt_fee: string; + gt_maker_fee?: string; + gt_taker_fee?: string; + gt_discount?: boolean; + rebated_fee: string; + rebated_fee_currency: string; + stp_id?: number; + stp_act?: string; + finish_as: string; } ⋮---- -export interface SubmitOptionsOrderResp { +export interface WSAPISpotOrderCancelIdsRespItem { + currency_pair: string; + id: string; + succeeded: boolean; +} +⋮---- +// ==================================== +// Futures WebSocket API Response Types +// ==================================== +⋮---- +export interface WSAPIFuturesOrder { id: number; user: number; create_time: number; - finish_time: number; - finish_as: - | 'filled' - | 'cancelled' - | 'liquidated' - | 'ioc' - | 'auto_deleveraged' - | 'reduce_only' - | 'position_closed'; - status: 'open' | 'finished'; + finish_time?: number; + update_time?: number; + finish_as?: string; + status: string; contract: string; - size: number; - iceberg: number; + /** String when `futuresSizeDecimal` is enabled on the client. */ + size: FuturesContractSize; price: string; - is_close: boolean; - is_reduce_only: boolean; - is_liq: boolean; - tif: 'gtc' | 'ioc' | 'poc'; - left: number; + tif: string; + /** String when `futuresSizeDecimal` is enabled on the client. */ + left?: FuturesContractSize; + /** String when `futuresSizeDecimal` is enabled on the client. */ + iceberg?: FuturesContractSize; fill_price: string; text: string; tkfr: string; mkfr: string; - refu: number; - refr: string; + stp_id?: number; + stp_act?: string; + amend_text?: string; } ⋮---- -export interface OptionsUserHistoryRecord { - id: number; - create_time: number; - contract: string; - order_id: number; - size: number; - price: string; - underlying_price: string; // Forward futures price for the delivery date - role: 'taker' | 'maker'; -} +/** String when `futuresSizeDecimal` is enabled on the client. */ ⋮---- -underlying_price: string; // Forward futures price for the delivery date +/** String when `futuresSizeDecimal` is enabled on the client. */ ⋮---- -export interface OptionsMMPSettings { - underlying: string; - window: number; - frozen_period: number; - qty_limit: string; - delta_limit: string; - trigger_time_ms: number; // Trigger freeze time in milliseconds, 0 means no freeze triggered - frozen_until_ms: number; // Unfreeze time in milliseconds, if no frozen period is configured, no unfreeze time after freeze is triggered +/** String when `futuresSizeDecimal` is enabled on the client. */ +⋮---- +export interface WSAPIFuturesOrderBatchPlaceRespItem extends WSAPIFuturesOrder { + succeeded: boolean; } ⋮---- -trigger_time_ms: number; // Trigger freeze time in milliseconds, 0 means no freeze triggered -frozen_until_ms: number; // Unfreeze time in milliseconds, if no frozen period is configured, no unfreeze time after freeze is triggered - -================ -File: src/types/response/rebate.ts -================ -export interface AgencyTransactionHistoryRecord { - transaction_time: number; +export interface WSAPIFuturesOrderCancelIdsRespItem { + id: string; user_id: number; - group_name: string; - fee: string; - fee_asset: string; - currency_pair: string; - amount: string; - amount_asset: string; - source: string; + succeeded?: boolean; + message?: string; } ⋮---- -export interface AgencyCommissionHistoryRecord { - commission_time: number; - user_id: number; - group_name: string; - /** Rebate commission amount (not a generic trade notional). */ - commission_amount: string; - /** Asset of the rebate commission. */ - commission_asset: string; - source: string; +// ==================================== +// Request Parameter Mapping +// ==================================== +⋮---- +export interface WsAPITopicRequestParamMap { + 'spot.login': undefined; + 'futures.login': undefined; + + 'spot.order_place': WSAPISpotOrderPlaceReq; + 'spot.order_cancel': WSAPISpotOrderCancelReq; + 'spot.order_cancel_ids': WSAPISpotOrderCancelIdsReq[]; + 'spot.order_cancel_cp': WSAPISpotOrderCancelCPReq; + 'spot.order_amend': WSAPISpotOrderAmendReq; + 'spot.order_status': WSAPISpotOrderStatusReq; + 'spot.order_list': WSAPISpotOrderListReq; + + 'futures.order_place': WSAPIFuturesOrderPlaceReq; + 'futures.order_batch_place': WSAPIFuturesOrderPlaceReq[]; + 'futures.order_cancel': WSAPIFuturesOrderCancelReq; + 'futures.order_cancel_ids': string[]; + 'futures.order_cancel_cp': WSAPIFuturesOrderCancelCPReq; + 'futures.order_amend': WSAPIFuturesOrderAmendReq; + 'futures.order_list': WSAPIFuturesOrderListReq; + 'futures.order_status': WSAPIFuturesOrderStatusReq; } ⋮---- -/** Rebate commission amount (not a generic trade notional). */ +export type WsAPITopicRequestParams = + WsAPITopicRequestParamMap[keyof WsAPITopicRequestParamMap]; ⋮---- -/** Asset of the rebate commission. */ +// ==================================== +// Response Headers and Base Response +// ==================================== ⋮---- -export interface PartnerSubordinate { - user_id: number; - user_join_time: number; - type: number; - desc: string; +export interface WSAPIResponseHeader { + /** String timestamp as ms */ + response_time: string; + /** Status of WS API call. "200" if successful, else exception is thrown */ + status: '200' | string; + channel: TChannel; + event: 'api'; + client_id: string; } ⋮---- -export interface BrokerCommissionHistoryRecord { - commission_time: number; - user_id: number; - group_name: string; +/** String timestamp as ms */ +⋮---- +/** Status of WS API call. "200" if successful, else exception is thrown */ +⋮---- +export interface WSAPILoginResponse { + api_key: string; + uid: string; +} +⋮---- +export interface WSAPIOrderStatusResponse { + left: string; + update_time: string; amount: string; - fee: string; - fee_asset: string; - rebate_fee: string; - source: string; // Rebate source, e.g. Spot, Futures, Options, Alpha, TradFi + create_time: string; + price: string; + finish_as: string; + time_in_force: string; currency_pair: string; - sub_broker_info: { - user_id: number; - original_commission_rate: string; - relative_commission_rate: string; - commission_rate: string; - }; + type: string; + account: string; + side: string; + amend_text: string; + text: string; + status: string; + iceberg: string; + avg_deal_price: string; + filled_total: string; + id: string; + fill_price: string; + update_time_ms: number; + create_time_ms: number; } ⋮---- -source: string; // Rebate source, e.g. Spot, Futures, Options, Alpha, TradFi +export type WSAPIResponseData = WSAPILoginResponse | WSAPIOrderStatusResponse; ⋮---- -export interface BrokerTransactionHistoryRecord { - transaction_time: number; - user_id: number; - group_name: string; - fee: string; - currency_pair: string; - amount: string; - fee_asset: string; - source: string; // Rebate source, e.g. Spot, Futures, Options, Alpha, TradFi - sub_broker_info: { - user_id: number; - original_commission_rate: string; - relative_commission_rate: string; - commission_rate: string; +export interface WSAPIResponse< + TResponseData extends object = WSAPIResponseData | object, + TChannel extends WSAPITopic = WSAPITopic, +> { + wsKey: WsKey; + header: WSAPIResponseHeader; + data: { + result: TResponseData; }; + /** Auto-generated */ + request_id: string; } ⋮---- -source: string; // Rebate source, e.g. Spot, Futures, Options, Alpha, TradFi +/** Auto-generated */ ⋮---- -export interface PartnerCommission { - commission_time: number; - user_id: number; - group_name: string; - /** Rebate commission amount (not a generic trade notional). */ - commission_amount: string; - /** Asset of the rebate commission. */ - commission_asset: string; - source: string; -} +// ==================================== +// Response Type Mapping +// ==================================== ⋮---- -/** Rebate commission amount (not a generic trade notional). */ +export interface WsAPITopicResponseMap { + 'spot.login': WSAPIResponse; + 'futures.login': WSAPIResponse; + + 'spot.order_place': WSAPIResponse; + 'spot.order_cancel': WSAPIResponse; + 'spot.order_cancel_ids': WSAPIResponse< + WSAPISpotOrderCancelIdsRespItem[], + 'spot.order_cancel_ids' + >; + 'spot.order_cancel_cp': WSAPIResponse< + WSAPISpotOrder[], + 'spot.order_cancel_cp' + >; + 'spot.order_amend': WSAPIResponse; + 'spot.order_status': WSAPIResponse; + 'spot.order_list': WSAPIResponse; + + 'futures.order_place': WSAPIResponse< + WSAPIFuturesOrder, + 'futures.order_place' + >; + 'futures.order_batch_place': WSAPIResponse< + WSAPIFuturesOrderBatchPlaceRespItem[], + 'futures.order_batch_place' + >; + 'futures.order_cancel': WSAPIResponse< + WSAPIFuturesOrder, + 'futures.order_cancel' + >; + 'futures.order_cancel_ids': WSAPIResponse< + WSAPIFuturesOrderCancelIdsRespItem[], + 'futures.order_cancel_ids' + >; + 'futures.order_cancel_cp': WSAPIResponse< + WSAPIFuturesOrder[], + 'futures.order_cancel_cp' + >; + 'futures.order_amend': WSAPIResponse< + WSAPIFuturesOrder, + 'futures.order_amend' + >; + 'futures.order_list': WSAPIResponse< + WSAPIFuturesOrder[], + 'futures.order_list' + >; + 'futures.order_status': WSAPIResponse< + WSAPIFuturesOrder, + 'futures.order_status' + >; +} ⋮---- -/** Asset of the rebate commission. */ +// export interface WsAPIResponseMap { +// 'spot.login': WSAPIResponse; +// 'futures.login': WSAPIResponse; +// string: object; +// } + +================ +File: src/WebsocketClient.ts +================ +import { BaseWebsocketClient, EmittableEvent } from './lib/BaseWSClient.js'; +import { neverGuard } from './lib/misc-util.js'; +import { + CHANNEL_ID, + getFuturesSizeDecimalHeaders, + isFuturesMarketWsKey, + MessageEventLike, +} from './lib/requestUtils.js'; +import { + SignAlgorithm, + SignEncodeMethod, + signMessage, +} from './lib/webCryptoAPI.js'; +import { + getPrivateFuturesTopics, + getPrivateOptionsTopics, + getPrivateSpotTopics, + getPromiseRefForWSAPIRequest, + WS_BASE_URL_MAP, + WS_KEY_MAP, + WsKey, + WsMarket, + WsTopicRequest, +} from './lib/websocket/websocket-util.js'; +import { WSConnectedResult } from './lib/websocket/WsStore.types.js'; +import { + WSAPIRequest, + WsOperation, + WsRequestOperationGate, + WsRequestPing, +} from './types/websockets/requests.js'; +import { + WsAPITopicRequestParamMap, + WsAPITopicResponseMap, + WSAPIWsKey, + WsAPIWsKeyTopicMap, +} from './types/websockets/wsAPI.js'; ⋮---- -export interface PartnerTransaction { - transaction_time: number; - user_id: number; - group_name: string; - fee: string; - fee_asset: string; - currency_pair: string; - amount: string; - amount_asset: string; - source: string; +export interface WSAPIRequestFlags { + /** If true, will skip auth requirement for WS API connection */ + authIsOptional?: boolean | undefined; } ⋮---- -/** `data` object for GET /rebate/partner/data/aggregated */ -export interface PartnerDataAggregated { - rebate_amount: string; - trade_volume: string; - net_fee: string; - customer_count: number; - /** Only when querying all business types (`business_type=0`); may be null */ - trading_user_count?: string | null; - time_range_desc: string; - business_type: number; - business_type_desc: string; -} +/** If true, will skip auth requirement for WS API connection */ ⋮---- -/** Only when querying all business types (`business_type=0`); may be null */ +/** + * WS topics are always a string for gate. Some exchanges use complex objects + */ +export type WsTopic = string; ⋮---- -export interface PartnerDataAggregatedResponse { - code: number; - message: string; - data: PartnerDataAggregated; - timestamp: number; -} - -================ -File: src/types/response/stock.ts -================ -export type StockCategory = - | 'CS' - | 'ETF' - | 'ADRC' - | 'ADR' - | 'ETV' - | 'PFD' - | 'ETS' - | 'ETN' - | 'FUND'; +export class WebsocketClient extends BaseWebsocketClient ⋮---- -export type StockAssetType = 'STOCK' | 'ETF'; +protected getWsConnectRequestHeaders(wsKey: WsKey): Record ⋮---- -export interface StockApiResp { - timestamp?: number; - data?: T; - code?: number; - message?: string; - label?: string; -} +private getFuturesWsApiReqHeader(): ⋮---- -export interface StockListData { - list?: T[]; - total?: number; - total_page?: number; -} +/** + * Request connection of all dependent (public & private) websockets, instead of waiting for automatic connection by library. + * + * Returns array of promises that individually resolve when each connection is successfully opened. + */ +public connectAll(): Promise[] ⋮---- -export interface StockUserAssets { - equity?: string; - balance?: string; - available?: string; - position_market_value?: string; - position_pnl?: string; - today_pnl?: string; - user_exists?: boolean; - option_position_market_value?: string; - option_position_pnl?: string; - option_today_pnl?: string; -} +/** + * Ensures the WS API connection is active and ready. + * + * You do not need to call this, but if you call this before making any WS API requests, + * it can accelerate the first request (by preparing the connection in advance). + */ +public connectWSAPI(wsKey: WSAPIWsKey, skipAuth?: boolean): Promise ⋮---- -export interface StockSymbolDescI18n { - lang?: string; - value?: string; -} +/** This call automatically ensures the connection is active AND authenticated before resolving */ ⋮---- -export interface StockSymbolItem { - symbol?: string; - exchange?: string; - exchange_desc?: string; - quote_currency?: string; - quote_currency_precision?: number; - fx_rate?: string; - symbol_desc?: string; - category?: StockCategory | string; - asset_type?: StockAssetType; - trade_status?: string; - trade_mode?: number; - order_fill_timing?: number; - icon_link?: string; - quote_currency_symbol?: string; - price_precision?: number; - volume_precision?: number; - is_ipo?: boolean; - ipo_price?: string; - sell_price_protection?: string; - buy_price_protection?: string; - symbol_descs?: StockSymbolDescI18n[]; - timestamp?: number; -} +/** + * Request subscription to one or more topics. Pass topics as either an array of strings, or array of objects (if the topic has parameters). + * Objects should be formatted as {topic: string, params: object}. + * + * - Subscriptions are automatically routed to the correct websocket connection. + * - Authentication/connection is automatic. + * - Resubscribe after network issues is automatic. + * + * Call `unsubscribe(topics)` to remove topics + */ +public subscribe( + requests: + | (WsTopicRequest | WsTopic) + | (WsTopicRequest | WsTopic)[], + wsKey: WsKey, +) ⋮---- -export interface StockSymbolDetailItem { - symbol?: string; - exchange?: string; - exchange_desc?: string; - quote_currency?: string; - quote_currency_precision?: number; - fx_rate?: string; - symbol_desc?: string; - category?: StockCategory | string; - asset_type?: StockAssetType; - settlement_currency?: string; - max_order_volume?: string; - step_order_volume?: string; - min_order_volume?: string; - price_precision?: number; - volume_precision?: number; - is_ipo?: boolean; - ipo_price?: string; - price_protection?: string; - sell_price_protection?: string; - buy_price_protection?: string; - slippage_rate?: string; - commission_rate?: string; - trade_status?: string; - trade_mode?: number; - order_fill_timing?: number; - symbol_descs?: StockSymbolDescI18n[]; - [key: string]: unknown; +/** + * Unsubscribe from one or more topics. Similar to subscribe() but in reverse. + * + * - Requests are automatically routed to the correct websocket connection. + * - These topics will be removed from the topic cache, so they won't be subscribed to again. + */ +public unsubscribe( + requests: + | (WsTopicRequest | WsTopic) + | (WsTopicRequest | WsTopic)[], + wsKey: WsKey, +) +⋮---- +/** + * WS API Methods - similar to the REST API, but via WebSockets + */ +⋮---- +/** + * Send a Websocket API event on a connection. Returns a promise that resolves on reply. + * + * Returned promise is rejected if an exception is detected in the reply OR the connection disconnects for any reason (even if automatic reconnect will happen). + * + * After a fresh connection, you should always send a login request first. + * + * If you authenticated once and you're reconnected later (e.g. connection temporarily lost), the SDK will by default automatically: + * - Detect you were authenticated to the WS API before + * - Try to re-authenticate (up to 5 times, in case something (bad timestamp) goes wrong) + * - If it succeeds, it will emit the 'authenticated' event. + * - If it fails and gives up, it will emit an 'exception' event (type: 'wsapi.auth', reason: detailed text). + * + * You can turn off the automatic re-auth WS API logic using `reauthWSAPIOnReconnect: false` in the WSClient config. + * + * @param wsKey - The connection this event is for (e.g. "spotV4" | "perpFuturesUSDTV4" | "perpFuturesBTCV4" | "deliveryFuturesUSDTV4" | "deliveryFuturesBTCV4" | "optionsV4") + * @param channel - The channel this event is for (e.g. "spot.login" to authenticate) + * @param params - Any request parameters for the payload (contents of req_param in the docs). Signature generation is automatic, only send parameters such as order ID as per the docs. + * @returns Promise - tries to resolve with async WS API response. Rejects if disconnected or exception is seen in async WS API response + */ +⋮---- +// This overload allows the caller to omit the 3rd param, if it isn't required (e.g. for the login call) +async sendWSAPIRequest< + TWSKey extends keyof WsAPIWsKeyTopicMap, + TWSChannel extends WsAPIWsKeyTopicMap[TWSKey] = WsAPIWsKeyTopicMap[TWSKey], + TWSParams extends + WsAPITopicRequestParamMap[TWSChannel] = WsAPITopicRequestParamMap[TWSChannel], + TWSAPIResponse extends + | WsAPITopicResponseMap[TWSChannel] + | object = WsAPITopicResponseMap[TWSChannel], + >( + wsKey: TWSKey, + channel: TWSChannel, + params?: TWSParams extends void | never ? undefined : TWSParams, + requestFlags?: WSAPIRequestFlags, + ): Promise; +⋮---- +async sendWSAPIRequest< + TWSKey extends keyof WsAPIWsKeyTopicMap = keyof WsAPIWsKeyTopicMap, + TWSChannel extends WsAPIWsKeyTopicMap[TWSKey] = WsAPIWsKeyTopicMap[TWSKey], + TWSParams extends + WsAPITopicRequestParamMap[TWSChannel] = WsAPITopicRequestParamMap[TWSChannel], + TWSAPIResponse = object, + >( + wsKey: TWSKey, + channel: TWSChannel, + params: TWSParams & { signRequest?: boolean }, + requestFlags?: WSAPIRequestFlags, +): Promise +⋮---- +// Some commands don't require authentication. +⋮---- +// this.logger.trace('sendWSAPIRequest(): assertIsAuthenticated(${wsKey})...'); +⋮---- +// this.logger.trace('sendWSAPIRequest(): assertIsAuthenticated(${wsKey}) ok'); +⋮---- +// id: timeInSeconds, +⋮---- +/** + * Some WS API requests require a timestamp to be included. assertIsConnected and assertIsAuthenticated + * can introduce a small delay before the actual request is sent, if not connected before that request is + * made. This can lead to a curious race condition, where the request timestamp is before + * the "authorizedSince" timestamp - as such, binance does not recognise the session as already authenticated. + * + * The below mechanism measures any delay introduced from the assert calls, and if the request includes a timestamp, + * it offsets that timestamp by the delay. + */ +⋮---- +// Sign request +⋮---- +// Store deferred promise +⋮---- +// Enrich returned promise with request context for easier debugging +⋮---- +// throw e; +⋮---- +// Send event +⋮---- +// Return deferred promise, so caller can await this call +⋮---- +/** + * + * Internal methods - not intended for public use + * + */ +⋮---- +protected getWsUrl(wsKey: WsKey): string +⋮---- +protected sendPingEvent(wsKey: WsKey) +⋮---- +protected sendPongEvent(wsKey: WsKey) +⋮---- +// Send a protocol layer pong +⋮---- +// NOT IN USE for gate.io, pings for gate are protocol layer pings +// eslint-disable-next-line @typescript-eslint/no-unused-vars +protected isWsPing(_msg: any): boolean +⋮---- +protected isWsPong(msg: any): boolean +⋮---- +/** + * Parse incoming events into categories, before emitting to the user + */ +protected resolveEmittableEvents( + wsKey: WsKey, + event: MessageEventLike, +): EmittableEvent[] +⋮---- +// WS API Exception +⋮---- +// WS API Success +⋮---- +// Most events use "event: 'update'" for topic updates +// The legacy "futures.order_book" topic uses "all" for this field +// 'futures.obu' is used for the orderbook v2 event. Oddly in a different structure than the other topics. +⋮---- +// These are request/reply pattern events (e.g. after subscribing to topics or authenticating) +⋮---- +// Request/reply pattern for authentication success +⋮---- +/** + * Determines if a topic is for a private channel, using a hardcoded list of strings + */ +protected isPrivateTopicRequest( + request: WsTopicRequest, + wsKey: WsKey, +): boolean +⋮---- +// No private announcements channels +⋮---- +/** + * Not in use for gate.io + */ +⋮---- +// eslint-disable-next-line @typescript-eslint/no-unused-vars +protected getWsMarketForWsKey(_wsKey: WsKey): WsMarket +⋮---- +/** + * Not in use for gate.io + */ +protected getPrivateWSKeys(): WsKey[] +⋮---- +protected isAuthOnConnectWsKey(wsKey: WsKey): boolean +⋮---- +/** Force subscription requests to be sent in smaller batches, if a number is returned */ +// eslint-disable-next-line @typescript-eslint/no-unused-vars +protected getMaxTopicsPerSubscribeEvent(_wsKey: WsKey): number | null +⋮---- +/** + * Map one or more topics into fully prepared "subscribe request" events (already stringified and ready to send) + */ +protected async getWsOperationEventsForTopics( + topics: WsTopicRequest[], + wsKey: WsKey, + operation: WsOperation, +): Promise +⋮---- +// console.log(new Date(), `called getWsSubscribeEventsForTopics()`, topics); +// console.trace(); +⋮---- +// Events that are ready to send (usually stringified JSON) +⋮---- +/** + * @returns one or more correctly structured request events for performing a operations over WS. This can vary per exchange spec. + */ +private async getWsRequestEvents( + market: WsMarket, + operation: WsOperation, + requests: WsTopicRequest[], + wsKey: WsKey, +): Promise[]> +⋮---- +// If private topic request, build auth part for request +⋮---- +// No key or secret, push event as failed +⋮---- +private async signMessage( + paramsStr: string, + secret: string, + method: 'hex' | 'base64', + algorithm: SignAlgorithm, +): Promise +⋮---- +protected async getWsAuthRequestEvent(wsKey: WsKey): Promise +⋮---- +// id: timeInSeconds, +⋮---- +/** + * + * @param requestEvent + * @returns A signed updated WS API request object, ready to be sent + */ +private async signWSAPIRequest( + requestEvent: WSAPIRequest, +): Promise> + +================ +File: .npmrc +================ +min-release-age=30 +save-exact=true + +================ +File: .nvmrc +================ +v24.18.0 + +================ +File: examples/Rest/otc/submitOTCBankPersonalSupplement.ts +================ +import { readFileSync } from 'fs'; +⋮---- +import { RestClient } from '../../../src/index.js'; +// import { RestClient } from 'gateio-api'; +⋮---- +async function submitOTCBankPersonalSupplementExample() + +================ +File: src/lib/BaseWSClient.ts +================ +import EventEmitter from 'events'; +import WebSocket from 'isomorphic-ws'; +⋮---- +import { + WebsocketClientOptions, + WSClientConfigurableOptions, +} from '../types/websockets/client.js'; +import { WsOperation } from '../types/websockets/requests.js'; +import { WS_LOGGER_CATEGORY } from '../WebsocketClient.js'; +import { DefaultLogger } from './logger.js'; +import { isMessageEvent, MessageEventLike } from './requestUtils.js'; +import { checkWebCryptoAPISupported } from './webCryptoAPI.js'; +import { + safeTerminateWs, + WsTopicRequest, + WsTopicRequestOrStringTopic, +} from './websocket/websocket-util.js'; +import { WsStore } from './websocket/WsStore.js'; +import { + WSConnectedResult, + WsConnectionStateEnum, +} from './websocket/WsStore.types.js'; +⋮---- +interface WSClientEventMap { + /** Connection opened. If this connection was previously opened and reconnected, expect the reconnected event instead */ + open: (evt: { + wsKey: WsKey; + event: any; + wsUrl: string; + ws: WebSocket; + }) => void /** Reconnecting a dropped connection */; + reconnect: (evt: { wsKey: WsKey; event: any }) => void; + /** Successfully reconnected a connection that dropped */ + reconnected: (evt: { + wsKey: WsKey; + event: any; + wsUrl: string; + ws: WebSocket; + }) => void; + /** Connection closed */ + close: (evt: { wsKey: WsKey; event: any }) => void; + /** Received reply to websocket command (e.g. after subscribing to topics) */ + response: (response: any & { wsKey: WsKey }) => void; + /** Received data for topic */ + update: (response: any & { wsKey: WsKey }) => void; + /** Exception from ws client OR custom listeners (e.g. if you throw inside your event handler) */ + exception: (response: any & { wsKey: WsKey }) => void; + error: (response: any & { wsKey: WsKey }) => void; + /** Confirmation that a connection successfully authenticated */ + authenticated: (event: { wsKey: WsKey; event: any }) => void; } ⋮---- -export interface StockOrderBookLevel { - p?: string; - user_order?: boolean; - [key: string]: unknown; -} +/** Connection opened. If this connection was previously opened and reconnected, expect the reconnected event instead */ +⋮---- +}) => void /** Reconnecting a dropped connection */; +⋮---- +/** Successfully reconnected a connection that dropped */ +⋮---- +/** Connection closed */ +⋮---- +/** Received reply to websocket command (e.g. after subscribing to topics) */ +⋮---- +/** Received data for topic */ +⋮---- +/** Exception from ws client OR custom listeners (e.g. if you throw inside your event handler) */ +⋮---- +/** Confirmation that a connection successfully authenticated */ +⋮---- +export interface EmittableEvent { + eventType: 'response' | 'update' | 'exception' | 'authenticated'; + event: TEvent; +} +⋮---- +// Type safety for on and emit handlers: https://stackoverflow.com/a/61609010/880837 +export interface BaseWebsocketClient { + on>( + event: U, + listener: WSClientEventMap[U], + ): this; + + emit>( + event: U, + ...args: Parameters[U]> + ): boolean; +} +⋮---- +on>( + event: U, + listener: WSClientEventMap[U], + ): this; +⋮---- +emit>( + event: U, + ...args: Parameters[U]> + ): boolean; +⋮---- +/** + * Users can conveniently pass topics as strings or objects (object has topic name + optional params). + * + * This method normalises topics into objects (object has topic name + optional params). + */ +function getNormalisedTopicRequests( + wsTopicRequests: WsTopicRequestOrStringTopic[], +): WsTopicRequest[] +⋮---- +// passed as string, convert to object +⋮---- +// already a normalised object, thanks to user +⋮---- +/** + * Base WebSocket abstraction layer. Handles connections, tracking each connection as a unique "WS Key" + */ +// eslint-disable-next-line @typescript-eslint/no-unsafe-declaration-merging +export abstract class BaseWebsocketClient< +⋮---- +/** + * The WS connections supported by the client, each identified by a unique primary key + */ +⋮---- +/** + * State store to track a list of topics (topic requests) we are expected to be subscribed to if reconnected + */ +⋮---- +constructor( + options?: WSClientConfigurableOptions, + logger?: typeof DefaultLogger, +) +⋮---- +// Some defaults: +⋮---- +// Gate.io only has one connection (for both public & private). Auth works with every sub, not on connect, so this is turned off. +⋮---- +// Gate.io requires auth to be added to every request, when subscribing to private topics. This is handled automatically. +⋮---- +// Automatically re-auth WS API, if we were auth'd before and get reconnected +⋮---- +// Check Web Crypto API support when credentials are provided and no custom sign function is used +⋮---- +protected abstract isAuthOnConnectWsKey(wsKey: TWSKey): boolean; +⋮---- +protected abstract sendPingEvent(wsKey: TWSKey, ws: WebSocket): void; +⋮---- +protected abstract sendPongEvent(wsKey: TWSKey, ws: WebSocket): void; +⋮---- +protected abstract isWsPing(data: any): boolean; +⋮---- +protected abstract isWsPong(data: any): boolean; +⋮---- +protected abstract getWsAuthRequestEvent(wsKey: TWSKey): Promise; +⋮---- +protected abstract isPrivateTopicRequest( + request: WsTopicRequest, + wsKey: TWSKey, + ): boolean; +⋮---- +protected abstract getPrivateWSKeys(): TWSKey[]; +⋮---- +protected abstract getWsUrl(wsKey: TWSKey): string; +⋮---- +/** Optional headers for the WebSocket HTTP upgrade request (e.g. Gate size-decimal mode). */ +protected getWsConnectRequestHeaders( + // eslint-disable-next-line @typescript-eslint/no-unused-vars + _wsKey: TWSKey, +): Record +⋮---- +// eslint-disable-next-line @typescript-eslint/no-unused-vars +⋮---- +protected abstract getMaxTopicsPerSubscribeEvent( + wsKey: TWSKey, + ): number | null; +⋮---- +/** + * Returns a list of string events that can be individually sent upstream to complete subscribing/unsubscribing/etc to these topics + */ +protected abstract getWsOperationEventsForTopics( + topics: WsTopicRequest[], + wsKey: TWSKey, + operation: WsOperation, + ): Promise; +⋮---- +/** + * Abstraction called to sort ws events into emittable event types (response to a request, data update, etc) + */ +protected abstract resolveEmittableEvents( + wsKey: TWSKey, + event: MessageEventLike, + ): EmittableEvent[]; +⋮---- +/** + * Request connection of all dependent (public & private) websockets, instead of waiting for automatic connection by library + */ +protected abstract connectAll(): Promise[]; +⋮---- +protected isPrivateWsKey(wsKey: TWSKey): boolean +⋮---- +/** Returns auto-incrementing request ID, used to track promise references for async requests */ +protected getNewRequestId(): string +⋮---- +protected abstract sendWSAPIRequest( + wsKey: TWSKey, + channel: string, + params?: any, + ): Promise; +⋮---- +protected abstract sendWSAPIRequest( + wsKey: TWSKey, + channel: string, + params: any, + ): Promise; +⋮---- +public getTimeOffsetMs() +⋮---- +// TODO: not implemented +public setTimeOffsetMs(newOffset: number) +⋮---- +/** + * Don't call directly! Use subscribe() instead! + * + * Subscribe to one or more topics on a WS connection (identified by WS Key). + * + * - Topics are automatically cached + * - Connections are automatically opened, if not yet connected + * - Authentication is automatically handled + * - Topics are automatically resubscribed to, if something happens to the connection, unless you call unsubsribeTopicsForWsKey(topics, key). + * + * @param wsRequests array of topics to subscribe to + * @param wsKey ws key referring to the ws connection these topics should be subscribed on + */ +protected subscribeTopicsForWsKey( + wsTopicRequests: WsTopicRequestOrStringTopic[], + wsKey: TWSKey, +) +⋮---- +// Store topics, so future automation (post-auth, post-reconnect) has everything needed to resubscribe automatically +⋮---- +// start connection process if it hasn't yet begun. Topics are automatically subscribed to on-connect +⋮---- +// Subscribe should happen automatically once connected, nothing to do here after topics are added to wsStore. +⋮---- +/** + * Are we in the process of connection? Nothing to send yet. + */ +⋮---- +// We're connected. Check if auth is needed and if already authenticated +⋮---- +/** + * If not authenticated yet and auth is required, don't request topics yet. + * + * Auth should already automatically be in progress, so no action needed from here. Topics will automatically subscribe post-auth success. + */ +⋮---- +// Finally, request subscription to topics if the connection is healthy and ready +⋮---- +protected unsubscribeTopicsForWsKey( + wsTopicRequests: WsTopicRequestOrStringTopic[], + wsKey: TWSKey, +) +⋮---- +// Store topics, so future automation (post-auth, post-reconnect) has everything needed to resubscribe automatically +⋮---- +// If not connected, don't need to do anything. +// Removing the topic from the store is enough to stop it from being resubscribed to on reconnect. +⋮---- +// We're connected. Check if auth is needed and if already authenticated +⋮---- +/** + * If not authenticated yet and auth is required, don't need to do anything. + * We don't subscribe to topics until auth is complete anyway. + */ +⋮---- +// Finally, request subscription to topics if the connection is healthy and ready +⋮---- +/** + * Splits topic requests into two groups, public & private topic requests + */ +private sortTopicRequestsIntoPublicPrivate( + wsTopicRequests: WsTopicRequest[], + wsKey: TWSKey, +): +⋮---- +/** Get the WsStore that tracks websockets & topics */ +public getWsStore(): WsStore> +⋮---- +public close(wsKey: TWSKey, force?: boolean) +⋮---- +public closeAll(force?: boolean) +⋮---- +public isConnected(wsKey: TWSKey): boolean +⋮---- +/** + * Request connection to a specific websocket, instead of waiting for automatic connection. + */ +protected async connect( + wsKey: TWSKey, +): Promise +⋮---- +private connectToWsUrl(url: string, wsKey: TWSKey): WebSocket +⋮---- +private parseWsError(context: string, error: any, wsKey: TWSKey) +⋮---- +/** Get a signature, build the auth request and send it */ +private async sendAuthRequest(wsKey: TWSKey): Promise +⋮---- +// console.log('ws auth req', request); +⋮---- +private reconnectWithDelay(wsKey: TWSKey, connectionDelayMs: number) +⋮---- +private ping(wsKey: TWSKey) +⋮---- +private clearTimers(wsKey: TWSKey) +⋮---- +// Send a ping at intervals +private clearPingTimer(wsKey: TWSKey) +⋮---- +// Expect a pong within a time limit +private clearPongTimer(wsKey: TWSKey) +⋮---- +// this.logger.trace(`Cleared pong timeout for "${wsKey}"`); +⋮---- +// this.logger.trace(`No active pong timer for "${wsKey}"`); +⋮---- +/** + * Simply builds and sends subscribe events for a list of topics for a ws key + * + * @private Use the `subscribe(topics)` or `subscribeTopicsForWsKey(topics, wsKey)` method to subscribe to topics. Send WS message to subscribe to topics. + */ +private async requestSubscribeTopics( + wsKey: TWSKey, + topics: WsTopicRequest[], +) +⋮---- +// Automatically splits requests into smaller batches, if needed +⋮---- +`Subscribing to ${topics.length} "${wsKey}" topics in ${subscribeWsMessages.length} batches.`, // Events: "${JSON.stringify(topics)}" +⋮---- +// console.log(`batches: `, JSON.stringify(subscribeWsMessages, null, 2)); +⋮---- +// this.logger.trace(`Sending batch via message: "${wsMessage}"`); +⋮---- +/** + * Simply builds and sends unsubscribe events for a list of topics for a ws key + * + * @private Use the `unsubscribe(topics)` method to unsubscribe from topics. Send WS message to unsubscribe from topics. + */ +private async requestUnsubscribeTopics( + wsKey: TWSKey, + wsTopicRequests: WsTopicRequest[], +) +⋮---- +/** + * Try sending a string event on a WS connection (identified by the WS Key) + */ +public tryWsSend( + wsKey: TWSKey, + wsMessage: string, + throwExceptions?: boolean, +) +⋮---- +private async onWsOpen( + event: any, + wsKey: TWSKey, + url: string, + ws: WebSocket, +) +⋮---- +// Resolve & cleanup deferred "connection attempt in progress" promise +⋮---- +// eslint-disable-next-line @typescript-eslint/no-unused-vars +⋮---- +// Remove before resolving, in case there's more requests queued +⋮---- +// Some websockets require an auth packet to be sent after opening the connection +⋮---- +// Reconnect to topics known before it connected +⋮---- +// Request sub to public topics, if any +⋮---- +// Request sub to private topics, if auth on connect isn't needed ⋮---- -export interface StockOrderBook { - symbol?: string; - bids?: StockOrderBookLevel[]; - asks?: StockOrderBookLevel[]; - timestamp?: number; -} +// If enabled, automatically reauth WS API if reconnected ⋮---- -export interface StockOrderItem { - order_id?: string; - symbol?: string; - exchange?: string; - quote_currency?: string; - fx_rate?: string; - symbol_desc?: string; - trade_status?: string; - trade_mode?: number; - price_type?: string; - side?: number; - status?: number; - volume?: string; - fill_volume?: string; - price?: string; - time_setup?: number; - time_update?: number; - max_order_volume?: string; - step_order_volume?: string; - min_order_volume?: string; - price_precision?: number; - price_protection?: string; - sell_price_protection?: string; - buy_price_protection?: string; - commission_rate?: string; - slippage_rate?: string; - [key: string]: unknown; -} +// eslint-disable-next-line @typescript-eslint/no-unused-vars ⋮---- -export interface StockCreateOrderResult { - id?: string; -} +/** + * Handle subscription to private topics _after_ authentication successfully completes asynchronously. + * + * Only used for exchanges that require auth before sending private topic subscription requests + */ +private onWsAuthenticated( + wsKey: TWSKey, + event: { isWSAPI?: boolean; WSAPIAuthChannel?: string }, +) ⋮---- -export interface StockOrderHistoryItem { - order_id?: string; - symbol?: string; - exchange?: string; - quote_currency?: string; - fx_rate?: string; - symbol_desc?: string; - price_type?: string; - status?: number; - status_desc?: string; - status_detail?: { title?: string; message?: string } | null; - finish_as?: number; - side?: number; - time_in_force?: string; - volume?: string; - fill_volume?: string; - price?: string; - avg_fill_price?: string | null; - commission?: string; - time_setup?: number; - time_done?: number; - [key: string]: unknown; -} +// Resolve & cleanup deferred "auth attempt in progress" promise ⋮---- -export interface StockUpdateOrderResult { - order_id?: number; -} +// Remove before continuing, in case there's more requests queued ⋮---- -export interface StockPositionItem { - symbol?: string; - exchange?: string; - quote_currency?: string; - quote_currency_precision?: number; - fx_rate?: string; - trade_status?: string; - symbol_desc?: string; - position_pnl?: string; - today_pnl?: string; - pnl_rate?: string; - today_sell_amount?: string; - today_buy_amount?: string; - today_sell_volume?: string; - today_buy_volume?: string; - yesterday_volume?: string; - volume?: string; - available?: string; - transfer_out_pending_qty?: string; - avg_cost_price?: string; - diluted_cost_price?: string; - last_price?: string; - extended_last_price?: string | null; - max_order_volume?: string; - step_order_volume?: string; - min_order_volume?: string; - price_precision?: number; - price_protection?: string; - [key: string]: unknown; -} +private onWsMessage(event: unknown, wsKey: TWSKey, ws: WebSocket) ⋮---- -export interface StockClosePositionResult { - order_id?: number; -} +// any message can clear the pong timer - wouldn't get a message if the ws wasn't working ⋮---- -export interface StockTransactionItem { - asset?: string; - symbol?: string; - symbol_display?: string; - type?: string; - type_desc?: string; - change?: string; - balance?: string; - ref_id?: string; - time?: number; - unit_text?: string; - detail?: object; -} +// console.log(`raw event: `, { data, dataType, emittableEvents }); ⋮---- -export interface StockExchangeItem { - exchange?: string; - exchange_desc?: string; - icon_link?: string; - support_transfer?: boolean; -} +private onWsClose(event: unknown, wsKey: TWSKey) ⋮---- -export interface StockFeeRateItem { - vip_level?: number; - maker_fee?: string; - taker_fee?: string; -} - -================ -File: src/types/response/withdrawal.ts -================ -export interface WithdrawalRecord { - id: string; - txid: string; - block_number: string; - withdraw_order_id: string; - /** When `status` is DONE, withdrawal success time (not conditioned on `block_number`). */ - timestamp: string; - amount: string; - currency: string; - address: string; - memo?: string; - status: - | 'BCODE' // Deposit Code Operation - | 'CANCEL' // Cancelled - | 'CANCELPEND' // Withdrawal Cancellation Pending - | 'DMOVE' // Pending Manual Review - | 'DONE' // Completed - | 'EXTPEND' // Sent and Waiting for Confirmation - | 'FAIL' // On-Chain Failure Pending Confirmation - | 'FVERIFY' // Facial Verification in Progress - | 'INVALID' // Invalid Transaction - | 'LOCKED' // Wallet-Side Order Locked - | 'MANUAL' // Pending Manual Review - | 'PEND' // Processing - | 'PROCES' // Processing - | 'REJECT' // Rejected - | 'REQUEST' // Request in Progress - | 'REVIEW' // Under Review - | 'SPLITPEND' // Split Pending - | 'VERIFY'; // Verification in Progress - chain: string; -} +// unintentional close, attempt recovery ⋮---- -/** When `status` is DONE, withdrawal success time (not conditioned on `block_number`). */ +// clean up any pending promises for this connection ⋮---- -| 'BCODE' // Deposit Code Operation -| 'CANCEL' // Cancelled -| 'CANCELPEND' // Withdrawal Cancellation Pending -| 'DMOVE' // Pending Manual Review -| 'DONE' // Completed -| 'EXTPEND' // Sent and Waiting for Confirmation -| 'FAIL' // On-Chain Failure Pending Confirmation -| 'FVERIFY' // Facial Verification in Progress -| 'INVALID' // Invalid Transaction -| 'LOCKED' // Wallet-Side Order Locked -| 'MANUAL' // Pending Manual Review -| 'PEND' // Processing -| 'PROCES' // Processing -| 'REJECT' // Rejected -| 'REQUEST' // Request in Progress -| 'REVIEW' // Under Review -| 'SPLITPEND' // Split Pending -| 'VERIFY'; // Verification in Progress - -================ -File: src/types/shared.ts -================ -export type GateBaseUrlKey = - | 'live' - | 'futuresLiveAlternative' - | 'futuresTestnet'; +// intentional close - clean up +// clean up any pending promises for this connection ⋮---- -// interfaces +// clean up any pending promises for this connection ⋮---- -export interface FromToPageLimit { - from: number; - to: number; - page: number; - limit: number; -} +// This was an intentional close, delete all state for this connection, as if it never existed: ⋮---- -// Used for spot and flash swap -export interface CurrencyPair { - id?: string; - base?: string; - base_name?: string; - quote?: string; - quote_name?: string; - trade_quotes?: string[] | null; - fee?: string; - min_base_amount?: string; - min_quote_amount?: string; - max_base_amount?: string; - max_quote_amount?: string; - amount_precision?: number; - precision?: number; - trade_status?: 'untradable' | 'buyable' | 'sellable' | 'tradable'; - sell_start?: number; - buy_start?: number; - type: string; - delisting_time?: number; - trade_url?: string; - up_rate?: string; // v4.106.4: Maximum price increase percentage - down_rate?: string; // v4.106.4: Maximum price decrease percentage - market_order_max_stock?: string | null; - market_order_max_money?: string | null; -} +private getWs(wsKey: TWSKey) +⋮---- +private setWsState(wsKey: TWSKey, state: WsConnectionStateEnum) +⋮---- +/** + * Promise-driven method to assert that a ws has successfully connected (will await until connection is open) + */ +protected async assertIsConnected(wsKey: TWSKey): Promise +⋮---- +// Already in progress? Await shared promise and retry ⋮---- -up_rate?: string; // v4.106.4: Maximum price increase percentage -down_rate?: string; // v4.106.4: Maximum price decrease percentage - -================ -File: .npmrc -================ -min-release-age=30 -save-exact=true - -================ -File: .nvmrc -================ -v24.18.0 - -================ -File: examples/Rest/otc/submitOTCBankPersonalSupplement.ts -================ -import { readFileSync } from 'fs'; +// Start connection, it should automatically store/return a promise. ⋮---- -import { RestClient } from '../../../src/index.js'; -// import { RestClient } from 'gateio-api'; +/** + * Promise-driven method to assert that a ws has been successfully authenticated (will await until auth is confirmed) + */ +public async assertIsAuthenticated(wsKey: TWSKey): Promise ⋮---- -async function submitOTCBankPersonalSupplementExample() +// Already in progress? Await shared promise and retry +⋮---- +// this.logger.trace('assertIsAuthenticated(): ok'); +⋮---- +// Start authentication, it should automatically store/return a promise. ================ File: src/types/request/alpha.ts @@ -6252,291 +5698,645 @@ to?: number; // End time for order query, defaults to current time if not specif limit?: number; // Maximum number of items returned. Default: 100, minimum: 1, maximum: 100 page?: number; // Page number ⋮---- -export interface GetAlphaOrderReq { - order_id: string; // Order ID +export interface GetAlphaOrderReq { + order_id: string; // Order ID +} +⋮---- +order_id: string; // Order ID +⋮---- +export interface GetAlphaCurrenciesReq { + currency?: string; // Query currency information by currency symbol + limit?: number; // Maximum number of records returned in a single list + page?: number; // Page number +} +⋮---- +currency?: string; // Query currency information by currency symbol +limit?: number; // Maximum number of records returned in a single list +page?: number; // Page number +⋮---- +export interface GetAlphaTickersReq { + currency?: string; // Query by specified currency name + limit?: number; // Maximum number of records returned in a single list + page?: number; // Page number +} +⋮---- +currency?: string; // Query by specified currency name +limit?: number; // Maximum number of records returned in a single list +page?: number; // Page number + +================ +File: src/types/request/autoinvest.ts +================ +/**========================================================================================================================== + * EARN AUTO INVEST + * ========================================================================================================================== + */ +⋮---- +export interface AutoInvestPlanPortfolioItemInput { + asset: string; + ratio: string; +} +⋮---- +/** POST /earn/autoinvest/plans/create */ +export interface CreateAutoInvestPlanReq { + plan_name?: string; + plan_des?: string; + plan_money: string; + plan_amount: string; + plan_period_type: + | 'daily' + | 'weekly' + | 'biweekly' + | 'monthly' + | 'hourly' + | '4-hourly'; + plan_period_day: number; + plan_period_hour: number; + items: AutoInvestPlanPortfolioItemInput[]; + /** Fund source: `spot` or `earn`; default spot */ + fund_source?: string; + /** Fund flow: `auto_invest` or `earn`; default auto_invest */ + fund_flow?: string; + /** 0 normal creation, 1 quick investment */ + type?: number; +} +⋮---- +/** Fund source: `spot` or `earn`; default spot */ +⋮---- +/** Fund flow: `auto_invest` or `earn`; default auto_invest */ +⋮---- +/** 0 normal creation, 1 quick investment */ +⋮---- +/** POST /earn/autoinvest/plans/update */ +export interface UpdateAutoInvestPlanReq { + plan_id: number; + fund_source?: string; + fund_flow?: string; +} +⋮---- +/** POST /earn/autoinvest/plans/stop */ +export interface StopAutoInvestPlanReq { + plan_id: number; +} +⋮---- +/** POST /earn/autoinvest/plans/add_position */ +export interface AddAutoInvestPlanPositionReq { + plan_id: number; + amount: string; +} +⋮---- +/** POST /earn/autoinvest/min_invest_amount */ +export interface GetAutoInvestMinAmountReq { + money: string; + items: AutoInvestPlanPortfolioItemInput[]; +} +⋮---- +/** GET /earn/autoinvest/coins */ +export interface GetAutoInvestCoinsReq { + /** Pricing currency: USDT or BTC; default USDT */ + plan_money?: string; +} +⋮---- +/** Pricing currency: USDT or BTC; default USDT */ +⋮---- +/** GET /earn/autoinvest/plans/records */ +export interface GetAutoInvestPlanRecordsReq { + plan_id: number; + page?: number; + page_size?: number; +} +⋮---- +/** GET /earn/autoinvest/orders */ +export interface GetAutoInvestOrdersReq { + plan_id: number; + record_id: number; +} +⋮---- +/** GET /earn/autoinvest/plans/detail */ +export interface GetAutoInvestPlanDetailReq { + plan_id: number; +} +⋮---- +/** GET /earn/autoinvest/plans/list_info */ +export interface GetAutoInvestPlansReq { + /** Plan status: e.g. History (history) or Active (active) */ + status: string; + page?: number; + page_size?: number; +} +⋮---- +/** Plan status: e.g. History (history) or Active (active) */ + +================ +File: src/types/request/p2pMerchant.ts +================ +/** P2P Merchant API request types */ +⋮---- +export interface P2PMerchantGetCounterpartyUserInfoReq { + biz_uid: string; +} +⋮---- +export interface P2PMerchantGetMyselfPaymentReq { + fiat?: string; +} +⋮---- +export interface P2PMerchantGetPendingTransactionListReq { + crypto_currency: string; + fiat_currency: string; + order_tab?: string; + select_type?: string; + status?: string; + txid?: number; + start_time?: number; + end_time?: number; +} +⋮---- +export interface P2PMerchantGetCompletedTransactionListReq { + crypto_currency: string; + fiat_currency: string; + select_type?: string; + status?: string; + txid?: number; + start_time?: number; + end_time?: number; + query_dispute?: number; + page?: number; + per_page?: number; +} +⋮---- +export interface P2PMerchantGetTransactionDetailsReq { + txid: number; + channel?: string; +} +⋮---- +export interface P2PMerchantConfirmPaymentReq { + trade_id: string; + payment_method: string; +} +⋮---- +export interface P2PMerchantConfirmReceiptReq { + trade_id: string; +} +⋮---- +export interface P2PMerchantCancelTransactionReq { + trade_id: string; + reason_id?: string; + reason_memo?: string; +} +⋮---- +export interface P2PMerchantPlaceBizPushOrderReq { + currencyType: string; + exchangeType: string; + type: string; + unitPrice: string; + number: string; + payType: string; + minAmount?: string; // v4.106.102: No longer required; trade quantity priced by currencyType + maxAmount?: string; // v4.106.102: No longer required; trade quantity priced by currencyType + pay_type_json?: string; + rateFixed?: string; + oid?: string; + tierLimit?: string; + verifiedLimit?: string; + regTimeLimit?: string; + advertisersLimit?: string; + hide_payment?: string; + expire_min?: string; + trade_tips?: string; + auto_reply?: string; + min_completed_limit?: string; + max_completed_limit?: string; + completed_rate_limit?: string; + user_country_limit?: string; + user_order_limit?: string; + rateReferenceId?: string; + rateOffset?: string; + float_trend?: string; + limitBasis?: string; // v4.106.102: 0 by crypto quantity, 1 by fiat amount; defaults to 0 + fiatMinAmount?: string; // v4.106.102: Required when limitBasis is 1 + fiatMaxAmount?: string; // v4.106.102: Required when limitBasis is 1 + polymarket_limit?: string; // v4.106.102: Restrict trading with Polymarket users +} +⋮---- +minAmount?: string; // v4.106.102: No longer required; trade quantity priced by currencyType +maxAmount?: string; // v4.106.102: No longer required; trade quantity priced by currencyType +⋮---- +limitBasis?: string; // v4.106.102: 0 by crypto quantity, 1 by fiat amount; defaults to 0 +fiatMinAmount?: string; // v4.106.102: Required when limitBasis is 1 +fiatMaxAmount?: string; // v4.106.102: Required when limitBasis is 1 +polymarket_limit?: string; // v4.106.102: Restrict trading with Polymarket users +⋮---- +/** POST /p2p/merchant/account/set_merchant_work_hours — v4.106.96 */ +export interface P2PMerchantSetMerchantWorkHoursReq { + work_status: 0 | 1 | 2; // 0 resting, 1 working, 2 custom working hours + cycle_type?: string; + day_of_week?: string; + time_zone?: string; // UTC offset -12 to +14 + start_time?: string; + end_time?: string; } ⋮---- -order_id: string; // Order ID +work_status: 0 | 1 | 2; // 0 resting, 1 working, 2 custom working hours ⋮---- -export interface GetAlphaCurrenciesReq { - currency?: string; // Query currency information by currency symbol - limit?: number; // Maximum number of records returned in a single list - page?: number; // Page number +time_zone?: string; // UTC offset -12 to +14 +⋮---- +export interface P2PMerchantAdsUpdateStatusReq { + adv_no: number; + adv_status: 1 | 3 | 4; + /** Optional query param */ + trade_type?: string; } ⋮---- -currency?: string; // Query currency information by currency symbol -limit?: number; // Maximum number of records returned in a single list -page?: number; // Page number +/** Optional query param */ ⋮---- -export interface GetAlphaTickersReq { - currency?: string; // Query by specified currency name - limit?: number; // Maximum number of records returned in a single list - page?: number; // Page number +export interface P2PMerchantAdsDetailReq { + adv_no: string; } ⋮---- -currency?: string; // Query by specified currency name -limit?: number; // Maximum number of records returned in a single list -page?: number; // Page number - -================ -File: src/types/request/autoinvest.ts -================ -/**========================================================================================================================== - * EARN AUTO INVEST - * ========================================================================================================================== - */ +export interface P2PMerchantMyAdsListReq { + asset?: string; + fiat_unit?: string; + trade_type?: string; +} ⋮---- -export interface AutoInvestPlanPortfolioItemInput { +export interface P2PMerchantGetAdsListReq { asset: string; - ratio: string; + fiat_unit: string; + trade_type: string; } ⋮---- -/** POST /earn/autoinvest/plans/create */ -export interface CreateAutoInvestPlanReq { - plan_name?: string; - plan_des?: string; - plan_money: string; - plan_amount: string; - plan_period_type: - | 'daily' - | 'weekly' - | 'biweekly' - | 'monthly' - | 'hourly' - | '4-hourly'; - plan_period_day: number; - plan_period_hour: number; - items: AutoInvestPlanPortfolioItemInput[]; - /** Fund source: `spot` or `earn`; default spot */ - fund_source?: string; - /** Fund flow: `auto_invest` or `earn`; default auto_invest */ - fund_flow?: string; - /** 0 normal creation, 1 quick investment */ - type?: number; +export interface P2PMerchantGetChatsListReq { + txid: number; + lastreceived?: number; + firstreceived?: number; } ⋮---- -/** Fund source: `spot` or `earn`; default spot */ +export interface P2PMerchantSendChatMessageReq { + txid: number; + message: string; + /** 0=Text, 1=File (video or image). Default 0 */ + type?: 0 | 1; +} ⋮---- -/** Fund flow: `auto_invest` or `earn`; default auto_invest */ +/** 0=Text, 1=File (video or image). Default 0 */ ⋮---- -/** 0 normal creation, 1 quick investment */ +export interface P2PMerchantUploadChatFileReq { + image_content_type: string; + base64_img: string; +} + +================ +File: src/types/request/stock.ts +================ +/** Stock / TradFi Spot API request types */ ⋮---- -/** POST /earn/autoinvest/plans/update */ -export interface UpdateAutoInvestPlanReq { - plan_id: number; - fund_source?: string; - fund_flow?: string; +export interface GetStockUserAssetsReq { + pnl_calc_type?: number; + pnl_calc_price?: number; } ⋮---- -/** POST /earn/autoinvest/plans/stop */ -export interface StopAutoInvestPlanReq { - plan_id: number; +export interface GetStockSymbolsReq { + symbols?: string; + exchange?: string; // us | hk | jp + with_desc_i18n?: boolean; + page?: number; + page_size?: number; } ⋮---- -/** POST /earn/autoinvest/plans/add_position */ -export interface AddAutoInvestPlanPositionReq { - plan_id: number; - amount: string; +exchange?: string; // us | hk | jp +⋮---- +export interface GetStockSymbolDetailReq { + symbols?: string; + exchange?: string; // us | hk | jp + page?: number; + page_size?: number; } ⋮---- -/** POST /earn/autoinvest/min_invest_amount */ -export interface GetAutoInvestMinAmountReq { - money: string; - items: AutoInvestPlanPortfolioItemInput[]; +exchange?: string; // us | hk | jp +⋮---- +export interface GetStockOrdersReq { + symbol?: string; } ⋮---- -/** GET /earn/autoinvest/coins */ -export interface GetAutoInvestCoinsReq { - /** Pricing currency: USDT or BTC; default USDT */ - plan_money?: string; +export interface CreateStockOrderReq { + volume: string; + symbol: string; + side: 1 | 2; + price_type: 'market' | 'limit'; + /** Limit: all only; market: regular only */ + trading_session: 'all' | 'regular'; + time_in_force: 'day'; + price?: string; + client_order_id?: string; } ⋮---- -/** Pricing currency: USDT or BTC; default USDT */ +/** Limit: all only; market: regular only */ ⋮---- -/** GET /earn/autoinvest/plans/records */ -export interface GetAutoInvestPlanRecordsReq { - plan_id: number; +export interface GetStockOrderHistoryReq { + symbol?: string; + order_ids?: string; + begin_time?: number; + end_time?: number; + side?: 1 | 2; page?: number; page_size?: number; } ⋮---- -/** GET /earn/autoinvest/orders */ -export interface GetAutoInvestOrdersReq { - plan_id: number; - record_id: number; +export interface UpdateStockOrderReq { + volume: string; + price: string; } ⋮---- -/** GET /earn/autoinvest/plans/detail */ -export interface GetAutoInvestPlanDetailReq { - plan_id: number; +export interface GetStockPositionsReq { + pnl_calc_type?: number; + pnl_calc_price?: number; + symbol?: string; + exchange?: string; // us | hk | jp } ⋮---- -/** GET /earn/autoinvest/plans/list_info */ -export interface GetAutoInvestPlansReq { - /** Plan status: e.g. History (history) or Active (active) */ - status: string; +exchange?: string; // us | hk | jp +⋮---- +export interface CloseStockPositionReq { + symbol: string; + close_type: 1 | 2; + close_volume?: string; +} +⋮---- +export interface GetStockTransactionsReq { + begin_time?: number; + end_time?: number; + ref_id?: string; + type?: string; page?: number; page_size?: number; } ⋮---- -/** Plan status: e.g. History (history) or Active (active) */ +export interface CreateStockTransactionReq { + asset: string; + change: string; + type: 'deposit' | 'withdraw'; + ref_id: string; +} ================ -File: src/types/request/p2pMerchant.ts +File: src/types/response/delivery.ts ================ -/** P2P Merchant API request types */ +import { FuturesContractSize } from '../shared.js'; ⋮---- -export interface P2PMerchantGetCounterpartyUserInfoReq { - biz_uid: string; +/**========================================================================================================================== + * DELIVERY + * ========================================================================================================================== + */ +⋮---- +export interface DeliveryOrderBook { + id?: number; + current: number; + update: number; + asks: { p: string; s: FuturesContractSize }[]; + bids: { p: string; s: FuturesContractSize }[]; +} +⋮---- +export interface DeliveryTrade { + id: number; + create_time: number; + create_time_ms: number; + contract: string; + /** String when `futuresSizeDecimal` is enabled on the client. */ + size: FuturesContractSize; + price: string; + is_internal?: boolean; // Deprecated +} +⋮---- +/** String when `futuresSizeDecimal` is enabled on the client. */ +⋮---- +is_internal?: boolean; // Deprecated +⋮---- +export interface DeliveryCandle { + t: number; + /** String when `futuresSizeDecimal` is enabled on the client. */ + v?: FuturesContractSize; + c: string; + h: string; + l: string; + o: string; +} +⋮---- +/** String when `futuresSizeDecimal` is enabled on the client. */ +⋮---- +export interface DeliveryTicker { + contract: string; + last: string; + change_percentage: string; + total_size: string; + low_24h: string; + high_24h: string; + volume_24h: string; + volume_24h_btc?: string; + volume_24h_usd?: string; + volume_24h_base: string; + volume_24h_quote: string; + volume_24h_settle: string; + mark_price: string; + funding_rate: string; + funding_rate_indicative: string; + index_price: string; + quanto_base_rate?: string; // Deprecated + basis_rate: string; + basis_value: string; + lowest_ask: string; + highest_bid: string; } ⋮---- -export interface P2PMerchantGetMyselfPaymentReq { - fiat?: string; -} +quanto_base_rate?: string; // Deprecated ⋮---- -export interface P2PMerchantGetPendingTransactionListReq { - crypto_currency: string; - fiat_currency: string; - order_tab?: string; - select_type?: string; - status?: string; - txid?: number; - start_time?: number; - end_time?: number; +export interface DeliveryAccount { + total: string; // Balance, only applicable to classic contract account + unrealised_pnl: string; + position_margin?: string; // Deprecated + order_margin: string; // Initial margin for all pending orders + available: string; + point: string; + currency: string; + in_dual_mode: boolean; + position_mode?: string; // Position mode: single - one-way, dual - dual-side, split - sub-positions (in_dual_mode is deprecated) + enable_credit: boolean; + position_initial_margin: string; + maintenance_margin: string; + bonus: string; + enable_evolved_classic?: boolean; // Deprecated + cross_order_margin: string; + cross_initial_margin: string; + cross_maintenance_margin: string; + cross_unrealised_pnl: string; + cross_available: string; + isolated_position_margin: string; + enable_new_dual_mode?: boolean; // Deprecated + margin_mode?: number; // 0: classic delivery account; 1: Multi-Currency Margin Mode; 2: Portfolio Margin Mode; 3: Single-Currency Margin Mode + history: { + dnw: string; + pnl: string; + fee: string; + refr: string; + fund: string; + point_dnw: string; + point_fee: string; + point_refr: string; + bonus_dnw: string; + bonus_offset: string; + }; + enable_tiered_mm: boolean; } ⋮---- -export interface P2PMerchantGetCompletedTransactionListReq { - crypto_currency: string; - fiat_currency: string; - select_type?: string; - status?: string; - txid?: number; - start_time?: number; - end_time?: number; - query_dispute?: number; - page?: number; - per_page?: number; -} +total: string; // Balance, only applicable to classic contract account ⋮---- -export interface P2PMerchantGetTransactionDetailsReq { - txid: number; - channel?: string; -} +position_margin?: string; // Deprecated +order_margin: string; // Initial margin for all pending orders ⋮---- -export interface P2PMerchantConfirmPaymentReq { - trade_id: string; - payment_method: string; -} +position_mode?: string; // Position mode: single - one-way, dual - dual-side, split - sub-positions (in_dual_mode is deprecated) ⋮---- -export interface P2PMerchantConfirmReceiptReq { - trade_id: string; -} +enable_evolved_classic?: boolean; // Deprecated ⋮---- -export interface P2PMerchantCancelTransactionReq { - trade_id: string; - reason_id?: string; - reason_memo?: string; +enable_new_dual_mode?: boolean; // Deprecated +margin_mode?: number; // 0: classic delivery account; 1: Multi-Currency Margin Mode; 2: Portfolio Margin Mode; 3: Single-Currency Margin Mode +⋮---- +export interface DeliveryBook { + time: number; + change: string; + balance: string; + type: + | 'dnw' + | 'pnl' + | 'fee' + | 'refr' + | 'fund' + | 'point_dnw' + | 'point_fee' + | 'point_refr' + | 'bonus_offset'; + text: string; + contract?: string; + trade_id?: string; } ⋮---- -export interface P2PMerchantPlaceBizPushOrderReq { - currencyType: string; - exchangeType: string; - type: string; - unitPrice: string; - number: string; - payType: string; - minAmount?: string; // v4.106.102: No longer required; trade quantity priced by currencyType - maxAmount?: string; // v4.106.102: No longer required; trade quantity priced by currencyType - pay_type_json?: string; - rateFixed?: string; - oid?: string; - tierLimit?: string; - verifiedLimit?: string; - regTimeLimit?: string; - advertisersLimit?: string; - hide_payment?: string; - expire_min?: string; - trade_tips?: string; - auto_reply?: string; - min_completed_limit?: string; - max_completed_limit?: string; - completed_rate_limit?: string; - user_country_limit?: string; - user_order_limit?: string; - rateReferenceId?: string; - rateOffset?: string; - float_trend?: string; - limitBasis?: string; // v4.106.102: 0 by crypto quantity, 1 by fiat amount; defaults to 0 - fiatMinAmount?: string; // v4.106.102: Required when limitBasis is 1 - fiatMaxAmount?: string; // v4.106.102: Required when limitBasis is 1 - polymarket_limit?: string; // v4.106.102: Restrict trading with Polymarket users +export interface DeliveryTradingHistoryRecord { + id: number; + create_time: number; + contract: string; + order_id: string; + /** String when `futuresSizeDecimal` is enabled on the client. */ + size: FuturesContractSize; + price: string; + role: 'taker' | 'maker'; + text: string; + fee: string; + point_fee: string; } ⋮---- -minAmount?: string; // v4.106.102: No longer required; trade quantity priced by currencyType -maxAmount?: string; // v4.106.102: No longer required; trade quantity priced by currencyType +/** String when `futuresSizeDecimal` is enabled on the client. */ ⋮---- -limitBasis?: string; // v4.106.102: 0 by crypto quantity, 1 by fiat amount; defaults to 0 -fiatMinAmount?: string; // v4.106.102: Required when limitBasis is 1 -fiatMaxAmount?: string; // v4.106.102: Required when limitBasis is 1 -polymarket_limit?: string; // v4.106.102: Restrict trading with Polymarket users +export interface DeliveryClosedPosition { + time: number; + contract: string; + side: 'long' | 'short'; + pnl: string; + pnl_pnl: string; + pnl_fund: string; + pnl_fee: string; + text: string; + max_size: string; + first_open_time: number; + long_price: string; + short_price: string; +} ⋮---- -/** POST /p2p/merchant/account/set_merchant_work_hours — v4.106.96 */ -export interface P2PMerchantSetMerchantWorkHoursReq { - work_status: 0 | 1 | 2; // 0 resting, 1 working, 2 custom working hours - cycle_type?: string; - day_of_week?: string; - time_zone?: string; // UTC offset -12 to +14 - start_time?: string; - end_time?: string; +export interface DeliveryLiquidationHistoryRecord { + time: number; + contract: string; + leverage?: string; + /** String when `futuresSizeDecimal` is enabled on the client. */ + size: FuturesContractSize; + margin?: string; + entry_price?: string; + liq_price?: string; + mark_price?: string; + order_id?: number; + order_price: string; + fill_price: string; + /** String when `futuresSizeDecimal` is enabled on the client. */ + left: FuturesContractSize; } ⋮---- -work_status: 0 | 1 | 2; // 0 resting, 1 working, 2 custom working hours +/** String when `futuresSizeDecimal` is enabled on the client. */ ⋮---- -time_zone?: string; // UTC offset -12 to +14 +/** String when `futuresSizeDecimal` is enabled on the client. */ ⋮---- -export interface P2PMerchantAdsUpdateStatusReq { - adv_no: number; - adv_status: 1 | 3 | 4; - /** Optional query param */ - trade_type?: string; +export interface DeliverySettlementHistoryRecord { + time: number; + contract: string; + leverage: string; + /** String when `futuresSizeDecimal` is enabled on the client. */ + size: FuturesContractSize; + margin: string; + entry_price: string; + settle_price: string; + profit: string; + fee: string; } ⋮---- -/** Optional query param */ +/** String when `futuresSizeDecimal` is enabled on the client. */ + +================ +File: src/types/response/marginuni.ts +================ +/**========================================================================================================================== + * MARGIN UNI + * ========================================================================================================================== + */ ⋮---- -export interface P2PMerchantAdsDetailReq { - adv_no: string; +export interface LendingMarket { + currency_pair: string; + base_min_borrow_amount: string; + quote_min_borrow_amount: string; + leverage: string; + status?: string | number; + delisted_time?: number; } ⋮---- -export interface P2PMerchantMyAdsListReq { - asset?: string; - fiat_unit?: string; - trade_type?: string; +export interface MarginUNILoan { + currency: string; + currency_pair: string; + amount: string; + type: string; // Lending type, margin indicates margin borrowing + create_time: number; + update_time: number; } ⋮---- -export interface P2PMerchantGetAdsListReq { - asset: string; - fiat_unit: string; - trade_type: string; -} +type: string; // Lending type, margin indicates margin borrowing ⋮---- -export interface P2PMerchantGetChatsListReq { - txid: number; - lastreceived?: number; - firstreceived?: number; +export interface MarginUNILoanRecord { + type: string; + currency_pair: string; + currency: string; + amount: string; + create_time: number; } ⋮---- -export interface P2PMerchantSendChatMessageReq { - txid: number; - message: string; - /** 0=Text, 1=File (video or image). Default 0 */ - type?: 0 | 1; +export interface MarginUNIInterestRecord { + currency: string; + currency_pair: string; + actual_rate: string; + interest: string; + status: number; + type: string; // Lending type, margin indicates margin borrowing + create_time: number; } ⋮---- -/** 0=Text, 1=File (video or image). Default 0 */ +type: string; // Lending type, margin indicates margin borrowing ⋮---- -export interface P2PMerchantUploadChatFileReq { - image_content_type: string; - base64_img: string; +export interface MarginUNIMaxBorrowable { + currency: string; + currency_pair: string; + borrowable: string; } ================ @@ -6776,20 +6576,259 @@ export interface P2PMerchantPlaceOrderRiskData { }; } ⋮---- -/** v4.106.96: send_chat_message risk fields in data */ -export interface P2PMerchantSendChatMessageData { - risk_type?: number; - toast_msg?: string; - [key: string]: unknown; +/** v4.106.96: send_chat_message risk fields in data */ +export interface P2PMerchantSendChatMessageData { + risk_type?: number; + toast_msg?: string; + [key: string]: unknown; +} +⋮---- +export interface P2PMerchantChatsListData { + messages: P2PMerchantChatMessage[]; + has_history?: boolean; + txid?: number; + SRVTM?: number; + order_status?: string; + memo?: string; +} + +================ +File: src/types/response/stock.ts +================ +export type StockCategory = + | 'CS' + | 'ETF' + | 'ADRC' + | 'ADR' + | 'ETV' + | 'PFD' + | 'ETS' + | 'ETN' + | 'FUND'; +⋮---- +export type StockAssetType = 'STOCK' | 'ETF'; +⋮---- +export interface StockApiResp { + timestamp?: number; + data?: T; + code?: number; + message?: string; + label?: string; +} +⋮---- +export interface StockListData { + list?: T[]; + total?: number; + total_page?: number; +} +⋮---- +export interface StockUserAssets { + equity?: string; + balance?: string; + available?: string; + position_market_value?: string; + position_pnl?: string; + today_pnl?: string; + user_exists?: boolean; + option_position_market_value?: string; + option_position_pnl?: string; + option_today_pnl?: string; +} +⋮---- +export interface StockSymbolDescI18n { + lang?: string; + value?: string; +} +⋮---- +export interface StockSymbolItem { + symbol?: string; + exchange?: string; + exchange_desc?: string; + quote_currency?: string; + quote_currency_precision?: number; + fx_rate?: string; + symbol_desc?: string; + category?: StockCategory | string; + asset_type?: StockAssetType; + trade_status?: string; + trade_mode?: number; + order_fill_timing?: number; + icon_link?: string; + quote_currency_symbol?: string; + price_precision?: number; + volume_precision?: number; + is_ipo?: boolean; + ipo_price?: string; + sell_price_protection?: string; + buy_price_protection?: string; + symbol_descs?: StockSymbolDescI18n[]; + timestamp?: number; +} +⋮---- +export interface StockSymbolDetailItem { + symbol?: string; + exchange?: string; + exchange_desc?: string; + quote_currency?: string; + quote_currency_precision?: number; + fx_rate?: string; + symbol_desc?: string; + category?: StockCategory | string; + asset_type?: StockAssetType; + settlement_currency?: string; + max_order_volume?: string; + step_order_volume?: string; + min_order_volume?: string; + price_precision?: number; + volume_precision?: number; + is_ipo?: boolean; + ipo_price?: string; + price_protection?: string; + sell_price_protection?: string; + buy_price_protection?: string; + slippage_rate?: string; + commission_rate?: string; + trade_status?: string; + trade_mode?: number; + order_fill_timing?: number; + symbol_descs?: StockSymbolDescI18n[]; + [key: string]: unknown; +} +⋮---- +export interface StockOrderBookLevel { + p?: string; + user_order?: boolean; + [key: string]: unknown; +} +⋮---- +export interface StockOrderBook { + symbol?: string; + bids?: StockOrderBookLevel[]; + asks?: StockOrderBookLevel[]; + timestamp?: number; +} +⋮---- +export interface StockOrderItem { + order_id?: string; + symbol?: string; + exchange?: string; + quote_currency?: string; + fx_rate?: string; + symbol_desc?: string; + trade_status?: string; + trade_mode?: number; + price_type?: string; + side?: number; + status?: number; + volume?: string; + fill_volume?: string; + price?: string; + time_setup?: number; + time_update?: number; + max_order_volume?: string; + step_order_volume?: string; + min_order_volume?: string; + price_precision?: number; + price_protection?: string; + sell_price_protection?: string; + buy_price_protection?: string; + commission_rate?: string; + slippage_rate?: string; + [key: string]: unknown; +} +⋮---- +export interface StockCreateOrderResult { + id?: string; +} +⋮---- +export interface StockOrderHistoryItem { + order_id?: string; + symbol?: string; + exchange?: string; + quote_currency?: string; + fx_rate?: string; + symbol_desc?: string; + price_type?: string; + status?: number; + status_desc?: string; + status_detail?: { title?: string; message?: string } | null; + finish_as?: number; + side?: number; + time_in_force?: string; + volume?: string; + fill_volume?: string; + price?: string; + avg_fill_price?: string | null; + commission?: string; + time_setup?: number; + time_done?: number; + [key: string]: unknown; +} +⋮---- +export interface StockUpdateOrderResult { + order_id?: number; +} +⋮---- +export interface StockPositionItem { + symbol?: string; + exchange?: string; + quote_currency?: string; + quote_currency_precision?: number; + fx_rate?: string; + trade_status?: string; + symbol_desc?: string; + position_pnl?: string; + today_pnl?: string; + pnl_rate?: string; + today_sell_amount?: string; + today_buy_amount?: string; + today_sell_volume?: string; + today_buy_volume?: string; + yesterday_volume?: string; + volume?: string; + available?: string; + transfer_out_pending_qty?: string; + avg_cost_price?: string; + diluted_cost_price?: string; + last_price?: string; + extended_last_price?: string | null; + max_order_volume?: string; + step_order_volume?: string; + min_order_volume?: string; + price_precision?: number; + price_protection?: string; + [key: string]: unknown; +} +⋮---- +export interface StockClosePositionResult { + order_id?: number; +} +⋮---- +export interface StockTransactionItem { + asset?: string; + symbol?: string; + symbol_display?: string; + type?: string; + type_desc?: string; + change?: string; + balance?: string; + ref_id?: string; + time?: number; + unit_text?: string; + detail?: object; +} +⋮---- +export interface StockExchangeItem { + exchange?: string; + exchange_desc?: string; + icon_link?: string; + support_transfer?: boolean; } ⋮---- -export interface P2PMerchantChatsListData { - messages: P2PMerchantChatMessage[]; - has_history?: boolean; - txid?: number; - SRVTM?: number; - order_status?: string; - memo?: string; +export interface StockFeeRateItem { + vip_level?: number; + maker_fee?: string; + taker_fee?: string; } ================ @@ -9228,3354 +9267,3254 @@ export interface GetEarnFixedTermHistoryReq { type: '1' | '2' | '3' | '4'; // 1 subscribe, 2 redeem, 3 interest, 4 bonus ================ -File: src/types/request/otc.ts +File: src/types/request/unified.ts ================ -import { GateMultipartFile } from '../../lib/multipartUtil.js'; -⋮---- -/**========================================================================================================================== - * OTC - * ========================================================================================================================== - */ -⋮---- -export interface CreateOTCQuoteReq { - side: 'PAY' | 'GET'; // PAY means user inputs pay amount, GET means user inputs get amount - pay_coin: string; // Currency the user pays - get_coin: string; // Currency the user receives - pay_amount?: string; // User payment currency amount (required if side is PAY) - get_amount?: string; // Amount of currency received by user (required if side is GET) - create_quote_token?: string; // Create quote token: 0: quote preview only; 1: generate quote token for order placement - promotion_code?: string; // Promotion code (optional) -} -⋮---- -side: 'PAY' | 'GET'; // PAY means user inputs pay amount, GET means user inputs get amount -pay_coin: string; // Currency the user pays -get_coin: string; // Currency the user receives -pay_amount?: string; // User payment currency amount (required if side is PAY) -get_amount?: string; // Amount of currency received by user (required if side is GET) -create_quote_token?: string; // Create quote token: 0: quote preview only; 1: generate quote token for order placement -promotion_code?: string; // Promotion code (optional) -⋮---- -export interface CreateOTCFiatOrderReq { - type: 'BUY' | 'SELL'; // BUY (on-ramp) or SELL (off-ramp) - side: string; // Quote direction returned by the quote API (used for order validation) - crypto_currency: string; // Cryptocurrency - fiat_currency: string; // Fiat currency - crypto_amount: string; // Amount of cryptocurrency - fiat_amount: string; // Fiat amount - promotion_code?: string; // Promotion code - quote_token: string; // Parameter returned by the quote API - /** From GET /otc/bank/list; default card has is_default=1 */ - bank_id: string; - receive_type?: string; -} -⋮---- -type: 'BUY' | 'SELL'; // BUY (on-ramp) or SELL (off-ramp) -side: string; // Quote direction returned by the quote API (used for order validation) -crypto_currency: string; // Cryptocurrency -fiat_currency: string; // Fiat currency -crypto_amount: string; // Amount of cryptocurrency -fiat_amount: string; // Fiat amount -promotion_code?: string; // Promotion code -quote_token: string; // Parameter returned by the quote API -/** From GET /otc/bank/list; default card has is_default=1 */ -⋮---- -export interface CreateOTCStablecoinOrderReq { - pay_coin: string; // Currency paid by the user - get_coin: string; // Currency to be received by the user - pay_amount: string; // User payment currency amount - get_amount: string; // Amount of currency received by the user - side: string; // Quote direction returned by the quote API (used for order validation) - quote_token: string; // Parameter returned by the quote API - promotion_code?: string; // Promotion code (optional) -} -⋮---- -pay_coin: string; // Currency paid by the user -get_coin: string; // Currency to be received by the user -pay_amount: string; // User payment currency amount -get_amount: string; // Amount of currency received by the user -side: string; // Quote direction returned by the quote API (used for order validation) -quote_token: string; // Parameter returned by the quote API -promotion_code?: string; // Promotion code (optional) -⋮---- -export interface MarkOTCOrderAsPaidReq { - order_id: string; // Order ID - client_order_id?: string; // Client order ID (gateway/Inner Pay paths) - payment_receipt_file_key: string; // Required. Stored as file_key; jpg/jpeg/png/pdf; ≤10MB - payment_receipt?: string; // Alias compatible with payment_receipt_file_key -} -⋮---- -order_id: string; // Order ID -client_order_id?: string; // Client order ID (gateway/Inner Pay paths) -payment_receipt_file_key: string; // Required. Stored as file_key; jpg/jpeg/png/pdf; ≤10MB -payment_receipt?: string; // Alias compatible with payment_receipt_file_key -⋮---- -export interface CancelOTCOrderReq { - order_id: string; // Order ID -} -⋮---- -order_id: string; // Order ID -⋮---- -export interface GetOTCFiatOrderListReq { - type?: 'BUY' | 'SELL'; // BUY (on-ramp) or SELL (off-ramp) - fiat_currency?: string; // Fiat currency - crypto_currency?: string; // Digital currency - start_time?: string; // Start Time - end_time?: string; // End time - status?: string; // DONE: Completed - pn?: string; // Page number - ps?: string; // Number of items per page -} -⋮---- -type?: 'BUY' | 'SELL'; // BUY (on-ramp) or SELL (off-ramp) -fiat_currency?: string; // Fiat currency -crypto_currency?: string; // Digital currency -start_time?: string; // Start Time -end_time?: string; // End time -status?: string; // DONE: Completed -pn?: string; // Page number -ps?: string; // Number of items per page -⋮---- -export interface GetOTCStablecoinOrderListReq { - page_size?: string; // Number of records per page - page_number?: string; // Page number - coin_name?: string; // Order currency - start_time?: string; // Start Time - end_time?: string; // End time - status?: string; // Status: PROCESSING: in progress / DONE: completed / FAILED: failed -} -⋮---- -page_size?: string; // Number of records per page -page_number?: string; // Page number -coin_name?: string; // Order currency -start_time?: string; // Start Time -end_time?: string; // End time -status?: string; // Status: PROCESSING: in progress / DONE: completed / FAILED: failed -⋮---- -export interface GetOTCFiatOrderDetailReq { - order_id: string; // Order ID +export interface SubmitUnifiedBorrowOrRepayReq { + currency: string; + type: 'borrow' | 'repay'; + amount: string; + repaid_all?: boolean; + text?: string; } ⋮---- -order_id: string; // Order ID -⋮---- -export interface OTCBankIdReq { - bank_id: string; +export interface GetUnifiedLoansReq { + currency?: string; + page?: number; + limit?: number; + type?: 'platform' | 'margin'; } ⋮---- -export interface GetOTCBankSupplementChecklistReq { - bank_id: string; +export interface GetUnifiedLoanRecordsReq { + type?: 'borrow' | 'repay'; + currency?: string; + page?: number; + limit?: number; } -⋮---- -export interface CreateOTCBankReq { - bank_account_name: string; - bank_name: string; - bank_country: string; - bank_address: string; - iban: string; - swift: string; - remittance_line_number?: string; - agent_bank_name?: string; - agent_bank_swift?: string; - documentation_file?: GateMultipartFile; - documentation_file_key?: string; - file_type?: string; +export interface GetUnifiedInterestRecordsReq { + currency?: string; + page?: number; + limit?: number; + from?: number; + to?: number; + type?: 'platform' | 'margin'; } ⋮---- -export interface SubmitOTCBankPersonalSupplementReq { - bank_id: string; - id_document_front: GateMultipartFile; - id_document_back: GateMultipartFile; - address_proof: GateMultipartFile; +export interface SetUnifiedAccountModeReq { + mode: 'classic' | 'multi_currency' | 'portfolio' | 'single_currency'; + settings?: { + usdt_futures?: boolean; + spot_hedge?: boolean; + use_funding?: boolean; + options?: boolean; + }; } ⋮---- -export interface SubmitOTCBankEnterpriseSupplementReq { - bank_id: string; - certificate: GateMultipartFile; - share_holders: GateMultipartFile; - passport: GateMultipartFile; - share_holding_structure: GateMultipartFile; - uid?: string; - funds_statement?: GateMultipartFile; - additional?: GateMultipartFile; +export interface PortfolioMarginCalculatorReq { + spot_balances?: { + currency: string; + equity: string; + }[]; + spot_orders?: { + currency_pairs: string; + order_price: string; + count?: string; + left: string; + type: 'sell' | 'buy'; + }[]; + futures_positions?: { + contract: string; + size: string; + }[]; + futures_orders?: { + contract: string; + size: string; + left: string; + }[]; + options_positions?: { + options_name: string; + size: string; + }[]; + options_orders?: { + options_name: string; + size: string; + left: string; + }[]; + spot_hedge?: boolean; } ⋮---- -export interface CreateOTCUploadPreUploadReq { - content_type: string; - scene: 'general' | 'bank' | 'assessment' | 'credit'; -} - -================ -File: src/types/request/spot.ts -================ -/**========================================================================================================================== - * SPOT - * ========================================================================================================================== - */ +export interface GetUnifiedHistoryLendingRateReq { + currency: string; + tier?: string; + page?: number; + limit?: number; +} ⋮---- -/** Limit-order take-profit / stop-loss on create */ -export interface SpotOrderTPSL { - trigger_price: string; - order_price: string; +export interface SubmitUnifiedLoanRepayReq { + currency: string; + amount: string; + currency_pair?: string; } ⋮---- -/** Limit-order take-profit / stop-loss on amend; `{}` cancels, `null` leaves unchanged */ -export type PatchSpotOrderTPSL = SpotOrderTPSL | {} | null; +export interface SetUnifiedCollateralCurrenciesReq { + collateral_type?: 0 | 1; + enable_list?: string[]; + disable_list?: string[]; +} ⋮---- -export interface GetSpotOrderBookReq { - currency_pair: string; - interval?: string; - limit?: number; - with_id?: boolean; +export interface CreateQuickRepaymentReq { + debt_currencies: string[]; + available_currencies: string[]; } ⋮---- -export interface GetSpotTradesReq { - currency_pair: string; - limit?: number; - last_id?: string; - reverse?: boolean; - from?: number; - to?: number; - page?: number; +/** POST /unified/delta_neutral — v4.106.97 */ +export interface SetUnifiedDeltaNeutralReq { + enabled: boolean; } ⋮---- -export interface GetSpotCandlesReq { - currency_pair: string; +/** POST /unified/leverage/user_setting — set leverage for all borrowed currencies */ +export interface SetUserLeverageReq { + leverage?: string; +} + +================ +File: src/types/request/wallet.ts +================ +/** GET /wallet/sub_account_balances */ +export interface GetSubAccountBalancesReq { + sub_uid?: string; + page?: number; limit?: number; - from?: number; - to?: number; - interval?: - | '1s' - | '10s' - | '1m' - | '5m' - | '15m' - | '30m' - | '1h' - | '4h' - | '8h' - | '1d' - | '7d' - | '30d'; } ⋮---- -export interface GetSpotAccountBookReq { +export interface GetWithdrawalDepositRecordsReq { currency?: string; from?: number; to?: number; - page?: number; limit?: number; - /** - * BizType / business type filter. Sub-account transfer internal BizType values include - * 150215, 150216, 150217, 150218, 150219 (Subaccount Transfer); see Gate BizType reference. - */ - type?: string; - code?: string; + offset?: number; } ⋮---- -/** - * BizType / business type filter. Sub-account transfer internal BizType values include - * 150215, 150216, 150217, 150218, 150219 (Subaccount Transfer); see Gate BizType reference. - */ -⋮---- -export interface SubmitSpotClosePosCrossDisabledReq { - text?: string; - currency_pair: string; +export interface SubmitTransferReq { + currency: string; + from: 'spot' | 'margin' | 'futures' | 'delivery' | 'cross_margin' | 'options'; + to: 'spot' | 'margin' | 'futures' | 'delivery' | 'cross_margin' | 'options'; amount: string; - price: string; - action_mode?: 'ACK' | 'RESULT' | 'FULL'; + currency_pair?: string; + settle?: string; + client_order_id?: string; } ⋮---- -export interface GetSpotOrdersReq { - currency_pair: string; - status: 'open' | 'finished'; - page?: number; - limit?: number; - account?: 'spot' | 'margin' | 'cross_margin' | 'unified'; +export interface GetMainSubTransfersReq { + sub_uid?: string; from?: number; to?: number; - side?: 'buy' | 'sell'; -} -⋮---- -export interface CancelSpotBatchOrdersReq { - currency_pair: string; - id: string; - account?: 'cross_margin'; - action_mode?: 'ACK' | 'RESULT' | 'FULL'; -} -⋮---- -export interface DeleteSpotOrderReq { - order_id: string; - currency_pair: string; - account?: 'spot' | 'margin' | 'cross_margin' | 'unified'; - action_mode?: 'ACK' | 'RESULT' | 'FULL'; - xGateExptime?: number; -} -⋮---- -export interface GetSpotOrderReq { - order_id: string; - currency_pair: string; - account?: 'spot' | 'margin' | 'cross_margin' | 'unified'; + limit?: number; + offset?: number; } ⋮---- -export interface GetSpotTradingHistoryReq { - currency_pair?: string; - limit?: number; +export interface GetSavedAddressReq { + currency?: string; // v4.106.94: Optional filter by currency + chain?: string; + limit?: string; page?: number; - order_id?: string; - account?: 'spot' | 'margin' | 'cross_margin' | 'unified'; - from?: number; - to?: number; + verified?: string; // v4.106.94: 1 verification-free, 0 normal, empty for no filter } ⋮---- -export interface UpdateSpotBatchOrdersReq { - order_id?: string; - currency_pair?: string; - amount?: string; - price?: string; - amend_text?: string; - stop_loss?: PatchSpotOrderTPSL; - stop_profit?: PatchSpotOrderTPSL; -} +currency?: string; // v4.106.94: Optional filter by currency ⋮---- -export interface GetSpotInsuranceHistoryReq { - business: 'margin' | 'unified'; - currency: string; - from: number; - to: number; +verified?: string; // v4.106.94: 1 verification-free, 0 normal, empty for no filter +⋮---- +export interface GetSmallBalanceHistoryReq { + currency?: string; page?: number; limit?: number; } ⋮---- -export interface GetSpotAutoOrdersReq { - status: 'open' | 'finished'; - market?: string; - account?: 'normal' | 'margin' | 'cross_margin' | 'unified'; +export interface ListPushOrdersReq { + id?: number; + from?: number; + to?: number; limit?: number; offset?: number; + transaction_type?: string; } ⋮---- -export interface SubmitSpotOrderReq { - xGateExptime?: number; - side: 'buy' | 'sell'; +export interface SubmitSubToSubTransferReq { + currency: string; + sub_account_from: string; + sub_account_from_type: 'spot' | 'futures' | 'delivery' | 'cross_margin'; + sub_account_to: string; + sub_account_to_type: 'spot' | 'futures' | 'delivery' | 'cross_margin'; amount: string; - text?: string; - currency_pair: string; - type?: 'limit' | 'market'; - account?: 'spot' | 'margin' | 'cross_margin' | 'unified'; - price?: string; - time_in_force?: 'gtc' | 'ioc' | 'poc' | 'fok'; - iceberg?: string; - auto_borrow?: boolean; - auto_repay?: boolean; - stp_act?: string; - action_mode?: string; - stop_loss?: PatchSpotOrderTPSL; - stop_profit?: PatchSpotOrderTPSL; - post_only?: boolean; - trade_quote?: string; -} -⋮---- -export interface UpdateSpotOrderReq { - xGateExptime?: number; - order_id: string; - currency_pair: string; - account?: 'spot' | 'margin' | 'cross_margin' | 'unified'; - amount?: string; - price?: string; - amend_text?: string; - action_mode?: 'ACK' | 'RESULT' | 'FULL'; - stop_loss?: PatchSpotOrderTPSL; - stop_profit?: PatchSpotOrderTPSL; -} -⋮---- -/** GET /spot/pov_orders */ -export interface GetSpotPovOrdersReq { - status: 'open' | 'finished'; - currency_pair?: string; - side?: 'buy' | 'sell'; - page?: number; - limit?: number; + sub_account_type?: string; } ⋮---- -/** POST /spot/pov_orders */ -export interface CreateSpotPovOrderReq { - currency_pair: string; - side: 'buy' | 'sell'; +export interface SubmitMainSubTransferReq { + currency: string; + sub_account: string; + direction: 'to' | 'from'; amount: string; - participation_rate: 5 | 10 | 20 | 40; - ttl: '1h' | '6h' | '12h' | '1d' | '2d' | '3d' | '4d' | '5d' | '6d' | '7d'; - limit_price?: string; - trigger_price?: string; - text?: string; + client_order_id?: string; + sub_account_type?: 'spot' | 'futures' | 'cross_margin' | 'delivery'; } ⋮---- -/** DELETE /spot/pov_orders */ -export interface CancelSpotPovOrdersReq { - currency_pair?: string; +/** GET /wallet/transfers */ +export interface GetTransferReq { + tx_id: string; } ================ -File: src/types/request/tradfi.ts +File: src/types/response/wallet.ts ================ -/** TradFi API request types */ -⋮---- -export interface TradFiGetSymbolDetailParams { - symbols: string; -} -⋮---- -export interface TradFiGetKlinesParams { - kline_type: '1m' | '15m' | '1h' | '4h' | '1d' | '7d' | '30d'; - begin_time?: number; - end_time?: number; - limit?: number; +export interface CurrencyChain { + chain: string; + name_cn: string; + name_en: string; + contract_address: string; + is_disabled: number; + is_deposit_disabled: number; + is_withdraw_disabled: number; + decimal: string; } ⋮---- -export interface TradFiCreateTransactionReq { - asset: string; - change: string; - type: 'deposit' | 'withdraw'; +/** GET /wallet/sub_account_balances item */ +export interface SubAccountBalance { + uid: string; + available: { [key: string]: string }; + /** Locked amount per currency */ + locking?: { [key: string]: string }; } ⋮---- -export interface TradFiGetTransactionsParams { - begin_time?: number; - end_time?: number; - type?: 'deposit' | 'withdraw' | 'dividend' | 'fill_negative'; - page?: number; - page_size?: number; -} +/** Locked amount per currency */ ⋮---- -export interface TradFiCreateOrderReq { - price: string; - price_type: 'trigger' | 'market'; - side: 1 | 2; - symbol: string; - volume: string; - price_tp?: string; - price_sl?: string; - leverage?: number; +export interface DepositRecord { + id: string; + txid: string; + timestamp: string; + amount: string; + currency: string; + address: string; + memo?: string; + status: + | 'BLOCKED' // Deposit Blocked + | 'DEP_CREDITED' // Deposit Credited, Withdrawal Pending Unlock + | 'DONE' // Funds Credited to Spot Account + | 'INVALID' // Invalid Transaction + | 'MANUAL' // Manual Review Required + | 'PEND' // Processing + | 'REVIEW' // Under Compliance Review + | 'TRACK'; // Tracking Block Confirmations, Pending Spot Account Credit + chain: string; + refund_status?: // v4.106.95: Blocked deposit refund status + 'REFUNDING' | 'REFUNDED' | 'REFUND_FAILED' | 'REJECTED'; } ⋮---- -export interface TradFiModifyOrderReq { - price: string; - price_tp?: string | null; - price_sl?: string | null; -} +| 'BLOCKED' // Deposit Blocked +| 'DEP_CREDITED' // Deposit Credited, Withdrawal Pending Unlock +| 'DONE' // Funds Credited to Spot Account +| 'INVALID' // Invalid Transaction +| 'MANUAL' // Manual Review Required +| 'PEND' // Processing +| 'REVIEW' // Under Compliance Review +| 'TRACK'; // Tracking Block Confirmations, Pending Spot Account Credit ⋮---- -export interface TradFiModifyPositionReq { - price_tp?: string | null; - price_sl?: string | null; -} +refund_status?: // v4.106.95: Blocked deposit refund status ⋮---- -export interface TradFiClosePositionReq { - close_type: 1 | 2; - close_volume?: string | null; +export interface CreateDepositAddressResp { + currency: string; + address: string; + multichain_addresses: { + chain: string; + address: string; + payment_id: string; + payment_name: string; + obtain_failed: number; + }[]; } ⋮---- -export interface TradFiGetOrderHistoryParams { - begin_time?: number; - end_time?: number; - symbol?: string; - side?: 1 | 2; +export interface SubAccountTransferRecord { + currency: string; + sub_account: string; + direction: 'to' | 'from'; + amount: string; + uid: string; + client_order_id: string; + timest: string; + source: string; + sub_account_type: 'spot' | 'futures' | 'cross_margin' | 'delivery'; } ⋮---- -export interface TradFiGetPositionHistoryParams { - begin_time?: number; - end_time?: number; - symbol?: string; - position_dir?: 'Long' | 'Short'; - page?: number; - page_size?: number; +export interface WithdrawalStatus { + currency: string; + name: string; + name_cn: string; + deposit: string; + withdraw_percent: string; + withdraw_fix: string; + withdraw_day_limit: string; + withdraw_amount_mini: string; + withdraw_day_limit_remain: string; + withdraw_eachtime_limit: string; + withdraw_fix_on_chains: { [key: string]: string }; + withdraw_percent_on_chains: { [key: string]: string }; } ⋮---- -/** GET /tradfi/symbols/commissions */ -export interface TradFiGetSymbolCommissionsParams { - symbols?: string; - category_code?: string; -} - -================ -File: src/types/request/unified.ts -================ -export interface SubmitUnifiedBorrowOrRepayReq { - currency: string; - type: 'borrow' | 'repay'; - amount: string; - repaid_all?: boolean; - text?: string; +export interface SubAccountMarginBalance { + currency_pair: string; + locked: boolean; + risk: string; + base: { + currency: string; + available: string; + locked: string; + borrowed: string; + interest: string; + }; + quote: { + currency: string; + available: string; + locked: string; + borrowed: string; + interest: string; + }; } ⋮---- -export interface GetUnifiedLoansReq { - currency?: string; - page?: number; - limit?: number; - type?: 'platform' | 'margin'; +export interface SubAccountFuturesBalancesResp { + uid: string; + available: { + [key: string]: { + total: string; + unrealised_pnl: string; + position_margin: string; + order_margin: string; + available: string; + point: string; + currency: string; + in_dual_mode: boolean; + enable_credit: boolean; + position_initial_margin: string; + maintenance_margin: string; + bonus: string; + enable_evolved_classic: boolean; + cross_order_margin: string; + cross_initial_margin: string; + cross_maintenance_margin: string; + cross_unrealised_pnl: string; + cross_available: string; + isolated_position_margin: string; + history: { + dnw: string; + pnl: string; + fee: string; + refr: string; + fund: string; + point_dnw: string; + point_fee: string; + point_refr: string; + bonus_dnw: string; + bonus_offset: string; + }; + }; + }; } ⋮---- -export interface GetUnifiedLoanRecordsReq { - type?: 'borrow' | 'repay'; - currency?: string; - page?: number; - limit?: number; +export interface SubAccountCrossMarginBalancesResp { + uid: string; + available: { + user_id: number; + locked: boolean; + balances: { + [key: string]: { + available: string; + freeze: string; + borrowed: string; + interest: string; + }; + }; + total: string; + borrowed: string; + borrowed_net: string; + net: string; + leverage: string; + interest: string; + risk: string; + total_initial_margin: string; + total_margin_balance: string; + total_maintenance_margin: string; + total_initial_margin_rate: string; + total_maintenance_margin_rate: string; + total_available_margin: string; + }; } -export interface GetUnifiedInterestRecordsReq { - currency?: string; - page?: number; - limit?: number; - from?: number; - to?: number; - type?: 'platform' | 'margin'; +⋮---- +export interface SavedAddress { + currency: string; + chain: string; + address: string; + name: string; + tag: string; + verified: string; } ⋮---- -export interface SetUnifiedAccountModeReq { - mode: 'classic' | 'multi_currency' | 'portfolio' | 'single_currency'; - settings?: { - usdt_futures?: boolean; - spot_hedge?: boolean; - use_funding?: boolean; - options?: boolean; - }; +export interface TradingFees { + user_id: number; + taker_fee: string; + maker_fee: string; + gt_discount: boolean; + gt_taker_fee: string; + gt_maker_fee: string; + loan_fee: string; + point_type: string; + futures_taker_fee: string; + futures_maker_fee: string; + delivery_taker_fee: string; + delivery_maker_fee: string; + debit_fee: number; } ⋮---- -export interface PortfolioMarginCalculatorReq { - spot_balances?: { +export interface GetBalancesResp { + total: { + amount: string; currency: string; - equity: string; - }[]; - spot_orders?: { - currency_pairs: string; - order_price: string; - count?: string; - left: string; - type: 'sell' | 'buy'; - }[]; - futures_positions?: { - contract: string; - size: string; - }[]; - futures_orders?: { - contract: string; - size: string; - left: string; - }[]; - options_positions?: { - options_name: string; - size: string; - }[]; - options_orders?: { - options_name: string; - size: string; - left: string; - }[]; - spot_hedge?: boolean; + unrealised_pnl?: string; + borrowed?: string; + }; + details: { + [key: string]: { + amount: string; + currency: string; + unrealised_pnl?: string; + borrowed?: string; + }; + }; } ⋮---- -export interface GetUnifiedHistoryLendingRateReq { +export interface SmallBalanceRecord { currency: string; - tier?: string; - page?: number; - limit?: number; + available_balance: string; + estimated_as_btc: string; + convertible_to_gt: string; } ⋮---- -export interface SubmitUnifiedLoanRepayReq { +export interface SmallBalanceHistoryRecord { + id: string; currency: string; amount: string; - currency_pair?: string; -} -⋮---- -export interface SetUnifiedCollateralCurrenciesReq { - collateral_type?: 0 | 1; - enable_list?: string[]; - disable_list?: string[]; -} -⋮---- -export interface CreateQuickRepaymentReq { - debt_currencies: string[]; - available_currencies: string[]; + gt_amount: string; + create_time: number; } ⋮---- -/** POST /unified/delta_neutral — v4.106.97 */ -export interface SetUnifiedDeltaNeutralReq { - enabled: boolean; +export interface PushOrder { + id: string; + push_uid: number; + receive_uid: number; + currency: string; + amount: string; + create_time: number; + status: + | 'CREATING' + | 'PENDING' + | 'CANCELLING' + | 'CANCELLED' + | 'REFUSING' + | 'REFUSED' + | 'RECEIVING' + | 'RECEIVED'; + message: string; } ⋮---- -/** POST /unified/leverage/user_setting — set leverage for all borrowed currencies */ -export interface SetUserLeverageReq { - leverage?: string; +/** GET /wallet/transfers — AccountTransferDetail */ +export interface AccountTransferDetail { + tx_id: string; + status: 'pending' | 'success' | 'fail'; + currency: string; + amount: string; + from_account: + | 'spot' + | 'margin' + | 'futures' + | 'delivery' + | 'options' + | 'unknown'; + to_account: + | 'spot' + | 'margin' + | 'futures' + | 'delivery' + | 'options' + | 'unknown'; + settle?: string | null; + currency_pair?: string | null; } ================ -File: src/types/request/wallet.ts +File: src/types/shared.ts ================ -/** GET /wallet/sub_account_balances */ -export interface GetSubAccountBalancesReq { - sub_uid?: string; - page?: number; - limit?: number; -} -⋮---- -export interface GetWithdrawalDepositRecordsReq { - currency?: string; - from?: number; - to?: number; - limit?: number; - offset?: number; -} +export type GateBaseUrlKey = + | 'live' + | 'futuresLiveAlternative' + | 'futuresTestnet'; ⋮---- -export interface SubmitTransferReq { - currency: string; - from: 'spot' | 'margin' | 'futures' | 'delivery' | 'cross_margin' | 'options'; - to: 'spot' | 'margin' | 'futures' | 'delivery' | 'cross_margin' | 'options'; - amount: string; - currency_pair?: string; - settle?: string; - client_order_id?: string; -} +/** + * Futures or delivery contract size (in contracts). + * Integer when the client option `futuresSizeDecimal` is off (default); decimal string when `futuresSizeDecimal` is enabled (`X-Gate-Size-Decimal: 1`). + */ +export type FuturesContractSize = number | string; ⋮---- -export interface GetMainSubTransfersReq { - sub_uid?: string; - from?: number; - to?: number; - limit?: number; - offset?: number; -} +// interfaces ⋮---- -export interface GetSavedAddressReq { - currency?: string; // v4.106.94: Optional filter by currency - chain?: string; - limit?: string; - page?: number; - verified?: string; // v4.106.94: 1 verification-free, 0 normal, empty for no filter +export interface FromToPageLimit { + from: number; + to: number; + page: number; + limit: number; } ⋮---- -currency?: string; // v4.106.94: Optional filter by currency -⋮---- -verified?: string; // v4.106.94: 1 verification-free, 0 normal, empty for no filter -⋮---- -export interface GetSmallBalanceHistoryReq { - currency?: string; - page?: number; - limit?: number; +// Used for spot and flash swap +export interface CurrencyPair { + id?: string; + base?: string; + base_name?: string; + quote?: string; + quote_name?: string; + trade_quotes?: string[] | null; + fee?: string; + min_base_amount?: string; + min_quote_amount?: string; + max_base_amount?: string; + max_quote_amount?: string; + amount_precision?: number; + precision?: number; + trade_status?: 'untradable' | 'buyable' | 'sellable' | 'tradable'; + sell_start?: number; + buy_start?: number; + type: string; + delisting_time?: number; + trade_url?: string; + up_rate?: string; // v4.106.4: Maximum price increase percentage + down_rate?: string; // v4.106.4: Maximum price decrease percentage + market_order_max_stock?: string | null; + market_order_max_money?: string | null; } ⋮---- -export interface ListPushOrdersReq { - id?: number; - from?: number; - to?: number; - limit?: number; - offset?: number; - transaction_type?: string; -} +up_rate?: string; // v4.106.4: Maximum price increase percentage +down_rate?: string; // v4.106.4: Maximum price decrease percentage + +================ +File: webpack/webpack.config.cjs +================ +function generateConfig(name) ⋮---- -export interface SubmitSubToSubTransferReq { - currency: string; - sub_account_from: string; - sub_account_from_type: 'spot' | 'futures' | 'delivery' | 'cross_margin'; - sub_account_to: string; - sub_account_to_type: 'spot' | 'futures' | 'delivery' | 'cross_margin'; - amount: string; - sub_account_type?: string; -} +// Add '.ts' and '.tsx' as resolvable extensions. ⋮---- -export interface SubmitMainSubTransferReq { - currency: string; - sub_account: string; - direction: 'to' | 'from'; - amount: string; - client_order_id?: string; - sub_account_type?: 'spot' | 'futures' | 'cross_margin' | 'delivery'; -} +// Node.js core modules not available in browsers +// The REST client's https.Agent (for keepAlive) is Node.js-only and won't work in browsers ⋮---- -/** GET /wallet/transfers */ -export interface GetTransferReq { - tx_id: string; -} +// Code is already transpiled from TypeScript, no additional loaders needed ================ -File: src/types/response/wallet.ts +File: src/types/request/otc.ts ================ -export interface CurrencyChain { - chain: string; - name_cn: string; - name_en: string; - contract_address: string; - is_disabled: number; - is_deposit_disabled: number; - is_withdraw_disabled: number; - decimal: string; -} +import { GateMultipartFile } from '../../lib/multipartUtil.js'; +⋮---- +/**========================================================================================================================== + * OTC + * ========================================================================================================================== + */ ⋮---- -/** GET /wallet/sub_account_balances item */ -export interface SubAccountBalance { - uid: string; - available: { [key: string]: string }; - /** Locked amount per currency */ - locking?: { [key: string]: string }; +export interface CreateOTCQuoteReq { + side: 'PAY' | 'GET'; // PAY means user inputs pay amount, GET means user inputs get amount + pay_coin: string; // Currency the user pays + get_coin: string; // Currency the user receives + pay_amount?: string; // User payment currency amount (required if side is PAY) + get_amount?: string; // Amount of currency received by user (required if side is GET) + create_quote_token?: string; // Create quote token: 0: quote preview only; 1: generate quote token for order placement + promotion_code?: string; // Promotion code (optional) } ⋮---- -/** Locked amount per currency */ +side: 'PAY' | 'GET'; // PAY means user inputs pay amount, GET means user inputs get amount +pay_coin: string; // Currency the user pays +get_coin: string; // Currency the user receives +pay_amount?: string; // User payment currency amount (required if side is PAY) +get_amount?: string; // Amount of currency received by user (required if side is GET) +create_quote_token?: string; // Create quote token: 0: quote preview only; 1: generate quote token for order placement +promotion_code?: string; // Promotion code (optional) ⋮---- -export interface DepositRecord { - id: string; - txid: string; - timestamp: string; - amount: string; - currency: string; - address: string; - memo?: string; - status: - | 'BLOCKED' // Deposit Blocked - | 'DEP_CREDITED' // Deposit Credited, Withdrawal Pending Unlock - | 'DONE' // Funds Credited to Spot Account - | 'INVALID' // Invalid Transaction - | 'MANUAL' // Manual Review Required - | 'PEND' // Processing - | 'REVIEW' // Under Compliance Review - | 'TRACK'; // Tracking Block Confirmations, Pending Spot Account Credit - chain: string; - refund_status?: // v4.106.95: Blocked deposit refund status - 'REFUNDING' | 'REFUNDED' | 'REFUND_FAILED' | 'REJECTED'; +export interface CreateOTCFiatOrderReq { + type: 'BUY' | 'SELL'; // BUY (on-ramp) or SELL (off-ramp) + side: string; // Quote direction returned by the quote API (used for order validation) + crypto_currency: string; // Cryptocurrency + fiat_currency: string; // Fiat currency + crypto_amount: string; // Amount of cryptocurrency + fiat_amount: string; // Fiat amount + promotion_code?: string; // Promotion code + quote_token: string; // Parameter returned by the quote API + /** From GET /otc/bank/list; default card has is_default=1 */ + bank_id: string; + receive_type?: string; } ⋮---- -| 'BLOCKED' // Deposit Blocked -| 'DEP_CREDITED' // Deposit Credited, Withdrawal Pending Unlock -| 'DONE' // Funds Credited to Spot Account -| 'INVALID' // Invalid Transaction -| 'MANUAL' // Manual Review Required -| 'PEND' // Processing -| 'REVIEW' // Under Compliance Review -| 'TRACK'; // Tracking Block Confirmations, Pending Spot Account Credit -⋮---- -refund_status?: // v4.106.95: Blocked deposit refund status +type: 'BUY' | 'SELL'; // BUY (on-ramp) or SELL (off-ramp) +side: string; // Quote direction returned by the quote API (used for order validation) +crypto_currency: string; // Cryptocurrency +fiat_currency: string; // Fiat currency +crypto_amount: string; // Amount of cryptocurrency +fiat_amount: string; // Fiat amount +promotion_code?: string; // Promotion code +quote_token: string; // Parameter returned by the quote API +/** From GET /otc/bank/list; default card has is_default=1 */ ⋮---- -export interface CreateDepositAddressResp { - currency: string; - address: string; - multichain_addresses: { - chain: string; - address: string; - payment_id: string; - payment_name: string; - obtain_failed: number; - }[]; +export interface CreateOTCStablecoinOrderReq { + pay_coin: string; // Currency paid by the user + get_coin: string; // Currency to be received by the user + pay_amount: string; // User payment currency amount + get_amount: string; // Amount of currency received by the user + side: string; // Quote direction returned by the quote API (used for order validation) + quote_token: string; // Parameter returned by the quote API + promotion_code?: string; // Promotion code (optional) } ⋮---- -export interface SubAccountTransferRecord { - currency: string; - sub_account: string; - direction: 'to' | 'from'; - amount: string; - uid: string; - client_order_id: string; - timest: string; - source: string; - sub_account_type: 'spot' | 'futures' | 'cross_margin' | 'delivery'; -} +pay_coin: string; // Currency paid by the user +get_coin: string; // Currency to be received by the user +pay_amount: string; // User payment currency amount +get_amount: string; // Amount of currency received by the user +side: string; // Quote direction returned by the quote API (used for order validation) +quote_token: string; // Parameter returned by the quote API +promotion_code?: string; // Promotion code (optional) ⋮---- -export interface WithdrawalStatus { - currency: string; - name: string; - name_cn: string; - deposit: string; - withdraw_percent: string; - withdraw_fix: string; - withdraw_day_limit: string; - withdraw_amount_mini: string; - withdraw_day_limit_remain: string; - withdraw_eachtime_limit: string; - withdraw_fix_on_chains: { [key: string]: string }; - withdraw_percent_on_chains: { [key: string]: string }; +export interface MarkOTCOrderAsPaidReq { + order_id: string; // Order ID + client_order_id?: string; // Client order ID (gateway/Inner Pay paths) + payment_receipt_file_key: string; // Required. Stored as file_key; jpg/jpeg/png/pdf; ≤10MB + payment_receipt?: string; // Alias compatible with payment_receipt_file_key } ⋮---- -export interface SubAccountMarginBalance { - currency_pair: string; - locked: boolean; - risk: string; - base: { - currency: string; - available: string; - locked: string; - borrowed: string; - interest: string; - }; - quote: { - currency: string; - available: string; - locked: string; - borrowed: string; - interest: string; - }; +order_id: string; // Order ID +client_order_id?: string; // Client order ID (gateway/Inner Pay paths) +payment_receipt_file_key: string; // Required. Stored as file_key; jpg/jpeg/png/pdf; ≤10MB +payment_receipt?: string; // Alias compatible with payment_receipt_file_key +⋮---- +export interface CancelOTCOrderReq { + order_id: string; // Order ID } ⋮---- -export interface SubAccountFuturesBalancesResp { - uid: string; - available: { - [key: string]: { - total: string; - unrealised_pnl: string; - position_margin: string; - order_margin: string; - available: string; - point: string; - currency: string; - in_dual_mode: boolean; - enable_credit: boolean; - position_initial_margin: string; - maintenance_margin: string; - bonus: string; - enable_evolved_classic: boolean; - cross_order_margin: string; - cross_initial_margin: string; - cross_maintenance_margin: string; - cross_unrealised_pnl: string; - cross_available: string; - isolated_position_margin: string; - history: { - dnw: string; - pnl: string; - fee: string; - refr: string; - fund: string; - point_dnw: string; - point_fee: string; - point_refr: string; - bonus_dnw: string; - bonus_offset: string; - }; - }; - }; +order_id: string; // Order ID +⋮---- +export interface GetOTCFiatOrderListReq { + type?: 'BUY' | 'SELL'; // BUY (on-ramp) or SELL (off-ramp) + fiat_currency?: string; // Fiat currency + crypto_currency?: string; // Digital currency + start_time?: string; // Start Time + end_time?: string; // End time + status?: string; // DONE: Completed + pn?: string; // Page number + ps?: string; // Number of items per page } ⋮---- -export interface SubAccountCrossMarginBalancesResp { - uid: string; - available: { - user_id: number; - locked: boolean; - balances: { - [key: string]: { - available: string; - freeze: string; - borrowed: string; - interest: string; - }; - }; - total: string; - borrowed: string; - borrowed_net: string; - net: string; - leverage: string; - interest: string; - risk: string; - total_initial_margin: string; - total_margin_balance: string; - total_maintenance_margin: string; - total_initial_margin_rate: string; - total_maintenance_margin_rate: string; - total_available_margin: string; - }; +type?: 'BUY' | 'SELL'; // BUY (on-ramp) or SELL (off-ramp) +fiat_currency?: string; // Fiat currency +crypto_currency?: string; // Digital currency +start_time?: string; // Start Time +end_time?: string; // End time +status?: string; // DONE: Completed +pn?: string; // Page number +ps?: string; // Number of items per page +⋮---- +export interface GetOTCStablecoinOrderListReq { + page_size?: string; // Number of records per page + page_number?: string; // Page number + coin_name?: string; // Order currency + start_time?: string; // Start Time + end_time?: string; // End time + status?: string; // Status: PROCESSING: in progress / DONE: completed / FAILED: failed } ⋮---- -export interface SavedAddress { - currency: string; - chain: string; - address: string; - name: string; - tag: string; - verified: string; +page_size?: string; // Number of records per page +page_number?: string; // Page number +coin_name?: string; // Order currency +start_time?: string; // Start Time +end_time?: string; // End time +status?: string; // Status: PROCESSING: in progress / DONE: completed / FAILED: failed +⋮---- +export interface GetOTCFiatOrderDetailReq { + order_id: string; // Order ID } ⋮---- -export interface TradingFees { - user_id: number; - taker_fee: string; - maker_fee: string; - gt_discount: boolean; - gt_taker_fee: string; - gt_maker_fee: string; - loan_fee: string; - point_type: string; - futures_taker_fee: string; - futures_maker_fee: string; - delivery_taker_fee: string; - delivery_maker_fee: string; - debit_fee: number; +order_id: string; // Order ID +⋮---- +export interface OTCBankIdReq { + bank_id: string; } ⋮---- -export interface GetBalancesResp { - total: { - amount: string; - currency: string; - unrealised_pnl?: string; - borrowed?: string; - }; - details: { - [key: string]: { - amount: string; - currency: string; - unrealised_pnl?: string; - borrowed?: string; - }; - }; +export interface GetOTCBankSupplementChecklistReq { + bank_id: string; } ⋮---- -export interface SmallBalanceRecord { - currency: string; - available_balance: string; - estimated_as_btc: string; - convertible_to_gt: string; +export interface CreateOTCBankReq { + bank_account_name: string; + bank_name: string; + bank_country: string; + bank_address: string; + iban: string; + swift: string; + remittance_line_number?: string; + agent_bank_name?: string; + agent_bank_swift?: string; + documentation_file?: GateMultipartFile; + documentation_file_key?: string; + file_type?: string; } ⋮---- -export interface SmallBalanceHistoryRecord { - id: string; - currency: string; - amount: string; - gt_amount: string; - create_time: number; +export interface SubmitOTCBankPersonalSupplementReq { + bank_id: string; + id_document_front: GateMultipartFile; + id_document_back: GateMultipartFile; + address_proof: GateMultipartFile; } ⋮---- -export interface PushOrder { - id: string; - push_uid: number; - receive_uid: number; - currency: string; - amount: string; - create_time: number; - status: - | 'CREATING' - | 'PENDING' - | 'CANCELLING' - | 'CANCELLED' - | 'REFUSING' - | 'REFUSED' - | 'RECEIVING' - | 'RECEIVED'; - message: string; +export interface SubmitOTCBankEnterpriseSupplementReq { + bank_id: string; + certificate: GateMultipartFile; + share_holders: GateMultipartFile; + passport: GateMultipartFile; + share_holding_structure: GateMultipartFile; + uid?: string; + funds_statement?: GateMultipartFile; + additional?: GateMultipartFile; } ⋮---- -/** GET /wallet/transfers — AccountTransferDetail */ -export interface AccountTransferDetail { - tx_id: string; - status: 'pending' | 'success' | 'fail'; - currency: string; - amount: string; - from_account: - | 'spot' - | 'margin' - | 'futures' - | 'delivery' - | 'options' - | 'unknown'; - to_account: - | 'spot' - | 'margin' - | 'futures' - | 'delivery' - | 'options' - | 'unknown'; - settle?: string | null; - currency_pair?: string | null; +export interface CreateOTCUploadPreUploadReq { + content_type: string; + scene: 'general' | 'bank' | 'assessment' | 'credit'; } ================ -File: src/types/websockets/client.ts +File: src/types/request/spot.ts ================ -import type { ClientRequestArgs } from 'http'; -import WebSocket from 'isomorphic-ws'; -⋮---- -/** - * Event args for subscribing/unsubscribing +/**========================================================================================================================== + * SPOT + * ========================================================================================================================== */ ⋮---- -// export type WsTopicSubscribePrivateArgsV2 = -// | WsTopicSubscribePrivateInstIdArgsV2 -// | WsTopicSubscribePrivateCoinArgsV2; +/** Limit-order take-profit / stop-loss on create */ +export interface SpotOrderTPSL { + trigger_price: string; + order_price: string; +} ⋮---- -// export type WsTopicSubscribeEventArgsV2 = -// | WsTopicSubscribePublicArgsV2 -// | WsTopicSubscribePrivateArgsV2; +/** Limit-order take-profit / stop-loss on amend; `{}` cancels, `null` leaves unchanged */ +export type PatchSpotOrderTPSL = SpotOrderTPSL | {} | null; ⋮---- -/** General configuration for the WebsocketClient */ -export interface WSClientConfigurableOptions { - /** Your API key */ - apiKey?: string; - - /** Your API secret */ - apiSecret?: string; - - useTestnet?: boolean; - - /** Define a recv window when preparing a private websocket signature. This is in milliseconds, so 5000 == 5 seconds */ - recvWindow?: number; - - /** How often to check if the connection is alive */ - pingInterval?: number; - - /** How long to wait for a pong (heartbeat reply) before assuming the connection is dead */ - pongTimeout?: number; - - /** Delay in milliseconds before respawning the connection */ - reconnectTimeout?: number; - - requestOptions?: {}; - - wsUrl?: string; - - wsOptions?: { - protocols?: string[]; - agent?: any; - } & ( - | Omit, 'agent'> - | Omit, 'agent'> - ); - +export interface GetSpotOrderBookReq { + currency_pair: string; + interval?: string; + limit?: number; + with_id?: boolean; +} +⋮---- +export interface GetSpotTradesReq { + currency_pair: string; + limit?: number; + last_id?: string; + reverse?: boolean; + from?: number; + to?: number; + page?: number; +} +⋮---- +export interface GetSpotCandlesReq { + currency_pair: string; + limit?: number; + from?: number; + to?: number; + interval?: + | '1s' + | '10s' + | '1m' + | '5m' + | '15m' + | '30m' + | '1h' + | '4h' + | '8h' + | '1d' + | '7d' + | '30d'; +} +⋮---- +export interface GetSpotAccountBookReq { + currency?: string; + from?: number; + to?: number; + page?: number; + limit?: number; /** - * Allows you to provide a custom "signMessage" function, e.g. to use node's much faster createHmac method - * - * Look in the examples folder for a demonstration on using node's createHmac instead. + * BizType / business type filter. Sub-account transfer internal BizType values include + * 150215, 150216, 150217, 150218, 150219 (Subaccount Transfer); see Gate BizType reference. */ - customSignMessageFn?: (message: string, secret: string) => Promise; - - /** - * If you authenticated the WS API before, automatically try to re-authenticate the WS API if you're disconnected/reconnected for any reason. + type?: string; + code?: string; +} +⋮---- +/** + * BizType / business type filter. Sub-account transfer internal BizType values include + * 150215, 150216, 150217, 150218, 150219 (Subaccount Transfer); see Gate BizType reference. */ - reauthWSAPIOnReconnect?: boolean; +⋮---- +export interface SubmitSpotClosePosCrossDisabledReq { + text?: string; + currency_pair: string; + amount: string; + price: string; + action_mode?: 'ACK' | 'RESULT' | 'FULL'; +} +⋮---- +export interface GetSpotOrdersReq { + currency_pair: string; + status: 'open' | 'finished'; + page?: number; + limit?: number; + account?: 'spot' | 'margin' | 'cross_margin' | 'unified'; + from?: number; + to?: number; + side?: 'buy' | 'sell'; +} +⋮---- +export interface CancelSpotBatchOrdersReq { + currency_pair: string; + id: string; + account?: 'cross_margin'; + action_mode?: 'ACK' | 'RESULT' | 'FULL'; } ⋮---- -/** Your API key */ -⋮---- -/** Your API secret */ +export interface DeleteSpotOrderReq { + order_id: string; + currency_pair: string; + account?: 'spot' | 'margin' | 'cross_margin' | 'unified'; + action_mode?: 'ACK' | 'RESULT' | 'FULL'; + xGateExptime?: number; +} ⋮---- -/** Define a recv window when preparing a private websocket signature. This is in milliseconds, so 5000 == 5 seconds */ +export interface GetSpotOrderReq { + order_id: string; + currency_pair: string; + account?: 'spot' | 'margin' | 'cross_margin' | 'unified'; +} ⋮---- -/** How often to check if the connection is alive */ +export interface GetSpotTradingHistoryReq { + currency_pair?: string; + limit?: number; + page?: number; + order_id?: string; + account?: 'spot' | 'margin' | 'cross_margin' | 'unified'; + from?: number; + to?: number; +} ⋮---- -/** How long to wait for a pong (heartbeat reply) before assuming the connection is dead */ +export interface UpdateSpotBatchOrdersReq { + order_id?: string; + currency_pair?: string; + amount?: string; + price?: string; + amend_text?: string; + stop_loss?: PatchSpotOrderTPSL; + stop_profit?: PatchSpotOrderTPSL; +} ⋮---- -/** Delay in milliseconds before respawning the connection */ +export interface GetSpotInsuranceHistoryReq { + business: 'margin' | 'unified'; + currency: string; + from: number; + to: number; + page?: number; + limit?: number; +} ⋮---- -/** - * Allows you to provide a custom "signMessage" function, e.g. to use node's much faster createHmac method - * - * Look in the examples folder for a demonstration on using node's createHmac instead. - */ +export interface GetSpotAutoOrdersReq { + status: 'open' | 'finished'; + market?: string; + account?: 'normal' | 'margin' | 'cross_margin' | 'unified'; + limit?: number; + offset?: number; +} ⋮---- -/** - * If you authenticated the WS API before, automatically try to re-authenticate the WS API if you're disconnected/reconnected for any reason. - */ +export interface SubmitSpotOrderReq { + xGateExptime?: number; + side: 'buy' | 'sell'; + amount: string; + text?: string; + currency_pair: string; + type?: 'limit' | 'market'; + account?: 'spot' | 'margin' | 'cross_margin' | 'unified'; + price?: string; + time_in_force?: 'gtc' | 'ioc' | 'poc' | 'fok'; + iceberg?: string; + auto_borrow?: boolean; + auto_repay?: boolean; + stp_act?: string; + action_mode?: string; + stop_loss?: PatchSpotOrderTPSL; + stop_profit?: PatchSpotOrderTPSL; + post_only?: boolean; + trade_quote?: string; +} ⋮---- -/** - * WS configuration that's always defined, regardless of user configuration - * (usually comes from defaults if there's no user-provided values) - */ -export interface WebsocketClientOptions extends WSClientConfigurableOptions { - pingInterval: number; - pongTimeout: number; - reconnectTimeout: number; - recvWindow: number; - authPrivateConnectionsOnConnect: boolean; - authPrivateRequests: boolean; - reauthWSAPIOnReconnect: boolean; +export interface UpdateSpotOrderReq { + xGateExptime?: number; + order_id: string; + currency_pair: string; + account?: 'spot' | 'margin' | 'cross_margin' | 'unified'; + amount?: string; + price?: string; + amend_text?: string; + action_mode?: 'ACK' | 'RESULT' | 'FULL'; + stop_loss?: PatchSpotOrderTPSL; + stop_profit?: PatchSpotOrderTPSL; } - -================ -File: webpack/webpack.config.cjs -================ -function generateConfig(name) ⋮---- -// Add '.ts' and '.tsx' as resolvable extensions. +/** GET /spot/pov_orders */ +export interface GetSpotPovOrdersReq { + status: 'open' | 'finished'; + currency_pair?: string; + side?: 'buy' | 'sell'; + page?: number; + limit?: number; +} ⋮---- -// Node.js core modules not available in browsers -// The REST client's https.Agent (for keepAlive) is Node.js-only and won't work in browsers +/** POST /spot/pov_orders */ +export interface CreateSpotPovOrderReq { + currency_pair: string; + side: 'buy' | 'sell'; + amount: string; + participation_rate: 5 | 10 | 20 | 40; + ttl: '1h' | '6h' | '12h' | '1d' | '2d' | '3d' | '4d' | '5d' | '6d' | '7d'; + limit_price?: string; + trigger_price?: string; + text?: string; +} ⋮---- -// Code is already transpiled from TypeScript, no additional loaders needed +/** DELETE /spot/pov_orders */ +export interface CancelSpotPovOrdersReq { + currency_pair?: string; +} ================ -File: src/types/request/crossex.ts +File: src/types/request/tradfi.ts ================ -/**========================================================================================================================== - * CROSSEX - * ========================================================================================================================== - */ +/** TradFi API request types */ ⋮---- -export interface GetCrossExSymbolsReq { - symbols?: string; // Trading Pair List, multiple separated by commas +export interface TradFiGetSymbolDetailParams { + symbols: string; } ⋮---- -symbols?: string; // Trading Pair List, multiple separated by commas -⋮---- -export interface GetCrossExRiskLimitsReq { - symbols: string; // Trading Pair List, multiple separated by commas +export interface TradFiGetKlinesParams { + kline_type: '1m' | '15m' | '1h' | '4h' | '1d' | '7d' | '30d'; + begin_time?: number; + end_time?: number; + limit?: number; } ⋮---- -symbols: string; // Trading Pair List, multiple separated by commas -⋮---- -export interface GetCrossExTransferCoinsReq { - coin?: string; // Currency +export interface TradFiCreateTransactionReq { + asset: string; + change: string; + type: 'deposit' | 'withdraw'; } ⋮---- -coin?: string; // Currency -⋮---- -export interface CreateCrossExTransferReq { - coin: string; // Currency - amount: string; // Transfer amount - from: string; // CROSSEX_BINANCE, CROSSEX_OKX, CROSSEX_GATE, CROSSEX_BYBIT, CROSSEX_KRAKEN, CROSSEX_LIGHTER, CROSSEX, SPOT, etc. - to: string; - text?: string; // User-defined ID +export interface TradFiGetTransactionsParams { + begin_time?: number; + end_time?: number; + type?: 'deposit' | 'withdraw' | 'dividend' | 'fill_negative'; + page?: number; + page_size?: number; } ⋮---- -coin: string; // Currency -amount: string; // Transfer amount -from: string; // CROSSEX_BINANCE, CROSSEX_OKX, CROSSEX_GATE, CROSSEX_BYBIT, CROSSEX_KRAKEN, CROSSEX_LIGHTER, CROSSEX, SPOT, etc. -⋮---- -text?: string; // User-defined ID -⋮---- -export interface GetCrossExTransferHistoryReq { - coin?: string; // Query by specified currency name - order_id?: string; // Supports querying by the order ID returned when creating an order (tx_id), as well as a user-defined custom ID specified at creation (text) - from?: number; // Start timestamp for the query - to?: number; // End timestamp for the query, defaults to current time if not specified - page?: number; // Page number - limit?: number; // Maximum number returned by list, max 1000 +export interface TradFiCreateOrderReq { + price: string; + price_type: 'trigger' | 'market'; + side: 1 | 2; + symbol: string; + volume: string; + price_tp?: string; + price_sl?: string; + leverage?: number; } ⋮---- -coin?: string; // Query by specified currency name -order_id?: string; // Supports querying by the order ID returned when creating an order (tx_id), as well as a user-defined custom ID specified at creation (text) -from?: number; // Start timestamp for the query -to?: number; // End timestamp for the query, defaults to current time if not specified -page?: number; // Page number -limit?: number; // Maximum number returned by list, max 1000 +export interface TradFiModifyOrderReq { + price: string; + price_tp?: string | null; + price_sl?: string | null; +} ⋮---- -export interface CreateCrossExOrderReq { - text?: string; // Client-defined Order ID, supports letters (a-z), numbers (0-9), symbols (-, _) only - symbol: string; // Unique identifier Exchange_Business_Base_Counter - side: 'BUY' | 'SELL'; - type?: 'LIMIT' | 'MARKET'; // Order type (default: LIMIT) - time_in_force?: 'GTC' | 'IOC' | 'FOK' | 'POC' | 'RPI'; // Default GTC; RPI = Retail Price Improvement - qty?: string; // Order quantity (required unless spot market buy) - price?: string; // Limit Order Price (Required for Limit Orders) - quote_qty?: string; // Order quote quantity; required for spot and margin market buy orders - reduce_only?: 'true' | 'false'; // Reduce-only - position_side?: 'LONG' | 'SHORT' | 'NONE'; // Position side, defaults to NONE (single position mode) if not specified +export interface TradFiModifyPositionReq { + price_tp?: string | null; + price_sl?: string | null; } ⋮---- -text?: string; // Client-defined Order ID, supports letters (a-z), numbers (0-9), symbols (-, _) only -symbol: string; // Unique identifier Exchange_Business_Base_Counter +export interface TradFiClosePositionReq { + close_type: 1 | 2; + close_volume?: string | null; +} ⋮---- -type?: 'LIMIT' | 'MARKET'; // Order type (default: LIMIT) -time_in_force?: 'GTC' | 'IOC' | 'FOK' | 'POC' | 'RPI'; // Default GTC; RPI = Retail Price Improvement -qty?: string; // Order quantity (required unless spot market buy) -price?: string; // Limit Order Price (Required for Limit Orders) -quote_qty?: string; // Order quote quantity; required for spot and margin market buy orders -reduce_only?: 'true' | 'false'; // Reduce-only -position_side?: 'LONG' | 'SHORT' | 'NONE'; // Position side, defaults to NONE (single position mode) if not specified +export interface TradFiGetOrderHistoryParams { + begin_time?: number; + end_time?: number; + symbol?: string; + side?: 1 | 2; +} ⋮---- -export interface GetCrossExMarketTickersReq { - symbols?: string; +export interface TradFiGetPositionHistoryParams { + begin_time?: number; + end_time?: number; + symbol?: string; + position_dir?: 'Long' | 'Short'; + page?: number; + page_size?: number; } ⋮---- -export interface GetCrossExMarketFundingInfoReq { +/** GET /tradfi/symbols/commissions */ +export interface TradFiGetSymbolCommissionsParams { symbols?: string; + category_code?: string; } + +================ +File: src/types/response/earn.ts +================ +/**========================================================================================================================== + * EARN + * ========================================================================================================================== + */ ⋮---- -/** Either order_id or text required; order_id wins if both set */ -export interface CancelBatchCrossExOrdersReq { - order_id?: string; - text?: string; -} -⋮---- -export interface ModifyCrossExOrderReq { - qty?: string; // modify amount - price?: string; // modify price +export interface DualInvestmentProduct { + id: number; + instrument_name: string; + invest_currency: string; + exercise_currency: string; + exercise_price: number; + delivery_time: number; + min_amount?: string; + min_copies: number; + max_copies: number; + /** @deprecated */ + per_value: string; + apy_display: string; + start_time: number; + end_time: number; + status: 'NOTSTARTED' | 'ONGOING' | 'ENDED'; } ⋮---- -qty?: string; // modify amount -price?: string; // modify price +/** @deprecated */ ⋮---- -export interface CreateCrossExConvertQuoteReq { - exchange_type: string; // Exchange Type - from_coin: string; // Asset Sold (OKX and GATE only allow BTC, ETH, USDT; BN only allows USDT; LIGHTER_USDC <-> CROSSEX_USDT in cross-exchange mode) - to_coin: string; // Asset name to buy (OKX and GATE only allow BTC, ETH, USDT; BN only allows USDT; LIGHTER_USDC <-> CROSSEX_USDT in cross-exchange mode) - from_amount: string; // Amount to sell +/** GET /earn/dual/order-refund-preview */ +export interface DualOrderRefundPreview { + create_timest: number; + delivery_timest: number; + exercise_price: string; + invest_amount: string; + invest_currency: string; + name: string; + order_id: number; + req_id: string; + refund_service_charge: number; + settle_price: string; + settlement_amount: string; + settlement_currency: string; + settlement_interest: string; + settlement_principle: string; + type: string; + money_back_timest: number; } ⋮---- -exchange_type: string; // Exchange Type -from_coin: string; // Asset Sold (OKX and GATE only allow BTC, ETH, USDT; BN only allows USDT; LIGHTER_USDC <-> CROSSEX_USDT in cross-exchange mode) -to_coin: string; // Asset name to buy (OKX and GATE only allow BTC, ETH, USDT; BN only allows USDT; LIGHTER_USDC <-> CROSSEX_USDT in cross-exchange mode) -from_amount: string; // Amount to sell -⋮---- -export interface CreateCrossExConvertOrderReq { - quote_id: string; // Inquiry ID +/** GET /earn/dual/project-recommend item */ +export interface DualProjectRecommend { + id: number; + category: number; + type: string; + invest_currency: string; + exercise_currency: string; + apy_display: string; + exercise_price: string; + delivery_timest: number; + min_amount: string; + max_amount: string; + min_copies: number; + max_copies: number; + invest_days: number; + invest_hours: string; } ⋮---- -quote_id: string; // Inquiry ID -⋮---- -export interface UpdateCrossExAccountReq { - position_mode?: string; // Futures position mode (SINGLE/DUAL) - account_mode?: string; // Account mode (CROSS_EXCHANGE/ISOLATED_EXCHANGE, default: CROSS_EXCHANGE) - exchange_type?: string; // Exchange (BINANCE/OKX/GATE/BYBIT/CROSSEX) +export interface DualInvestmentOrder { + id: number; + plan_id: number; + copies: string; + invest_amount: string; + settlement_amount: string; + create_time: number; + complete_time: number; + status: + | 'INIT' + | 'SETTLEMENT_SUCCESS' + | 'SETTLEMENT_PROCESSING' + | 'CANCELED' + | 'FAILED'; + invest_currency: string; + exercise_currency: string; + exercise_price: string; + settlement_price: string; + settlement_currency: string; + apy_display: string; + apy_settlement: string; + delivery_time: number; + text: string; } ⋮---- -position_mode?: string; // Futures position mode (SINGLE/DUAL) -account_mode?: string; // Account mode (CROSS_EXCHANGE/ISOLATED_EXCHANGE, default: CROSS_EXCHANGE) -exchange_type?: string; // Exchange (BINANCE/OKX/GATE/BYBIT/CROSSEX) +/**========================================================================================================================== + * EARN FIXED-TERM + * ========================================================================================================================== + */ ⋮---- -export interface GetCrossExAccountsReq { - exchange_type?: string; // Exchange. Not required in cross-exchange mode; required in single-exchange mode (BINANCE/OKX/GATE/BYBIT) +export interface FixedTermLadderApr { + apr: string; + left: string; + right: string; } ⋮---- -exchange_type?: string; // Exchange. Not required in cross-exchange mode; required in single-exchange mode (BINANCE/OKX/GATE/BYBIT) -⋮---- -export interface SetCrossExPositionLeverageReq { - symbol: string; // Currency pair - leverage: string; // leverage +export interface FixedTermProductInfo { + pre_redeem: number; + reinvest: number; + redeem_account: number; + min_vip: number; + max_vip: number; } ⋮---- -symbol: string; // Currency pair -leverage: string; // leverage -⋮---- -export interface GetCrossExPositionLeverageReq { - symbols?: string; // Trading Pair List, multiple separated by commas +export interface FixedTermBonusInfo { + id?: number; + product_id?: number; + asset?: string; + bonus_asset?: string; + kyc_limit?: string; + ladder_apr?: FixedTermLadderApr[]; + total_bonus_amount?: string; + user_total_bonus_amount?: string; + status?: number; + start_time?: string; + end_time?: string; + create_time?: string; + start_at?: number; + end_at?: number; + total_issued_amount?: string; + user_total_issued_amount?: string; + bonus_asset_price?: string; + product_asset_price?: string; + product_year_rate?: string; } ⋮---- -symbols?: string; // Trading Pair List, multiple separated by commas -⋮---- -export interface SetCrossExMarginPositionLeverageReq { - symbol: string; // Currency pair - leverage: string; // leverage +export interface FixedTermCouponInfo { + id?: number; + business?: number; + user_id?: number; + asset?: string; + order_id?: number; + financial_rate_id?: number; + buy_limit_low?: string; + buy_limit_high?: string; + rate_day?: number; + rate_ratio?: string; + coupon_days?: number; + coupon_principal?: string; + coupon_year_rate?: string; + coupon_interest?: string; + status?: number; + finish_time?: string; + create_time?: string; } ⋮---- -symbol: string; // Currency pair -leverage: string; // leverage -⋮---- -export interface GetCrossExMarginPositionLeverageReq { - symbols?: string; // Trading Pair List, multiple separated by commas +export interface FixedTermLendOrder { + id?: number; + business?: number; + order_id?: number; + user_id?: number; + asset?: string; + product_id?: number; + lock_up_period?: number; + principal?: string; + year_rate?: string; + product_type?: number; + interest?: string; + status?: number; + reinvest_status?: number; + redeem_account_type?: number; + origin_order?: string; + redeem_type?: number; + redeem_time?: string; + finish_time?: string; + create_time?: string; + year_rate_perent?: string; + total_year_rate_percent?: string; + total_interest?: string; + product_info?: FixedTermProductInfo; + bonus_info?: FixedTermBonusInfo; + coupon_info?: FixedTermCouponInfo; + redeem_at?: number; + finish_at?: number; + create_at?: number; + icon?: string; } ⋮---- -symbols?: string; // Trading Pair List, multiple separated by commas +export interface FixedTermProduct { + id?: number; + name?: string; + asset?: string; + lock_up_period?: number; + min_lend_amount?: string; + user_max_lend_amount?: string; + total_lend_amount?: string; + year_rate?: string; + type?: number; + pre_redeem?: number; + reinvest?: number; + redeem_account?: number; + min_vip?: number; + max_vip?: number; + status?: number; + create_time?: string; + user_max_lend_volume?: string; + user_total_amount?: string; + sale_status?: number; +} ⋮---- -export interface CloseCrossExPositionReq { - symbol: string; // Trading Pair - position_side?: string; // Position Direction +export interface FixedTermProductSimple { + id?: number; + asset?: string; + lock_up_period?: number; + year_rate?: string; + type?: number; + pre_redeem?: number; + reinvest?: number; + simple_earn?: number; + min_vip?: number; + max_vip?: number; + sale_status?: number; } ⋮---- -symbol: string; // Trading Pair -position_side?: string; // Position Direction -⋮---- -export interface GetCrossExInterestRateReq { - coin?: string; // Currency - exchange_type?: string; // Exchange +export interface GetEarnFixedTermProductsResponse { + code: number; + message: string; + data: { + list: FixedTermProduct[]; + total: number; + }; + timestamp: number; } ⋮---- -coin?: string; // Currency -exchange_type?: string; // Exchange -⋮---- -export interface GetCrossExPositionsReq { - symbol?: string; // Trading Pair - exchange_type?: string; // Exchange +export interface GetEarnFixedTermProductsByAssetResponse { + code: number; + message: string; + data: { + list: FixedTermProductSimple[]; + }; + timestamp: number; } ⋮---- -symbol?: string; // Trading Pair -exchange_type?: string; // Exchange -⋮---- -export interface GetCrossExMarginPositionsReq { - symbol?: string; // Currency pair - exchange_type?: string; // Exchange +export interface CreateEarnFixedTermLendResponse { + code?: number; + message?: string; + data?: { + order_id?: number; + }; + timestamp?: number; } ⋮---- -symbol?: string; // Currency pair -exchange_type?: string; // Exchange -⋮---- -export interface GetCrossExAdlRankReq { - symbol: string; // Trading Pair +export interface GetEarnFixedTermLendsResponse { + code: number; + message: string; + data: { + list: FixedTermLendOrder[]; + total: number; + }; + timestamp: number; } ⋮---- -symbol: string; // Trading Pair -⋮---- -export interface GetCrossExOpenOrdersReq { - symbol?: string; // Trading Pair - exchange_type?: string; // Exchange - business_type?: string; // Business Type +export interface CreateEarnFixedTermPreRedeemResponse { + code?: number; + message?: string; + data?: Record; + timestamp?: number; } ⋮---- -symbol?: string; // Trading Pair -exchange_type?: string; // Exchange -business_type?: string; // Business Type -⋮---- -export interface GetCrossExHistoryOrdersReq { - page?: number; // Page number - limit?: number; // Maximum number of records returned in a single list - symbol?: string; - from?: number; // Start Millisecond Timestamp - to?: number; // End Millisecond Timestamp - /** Comma-separated: COMMON, LIQ, REDUCE, ADL, SETTLEMENT */ - attributes?: string; +export interface FixedTermHistoryRecord { + id?: number; + order_id?: number; + user_id?: number; + asset?: string; + uniq_time?: string; + bonus_id?: number; + product_id?: number; + bonus_asset?: string; + total_principal?: string; + amount?: string; + asset_price?: string; + status?: number; + detail?: string; + create_time?: string; + create_at?: number; + lock_up_period?: number; } ⋮---- -page?: number; // Page number -limit?: number; // Maximum number of records returned in a single list -⋮---- -from?: number; // Start Millisecond Timestamp -to?: number; // End Millisecond Timestamp -/** Comma-separated: COMMON, LIQ, REDUCE, ADL, SETTLEMENT */ -⋮---- -export interface GetCrossExHistoryPositionsReq { - page?: number; // Page number - limit?: number; // Maximum number returned by list, max 1000 - symbol?: string; - from?: number; // Start Millisecond Timestamp - to?: number; // End Millisecond Timestamp +export interface GetEarnFixedTermHistoryResponse { + code?: number; + message?: string; + data?: { + list?: FixedTermHistoryRecord[]; + total?: number; + }; + timestamp?: number; } + +================ +File: src/types/websockets/client.ts +================ +import type { ClientRequestArgs } from 'http'; +import WebSocket from 'isomorphic-ws'; ⋮---- -page?: number; // Page number -limit?: number; // Maximum number returned by list, max 1000 -⋮---- -from?: number; // Start Millisecond Timestamp -to?: number; // End Millisecond Timestamp -⋮---- -export interface GetCrossExHistoryMarginPositionsReq { - page?: number; // Page number - limit?: number; // Maximum number returned by list, max 1000 - symbol?: string; - from?: number; // Start Millisecond Timestamp - to?: number; // End Millisecond Timestamp -} +/** + * Event args for subscribing/unsubscribing + */ ⋮---- -page?: number; // Page number -limit?: number; // Maximum number returned by list, max 1000 +// export type WsTopicSubscribePrivateArgsV2 = +// | WsTopicSubscribePrivateInstIdArgsV2 +// | WsTopicSubscribePrivateCoinArgsV2; ⋮---- -from?: number; // Start Millisecond Timestamp -to?: number; // End Millisecond Timestamp +// export type WsTopicSubscribeEventArgsV2 = +// | WsTopicSubscribePublicArgsV2 +// | WsTopicSubscribePrivateArgsV2; ⋮---- -export interface GetCrossExHistoryMarginInterestsReq { - symbol?: string; - from?: number; - to?: number; - page?: number; - limit?: number; - exchange_type?: string; +/** General configuration for the WebsocketClient */ +export interface WSClientConfigurableOptions { + /** Your API key */ + apiKey?: string; + + /** Your API secret */ + apiSecret?: string; + + useTestnet?: boolean; + + /** Define a recv window when preparing a private websocket signature. This is in milliseconds, so 5000 == 5 seconds */ + recvWindow?: number; + + /** How often to check if the connection is alive */ + pingInterval?: number; + + /** How long to wait for a pong (heartbeat reply) before assuming the connection is dead */ + pongTimeout?: number; + + /** Delay in milliseconds before respawning the connection */ + reconnectTimeout?: number; + + requestOptions?: {}; + + wsUrl?: string; + + wsOptions?: { + protocols?: string[]; + agent?: any; + } & ( + | Omit, 'agent'> + | Omit, 'agent'> + ); + + /** + * Allows you to provide a custom "signMessage" function, e.g. to use node's much faster createHmac method + * + * Look in the examples folder for a demonstration on using node's createHmac instead. + */ + customSignMessageFn?: (message: string, secret: string) => Promise; + + /** + * If you authenticated the WS API before, automatically try to re-authenticate the WS API if you're disconnected/reconnected for any reason. + */ + reauthWSAPIOnReconnect?: boolean; + + /** + * When true, sends `X-Gate-Size-Decimal: 1` on futures/delivery WebSocket connections and WS API requests so size-related fields are returned as decimal strings instead of integers rounded down. + * @default false + */ + futuresSizeDecimal?: boolean; } ⋮---- -export interface GetCrossExHistoryTradesReq { - page?: number; // Page number - limit?: number; // Maximum number returned by list, max 1000 - symbol?: string; - from?: number; // Start Millisecond Timestamp - to?: number; // End Millisecond Timestamp -} +/** Your API key */ ⋮---- -page?: number; // Page number -limit?: number; // Maximum number returned by list, max 1000 +/** Your API secret */ ⋮---- -from?: number; // Start Millisecond Timestamp -to?: number; // End Millisecond Timestamp +/** Define a recv window when preparing a private websocket signature. This is in milliseconds, so 5000 == 5 seconds */ ⋮---- -export interface GetCrossExAccountBookReq { - page?: number; // Page number - limit?: number; // Maximum number returned by list, max 1000 - coin?: string; - from?: number; // Start Millisecond Timestamp - to?: number; // End Millisecond Timestamp -} +/** How often to check if the connection is alive */ ⋮---- -page?: number; // Page number -limit?: number; // Maximum number returned by list, max 1000 +/** How long to wait for a pong (heartbeat reply) before assuming the connection is dead */ ⋮---- -from?: number; // Start Millisecond Timestamp -to?: number; // End Millisecond Timestamp +/** Delay in milliseconds before respawning the connection */ ⋮---- -export interface GetCrossExCoinDiscountRateReq { - coin?: string; - exchange_type?: string; // OKX/GATE/BINANCE/BYBIT -} +/** + * Allows you to provide a custom "signMessage" function, e.g. to use node's much faster createHmac method + * + * Look in the examples folder for a demonstration on using node's createHmac instead. + */ ⋮---- -exchange_type?: string; // OKX/GATE/BINANCE/BYBIT +/** + * If you authenticated the WS API before, automatically try to re-authenticate the WS API if you're disconnected/reconnected for any reason. + */ ⋮---- -export interface UpdateCrossExPositionsMarginReq { - symbol: string; - margin: string; - position_side?: 'NONE' | 'LONG' | 'SHORT'; +/** + * When true, sends `X-Gate-Size-Decimal: 1` on futures/delivery WebSocket connections and WS API requests so size-related fields are returned as decimal strings instead of integers rounded down. + * @default false + */ +⋮---- +/** + * WS configuration that's always defined, regardless of user configuration + * (usually comes from defaults if there's no user-provided values) + */ +export interface WebsocketClientOptions extends WSClientConfigurableOptions { + pingInterval: number; + pongTimeout: number; + reconnectTimeout: number; + recvWindow: number; + authPrivateConnectionsOnConnect: boolean; + authPrivateRequests: boolean; + reauthWSAPIOnReconnect: boolean; } ================ -File: src/types/response/crossex.ts +File: src/types/request/crossex.ts ================ /**========================================================================================================================== * CROSSEX * ========================================================================================================================== */ ⋮---- -export interface CrossExSymbol { - symbol: string; - exchange_type: string; - business_type: string; - state: string; - min_size: string; - min_notional: string; - lot_size: string; - tick_size: string; - max_num_orders: string; - max_market_size: string; - max_limit_size: string; - contract_size: string; - liquidation_fee: string; - delist_time: string; - support_rpi?: string; // true/false whether RPI orders are supported - support_cross?: string; // "true"/"false" whether the symbol supports cross-margin orders -} -⋮---- -support_rpi?: string; // true/false whether RPI orders are supported -support_cross?: string; // "true"/"false" whether the symbol supports cross-margin orders -⋮---- -export interface CrossExRiskLimitTier { - min_risk_limit_value: string; // Minimum risk limit value - max_risk_limit_value: string; // Maximum risk limit value - leverage_max: string; // Maximum leverage - maintenance_rate: string; // Maintenance margin rate - tier: string; // Tier - quick_cal_amount: string; // Quick-calculation amount for this risk tier +export interface GetCrossExSymbolsReq { + symbols?: string; // Trading Pair List, multiple separated by commas } ⋮---- -min_risk_limit_value: string; // Minimum risk limit value -max_risk_limit_value: string; // Maximum risk limit value -leverage_max: string; // Maximum leverage -maintenance_rate: string; // Maintenance margin rate -tier: string; // Tier -quick_cal_amount: string; // Quick-calculation amount for this risk tier -⋮---- -export interface CrossExRiskLimit { - symbol: string; - tiers: CrossExRiskLimitTier[]; -} +symbols?: string; // Trading Pair List, multiple separated by commas ⋮---- -export interface CrossExTransferCoin { - coin: string; // Currency - min_trans_amount: number; // Minimum Transfer Quantity (including estimated fees) - est_fee: number; // Estimated Fee - precision: number; // Precision - is_disabled: number; // If it is disabled. 0 means NOT being disabled +export interface GetCrossExRiskLimitsReq { + symbols: string; // Trading Pair List, multiple separated by commas } ⋮---- -coin: string; // Currency -min_trans_amount: number; // Minimum Transfer Quantity (including estimated fees) -est_fee: number; // Estimated Fee -precision: number; // Precision -is_disabled: number; // If it is disabled. 0 means NOT being disabled +symbols: string; // Trading Pair List, multiple separated by commas ⋮---- -export interface CreateCrossExTransferResp { - tx_id: string; // Order ID - text: string; // User-defined Order ID +export interface GetCrossExTransferCoinsReq { + coin?: string; // Currency } ⋮---- -tx_id: string; // Order ID -text: string; // User-defined Order ID +coin?: string; // Currency ⋮---- -export interface CrossExTransferHistory { - id: string; // Order ID - text: string; // Client Custom ID - from_account_type: string; // Source from account (CROSSEX_BINANCE, CROSSEX_OKX, CROSSEX_GATE, CROSSEX_BYBIT, CROSSEX, SPOT) - to_account_type: string; +export interface CreateCrossExTransferReq { coin: string; // Currency - amount: string; // Transfer amount, the amount requested for the transfer - actual_receive: string; // Actual credited amount (has a value when status = SUCCESS; empty for other statuses) - status: string; // Transfer Status - FAIL: Failed, SUCCESS: Successful, PENDING: Transfer in Progress - fail_reason: string; // Failure reason (has a value when status = FAIL; empty for other statuses) - create_time: number; // Creation time of order - update_time: number; // Order Update Time + amount: string; // Transfer amount + from: string; // CROSSEX_BINANCE, CROSSEX_OKX, CROSSEX_GATE, CROSSEX_BYBIT, CROSSEX_KRAKEN, CROSSEX_LIGHTER, CROSSEX, SPOT, etc. + to: string; + text?: string; // User-defined ID } ⋮---- -id: string; // Order ID -text: string; // Client Custom ID -from_account_type: string; // Source from account (CROSSEX_BINANCE, CROSSEX_OKX, CROSSEX_GATE, CROSSEX_BYBIT, CROSSEX, SPOT) -⋮---- coin: string; // Currency -amount: string; // Transfer amount, the amount requested for the transfer -actual_receive: string; // Actual credited amount (has a value when status = SUCCESS; empty for other statuses) -status: string; // Transfer Status - FAIL: Failed, SUCCESS: Successful, PENDING: Transfer in Progress -fail_reason: string; // Failure reason (has a value when status = FAIL; empty for other statuses) -create_time: number; // Creation time of order -update_time: number; // Order Update Time -⋮---- -export interface CreateCrossExOrderResp { - order_id: number | string; - text: string; // User-defined Order ID -} -⋮---- -text: string; // User-defined Order ID -⋮---- -export interface CancelCrossExOrderResp { - order_id: number; - text: string; -} -⋮---- -export interface ModifyCrossExOrderResp { - order_id: number; - text: string; -} -⋮---- -export interface CrossExOrder { - user_id: string; // User ID - order_id: string; // Order ID - text: string; // Client Order ID - state: string; // Order Status - symbol: string; // Currency pair - side: string; // direction - type: string; // type - attribute: string; // COMMON, LIQ, REDUCE, ADL, SETTLEMENT - exchange_type: string; // Exchange - business_type: string; // Business Type - qty: string; // Base Currency Quantity - quote_qty: string; // Quote Currency Quantity - price: string; // Price - time_in_force: string; // Time in Force Strategy - executed_qty: string; // Filled Quantity - executed_amount: string; // Filled Amount - executed_avg_price: string; // Average Filled Price - fee_coin: string; // Fee currency - fee: string; // fee - reduce_only: string; // Reduce Position Only - leverage: string; // leverage - reason: string; // Reason - last_executed_qty: string; // Latest Filled Quantity - last_executed_price: string; // Latest Filled Price - last_executed_amount: string; // Latest Filled Amount - position_side: string; // Position Direction - create_time: string; // Created time - update_time: string; // Update time -} +amount: string; // Transfer amount +from: string; // CROSSEX_BINANCE, CROSSEX_OKX, CROSSEX_GATE, CROSSEX_BYBIT, CROSSEX_KRAKEN, CROSSEX_LIGHTER, CROSSEX, SPOT, etc. ⋮---- -user_id: string; // User ID -order_id: string; // Order ID -text: string; // Client Order ID -state: string; // Order Status -symbol: string; // Currency pair -side: string; // direction -type: string; // type -attribute: string; // COMMON, LIQ, REDUCE, ADL, SETTLEMENT -exchange_type: string; // Exchange -business_type: string; // Business Type -qty: string; // Base Currency Quantity -quote_qty: string; // Quote Currency Quantity -price: string; // Price -time_in_force: string; // Time in Force Strategy -executed_qty: string; // Filled Quantity -executed_amount: string; // Filled Amount -executed_avg_price: string; // Average Filled Price -fee_coin: string; // Fee currency -fee: string; // fee -reduce_only: string; // Reduce Position Only -leverage: string; // leverage -reason: string; // Reason -last_executed_qty: string; // Latest Filled Quantity -last_executed_price: string; // Latest Filled Price -last_executed_amount: string; // Latest Filled Amount -position_side: string; // Position Direction -create_time: string; // Created time -update_time: string; // Update time +text?: string; // User-defined ID ⋮---- -export interface CreateCrossExConvertQuoteResp { - quote_id: string; // Quote ID - valid_ms: string; // Valid time (milliseconds timestamp) - from_coin: string; // Asset Sold - to_coin: string; // Asset Bought - from_amount: string; // Amount to sell - to_amount: string; // Amount to buy - price: string; // Price +export interface GetCrossExTransferHistoryReq { + coin?: string; // Query by specified currency name + order_id?: string; // Supports querying by the order ID returned when creating an order (tx_id), as well as a user-defined custom ID specified at creation (text) + from?: number; // Start timestamp for the query + to?: number; // End timestamp for the query, defaults to current time if not specified + page?: number; // Page number + limit?: number; // Maximum number returned by list, max 1000 } ⋮---- -quote_id: string; // Quote ID -valid_ms: string; // Valid time (milliseconds timestamp) -from_coin: string; // Asset Sold -to_coin: string; // Asset Bought -from_amount: string; // Amount to sell -to_amount: string; // Amount to buy -price: string; // Price +coin?: string; // Query by specified currency name +order_id?: string; // Supports querying by the order ID returned when creating an order (tx_id), as well as a user-defined custom ID specified at creation (text) +from?: number; // Start timestamp for the query +to?: number; // End timestamp for the query, defaults to current time if not specified +page?: number; // Page number +limit?: number; // Maximum number returned by list, max 1000 ⋮---- -export interface CreateCrossExConvertOrderResp { - order_id: string; // Order ID - text: string; // User-defined order ID text +export interface CreateCrossExOrderReq { + text?: string; // Client-defined Order ID, supports letters (a-z), numbers (0-9), symbols (-, _) only + symbol: string; // Unique identifier Exchange_Business_Base_Counter + side: 'BUY' | 'SELL'; + type?: 'LIMIT' | 'MARKET'; // Order type (default: LIMIT) + time_in_force?: 'GTC' | 'IOC' | 'FOK' | 'POC' | 'RPI'; // Default GTC; RPI = Retail Price Improvement + qty?: string; // Order quantity (required unless spot market buy) + price?: string; // Limit Order Price (Required for Limit Orders) + quote_qty?: string; // Order quote quantity; required for spot and margin market buy orders + reduce_only?: 'true' | 'false'; // Reduce-only + position_side?: 'LONG' | 'SHORT' | 'NONE'; // Position side, defaults to NONE (single position mode) if not specified } ⋮---- -order_id: string; // Order ID -text: string; // User-defined order ID text -⋮---- -export interface UpdateCrossExAccountResp { - position_mode: string; // Requested futures position mode to modify (SINGLE/DUAL) - account_mode: string; // Requested account mode to modify (CROSS_EXCHANGE/ISOLATED_EXCHANGE, default: CROSS_EXCHANGE) - exchange_type: string; // Requested exchange to modify (BINANCE/OKX/GATE/BYBIT/CROSSEX) -} +text?: string; // Client-defined Order ID, supports letters (a-z), numbers (0-9), symbols (-, _) only +symbol: string; // Unique identifier Exchange_Business_Base_Counter ⋮---- -position_mode: string; // Requested futures position mode to modify (SINGLE/DUAL) -account_mode: string; // Requested account mode to modify (CROSS_EXCHANGE/ISOLATED_EXCHANGE, default: CROSS_EXCHANGE) -exchange_type: string; // Requested exchange to modify (BINANCE/OKX/GATE/BYBIT/CROSSEX) +type?: 'LIMIT' | 'MARKET'; // Order type (default: LIMIT) +time_in_force?: 'GTC' | 'IOC' | 'FOK' | 'POC' | 'RPI'; // Default GTC; RPI = Retail Price Improvement +qty?: string; // Order quantity (required unless spot market buy) +price?: string; // Limit Order Price (Required for Limit Orders) +quote_qty?: string; // Order quote quantity; required for spot and margin market buy orders +reduce_only?: 'true' | 'false'; // Reduce-only +position_side?: 'LONG' | 'SHORT' | 'NONE'; // Position side, defaults to NONE (single position mode) if not specified ⋮---- -export interface CrossExAccountAsset { - user_id: string; // User ID - coin: string; // Currency - exchange_type: string; // Exchange - balance: string; // Balance - upnl: string; // Unrealized P&L - equity: string; // Equity (only USDT has a value; other assets are 0) - futures_initial_margin: string; // Futures initial margin (only USDT has a value; other assets are 0) - futures_maintenance_margin: string; // Futures maintenance margin (only USDT has a value; other assets are 0) - borrowing_initial_margin: string; // Margin trading initial margin (only USDT has a value; other assets are 0) - borrowing_maintenance_margin: string; // Margin trading maintenance margin (only USDT has a value; other assets are 0) - available_balance: string; // Available Balance - liability: string; // Liabilities (only meaningful in isolated exchange mode; always 0 in cross-exchange mode) +export interface GetCrossExMarketTickersReq { + symbols?: string; } ⋮---- -user_id: string; // User ID -coin: string; // Currency -exchange_type: string; // Exchange -balance: string; // Balance -upnl: string; // Unrealized P&L -equity: string; // Equity (only USDT has a value; other assets are 0) -futures_initial_margin: string; // Futures initial margin (only USDT has a value; other assets are 0) -futures_maintenance_margin: string; // Futures maintenance margin (only USDT has a value; other assets are 0) -borrowing_initial_margin: string; // Margin trading initial margin (only USDT has a value; other assets are 0) -borrowing_maintenance_margin: string; // Margin trading maintenance margin (only USDT has a value; other assets are 0) -available_balance: string; // Available Balance -liability: string; // Liabilities (only meaningful in isolated exchange mode; always 0 in cross-exchange mode) +export interface GetCrossExMarketFundingInfoReq { + symbols?: string; +} ⋮---- -export interface CrossExAccount { - user_id: string; // User ID - available_margin: string; // Available Margin - margin_balance: string; // margin balance - initial_margin: string; // Initial Margin - maintenance_margin: string; // Maintenance margin - initial_margin_rate: string; // Initial margin rate - maintenance_margin_rate: string; // Maintenance margin rate - position_mode: string; // Contract Position Mode - account_limit: string; // Account limit - create_time: string; // Created time - update_time: string; // Update time - account_mode: string; // Account mode. CROSS_EXCHANGE: cross-exchange mode. ISOLATED_EXCHANGE: isolated exchange mode - exchange_type: string; // Exchange type. When account_mode is CROSS_EXCHANGE, this must be CROSSEX; otherwise, it represents a specific exchange - assets: CrossExAccountAsset[]; +/** Either order_id or text required; order_id wins if both set */ +export interface CancelBatchCrossExOrdersReq { + order_id?: string; + text?: string; } ⋮---- -user_id: string; // User ID -available_margin: string; // Available Margin -margin_balance: string; // margin balance -initial_margin: string; // Initial Margin -maintenance_margin: string; // Maintenance margin -initial_margin_rate: string; // Initial margin rate -maintenance_margin_rate: string; // Maintenance margin rate -position_mode: string; // Contract Position Mode -account_limit: string; // Account limit -create_time: string; // Created time -update_time: string; // Update time -account_mode: string; // Account mode. CROSS_EXCHANGE: cross-exchange mode. ISOLATED_EXCHANGE: isolated exchange mode -exchange_type: string; // Exchange type. When account_mode is CROSS_EXCHANGE, this must be CROSSEX; otherwise, it represents a specific exchange +export interface ModifyCrossExOrderReq { + qty?: string; // modify amount + price?: string; // modify price +} ⋮---- -export interface SetCrossExPositionLeverageResp { - symbol: string; // Currency pair - leverage: string; // Requested Modified Leverage +qty?: string; // modify amount +price?: string; // modify price +⋮---- +export interface CreateCrossExConvertQuoteReq { + exchange_type: string; // Exchange Type + from_coin: string; // Asset Sold (OKX and GATE only allow BTC, ETH, USDT; BN only allows USDT; LIGHTER_USDC <-> CROSSEX_USDT in cross-exchange mode) + to_coin: string; // Asset name to buy (OKX and GATE only allow BTC, ETH, USDT; BN only allows USDT; LIGHTER_USDC <-> CROSSEX_USDT in cross-exchange mode) + from_amount: string; // Amount to sell } ⋮---- -symbol: string; // Currency pair -leverage: string; // Requested Modified Leverage +exchange_type: string; // Exchange Type +from_coin: string; // Asset Sold (OKX and GATE only allow BTC, ETH, USDT; BN only allows USDT; LIGHTER_USDC <-> CROSSEX_USDT in cross-exchange mode) +to_coin: string; // Asset name to buy (OKX and GATE only allow BTC, ETH, USDT; BN only allows USDT; LIGHTER_USDC <-> CROSSEX_USDT in cross-exchange mode) +from_amount: string; // Amount to sell ⋮---- -export interface CrossExPositionLeverage { - symbol: string; // Currency pair - leverage: number | string; +export interface CreateCrossExConvertOrderReq { + quote_id: string; // Inquiry ID } ⋮---- -symbol: string; // Currency pair +quote_id: string; // Inquiry ID ⋮---- -export interface SetCrossExMarginPositionLeverageResp { - symbol: string; // Currency pair - leverage: string; // Requested Modified Leverage +export interface UpdateCrossExAccountReq { + position_mode?: string; // Futures position mode (SINGLE/DUAL) + account_mode?: string; // Account mode (CROSS_EXCHANGE/ISOLATED_EXCHANGE, default: CROSS_EXCHANGE) + exchange_type?: string; // Exchange (BINANCE/OKX/GATE/BYBIT/CROSSEX) } ⋮---- -symbol: string; // Currency pair -leverage: string; // Requested Modified Leverage +position_mode?: string; // Futures position mode (SINGLE/DUAL) +account_mode?: string; // Account mode (CROSS_EXCHANGE/ISOLATED_EXCHANGE, default: CROSS_EXCHANGE) +exchange_type?: string; // Exchange (BINANCE/OKX/GATE/BYBIT/CROSSEX) ⋮---- -export interface CrossExMarginPositionLeverage { - symbol: string; // Currency pair - leverage: number | string; +export interface GetCrossExAccountsReq { + exchange_type?: string; // Exchange. Not required in cross-exchange mode; required in single-exchange mode (BINANCE/OKX/GATE/BYBIT) } ⋮---- -symbol: string; // Currency pair +exchange_type?: string; // Exchange. Not required in cross-exchange mode; required in single-exchange mode (BINANCE/OKX/GATE/BYBIT) ⋮---- -export interface CloseCrossExPositionResp { - order_id: string; // Order ID - text: string; // User-defined Order ID +export interface SetCrossExPositionLeverageReq { + symbol: string; // Currency pair + leverage: string; // leverage } ⋮---- -order_id: string; // Order ID -text: string; // User-defined Order ID +symbol: string; // Currency pair +leverage: string; // leverage ⋮---- -export interface CrossExInterestRate { - coin: string; // Currency - exchange_type: string; // Exchange - hour_interest_rate: string; // Hourly Interest Rate - time: string; // Millisecond Timestamp +export interface GetCrossExPositionLeverageReq { + symbols?: string; // Trading Pair List, multiple separated by commas } ⋮---- -coin: string; // Currency -exchange_type: string; // Exchange -hour_interest_rate: string; // Hourly Interest Rate -time: string; // Millisecond Timestamp +symbols?: string; // Trading Pair List, multiple separated by commas ⋮---- -export interface CrossExSpecialFee { +export interface SetCrossExMarginPositionLeverageReq { symbol: string; // Currency pair - taker_fee_rate: string; // Taker fee rate - maker_fee_rate: string; // Maker fee rate - rpi_fee_rate?: string; // RPI order maker fee rate + leverage: string; // leverage } ⋮---- symbol: string; // Currency pair -taker_fee_rate: string; // Taker fee rate -maker_fee_rate: string; // Maker fee rate -rpi_fee_rate?: string; // RPI order maker fee rate +leverage: string; // leverage ⋮---- -export interface CrossExFeeRate { - exchange_type: string; // Exchange (e.g. BINANCE, OKX, GATE, BYBIT) - spot_maker_fee: string; // spot Maker fee rate - spot_taker_fee: string; // spot Taker fee rate - spot_rpi_maker_fee?: string; // Spot RPI order maker fee rate - future_maker_fee: string; // contract Maker fee rate - future_taker_fee: string; // contract Taker fee rate - future_rpi_maker_fee?: string; // Futures RPI order maker fee rate - special_fee_list: CrossExSpecialFee[]; +export interface GetCrossExMarginPositionLeverageReq { + symbols?: string; // Trading Pair List, multiple separated by commas } ⋮---- -exchange_type: string; // Exchange (e.g. BINANCE, OKX, GATE, BYBIT) -spot_maker_fee: string; // spot Maker fee rate -spot_taker_fee: string; // spot Taker fee rate -spot_rpi_maker_fee?: string; // Spot RPI order maker fee rate -future_maker_fee: string; // contract Maker fee rate -future_taker_fee: string; // contract Taker fee rate -future_rpi_maker_fee?: string; // Futures RPI order maker fee rate -⋮---- -export interface CrossExMarketTicker { - symbol: string; - last_price: string; - open_24h: string; - low_24h: string; - high_24h: string; - volume_24h_base: string; - volume_24h_quote: string; - mark_price: string; - index_price: string; - open_interest: string; - open_interest_quote: string; - timestamp: string; -} +symbols?: string; // Trading Pair List, multiple separated by commas ⋮---- -export interface CrossExMarketFundingInfo { - symbol: string; - funding_rate: string; - funding_interval: string; - funding_time: string; // Next funding time +export interface CloseCrossExPositionReq { + symbol: string; // Trading Pair + position_side?: string; // Position Direction } ⋮---- -funding_time: string; // Next funding time +symbol: string; // Trading Pair +position_side?: string; // Position Direction ⋮---- -export interface CancelBatchCrossExOrdersResp { - order_id: string; - text: string; - accepted: string; // "true" | "false" - label: string; - message: string; +export interface GetCrossExInterestRateReq { + coin?: string; // Currency + exchange_type?: string; // Exchange } ⋮---- -accepted: string; // "true" | "false" +coin?: string; // Currency +exchange_type?: string; // Exchange ⋮---- -export interface CrossExPosition { - user_id: string; // User ID - position_id: string; // Position ID - symbol: string; // Currency pair - position_side: string; // Position Direction - initial_margin: string; // Initial Margin - maintenance_margin: string; // Maintenance margin - position_qty: string; // Position Quantity - position_value: string; // Position Value - upnl: string; // Unrealized P&L - upnl_rate: string; // Unrealized P&L Ratio - entry_price: string; // Position Average Entry Price - mark_price: string; // Mark price - leverage: string; // Position Leverage - max_leverage: string; // Maximum leverage - risk_limit: string; // Position risk limit - fee: string; // Position Fee - funding_fee: string; // Position Funding Fee - funding_time: string; // Position funding fee collection time (0 indicates it has not been collected yet) - create_time: string; // Position Creation Time - update_time: string; // Position Update Time - closed_pnl: string; // Realized PnL +export interface GetCrossExPositionsReq { + symbol?: string; // Trading Pair + exchange_type?: string; // Exchange } ⋮---- -user_id: string; // User ID -position_id: string; // Position ID -symbol: string; // Currency pair -position_side: string; // Position Direction -initial_margin: string; // Initial Margin -maintenance_margin: string; // Maintenance margin -position_qty: string; // Position Quantity -position_value: string; // Position Value -upnl: string; // Unrealized P&L -upnl_rate: string; // Unrealized P&L Ratio -entry_price: string; // Position Average Entry Price -mark_price: string; // Mark price -leverage: string; // Position Leverage -max_leverage: string; // Maximum leverage -risk_limit: string; // Position risk limit -fee: string; // Position Fee -funding_fee: string; // Position Funding Fee -funding_time: string; // Position funding fee collection time (0 indicates it has not been collected yet) -create_time: string; // Position Creation Time -update_time: string; // Position Update Time -closed_pnl: string; // Realized PnL +symbol?: string; // Trading Pair +exchange_type?: string; // Exchange ⋮---- -export interface CrossExMarginPosition { - user_id: string; // User ID - position_id: string; // Leveraged Position ID - symbol: string; // Trading Pair - position_side: string; // Position Direction - initial_margin: string; // Initial position margin - maintenance_margin: string; // Position maintenance margin - asset_qty: string; // Position Asset Quantity - asset_coin: string; // Position Asset Currency - position_value: string; // Position Value - liability: string; // Debt Quantity - liability_coin: string; // Debt Currency - interest: string; // Deducted Interest - max_position_qty: string; // Max Trade Size - entry_price: string; // Position Cost Price (Average Opening Price) - index_price: string; // Index price - upnl: string; // Unrealized P&L - upnl_rate: string; // Unrealized P&L Ratio - leverage: string; // Opening Leverage - max_leverage: string; // Maximum leverage - create_time: string; // Created time - update_time: string; // Update time +export interface GetCrossExMarginPositionsReq { + symbol?: string; // Currency pair + exchange_type?: string; // Exchange +} +⋮---- +symbol?: string; // Currency pair +exchange_type?: string; // Exchange +⋮---- +export interface GetCrossExAdlRankReq { + symbol: string; // Trading Pair } ⋮---- -user_id: string; // User ID -position_id: string; // Leveraged Position ID symbol: string; // Trading Pair -position_side: string; // Position Direction -initial_margin: string; // Initial position margin -maintenance_margin: string; // Position maintenance margin -asset_qty: string; // Position Asset Quantity -asset_coin: string; // Position Asset Currency -position_value: string; // Position Value -liability: string; // Debt Quantity -liability_coin: string; // Debt Currency -interest: string; // Deducted Interest -max_position_qty: string; // Max Trade Size -entry_price: string; // Position Cost Price (Average Opening Price) -index_price: string; // Index price -upnl: string; // Unrealized P&L -upnl_rate: string; // Unrealized P&L Ratio -leverage: string; // Opening Leverage -max_leverage: string; // Maximum leverage -create_time: string; // Created time -update_time: string; // Update time ⋮---- -export interface CrossExAdlRank { - user_id: string; // User ID - symbol: string; // Currency pair - crossex_adl_rank: string; // CROSSEX position-reduction indicator ranking (1–5, higher value ranks higher) - exchange_adl_rank: string; // Original exchange information (Binance: 0–4, higher value ranks higher; OKX: 0–5, higher value ranks higher; Gate: 1–5, lower value ranks higher) +export interface GetCrossExOpenOrdersReq { + symbol?: string; // Trading Pair + exchange_type?: string; // Exchange + business_type?: string; // Business Type } ⋮---- -user_id: string; // User ID -symbol: string; // Currency pair -crossex_adl_rank: string; // CROSSEX position-reduction indicator ranking (1–5, higher value ranks higher) -exchange_adl_rank: string; // Original exchange information (Binance: 0–4, higher value ranks higher; OKX: 0–5, higher value ranks higher; Gate: 1–5, lower value ranks higher) +symbol?: string; // Trading Pair +exchange_type?: string; // Exchange +business_type?: string; // Business Type ⋮---- -export interface CrossExHistoryPosition { - position_id: string; // Position ID - user_id: string; // User ID - symbol: string; // Currency pair - closed_type: string; // Position close type (PARTIAL_CLOSED: partially closed; COMPLETE_CLOSED: fully closed) - closed_pnl: string; // Close Position P&L - closed_pnl_rate: string; // Close Position P&L Ratio - open_avg_price: string; // Average Opening Price - closed_avg_price: string; // Average Close Price - max_position_qty: string; // Max Trade Size - closed_qty: string; // Close Position Quantity - closed_value: string; // Close Position Value - fee: string; // Position Accumulated Fees - liq_fee: string; // Liquidation Fee - funding_fee: string; // Funding Fee - position_side: string; // Position Direction Before Close - position_mode: string; // Position Mode at Close - leverage: string; // Leverage at Close - margin_mode?: 'CROSS' | 'ISOLATED'; - business_type: string; // Business Type - create_time: string; // Created time - update_time: string; // Update time +export interface GetCrossExHistoryOrdersReq { + page?: number; // Page number + limit?: number; // Maximum number of records returned in a single list + symbol?: string; + from?: number; // Start Millisecond Timestamp + to?: number; // End Millisecond Timestamp + /** Comma-separated: COMMON, LIQ, REDUCE, ADL, SETTLEMENT */ + attributes?: string; } ⋮---- -position_id: string; // Position ID -user_id: string; // User ID -symbol: string; // Currency pair -closed_type: string; // Position close type (PARTIAL_CLOSED: partially closed; COMPLETE_CLOSED: fully closed) -closed_pnl: string; // Close Position P&L -closed_pnl_rate: string; // Close Position P&L Ratio -open_avg_price: string; // Average Opening Price -closed_avg_price: string; // Average Close Price -max_position_qty: string; // Max Trade Size -closed_qty: string; // Close Position Quantity -closed_value: string; // Close Position Value -fee: string; // Position Accumulated Fees -liq_fee: string; // Liquidation Fee -funding_fee: string; // Funding Fee -position_side: string; // Position Direction Before Close -position_mode: string; // Position Mode at Close -leverage: string; // Leverage at Close +page?: number; // Page number +limit?: number; // Maximum number of records returned in a single list ⋮---- -business_type: string; // Business Type -create_time: string; // Created time -update_time: string; // Update time +from?: number; // Start Millisecond Timestamp +to?: number; // End Millisecond Timestamp +/** Comma-separated: COMMON, LIQ, REDUCE, ADL, SETTLEMENT */ ⋮---- -export interface CrossExHistoryMarginPosition { - position_id: string; // Position ID - user_id: string; // User ID - symbol: string; // Currency pair - closed_type: string; // Position close type (PARTIAL_CLOSED: partially closed; COMPLETE_CLOSED: fully closed) - closed_pnl: string; // Close Position P&L - closed_pnl_rate: string; // Close Position P&L Ratio - open_avg_price: string; // Average Opening Price - closed_avg_price: string; // Average Close Price - max_position_qty: string; // Max Trade Size - closed_qty: string; // Close Position Quantity - closed_value: string; // Close Position Value - liq_fee: string; // Liquidation Fee - position_side: string; // Position Direction Before Close - leverage: string; // Leverage at Close - interest: string; // Total Deducted Interest - business_type: string; // Position Business Type - create_time: string; // Created time - update_time: string; // Update time +export interface GetCrossExHistoryPositionsReq { + page?: number; // Page number + limit?: number; // Maximum number returned by list, max 1000 + symbol?: string; + from?: number; // Start Millisecond Timestamp + to?: number; // End Millisecond Timestamp } ⋮---- -position_id: string; // Position ID -user_id: string; // User ID -symbol: string; // Currency pair -closed_type: string; // Position close type (PARTIAL_CLOSED: partially closed; COMPLETE_CLOSED: fully closed) -closed_pnl: string; // Close Position P&L -closed_pnl_rate: string; // Close Position P&L Ratio -open_avg_price: string; // Average Opening Price -closed_avg_price: string; // Average Close Price -max_position_qty: string; // Max Trade Size -closed_qty: string; // Close Position Quantity -closed_value: string; // Close Position Value -liq_fee: string; // Liquidation Fee -position_side: string; // Position Direction Before Close -leverage: string; // Leverage at Close -interest: string; // Total Deducted Interest -business_type: string; // Position Business Type -create_time: string; // Created time -update_time: string; // Update time +page?: number; // Page number +limit?: number; // Maximum number returned by list, max 1000 ⋮---- -export interface CrossExHistoryMarginInterest { - userId: string; // User ID - symbol: string; // Trading Pair - interest_id: string; // Interest Deduction ID - liability_id: string; // Debt Source ID, can be Order ID or Position ID - liability: string; // Debt Quantity - liability_coin: string; // Debt Currency - interest: string; // Interest - interest_rate: string; // interest rate - interest_type: string; // Interest deduction type (PERIODIC_POSITION: periodic position interest; PERIODIC_OPEN_ORDER: periodic open-order interest; PERIODIC_ISOLATED: hourly isolated debt interest; IMMEDIATE_OPEN_ORDER: interest charged on order opening) - create_time: string; // Created time - exchange_type: string; // Exchange +from?: number; // Start Millisecond Timestamp +to?: number; // End Millisecond Timestamp +⋮---- +export interface GetCrossExHistoryMarginPositionsReq { + page?: number; // Page number + limit?: number; // Maximum number returned by list, max 1000 + symbol?: string; + from?: number; // Start Millisecond Timestamp + to?: number; // End Millisecond Timestamp } ⋮---- -userId: string; // User ID -symbol: string; // Trading Pair -interest_id: string; // Interest Deduction ID -liability_id: string; // Debt Source ID, can be Order ID or Position ID -liability: string; // Debt Quantity -liability_coin: string; // Debt Currency -interest: string; // Interest -interest_rate: string; // interest rate -interest_type: string; // Interest deduction type (PERIODIC_POSITION: periodic position interest; PERIODIC_OPEN_ORDER: periodic open-order interest; PERIODIC_ISOLATED: hourly isolated debt interest; IMMEDIATE_OPEN_ORDER: interest charged on order opening) -create_time: string; // Created time -exchange_type: string; // Exchange +page?: number; // Page number +limit?: number; // Maximum number returned by list, max 1000 ⋮---- -export interface CrossExHistoryTrade { - user_id: string; // User ID - transaction_id: string; // filled records ID - order_id: string; // Order ID - text: string; // User Order ID - symbol: string; // Currency pair - exchange_type: string; // Exchange - business_type: string; // Business Type - side: string; // Buy/Sell Direction - qty: string; // Trading size - price: string; // Fill Price - fee: string; // fee - fee_coin: string; // Fee currency - fee_rate: string; // Fee Rate - match_role: string; // Filled Role - rpnl: string; // Realized P&L - position_mode: string; // Position Mode - position_side: string; // Position Direction - create_time: string; // Created time +from?: number; // Start Millisecond Timestamp +to?: number; // End Millisecond Timestamp +⋮---- +export interface GetCrossExHistoryMarginInterestsReq { + symbol?: string; + from?: number; + to?: number; + page?: number; + limit?: number; + exchange_type?: string; } ⋮---- -user_id: string; // User ID -transaction_id: string; // filled records ID -order_id: string; // Order ID -text: string; // User Order ID -symbol: string; // Currency pair -exchange_type: string; // Exchange -business_type: string; // Business Type -side: string; // Buy/Sell Direction -qty: string; // Trading size -price: string; // Fill Price -fee: string; // fee -fee_coin: string; // Fee currency -fee_rate: string; // Fee Rate -match_role: string; // Filled Role -rpnl: string; // Realized P&L -position_mode: string; // Position Mode -position_side: string; // Position Direction -create_time: string; // Created time +export interface GetCrossExHistoryTradesReq { + page?: number; // Page number + limit?: number; // Maximum number returned by list, max 1000 + symbol?: string; + from?: number; // Start Millisecond Timestamp + to?: number; // End Millisecond Timestamp +} ⋮---- -export interface CrossExAccountBook { - id: string; // Account Change Record ID - user_id: string; // User ID - business_id: string; // Business ID - type: string; // TRANSACTION, TRADING_FEE, FUNDING_FEE, LIQUIDATION_FEE, TRANSFER_IN, TRANSFER_OUT, BANKRUPT_COMPENSATION, AUTO_REPAY - exchange_type: string; // Exchange - coin: string; // Currency - change: string; // Change amount (positive indicates transfer in; negative indicates transfer out) - balance: string; // Balance after change - create_time: string; // Created time +page?: number; // Page number +limit?: number; // Maximum number returned by list, max 1000 +⋮---- +from?: number; // Start Millisecond Timestamp +to?: number; // End Millisecond Timestamp +⋮---- +export interface GetCrossExAccountBookReq { + page?: number; // Page number + limit?: number; // Maximum number returned by list, max 1000 + coin?: string; + from?: number; // Start Millisecond Timestamp + to?: number; // End Millisecond Timestamp } ⋮---- -id: string; // Account Change Record ID -user_id: string; // User ID -business_id: string; // Business ID -type: string; // TRANSACTION, TRADING_FEE, FUNDING_FEE, LIQUIDATION_FEE, TRANSFER_IN, TRANSFER_OUT, BANKRUPT_COMPENSATION, AUTO_REPAY -exchange_type: string; // Exchange -coin: string; // Currency -change: string; // Change amount (positive indicates transfer in; negative indicates transfer out) -balance: string; // Balance after change -create_time: string; // Created time +page?: number; // Page number +limit?: number; // Maximum number returned by list, max 1000 +⋮---- +from?: number; // Start Millisecond Timestamp +to?: number; // End Millisecond Timestamp ⋮---- -export interface CrossExCoinDiscountRate { - coin: string; // Currency - exchange_type: string; // Exchange - tier: string; // Tier - min_value: string; // Minimum value - max_value: string; // Maximum value - discount_rate: string; // Discount rate +export interface GetCrossExCoinDiscountRateReq { + coin?: string; + exchange_type?: string; // OKX/GATE/BINANCE/BYBIT } ⋮---- -coin: string; // Currency -exchange_type: string; // Exchange -tier: string; // Tier -min_value: string; // Minimum value -max_value: string; // Maximum value -discount_rate: string; // Discount rate +exchange_type?: string; // OKX/GATE/BINANCE/BYBIT ⋮---- -export interface UpdateCrossExPositionsMarginResp { - symbol?: string; - margin?: string; +export interface UpdateCrossExPositionsMarginReq { + symbol: string; + margin: string; position_side?: 'NONE' | 'LONG' | 'SHORT'; } ================ -File: src/types/response/earn.ts +File: src/types/response/crossex.ts ================ /**========================================================================================================================== - * EARN + * CROSSEX * ========================================================================================================================== */ ⋮---- -export interface DualInvestmentProduct { - id: number; - instrument_name: string; - invest_currency: string; - exercise_currency: string; - exercise_price: number; - delivery_time: number; - min_amount?: string; - min_copies: number; - max_copies: number; - /** @deprecated */ - per_value: string; - apy_display: string; - start_time: number; - end_time: number; - status: 'NOTSTARTED' | 'ONGOING' | 'ENDED'; +export interface CrossExSymbol { + symbol: string; + exchange_type: string; + business_type: string; + state: string; + min_size: string; + min_notional: string; + lot_size: string; + tick_size: string; + max_num_orders: string; + max_market_size: string; + max_limit_size: string; + contract_size: string; + liquidation_fee: string; + delist_time: string; + support_rpi?: string; // true/false whether RPI orders are supported + support_cross?: string; // "true"/"false" whether the symbol supports cross-margin orders } ⋮---- -/** @deprecated */ +support_rpi?: string; // true/false whether RPI orders are supported +support_cross?: string; // "true"/"false" whether the symbol supports cross-margin orders ⋮---- -/** GET /earn/dual/order-refund-preview */ -export interface DualOrderRefundPreview { - create_timest: number; - delivery_timest: number; - exercise_price: string; - invest_amount: string; - invest_currency: string; - name: string; - order_id: number; - req_id: string; - refund_service_charge: number; - settle_price: string; - settlement_amount: string; - settlement_currency: string; - settlement_interest: string; - settlement_principle: string; - type: string; - money_back_timest: number; +export interface CrossExRiskLimitTier { + min_risk_limit_value: string; // Minimum risk limit value + max_risk_limit_value: string; // Maximum risk limit value + leverage_max: string; // Maximum leverage + maintenance_rate: string; // Maintenance margin rate + tier: string; // Tier + quick_cal_amount: string; // Quick-calculation amount for this risk tier } ⋮---- -/** GET /earn/dual/project-recommend item */ -export interface DualProjectRecommend { - id: number; - category: number; - type: string; - invest_currency: string; - exercise_currency: string; - apy_display: string; - exercise_price: string; - delivery_timest: number; - min_amount: string; - max_amount: string; - min_copies: number; - max_copies: number; - invest_days: number; - invest_hours: string; +min_risk_limit_value: string; // Minimum risk limit value +max_risk_limit_value: string; // Maximum risk limit value +leverage_max: string; // Maximum leverage +maintenance_rate: string; // Maintenance margin rate +tier: string; // Tier +quick_cal_amount: string; // Quick-calculation amount for this risk tier +⋮---- +export interface CrossExRiskLimit { + symbol: string; + tiers: CrossExRiskLimitTier[]; } ⋮---- -export interface DualInvestmentOrder { - id: number; - plan_id: number; - copies: string; - invest_amount: string; - settlement_amount: string; - create_time: number; - complete_time: number; - status: - | 'INIT' - | 'SETTLEMENT_SUCCESS' - | 'SETTLEMENT_PROCESSING' - | 'CANCELED' - | 'FAILED'; - invest_currency: string; - exercise_currency: string; - exercise_price: string; - settlement_price: string; - settlement_currency: string; - apy_display: string; - apy_settlement: string; - delivery_time: number; +export interface CrossExTransferCoin { + coin: string; // Currency + min_trans_amount: number; // Minimum Transfer Quantity (including estimated fees) + est_fee: number; // Estimated Fee + precision: number; // Precision + is_disabled: number; // If it is disabled. 0 means NOT being disabled +} +⋮---- +coin: string; // Currency +min_trans_amount: number; // Minimum Transfer Quantity (including estimated fees) +est_fee: number; // Estimated Fee +precision: number; // Precision +is_disabled: number; // If it is disabled. 0 means NOT being disabled +⋮---- +export interface CreateCrossExTransferResp { + tx_id: string; // Order ID + text: string; // User-defined Order ID +} +⋮---- +tx_id: string; // Order ID +text: string; // User-defined Order ID +⋮---- +export interface CrossExTransferHistory { + id: string; // Order ID + text: string; // Client Custom ID + from_account_type: string; // Source from account (CROSSEX_BINANCE, CROSSEX_OKX, CROSSEX_GATE, CROSSEX_BYBIT, CROSSEX, SPOT) + to_account_type: string; + coin: string; // Currency + amount: string; // Transfer amount, the amount requested for the transfer + actual_receive: string; // Actual credited amount (has a value when status = SUCCESS; empty for other statuses) + status: string; // Transfer Status - FAIL: Failed, SUCCESS: Successful, PENDING: Transfer in Progress + fail_reason: string; // Failure reason (has a value when status = FAIL; empty for other statuses) + create_time: number; // Creation time of order + update_time: number; // Order Update Time +} +⋮---- +id: string; // Order ID +text: string; // Client Custom ID +from_account_type: string; // Source from account (CROSSEX_BINANCE, CROSSEX_OKX, CROSSEX_GATE, CROSSEX_BYBIT, CROSSEX, SPOT) +⋮---- +coin: string; // Currency +amount: string; // Transfer amount, the amount requested for the transfer +actual_receive: string; // Actual credited amount (has a value when status = SUCCESS; empty for other statuses) +status: string; // Transfer Status - FAIL: Failed, SUCCESS: Successful, PENDING: Transfer in Progress +fail_reason: string; // Failure reason (has a value when status = FAIL; empty for other statuses) +create_time: number; // Creation time of order +update_time: number; // Order Update Time +⋮---- +export interface CreateCrossExOrderResp { + order_id: number | string; + text: string; // User-defined Order ID +} +⋮---- +text: string; // User-defined Order ID +⋮---- +export interface CancelCrossExOrderResp { + order_id: number; text: string; } ⋮---- -/**========================================================================================================================== - * EARN FIXED-TERM - * ========================================================================================================================== - */ +export interface ModifyCrossExOrderResp { + order_id: number; + text: string; +} +⋮---- +export interface CrossExOrder { + user_id: string; // User ID + order_id: string; // Order ID + text: string; // Client Order ID + state: string; // Order Status + symbol: string; // Currency pair + side: string; // direction + type: string; // type + attribute: string; // COMMON, LIQ, REDUCE, ADL, SETTLEMENT + exchange_type: string; // Exchange + business_type: string; // Business Type + qty: string; // Base Currency Quantity + quote_qty: string; // Quote Currency Quantity + price: string; // Price + time_in_force: string; // Time in Force Strategy + executed_qty: string; // Filled Quantity + executed_amount: string; // Filled Amount + executed_avg_price: string; // Average Filled Price + fee_coin: string; // Fee currency + fee: string; // fee + reduce_only: string; // Reduce Position Only + leverage: string; // leverage + reason: string; // Reason + last_executed_qty: string; // Latest Filled Quantity + last_executed_price: string; // Latest Filled Price + last_executed_amount: string; // Latest Filled Amount + position_side: string; // Position Direction + create_time: string; // Created time + update_time: string; // Update time +} +⋮---- +user_id: string; // User ID +order_id: string; // Order ID +text: string; // Client Order ID +state: string; // Order Status +symbol: string; // Currency pair +side: string; // direction +type: string; // type +attribute: string; // COMMON, LIQ, REDUCE, ADL, SETTLEMENT +exchange_type: string; // Exchange +business_type: string; // Business Type +qty: string; // Base Currency Quantity +quote_qty: string; // Quote Currency Quantity +price: string; // Price +time_in_force: string; // Time in Force Strategy +executed_qty: string; // Filled Quantity +executed_amount: string; // Filled Amount +executed_avg_price: string; // Average Filled Price +fee_coin: string; // Fee currency +fee: string; // fee +reduce_only: string; // Reduce Position Only +leverage: string; // leverage +reason: string; // Reason +last_executed_qty: string; // Latest Filled Quantity +last_executed_price: string; // Latest Filled Price +last_executed_amount: string; // Latest Filled Amount +position_side: string; // Position Direction +create_time: string; // Created time +update_time: string; // Update time ⋮---- -export interface FixedTermLadderApr { - apr: string; - left: string; - right: string; +export interface CreateCrossExConvertQuoteResp { + quote_id: string; // Quote ID + valid_ms: string; // Valid time (milliseconds timestamp) + from_coin: string; // Asset Sold + to_coin: string; // Asset Bought + from_amount: string; // Amount to sell + to_amount: string; // Amount to buy + price: string; // Price } ⋮---- -export interface FixedTermProductInfo { - pre_redeem: number; - reinvest: number; - redeem_account: number; - min_vip: number; - max_vip: number; -} +quote_id: string; // Quote ID +valid_ms: string; // Valid time (milliseconds timestamp) +from_coin: string; // Asset Sold +to_coin: string; // Asset Bought +from_amount: string; // Amount to sell +to_amount: string; // Amount to buy +price: string; // Price ⋮---- -export interface FixedTermBonusInfo { - id?: number; - product_id?: number; - asset?: string; - bonus_asset?: string; - kyc_limit?: string; - ladder_apr?: FixedTermLadderApr[]; - total_bonus_amount?: string; - user_total_bonus_amount?: string; - status?: number; - start_time?: string; - end_time?: string; - create_time?: string; - start_at?: number; - end_at?: number; - total_issued_amount?: string; - user_total_issued_amount?: string; - bonus_asset_price?: string; - product_asset_price?: string; - product_year_rate?: string; +export interface CreateCrossExConvertOrderResp { + order_id: string; // Order ID + text: string; // User-defined order ID text } ⋮---- -export interface FixedTermCouponInfo { - id?: number; - business?: number; - user_id?: number; - asset?: string; - order_id?: number; - financial_rate_id?: number; - buy_limit_low?: string; - buy_limit_high?: string; - rate_day?: number; - rate_ratio?: string; - coupon_days?: number; - coupon_principal?: string; - coupon_year_rate?: string; - coupon_interest?: string; - status?: number; - finish_time?: string; - create_time?: string; -} +order_id: string; // Order ID +text: string; // User-defined order ID text ⋮---- -export interface FixedTermLendOrder { - id?: number; - business?: number; - order_id?: number; - user_id?: number; - asset?: string; - product_id?: number; - lock_up_period?: number; - principal?: string; - year_rate?: string; - product_type?: number; - interest?: string; - status?: number; - reinvest_status?: number; - redeem_account_type?: number; - origin_order?: string; - redeem_type?: number; - redeem_time?: string; - finish_time?: string; - create_time?: string; - year_rate_perent?: string; - total_year_rate_percent?: string; - total_interest?: string; - product_info?: FixedTermProductInfo; - bonus_info?: FixedTermBonusInfo; - coupon_info?: FixedTermCouponInfo; - redeem_at?: number; - finish_at?: number; - create_at?: number; - icon?: string; +export interface UpdateCrossExAccountResp { + position_mode: string; // Requested futures position mode to modify (SINGLE/DUAL) + account_mode: string; // Requested account mode to modify (CROSS_EXCHANGE/ISOLATED_EXCHANGE, default: CROSS_EXCHANGE) + exchange_type: string; // Requested exchange to modify (BINANCE/OKX/GATE/BYBIT/CROSSEX) } ⋮---- -export interface FixedTermProduct { - id?: number; - name?: string; - asset?: string; - lock_up_period?: number; - min_lend_amount?: string; - user_max_lend_amount?: string; - total_lend_amount?: string; - year_rate?: string; - type?: number; - pre_redeem?: number; - reinvest?: number; - redeem_account?: number; - min_vip?: number; - max_vip?: number; - status?: number; - create_time?: string; - user_max_lend_volume?: string; - user_total_amount?: string; - sale_status?: number; -} +position_mode: string; // Requested futures position mode to modify (SINGLE/DUAL) +account_mode: string; // Requested account mode to modify (CROSS_EXCHANGE/ISOLATED_EXCHANGE, default: CROSS_EXCHANGE) +exchange_type: string; // Requested exchange to modify (BINANCE/OKX/GATE/BYBIT/CROSSEX) ⋮---- -export interface FixedTermProductSimple { - id?: number; - asset?: string; - lock_up_period?: number; - year_rate?: string; - type?: number; - pre_redeem?: number; - reinvest?: number; - simple_earn?: number; - min_vip?: number; - max_vip?: number; - sale_status?: number; +export interface CrossExAccountAsset { + user_id: string; // User ID + coin: string; // Currency + exchange_type: string; // Exchange + balance: string; // Balance + upnl: string; // Unrealized P&L + equity: string; // Equity (only USDT has a value; other assets are 0) + futures_initial_margin: string; // Futures initial margin (only USDT has a value; other assets are 0) + futures_maintenance_margin: string; // Futures maintenance margin (only USDT has a value; other assets are 0) + borrowing_initial_margin: string; // Margin trading initial margin (only USDT has a value; other assets are 0) + borrowing_maintenance_margin: string; // Margin trading maintenance margin (only USDT has a value; other assets are 0) + available_balance: string; // Available Balance + liability: string; // Liabilities (only meaningful in isolated exchange mode; always 0 in cross-exchange mode) } ⋮---- -export interface GetEarnFixedTermProductsResponse { - code: number; - message: string; - data: { - list: FixedTermProduct[]; - total: number; - }; - timestamp: number; -} +user_id: string; // User ID +coin: string; // Currency +exchange_type: string; // Exchange +balance: string; // Balance +upnl: string; // Unrealized P&L +equity: string; // Equity (only USDT has a value; other assets are 0) +futures_initial_margin: string; // Futures initial margin (only USDT has a value; other assets are 0) +futures_maintenance_margin: string; // Futures maintenance margin (only USDT has a value; other assets are 0) +borrowing_initial_margin: string; // Margin trading initial margin (only USDT has a value; other assets are 0) +borrowing_maintenance_margin: string; // Margin trading maintenance margin (only USDT has a value; other assets are 0) +available_balance: string; // Available Balance +liability: string; // Liabilities (only meaningful in isolated exchange mode; always 0 in cross-exchange mode) ⋮---- -export interface GetEarnFixedTermProductsByAssetResponse { - code: number; - message: string; - data: { - list: FixedTermProductSimple[]; - }; - timestamp: number; +export interface CrossExAccount { + user_id: string; // User ID + available_margin: string; // Available Margin + margin_balance: string; // margin balance + initial_margin: string; // Initial Margin + maintenance_margin: string; // Maintenance margin + initial_margin_rate: string; // Initial margin rate + maintenance_margin_rate: string; // Maintenance margin rate + position_mode: string; // Contract Position Mode + account_limit: string; // Account limit + create_time: string; // Created time + update_time: string; // Update time + account_mode: string; // Account mode. CROSS_EXCHANGE: cross-exchange mode. ISOLATED_EXCHANGE: isolated exchange mode + exchange_type: string; // Exchange type. When account_mode is CROSS_EXCHANGE, this must be CROSSEX; otherwise, it represents a specific exchange + assets: CrossExAccountAsset[]; } ⋮---- -export interface CreateEarnFixedTermLendResponse { - code?: number; - message?: string; - data?: { - order_id?: number; - }; - timestamp?: number; -} +user_id: string; // User ID +available_margin: string; // Available Margin +margin_balance: string; // margin balance +initial_margin: string; // Initial Margin +maintenance_margin: string; // Maintenance margin +initial_margin_rate: string; // Initial margin rate +maintenance_margin_rate: string; // Maintenance margin rate +position_mode: string; // Contract Position Mode +account_limit: string; // Account limit +create_time: string; // Created time +update_time: string; // Update time +account_mode: string; // Account mode. CROSS_EXCHANGE: cross-exchange mode. ISOLATED_EXCHANGE: isolated exchange mode +exchange_type: string; // Exchange type. When account_mode is CROSS_EXCHANGE, this must be CROSSEX; otherwise, it represents a specific exchange ⋮---- -export interface GetEarnFixedTermLendsResponse { - code: number; - message: string; - data: { - list: FixedTermLendOrder[]; - total: number; - }; - timestamp: number; +export interface SetCrossExPositionLeverageResp { + symbol: string; // Currency pair + leverage: string; // Requested Modified Leverage } ⋮---- -export interface CreateEarnFixedTermPreRedeemResponse { - code?: number; - message?: string; - data?: Record; - timestamp?: number; +symbol: string; // Currency pair +leverage: string; // Requested Modified Leverage +⋮---- +export interface CrossExPositionLeverage { + symbol: string; // Currency pair + leverage: number | string; } ⋮---- -export interface FixedTermHistoryRecord { - id?: number; - order_id?: number; - user_id?: number; - asset?: string; - uniq_time?: string; - bonus_id?: number; - product_id?: number; - bonus_asset?: string; - total_principal?: string; - amount?: string; - asset_price?: string; - status?: number; - detail?: string; - create_time?: string; - create_at?: number; - lock_up_period?: number; -} +symbol: string; // Currency pair ⋮---- -export interface GetEarnFixedTermHistoryResponse { - code?: number; - message?: string; - data?: { - list?: FixedTermHistoryRecord[]; - total?: number; - }; - timestamp?: number; +export interface SetCrossExMarginPositionLeverageResp { + symbol: string; // Currency pair + leverage: string; // Requested Modified Leverage } - -================ -File: src/types/response/otc.ts -================ -/**========================================================================================================================== - * OTC - * ========================================================================================================================== - */ ⋮---- -export interface OTCActionResp { - code: number; - message: string; - timestamp: number; +symbol: string; // Currency pair +leverage: string; // Requested Modified Leverage +⋮---- +export interface CrossExMarginPositionLeverage { + symbol: string; // Currency pair + leverage: number | string; } ⋮---- -export interface CreateOTCQuoteResp { - code: number; - message: string; - data: { - type: string; // BUY (on-ramp) or SELL (off-ramp) - pay_coin: string; - get_coin: string; - pay_amount: string; - get_amount: string; - rate: string; - rate_reci: string; // Reciprocal of the exchange rate - promotion_code: string; - side: string; - order_type: string; // FIAT or STABLE - quote_token: string; // Quote token required when placing an order - url?: string; - memo?: string; - has_signature?: string; - validity_period?: string; - ex_rate?: string; - usdc_rate?: string; - is_need_file?: string; - gate_bank_id?: string; - gate_bank_name?: string; - refresh_limit?: number; - refresh_limit_msg?: string; - }; - timestamp: number; +symbol: string; // Currency pair +⋮---- +export interface CloseCrossExPositionResp { + order_id: string; // Order ID + text: string; // User-defined Order ID } ⋮---- -type: string; // BUY (on-ramp) or SELL (off-ramp) +order_id: string; // Order ID +text: string; // User-defined Order ID ⋮---- -rate_reci: string; // Reciprocal of the exchange rate +export interface CrossExInterestRate { + coin: string; // Currency + exchange_type: string; // Exchange + hour_interest_rate: string; // Hourly Interest Rate + time: string; // Millisecond Timestamp +} ⋮---- -order_type: string; // FIAT or STABLE -quote_token: string; // Quote token required when placing an order +coin: string; // Currency +exchange_type: string; // Exchange +hour_interest_rate: string; // Hourly Interest Rate +time: string; // Millisecond Timestamp ⋮---- -export type CreateOTCFiatOrderResp = OTCActionResp; +export interface CrossExSpecialFee { + symbol: string; // Currency pair + taker_fee_rate: string; // Taker fee rate + maker_fee_rate: string; // Maker fee rate + rpi_fee_rate?: string; // RPI order maker fee rate +} ⋮---- -export interface CreateOTCStablecoinOrderResp { - code: number; - message: string; - timestamp: number; +symbol: string; // Currency pair +taker_fee_rate: string; // Taker fee rate +maker_fee_rate: string; // Maker fee rate +rpi_fee_rate?: string; // RPI order maker fee rate +⋮---- +export interface CrossExFeeRate { + exchange_type: string; // Exchange (e.g. BINANCE, OKX, GATE, BYBIT) + spot_maker_fee: string; // spot Maker fee rate + spot_taker_fee: string; // spot Taker fee rate + spot_rpi_maker_fee?: string; // Spot RPI order maker fee rate + future_maker_fee: string; // contract Maker fee rate + future_taker_fee: string; // contract Taker fee rate + future_rpi_maker_fee?: string; // Futures RPI order maker fee rate + special_fee_list: CrossExSpecialFee[]; } ⋮---- -export interface OTCBankListItem { - id: string; // Bank ID (required for order placement) - bank_account_name: string; - bank_name: string; - bank_country?: string; - bank_address?: string; - bank_code?: string; - branch_code?: string; - iban?: string; - swift?: string; - remittance_line_number?: string; - agent_bank_name?: string; - agent_bank_swift?: string; - submit_time?: string; - update_time?: string; - status?: string; - documentation_file_type?: string; - memo?: string; - /** 1 = default bank card, 0 = not default */ - is_default?: 0 | 1; - bank_id?: string; - documentation_file_key_url?: string; +exchange_type: string; // Exchange (e.g. BINANCE, OKX, GATE, BYBIT) +spot_maker_fee: string; // spot Maker fee rate +spot_taker_fee: string; // spot Taker fee rate +spot_rpi_maker_fee?: string; // Spot RPI order maker fee rate +future_maker_fee: string; // contract Maker fee rate +future_taker_fee: string; // contract Taker fee rate +future_rpi_maker_fee?: string; // Futures RPI order maker fee rate +⋮---- +export interface CrossExMarketTicker { + symbol: string; + last_price: string; + open_24h: string; + low_24h: string; + high_24h: string; + volume_24h_base: string; + volume_24h_quote: string; + mark_price: string; + index_price: string; + open_interest: string; + open_interest_quote: string; + timestamp: string; } ⋮---- -id: string; // Bank ID (required for order placement) +export interface CrossExMarketFundingInfo { + symbol: string; + funding_rate: string; + funding_interval: string; + funding_time: string; // Next funding time +} ⋮---- -/** 1 = default bank card, 0 = not default */ +funding_time: string; // Next funding time ⋮---- -export interface GetOTCBankListResp { - code: number; +export interface CancelBatchCrossExOrdersResp { + order_id: string; + text: string; + accepted: string; // "true" | "false" + label: string; message: string; - data: { - lists: OTCBankListItem[]; - }; - timestamp: number; } ⋮---- -export interface CreateOTCBankResp { - code: number; - message: string; - data: { - bank_id: number; - status: number; - }; - timestamp?: number; +accepted: string; // "true" | "false" +⋮---- +export interface CrossExPosition { + user_id: string; // User ID + position_id: string; // Position ID + symbol: string; // Currency pair + position_side: string; // Position Direction + initial_margin: string; // Initial Margin + maintenance_margin: string; // Maintenance margin + position_qty: string; // Position Quantity + position_value: string; // Position Value + upnl: string; // Unrealized P&L + upnl_rate: string; // Unrealized P&L Ratio + entry_price: string; // Position Average Entry Price + mark_price: string; // Mark price + leverage: string; // Position Leverage + max_leverage: string; // Maximum leverage + risk_limit: string; // Position risk limit + fee: string; // Position Fee + funding_fee: string; // Position Funding Fee + funding_time: string; // Position funding fee collection time (0 indicates it has not been collected yet) + create_time: string; // Position Creation Time + update_time: string; // Position Update Time + closed_pnl: string; // Realized PnL +} +⋮---- +user_id: string; // User ID +position_id: string; // Position ID +symbol: string; // Currency pair +position_side: string; // Position Direction +initial_margin: string; // Initial Margin +maintenance_margin: string; // Maintenance margin +position_qty: string; // Position Quantity +position_value: string; // Position Value +upnl: string; // Unrealized P&L +upnl_rate: string; // Unrealized P&L Ratio +entry_price: string; // Position Average Entry Price +mark_price: string; // Mark price +leverage: string; // Position Leverage +max_leverage: string; // Maximum leverage +risk_limit: string; // Position risk limit +fee: string; // Position Fee +funding_fee: string; // Position Funding Fee +funding_time: string; // Position funding fee collection time (0 indicates it has not been collected yet) +create_time: string; // Position Creation Time +update_time: string; // Position Update Time +closed_pnl: string; // Realized PnL +⋮---- +export interface CrossExMarginPosition { + user_id: string; // User ID + position_id: string; // Leveraged Position ID + symbol: string; // Trading Pair + position_side: string; // Position Direction + initial_margin: string; // Initial position margin + maintenance_margin: string; // Position maintenance margin + asset_qty: string; // Position Asset Quantity + asset_coin: string; // Position Asset Currency + position_value: string; // Position Value + liability: string; // Debt Quantity + liability_coin: string; // Debt Currency + interest: string; // Deducted Interest + max_position_qty: string; // Max Trade Size + entry_price: string; // Position Cost Price (Average Opening Price) + index_price: string; // Index price + upnl: string; // Unrealized P&L + upnl_rate: string; // Unrealized P&L Ratio + leverage: string; // Opening Leverage + max_leverage: string; // Maximum leverage + create_time: string; // Created time + update_time: string; // Update time } ⋮---- -export interface OTCBankSupplementChecklistItem { - description: string; - code?: string; - zh?: string; - en?: string; - required?: boolean; -} +user_id: string; // User ID +position_id: string; // Leveraged Position ID +symbol: string; // Trading Pair +position_side: string; // Position Direction +initial_margin: string; // Initial position margin +maintenance_margin: string; // Position maintenance margin +asset_qty: string; // Position Asset Quantity +asset_coin: string; // Position Asset Currency +position_value: string; // Position Value +liability: string; // Debt Quantity +liability_coin: string; // Debt Currency +interest: string; // Deducted Interest +max_position_qty: string; // Max Trade Size +entry_price: string; // Position Cost Price (Average Opening Price) +index_price: string; // Index price +upnl: string; // Unrealized P&L +upnl_rate: string; // Unrealized P&L Ratio +leverage: string; // Opening Leverage +max_leverage: string; // Maximum leverage +create_time: string; // Created time +update_time: string; // Update time ⋮---- -export interface GetOTCBankSupplementChecklistResp { - code: number; - message: string; - data: { - user_type: 'personal' | 'enterprise'; - items: OTCBankSupplementChecklistItem[]; - }; - timestamp?: number; +export interface CrossExAdlRank { + user_id: string; // User ID + symbol: string; // Currency pair + crossex_adl_rank: string; // CROSSEX position-reduction indicator ranking (1–5, higher value ranks higher) + exchange_adl_rank: string; // Original exchange information (Binance: 0–4, higher value ranks higher; OKX: 0–5, higher value ranks higher; Gate: 1–5, lower value ranks higher) } ⋮---- -export type MarkOTCOrderAsPaidResp = OTCActionResp; -⋮---- -export type CancelOTCOrderResp = OTCActionResp; +user_id: string; // User ID +symbol: string; // Currency pair +crossex_adl_rank: string; // CROSSEX position-reduction indicator ranking (1–5, higher value ranks higher) +exchange_adl_rank: string; // Original exchange information (Binance: 0–4, higher value ranks higher; OKX: 0–5, higher value ranks higher; Gate: 1–5, lower value ranks higher) ⋮---- -export interface OTCFiatOrderListItem { - time: string; // Current time - timestamp: number; // Current timestamp - order_id: string; - trade_no: string; // Trade number - type: string; // Quote direction buy/sell/all - status: string; // Order Status (includes DISBURSED) - db_status: string; - fiat_currency: string; // Fiat type - fiat_currency_info: { - name: string; - icon: string; - }; - fiat_amount: string; // Fiat amount - crypto_currency: string; // Stablecoin - crypto_currency_info: { - name: string; - icon: string; - }; - crypto_amount: string; // Stablecoin amount - rate: string; // Exchange rate - transfer_remark: string; // Remark; empty when reference_code is set (v4.106.95) - reference_code?: string; // v4.106.95: Unique bank transfer reference code for SGB deposit buy orders - gate_bank_account_iban: string; // Bank account - promotion_code: string; // Promotion code +export interface CrossExHistoryPosition { + position_id: string; // Position ID + user_id: string; // User ID + symbol: string; // Currency pair + closed_type: string; // Position close type (PARTIAL_CLOSED: partially closed; COMPLETE_CLOSED: fully closed) + closed_pnl: string; // Close Position P&L + closed_pnl_rate: string; // Close Position P&L Ratio + open_avg_price: string; // Average Opening Price + closed_avg_price: string; // Average Close Price + max_position_qty: string; // Max Trade Size + closed_qty: string; // Close Position Quantity + closed_value: string; // Close Position Value + fee: string; // Position Accumulated Fees + liq_fee: string; // Liquidation Fee + funding_fee: string; // Funding Fee + position_side: string; // Position Direction Before Close + position_mode: string; // Position Mode at Close + leverage: string; // Leverage at Close + margin_mode?: 'CROSS' | 'ISOLATED'; + business_type: string; // Business Type + create_time: string; // Created time + update_time: string; // Update time } ⋮---- -time: string; // Current time -timestamp: number; // Current timestamp -⋮---- -trade_no: string; // Trade number -type: string; // Quote direction buy/sell/all -status: string; // Order Status (includes DISBURSED) -⋮---- -fiat_currency: string; // Fiat type -⋮---- -fiat_amount: string; // Fiat amount -crypto_currency: string; // Stablecoin -⋮---- -crypto_amount: string; // Stablecoin amount -rate: string; // Exchange rate -transfer_remark: string; // Remark; empty when reference_code is set (v4.106.95) -reference_code?: string; // v4.106.95: Unique bank transfer reference code for SGB deposit buy orders -gate_bank_account_iban: string; // Bank account -promotion_code: string; // Promotion code +position_id: string; // Position ID +user_id: string; // User ID +symbol: string; // Currency pair +closed_type: string; // Position close type (PARTIAL_CLOSED: partially closed; COMPLETE_CLOSED: fully closed) +closed_pnl: string; // Close Position P&L +closed_pnl_rate: string; // Close Position P&L Ratio +open_avg_price: string; // Average Opening Price +closed_avg_price: string; // Average Close Price +max_position_qty: string; // Max Trade Size +closed_qty: string; // Close Position Quantity +closed_value: string; // Close Position Value +fee: string; // Position Accumulated Fees +liq_fee: string; // Liquidation Fee +funding_fee: string; // Funding Fee +position_side: string; // Position Direction Before Close +position_mode: string; // Position Mode at Close +leverage: string; // Leverage at Close ⋮---- -export interface GetOTCFiatOrderListResp { - code: number; - message: string; - data: { - pn: number; - ps: number; - total_pn: number; - count: number; - list: OTCFiatOrderListItem[]; - }; -} +business_type: string; // Business Type +create_time: string; // Created time +update_time: string; // Update time ⋮---- -export interface OTCStablecoinOrderListItem { - id: number; // Order ID - trade_no: string; // Transaction reference number - pay_coin: string; // Payment currency - pay_amount: string; // Payment amount - get_coin: string; // Received currency - get_amount: string; // Received amount - rate: string; // Exchange rate - rate_reci: string; // Reciprocal of the exchange rate - status: string; // PROCESSING: in progress / DONE: completed / FAILED: failed - create_timest: number; // Timestamp +export interface CrossExHistoryMarginPosition { + position_id: string; // Position ID + user_id: string; // User ID + symbol: string; // Currency pair + closed_type: string; // Position close type (PARTIAL_CLOSED: partially closed; COMPLETE_CLOSED: fully closed) + closed_pnl: string; // Close Position P&L + closed_pnl_rate: string; // Close Position P&L Ratio + open_avg_price: string; // Average Opening Price + closed_avg_price: string; // Average Close Price + max_position_qty: string; // Max Trade Size + closed_qty: string; // Close Position Quantity + closed_value: string; // Close Position Value + liq_fee: string; // Liquidation Fee + position_side: string; // Position Direction Before Close + leverage: string; // Leverage at Close + interest: string; // Total Deducted Interest + business_type: string; // Position Business Type create_time: string; // Created time - pay_icon?: string; - get_icon?: string; + update_time: string; // Update time } ⋮---- -id: number; // Order ID -trade_no: string; // Transaction reference number -pay_coin: string; // Payment currency -pay_amount: string; // Payment amount -get_coin: string; // Received currency -get_amount: string; // Received amount -rate: string; // Exchange rate -rate_reci: string; // Reciprocal of the exchange rate -status: string; // PROCESSING: in progress / DONE: completed / FAILED: failed -create_timest: number; // Timestamp +position_id: string; // Position ID +user_id: string; // User ID +symbol: string; // Currency pair +closed_type: string; // Position close type (PARTIAL_CLOSED: partially closed; COMPLETE_CLOSED: fully closed) +closed_pnl: string; // Close Position P&L +closed_pnl_rate: string; // Close Position P&L Ratio +open_avg_price: string; // Average Opening Price +closed_avg_price: string; // Average Close Price +max_position_qty: string; // Max Trade Size +closed_qty: string; // Close Position Quantity +closed_value: string; // Close Position Value +liq_fee: string; // Liquidation Fee +position_side: string; // Position Direction Before Close +leverage: string; // Leverage at Close +interest: string; // Total Deducted Interest +business_type: string; // Position Business Type create_time: string; // Created time +update_time: string; // Update time ⋮---- -export interface GetOTCStablecoinOrderListResp { - code: number; - message: string; - data: { - total: number; - page_size: number; - page_number: number; - total_page: number; - list: OTCStablecoinOrderListItem[]; - }; +export interface CrossExHistoryMarginInterest { + userId: string; // User ID + symbol: string; // Trading Pair + interest_id: string; // Interest Deduction ID + liability_id: string; // Debt Source ID, can be Order ID or Position ID + liability: string; // Debt Quantity + liability_coin: string; // Debt Currency + interest: string; // Interest + interest_rate: string; // interest rate + interest_type: string; // Interest deduction type (PERIODIC_POSITION: periodic position interest; PERIODIC_OPEN_ORDER: periodic open-order interest; PERIODIC_ISOLATED: hourly isolated debt interest; IMMEDIATE_OPEN_ORDER: interest charged on order opening) + create_time: string; // Created time + exchange_type: string; // Exchange } ⋮---- -export interface OTCFiatOrderDetail { - order_id: string; // Order ID - uid: string; // User ID - type: string; // Order Type - fiat_currency: string; // Fiat type - fiat_amount: string; // Fiat amount - crypto_currency: string; // Stablecoin - crypto_amount: string; // Stablecoin amount - rate: string; // Exchange rate - transfer_remark: string; // Remark; empty when reference_code is set (v4.106.95) - reference_code?: string; // v4.106.95: Unique bank transfer reference code for SGB deposit buy orders - status: string; // Status - db_status: string; +userId: string; // User ID +symbol: string; // Trading Pair +interest_id: string; // Interest Deduction ID +liability_id: string; // Debt Source ID, can be Order ID or Position ID +liability: string; // Debt Quantity +liability_coin: string; // Debt Currency +interest: string; // Interest +interest_rate: string; // interest rate +interest_type: string; // Interest deduction type (PERIODIC_POSITION: periodic position interest; PERIODIC_OPEN_ORDER: periodic open-order interest; PERIODIC_ISOLATED: hourly isolated debt interest; IMMEDIATE_OPEN_ORDER: interest charged on order opening) +create_time: string; // Created time +exchange_type: string; // Exchange +⋮---- +export interface CrossExHistoryTrade { + user_id: string; // User ID + transaction_id: string; // filled records ID + order_id: string; // Order ID + text: string; // User Order ID + symbol: string; // Currency pair + exchange_type: string; // Exchange + business_type: string; // Business Type + side: string; // Buy/Sell Direction + qty: string; // Trading size + price: string; // Fill Price + fee: string; // fee + fee_coin: string; // Fee currency + fee_rate: string; // Fee Rate + match_role: string; // Filled Role + rpnl: string; // Realized P&L + position_mode: string; // Position Mode + position_side: string; // Position Direction create_time: string; // Created time - memo: string; // Cancellation or rejection reason - side: string; // Quote direction - promotion_code: string; // Promotion code - trade_no: string; // Trade number } ⋮---- +user_id: string; // User ID +transaction_id: string; // filled records ID order_id: string; // Order ID -uid: string; // User ID -type: string; // Order Type -fiat_currency: string; // Fiat type -fiat_amount: string; // Fiat amount -crypto_currency: string; // Stablecoin -crypto_amount: string; // Stablecoin amount -rate: string; // Exchange rate -transfer_remark: string; // Remark; empty when reference_code is set (v4.106.95) -reference_code?: string; // v4.106.95: Unique bank transfer reference code for SGB deposit buy orders -status: string; // Status -⋮---- +text: string; // User Order ID +symbol: string; // Currency pair +exchange_type: string; // Exchange +business_type: string; // Business Type +side: string; // Buy/Sell Direction +qty: string; // Trading size +price: string; // Fill Price +fee: string; // fee +fee_coin: string; // Fee currency +fee_rate: string; // Fee Rate +match_role: string; // Filled Role +rpnl: string; // Realized P&L +position_mode: string; // Position Mode +position_side: string; // Position Direction create_time: string; // Created time -memo: string; // Cancellation or rejection reason -side: string; // Quote direction -promotion_code: string; // Promotion code -trade_no: string; // Trade number ⋮---- -export interface GetOTCFiatOrderDetailResp { - message: string; - code: number; - data: OTCFiatOrderDetail; +export interface CrossExAccountBook { + id: string; // Account Change Record ID + user_id: string; // User ID + business_id: string; // Business ID + type: string; // TRANSACTION, TRADING_FEE, FUNDING_FEE, LIQUIDATION_FEE, TRANSFER_IN, TRANSFER_OUT, BANKRUPT_COMPENSATION, AUTO_REPAY + exchange_type: string; // Exchange + coin: string; // Currency + change: string; // Change amount (positive indicates transfer in; negative indicates transfer out) + balance: string; // Balance after change + create_time: string; // Created time } ⋮---- -export interface CreateOTCUploadPreUploadFields { - key?: string; - content_type?: string; - x_amz_credential?: string; - x_amz_algorithm?: string; - x_amz_date?: string; - policy?: string; - x_amz_signature?: string; -} +id: string; // Account Change Record ID +user_id: string; // User ID +business_id: string; // Business ID +type: string; // TRANSACTION, TRADING_FEE, FUNDING_FEE, LIQUIDATION_FEE, TRANSFER_IN, TRANSFER_OUT, BANKRUPT_COMPENSATION, AUTO_REPAY +exchange_type: string; // Exchange +coin: string; // Currency +change: string; // Change amount (positive indicates transfer in; negative indicates transfer out) +balance: string; // Balance after change +create_time: string; // Created time ⋮---- -export interface CreateOTCUploadPreUploadData { - file_key?: string; - url?: string; - fields?: CreateOTCUploadPreUploadFields; - expires_in?: number; +export interface CrossExCoinDiscountRate { + coin: string; // Currency + exchange_type: string; // Exchange + tier: string; // Tier + min_value: string; // Minimum value + max_value: string; // Maximum value + discount_rate: string; // Discount rate } ⋮---- -export interface CreateOTCUploadPreUploadResp { - code?: number; - message?: string; - timestamp?: number; - data?: CreateOTCUploadPreUploadData; +coin: string; // Currency +exchange_type: string; // Exchange +tier: string; // Tier +min_value: string; // Minimum value +max_value: string; // Maximum value +discount_rate: string; // Discount rate +⋮---- +export interface UpdateCrossExPositionsMarginResp { + symbol?: string; + margin?: string; + position_side?: 'NONE' | 'LONG' | 'SHORT'; } ================ -File: src/types/response/tradfi.ts +File: src/types/response/otc.ts ================ -/** TradFi API response types */ -⋮---- -export interface TradFiApiResp { - timestamp?: number; - data?: T; - code?: number; - message?: string; - label?: string; -} +/**========================================================================================================================== + * OTC + * ========================================================================================================================== + */ ⋮---- -export interface TradFiListData { - list?: T[]; - total?: number; - total_page?: number; +export interface OTCActionResp { + code: number; + message: string; + timestamp: number; } ⋮---- -export interface TradFiMT5Account { - mt5_uid?: number; // Removed from API in v4.106.132; kept optional for compatibility - leverage?: number; - stop_out_level?: string; - status?: number; +export interface CreateOTCQuoteResp { + code: number; + message: string; + data: { + type: string; // BUY (on-ramp) or SELL (off-ramp) + pay_coin: string; + get_coin: string; + pay_amount: string; + get_amount: string; + rate: string; + rate_reci: string; // Reciprocal of the exchange rate + promotion_code: string; + side: string; + order_type: string; // FIAT or STABLE + quote_token: string; // Quote token required when placing an order + url?: string; + memo?: string; + has_signature?: string; + validity_period?: string; + ex_rate?: string; + usdc_rate?: string; + is_need_file?: string; + gate_bank_id?: string; + gate_bank_name?: string; + refresh_limit?: number; + refresh_limit_msg?: string; + }; + timestamp: number; } ⋮---- -mt5_uid?: number; // Removed from API in v4.106.132; kept optional for compatibility +type: string; // BUY (on-ramp) or SELL (off-ramp) ⋮---- -export interface TradFiCategoryItem { - category_id?: number; - is_favorite?: boolean; - category_name?: string; -} +rate_reci: string; // Reciprocal of the exchange rate ⋮---- -export interface TradFiSymbolItem { - symbol?: string; - symbol_desc?: string; - category_id?: number; - status?: string; - trade_mode?: string; - icon_link?: string; - close_time?: number; - open_time?: number; - next_open_time?: number; - settlement_currency?: string; - settlement_currency_symbol?: string; - price_precision?: number; -} +order_type: string; // FIAT or STABLE +quote_token: string; // Quote token required when placing an order ⋮---- -export interface TradFiSymbolDetailItem { - symbol?: string; - symbol_desc?: string; - category_name?: string; - contract_volume?: string; - settlement_currency?: string; - max_order_volume?: string; - min_order_volume?: string; - leverage?: string; - price_precision?: number; - price_sl_level?: string; - swap_cost_type?: string; - buy_swap_cost_rate?: string; - sell_swap_cost_rate?: string; - swap_cost_3day?: string; - trade_timezone?: string; - trade_mode?: string; - icon_link?: string; - [key: string]: unknown; -} +export type CreateOTCFiatOrderResp = OTCActionResp; ⋮---- -export interface TradFiKlineItem { - o?: string; - c?: string; - h?: string; - l?: string; - t?: number; +export interface CreateOTCStablecoinOrderResp { + code: number; + message: string; + timestamp: number; } ⋮---- -export interface TradFiTicker { - highest_price?: string; - lowest_price?: string; - price_change?: string; - price_change_amount?: string; - today_open_price?: string; - last_today_close_price?: string; - last_price?: string; - bid_price?: string; - ask_price?: string; - favorite?: boolean; +export interface OTCBankListItem { + id: string; // Bank ID (required for order placement) + bank_account_name: string; + bank_name: string; + bank_country?: string; + bank_address?: string; + bank_code?: string; + branch_code?: string; + iban?: string; + swift?: string; + remittance_line_number?: string; + agent_bank_name?: string; + agent_bank_swift?: string; + submit_time?: string; + update_time?: string; status?: string; - close_time?: number; - open_time?: number; - next_open_time?: number; - trade_mode?: string; - category_name?: string; + documentation_file_type?: string; + memo?: string; + /** 1 = default bank card, 0 = not default */ + is_default?: 0 | 1; + bank_id?: string; + documentation_file_key_url?: string; } ⋮---- -export interface TradFiCreateUserResult { - status?: number; - leverage?: number; - mt5_uid?: string; // Removed from API in v4.106.132; kept optional for compatibility -} +id: string; // Bank ID (required for order placement) ⋮---- -mt5_uid?: string; // Removed from API in v4.106.132; kept optional for compatibility +/** 1 = default bank card, 0 = not default */ ⋮---- -export interface TradFiAssets { - equity?: string; - margin_level?: string; - balance?: string; - margin?: string; - margin_free?: string; - unrealized_pnl?: string; - mt5_uid?: string; // Removed from API in v4.106.132; kept optional for compatibility +export interface GetOTCBankListResp { + code: number; + message: string; + data: { + lists: OTCBankListItem[]; + }; + timestamp: number; } ⋮---- -mt5_uid?: string; // Removed from API in v4.106.132; kept optional for compatibility -⋮---- -export interface TradFiTransactionRecord { - asset?: string; - type?: string; - type_desc?: string; - change?: string; - balance?: string; - time?: number; +export interface CreateOTCBankResp { + code: number; + message: string; + data: { + bank_id: number; + status: number; + }; + timestamp?: number; } ⋮---- -export interface TradFiTransactionListData { - total?: number; - total_page?: number; - list?: TradFiTransactionRecord[]; +export interface OTCBankSupplementChecklistItem { + description: string; + code?: string; + zh?: string; + en?: string; + required?: boolean; } ⋮---- -export interface TradFiCreateOrderResult { - id?: string; +export interface GetOTCBankSupplementChecklistResp { + code: number; + message: string; + data: { + user_type: 'personal' | 'enterprise'; + items: OTCBankSupplementChecklistItem[]; + }; + timestamp?: number; } ⋮---- -export interface TradFiOrderItem { - order_id?: number; - symbol?: string; - symbol_desc?: string; - price_type?: string; - state?: number; - state_desc?: string; - finished?: number; - side?: number; - volume?: string; - price?: string; - price_tp?: string; - price_sl?: string; - time_setup?: number; -} +export type MarkOTCOrderAsPaidResp = OTCActionResp; ⋮---- -export interface TradFiOrderListData { - list?: TradFiOrderItem[]; - timestamp?: number; -} +export type CancelOTCOrderResp = OTCActionResp; ⋮---- -export interface TradFiModifyOrderResult { - order_id?: number; - symbol?: string; - state?: string; - volume?: string; - price?: string; - price_tp?: string; - price_sl?: string; +export interface OTCFiatOrderListItem { + time: string; // Current time + timestamp: number; // Current timestamp + order_id: string; + trade_no: string; // Trade number + type: string; // Quote direction buy/sell/all + status: string; // Order Status (includes DISBURSED) + db_status: string; + fiat_currency: string; // Fiat type + fiat_currency_info: { + name: string; + icon: string; + }; + fiat_amount: string; // Fiat amount + crypto_currency: string; // Stablecoin + crypto_currency_info: { + name: string; + icon: string; + }; + crypto_amount: string; // Stablecoin amount + rate: string; // Exchange rate + transfer_remark: string; // Remark; empty when reference_code is set (v4.106.95) + reference_code?: string; // v4.106.95: Unique bank transfer reference code for SGB deposit buy orders + gate_bank_account_iban: string; // Bank account + promotion_code: string; // Promotion code } ⋮---- -export interface TradFiOrderHistoryItem { - order_id?: number; - symbol?: string; - symbol_desc?: string; - price_type?: string; - order_opt_type?: number; - state?: number; - state_desc?: string; - side?: number; - volume?: string; - fill_volume?: string; - close_pnl?: string; - price?: string; - trigger_price?: string; - price_tp?: string; - price_sl?: string; - time_setup?: number; - time_done?: number; -} +time: string; // Current time +timestamp: number; // Current timestamp ⋮---- -export interface TradFiPositionItem { - position_id?: number; - symbol?: string; - symbol_desc?: string; - margin?: string; - unrealized_pnl?: string; - unrealized_pnl_rate?: string; - volume?: string; - price_open?: string; - position_dir?: string; - price_tp?: string; - price_sl?: string; - counterparty_price?: string; - time_create?: number; +trade_no: string; // Trade number +type: string; // Quote direction buy/sell/all +status: string; // Order Status (includes DISBURSED) +⋮---- +fiat_currency: string; // Fiat type +⋮---- +fiat_amount: string; // Fiat amount +crypto_currency: string; // Stablecoin +⋮---- +crypto_amount: string; // Stablecoin amount +rate: string; // Exchange rate +transfer_remark: string; // Remark; empty when reference_code is set (v4.106.95) +reference_code?: string; // v4.106.95: Unique bank transfer reference code for SGB deposit buy orders +gate_bank_account_iban: string; // Bank account +promotion_code: string; // Promotion code +⋮---- +export interface GetOTCFiatOrderListResp { + code: number; + message: string; + data: { + pn: number; + ps: number; + total_pn: number; + count: number; + list: OTCFiatOrderListItem[]; + }; } ⋮---- -export interface TradFiPositionListData { - list?: TradFiPositionItem[]; - timestamp?: number; +export interface OTCStablecoinOrderListItem { + id: number; // Order ID + trade_no: string; // Transaction reference number + pay_coin: string; // Payment currency + pay_amount: string; // Payment amount + get_coin: string; // Received currency + get_amount: string; // Received amount + rate: string; // Exchange rate + rate_reci: string; // Reciprocal of the exchange rate + status: string; // PROCESSING: in progress / DONE: completed / FAILED: failed + create_timest: number; // Timestamp + create_time: string; // Created time + pay_icon?: string; + get_icon?: string; } ⋮---- -export interface TradFiPositionHistoryItem { - position_id?: number; - symbol?: string; - realized_pnl?: string; - realized_pnl_rate?: string; - volume?: string; - volume_closed?: string; - price_open?: string; - position_dir?: string; - price_tp?: string; - price_sl?: string; - counterparty_price?: string; - close_price?: string; - time_create?: string; - time_close?: string; - position_status?: string; - close_detail?: Record | null; - realized_pnl_detail?: { - closed_pnl?: string; - swap?: string; - fee?: string; +id: number; // Order ID +trade_no: string; // Transaction reference number +pay_coin: string; // Payment currency +pay_amount: string; // Payment amount +get_coin: string; // Received currency +get_amount: string; // Received amount +rate: string; // Exchange rate +rate_reci: string; // Reciprocal of the exchange rate +status: string; // PROCESSING: in progress / DONE: completed / FAILED: failed +create_timest: number; // Timestamp +create_time: string; // Created time +⋮---- +export interface GetOTCStablecoinOrderListResp { + code: number; + message: string; + data: { + total: number; + page_size: number; + page_number: number; + total_page: number; + list: OTCStablecoinOrderListItem[]; }; } ⋮---- -/** GET /tradfi/orders/log/{log_id} — v4.106.94 */ -export interface TradFiOrderLog { - order_id?: number; - log_id?: number; - symbol?: string; - price_type?: 'market' | 'trigger'; - state?: number; - side?: number; - volume?: string; - price?: string; - [key: string]: unknown; -} +export interface OTCFiatOrderDetail { + order_id: string; // Order ID + uid: string; // User ID + type: string; // Order Type + fiat_currency: string; // Fiat type + fiat_amount: string; // Fiat amount + crypto_currency: string; // Stablecoin + crypto_amount: string; // Stablecoin amount + rate: string; // Exchange rate + transfer_remark: string; // Remark; empty when reference_code is set (v4.106.95) + reference_code?: string; // v4.106.95: Unique bank transfer reference code for SGB deposit buy orders + status: string; // Status + db_status: string; + create_time: string; // Created time + memo: string; // Cancellation or rejection reason + side: string; // Quote direction + promotion_code: string; // Promotion code + trade_no: string; // Trade number +} +⋮---- +order_id: string; // Order ID +uid: string; // User ID +type: string; // Order Type +fiat_currency: string; // Fiat type +fiat_amount: string; // Fiat amount +crypto_currency: string; // Stablecoin +crypto_amount: string; // Stablecoin amount +rate: string; // Exchange rate +transfer_remark: string; // Remark; empty when reference_code is set (v4.106.95) +reference_code?: string; // v4.106.95: Unique bank transfer reference code for SGB deposit buy orders +status: string; // Status ⋮---- -export interface TradFiSymbolCommissionItem { - category_code?: string; - symbol?: string; - fee_per_lot?: string; +create_time: string; // Created time +memo: string; // Cancellation or rejection reason +side: string; // Quote direction +promotion_code: string; // Promotion code +trade_no: string; // Trade number +⋮---- +export interface GetOTCFiatOrderDetailResp { + message: string; + code: number; + data: OTCFiatOrderDetail; } - -================ -File: src/index.ts -================ -// Request Types ⋮---- -// Response Types +export interface CreateOTCUploadPreUploadFields { + key?: string; + content_type?: string; + x_amz_credential?: string; + x_amz_algorithm?: string; + x_amz_date?: string; + policy?: string; + x_amz_signature?: string; +} ⋮---- -// Websockets Types +export interface CreateOTCUploadPreUploadData { + file_key?: string; + url?: string; + fields?: CreateOTCUploadPreUploadFields; + expires_in?: number; +} ⋮---- -// Shared Types +export interface CreateOTCUploadPreUploadResp { + code?: number; + message?: string; + timestamp?: number; + data?: CreateOTCUploadPreUploadData; +} ================ -File: src/types/request/futures.ts +File: src/types/response/tradfi.ts ================ -/**========================================================================================================================== - * FUTURES - * ========================================================================================================================== - */ -⋮---- -export type FuturesSettle = 'btc' | 'usdt' | 'usd' | 'usd1'; +/** TradFi API response types */ ⋮---- -export interface GetFuturesOrderBookReq { - settle: FuturesSettle; - contract: string; - interval?: string; - limit?: number; - with_id?: boolean; +export interface TradFiApiResp { + timestamp?: number; + data?: T; + code?: number; + message?: string; + label?: string; } ⋮---- -export interface GetFuturesTradesReq { - settle: FuturesSettle; - contract: string; - limit?: number; - offset?: number; - last_id?: string; - from?: number; - to?: number; +export interface TradFiListData { + list?: T[]; + total?: number; + total_page?: number; } ⋮---- -export interface GetFuturesCandlesReq { - settle: FuturesSettle; - contract: string; - from?: number; - to?: number; - limit?: number; - interval?: string; +export interface TradFiMT5Account { + mt5_uid?: number; // Removed from API in v4.106.132; kept optional for compatibility + leverage?: number; + stop_out_level?: string; + status?: number; } ⋮---- -export interface GetFuturesStatsReq { - settle: FuturesSettle; - contract: string; - from?: number; - interval?: string; - limit?: number; -} +mt5_uid?: number; // Removed from API in v4.106.132; kept optional for compatibility ⋮---- -export interface GetFundingRatesReq { - settle: FuturesSettle; - contract: string; - limit?: number; - from?: number; - to?: number; +export interface TradFiCategoryItem { + category_id?: number; + is_favorite?: boolean; + category_name?: string; } ⋮---- -export interface BatchFundingRatesReq { - settle: 'btc' | 'usdt' | 'usd1'; - contracts: string[]; +export interface TradFiSymbolItem { + symbol?: string; + symbol_desc?: string; + category_id?: number; + status?: string; + trade_mode?: string; + icon_link?: string; + close_time?: number; + open_time?: number; + next_open_time?: number; + settlement_currency?: string; + settlement_currency_symbol?: string; + price_precision?: number; } ⋮---- -export interface GetLiquidationHistoryReq { - settle: FuturesSettle; - contract?: string; - from?: number; - to?: number; - limit?: number; +export interface TradFiSymbolDetailItem { + symbol?: string; + symbol_desc?: string; + category_name?: string; + contract_volume?: string; + settlement_currency?: string; + max_order_volume?: string; + min_order_volume?: string; + leverage?: string; + price_precision?: number; + price_sl_level?: string; + swap_cost_type?: string; + buy_swap_cost_rate?: string; + sell_swap_cost_rate?: string; + swap_cost_3day?: string; + trade_timezone?: string; + trade_mode?: string; + icon_link?: string; + [key: string]: unknown; } ⋮---- -export interface GetRiskLimitTiersReq { - settle: FuturesSettle; - contract: string; - limit?: number; - offset?: number; +export interface TradFiKlineItem { + o?: string; + c?: string; + h?: string; + l?: string; + t?: number; } ⋮---- -export interface GetRiskLimitTableReq { - settle: FuturesSettle; - table_id: string; +export interface TradFiTicker { + highest_price?: string; + lowest_price?: string; + price_change?: string; + price_change_amount?: string; + today_open_price?: string; + last_today_close_price?: string; + last_price?: string; + bid_price?: string; + ask_price?: string; + favorite?: boolean; + status?: string; + close_time?: number; + open_time?: number; + next_open_time?: number; + trade_mode?: string; + category_name?: string; } ⋮---- -export interface GetFuturesAccountBookReq { - settle: FuturesSettle; - contract?: string; - limit?: number; - offset?: number; - from?: number; - to?: number; - type?: - | 'dnw' - | 'pnl' - | 'fee' - | 'refr' - | 'fund' - | 'point_dnw' - | 'point_fee' - | 'point_refr' - | 'bonus_offset'; +export interface TradFiCreateUserResult { + status?: number; + leverage?: number; + mt5_uid?: string; // Removed from API in v4.106.132; kept optional for compatibility } ⋮---- -export interface GetFuturesADLRiskStatesReq { - settle: 'btc' | 'usdt' | 'usd1'; -} +mt5_uid?: string; // Removed from API in v4.106.132; kept optional for compatibility ⋮---- -export interface GetFuturesPositionsReq { - settle: FuturesSettle; - holding?: boolean; - limit?: number; // deprecated, use positions_limit instead - positions_limit?: number; // v4.106.104: Replaces limit; omit to return full list, explicit values capped at 1-100 - offset?: number; - position_side?: string; // v4.105.3: Add position_side parameter for hedge mode support - hedge_mode?: boolean; // v4.104.3: Add hedge_mode parameter +export interface TradFiAssets { + equity?: string; + margin_level?: string; + balance?: string; + margin?: string; + margin_free?: string; + unrealized_pnl?: string; + mt5_uid?: string; // Removed from API in v4.106.132; kept optional for compatibility } ⋮---- -limit?: number; // deprecated, use positions_limit instead -positions_limit?: number; // v4.106.104: Replaces limit; omit to return full list, explicit values capped at 1-100 -⋮---- -position_side?: string; // v4.105.3: Add position_side parameter for hedge mode support -hedge_mode?: boolean; // v4.104.3: Add hedge_mode parameter -⋮---- -export interface UpdateDualModePositionMarginReq { - settle: FuturesSettle; - contract: string; - change: string; - dual_side: 'dual_long' | 'dual_short'; +mt5_uid?: string; // Removed from API in v4.106.132; kept optional for compatibility +⋮---- +export interface TradFiTransactionRecord { + asset?: string; + type?: string; + type_desc?: string; + change?: string; + balance?: string; + time?: number; } ⋮---- -export interface UpdateDualModePositionLeverageReq { - settle: FuturesSettle; - contract: string; - leverage: string; - cross_leverage_limit?: string; +export interface TradFiTransactionListData { + total?: number; + total_page?: number; + list?: TradFiTransactionRecord[]; } ⋮---- -export interface SubmitFuturesOrderReq { - xGateExptime?: number; - settle: FuturesSettle; - contract: string; - size: number; - iceberg?: number; - price?: string; - close?: boolean; - reduce_only?: boolean; - tif?: string; - text?: string; - auto_size?: string; - stp_act?: string; - action_mode?: 'ACK' | 'RESULT' | 'FULL'; - tpsl_tp_trigger_price?: string; - tpsl_sl_trigger_price?: string; - pos_margin_mode?: 'isolated' | 'cross'; +export interface TradFiCreateOrderResult { + id?: string; } ⋮---- -export interface GetFuturesOrdersReq { - settle: FuturesSettle; - contract?: string; - status: string; - limit?: number; - offset?: number; - last_id?: string; +export interface TradFiOrderItem { + order_id?: number; + symbol?: string; + symbol_desc?: string; + price_type?: string; + state?: number; + state_desc?: string; + finished?: number; + side?: number; + volume?: string; + price?: string; + price_tp?: string; + price_sl?: string; + time_setup?: number; } ⋮---- -export interface DeleteAllFuturesOrdersReq { - xGateExptime?: number; - settle: FuturesSettle; - contract: string; - side?: string; - action_mode?: 'ACK' | 'RESULT' | 'FULL'; +export interface TradFiOrderListData { + list?: TradFiOrderItem[]; + timestamp?: number; } ⋮---- -export interface GetFuturesOrdersByTimeRangeReq { - settle: FuturesSettle; - contract?: string; - from?: number; - to?: number; - limit?: number; - offset?: number; +export interface TradFiModifyOrderResult { + order_id?: number; + symbol?: string; + state?: string; + volume?: string; + price?: string; + price_tp?: string; + price_sl?: string; } ⋮---- -export interface UpdateFuturesOrderReq { - xGateExptime?: number; - settle: FuturesSettle; - order_id: string; - size?: number; +export interface TradFiOrderHistoryItem { + order_id?: number; + symbol?: string; + symbol_desc?: string; + price_type?: string; + order_opt_type?: number; + state?: number; + state_desc?: string; + side?: number; + volume?: string; + fill_volume?: string; + close_pnl?: string; price?: string; - amend_text?: string; + trigger_price?: string; + price_tp?: string; + price_sl?: string; + time_setup?: number; + time_done?: number; } ⋮---- -export interface GetFuturesTradingHistoryReq { - settle: FuturesSettle; - contract?: string; - order?: number; - limit?: number; - offset?: number; - last_id?: string; +export interface TradFiPositionItem { + position_id?: number; + symbol?: string; + symbol_desc?: string; + margin?: string; + unrealized_pnl?: string; + unrealized_pnl_rate?: string; + volume?: string; + price_open?: string; + position_dir?: string; + price_tp?: string; + price_sl?: string; + counterparty_price?: string; + time_create?: number; } ⋮---- -export interface GetFuturesTradingHistoryByTimeRangeReq { - settle: FuturesSettle; - contract?: string; - from?: number; - to?: number; - limit?: number; - offset?: number; - role?: 'maker' | 'taker'; +export interface TradFiPositionListData { + list?: TradFiPositionItem[]; + timestamp?: number; } ⋮---- -export interface GetFuturesPositionHistoryReq { - settle: FuturesSettle; - contract?: string; - limit?: number; - offset?: number; - from?: number; - to?: number; - side?: 'long' | 'short'; - pnl?: string; +export interface TradFiPositionHistoryItem { + position_id?: number; + symbol?: string; + realized_pnl?: string; + realized_pnl_rate?: string; + volume?: string; + volume_closed?: string; + price_open?: string; + position_dir?: string; + price_tp?: string; + price_sl?: string; + counterparty_price?: string; + close_price?: string; + time_create?: string; + time_close?: string; + position_status?: string; + close_detail?: Record | null; + realized_pnl_detail?: { + closed_pnl?: string; + swap?: string; + fee?: string; + }; } ⋮---- -export interface GetFuturesLiquidationHistoryReq { - settle: FuturesSettle; - contract?: string; - limit?: number; - at?: number; +/** GET /tradfi/orders/log/{log_id} — v4.106.94 */ +export interface TradFiOrderLog { + order_id?: number; + log_id?: number; + symbol?: string; + price_type?: 'market' | 'trigger'; + state?: number; + side?: number; + volume?: string; + price?: string; + [key: string]: unknown; } ⋮---- -export interface SubmitFuturesTriggeredOrderReq { - initial: { - contract: string; - size?: number; - /** Decimal contract size; if both `size` and `amount` are set, `amount` takes precedence */ - amount?: string; - price: string; // Required: Order price. Set to 0 to use market price - close?: boolean; - tif?: 'gtc' | 'ioc'; - text?: string; - reduce_only?: boolean; - auto_size?: string; - }; - trigger: { - strategy_type?: 0 | 1; - price_type?: 0 | 1 | 2; - price: string; // Required: Price value for price trigger - rule: 1 | 2; // Required: Price Condition Type (1: >=, 2: <=) - expiration?: number; +export interface TradFiSymbolCommissionItem { + category_code?: string; + symbol?: string; + fee_per_lot?: string; +} + +================ +File: src/types/response/unified.ts +================ +export interface UnifiedAccountInfo { + mode: 'classic' | 'multi_currency' | 'portfolio' | 'single_currency'; // classic: Classic account; multi_currency: Multi-currency margin; portfolio: Portfolio margin; single_currency: Single-currency margin + user_id: number; + refresh_time: number; + locked: boolean; // Whether the account is locked; valid in cross-currency/combined margin mode, false in other modes such as single-currency margin + balances: { + [key: string]: { + available: string; // Cross available balance, after deducting futures isolated margin occupation and frozen amount (futures isolated occupation = futures isolated balance); effective in single-currency/multi-currency/portfolio margin mode + freeze: string; // Frozen amount; effective in single-currency/multi-currency/portfolio margin mode + borrowed: string; // Borrowed amount; valid in cross-currency/combined margin mode, 0 in other modes such as single-currency margin + negative_liab: string; // Negative balance borrowing; valid in cross-currency/combined margin mode, 0 in other modes such as single-currency margin + futures_pos_liab: string; // Contract opening position borrowing currency (abandoned, to be removed) + equity: string; // Currency equity amount (cross); effective in single-currency/multi-currency/portfolio margin mode + total_freeze: string; // Total frozen (deprecated, to be removed) + total_liab: string; // Total borrowed amount; valid in cross-currency/combined margin mode, 0 in other modes such as single-currency margin + spot_in_use: string; // Spot hedging amount; valid in combined (portfolio) margin mode, 0 in single-currency and cross-currency margin modes + funding: string; // Uniloan / Earn amount; effective when Earn is enabled as unified account margin + funding_version: string; // Funding version + cross_balance: string; // Full margin balance; valid in single-currency margin mode, 0 in cross-currency/combined margin mode + iso_balance: string; // Futures isolated balance; effective in single-currency and multi-currency margin mode, 0 in portfolio margin mode + im: string; // Cross initial margin; only effective for USDT in single-currency margin mode, 0 in multi-currency/portfolio margin mode + mm: string; // Cross maintenance margin; only effective for USDT in single-currency margin mode, 0 in multi-currency/portfolio margin mode + mmr: string; // Cross maintenance margin rate; only effective for USDT in single-currency margin mode, 0 in multi-currency/portfolio margin mode + margin_balance: string; // Cross margin balance; only effective for USDT in single-currency margin mode, 0 in multi-currency/portfolio margin mode + available_margin: string; // Cross available margin; only effective for USDT in single-currency margin mode, 0 in multi-currency/portfolio margin mode + imr?: string; // Cross initial margin rate; only effective for USDT in single-currency margin mode, 0 in multi-currency/portfolio margin mode + enabled_collateral?: boolean; // Currency enabled as margin: true — enabled, false — disabled + balance_version?: number; // Balance version number (int64) + }; }; - order_type?: - | 'close-long-order' - | 'close-short-order' - | 'close-long-position' - | 'close-short-position' - | 'plan-close-long-position' - | 'plan-close-short-position'; - settle: FuturesSettle; + total: string; // Total account assets in USD: sum of (available + freeze) * price per currency (deprecated; use unified_account_total) + borrowed: string; // Total borrowed in USD: sum of borrowed * price (excluding point cards); valid in cross-currency/combined margin mode, 0 in single-currency margin mode + total_initial_margin: string; // Total initial margin (cross); effective in multi-currency/portfolio margin mode, 0 in single-currency margin mode + total_margin_balance: string; // Total margin balance (cross); effective in multi-currency/portfolio margin mode, 0 in single-currency margin mode + total_maintenance_margin: string; // Total maintenance margin (cross); effective in multi-currency/portfolio margin mode, 0 in single-currency margin mode + total_initial_margin_rate: string; // Total initial margin rate (cross); effective in multi-currency/portfolio margin mode, 0 in single-currency margin mode + total_maintenance_margin_rate: string; // Total maintenance margin rate (cross); effective in multi-currency/portfolio margin mode, 0 in single-currency margin mode + total_available_margin: string; // Available margin; valid in cross-currency/combined margin mode, 0 in single-currency margin mode + unified_account_total: string; // Total unified account assets: cross + isolated in single/multi-currency mode; cross only in portfolio margin mode + unified_account_total_liab: string; // Total unified borrowed (cross); effective in multi-currency/portfolio margin mode, 0 in single-currency margin mode + unified_account_total_equity: string; // Total unified equity: cross + isolated in single/multi-currency mode; cross only in portfolio margin mode + leverage: string; // Account leverage; effective in multi-currency/portfolio margin mode (deprecated; prefer GET /unified/leverage/user_currency_setting) + spot_order_loss: string; // Spot pending order loss (USDT); only in cross-currency and portfolio margin mode + options_order_loss?: string; // v4.105.29: Option pending order loss (USDT); only in portfolio margin mode + spot_hedge: boolean; // Spot hedging: true — enabled, false — disabled + margin_mode?: string; + total_balance?: string; + cross_leverage?: string; + portfolio_margin?: string; + risk_level?: string; + is_all_collateral?: boolean; // Whether all currencies are used as margin: true — all as margin, false — not all + borrow_amount?: string; + cross_margin_leverage?: string; + use_funding?: boolean; // Whether Earn funds are used as margin } ⋮---- -/** Decimal contract size; if both `size` and `amount` are set, `amount` takes precedence */ +mode: 'classic' | 'multi_currency' | 'portfolio' | 'single_currency'; // classic: Classic account; multi_currency: Multi-currency margin; portfolio: Portfolio margin; single_currency: Single-currency margin ⋮---- -price: string; // Required: Order price. Set to 0 to use market price +locked: boolean; // Whether the account is locked; valid in cross-currency/combined margin mode, false in other modes such as single-currency margin ⋮---- -price: string; // Required: Price value for price trigger -rule: 1 | 2; // Required: Price Condition Type (1: >=, 2: <=) +available: string; // Cross available balance, after deducting futures isolated margin occupation and frozen amount (futures isolated occupation = futures isolated balance); effective in single-currency/multi-currency/portfolio margin mode +freeze: string; // Frozen amount; effective in single-currency/multi-currency/portfolio margin mode +borrowed: string; // Borrowed amount; valid in cross-currency/combined margin mode, 0 in other modes such as single-currency margin +negative_liab: string; // Negative balance borrowing; valid in cross-currency/combined margin mode, 0 in other modes such as single-currency margin +futures_pos_liab: string; // Contract opening position borrowing currency (abandoned, to be removed) +equity: string; // Currency equity amount (cross); effective in single-currency/multi-currency/portfolio margin mode +total_freeze: string; // Total frozen (deprecated, to be removed) +total_liab: string; // Total borrowed amount; valid in cross-currency/combined margin mode, 0 in other modes such as single-currency margin +spot_in_use: string; // Spot hedging amount; valid in combined (portfolio) margin mode, 0 in single-currency and cross-currency margin modes +funding: string; // Uniloan / Earn amount; effective when Earn is enabled as unified account margin +funding_version: string; // Funding version +cross_balance: string; // Full margin balance; valid in single-currency margin mode, 0 in cross-currency/combined margin mode +iso_balance: string; // Futures isolated balance; effective in single-currency and multi-currency margin mode, 0 in portfolio margin mode +im: string; // Cross initial margin; only effective for USDT in single-currency margin mode, 0 in multi-currency/portfolio margin mode +mm: string; // Cross maintenance margin; only effective for USDT in single-currency margin mode, 0 in multi-currency/portfolio margin mode +mmr: string; // Cross maintenance margin rate; only effective for USDT in single-currency margin mode, 0 in multi-currency/portfolio margin mode +margin_balance: string; // Cross margin balance; only effective for USDT in single-currency margin mode, 0 in multi-currency/portfolio margin mode +available_margin: string; // Cross available margin; only effective for USDT in single-currency margin mode, 0 in multi-currency/portfolio margin mode +imr?: string; // Cross initial margin rate; only effective for USDT in single-currency margin mode, 0 in multi-currency/portfolio margin mode +enabled_collateral?: boolean; // Currency enabled as margin: true — enabled, false — disabled +balance_version?: number; // Balance version number (int64) ⋮---- -export interface GetFuturesAutoOrdersReq { - settle: FuturesSettle; - status: 'open' | 'finished'; - contract?: string; - limit?: number; - offset?: number; -} +total: string; // Total account assets in USD: sum of (available + freeze) * price per currency (deprecated; use unified_account_total) +borrowed: string; // Total borrowed in USD: sum of borrowed * price (excluding point cards); valid in cross-currency/combined margin mode, 0 in single-currency margin mode +total_initial_margin: string; // Total initial margin (cross); effective in multi-currency/portfolio margin mode, 0 in single-currency margin mode +total_margin_balance: string; // Total margin balance (cross); effective in multi-currency/portfolio margin mode, 0 in single-currency margin mode +total_maintenance_margin: string; // Total maintenance margin (cross); effective in multi-currency/portfolio margin mode, 0 in single-currency margin mode +total_initial_margin_rate: string; // Total initial margin rate (cross); effective in multi-currency/portfolio margin mode, 0 in single-currency margin mode +total_maintenance_margin_rate: string; // Total maintenance margin rate (cross); effective in multi-currency/portfolio margin mode, 0 in single-currency margin mode +total_available_margin: string; // Available margin; valid in cross-currency/combined margin mode, 0 in single-currency margin mode +unified_account_total: string; // Total unified account assets: cross + isolated in single/multi-currency mode; cross only in portfolio margin mode +unified_account_total_liab: string; // Total unified borrowed (cross); effective in multi-currency/portfolio margin mode, 0 in single-currency margin mode +unified_account_total_equity: string; // Total unified equity: cross + isolated in single/multi-currency mode; cross only in portfolio margin mode +leverage: string; // Account leverage; effective in multi-currency/portfolio margin mode (deprecated; prefer GET /unified/leverage/user_currency_setting) +spot_order_loss: string; // Spot pending order loss (USDT); only in cross-currency and portfolio margin mode +options_order_loss?: string; // v4.105.29: Option pending order loss (USDT); only in portfolio margin mode +spot_hedge: boolean; // Spot hedging: true — enabled, false — disabled ⋮---- -/** - * Modify contract order parameters - */ -export interface BatchAmendOrderReq { - order_id?: number; // Order id, order_id and text must contain at least one - text?: string; // User-defined order text, at least one of order_id and text must be passed - size?: number; // The new order size, including the executed order size - price?: string; // New order price - amend_text?: string; // Custom info during amending order -} +is_all_collateral?: boolean; // Whether all currencies are used as margin: true — all as margin, false — not all ⋮---- -order_id?: number; // Order id, order_id and text must contain at least one -text?: string; // User-defined order text, at least one of order_id and text must be passed -size?: number; // The new order size, including the executed order size -price?: string; // New order price -amend_text?: string; // Custom info during amending order +use_funding?: boolean; // Whether Earn funds are used as margin ⋮---- -// v4.105.8: New GET /futures/{settle}/position_close_history endpoint request -export interface GetFuturesPositionCloseHistoryReq { - settle: FuturesSettle; - contract?: string; - limit?: number; - offset?: number; - from?: number; - to?: number; +export interface UnifiedLoan { + currency: string; + currency_pair: string; + amount: string; + type: 'platform' | 'margin'; + create_time: number; + update_time: number; } ⋮---- -// v4.104.6: New GET /futures/{settle}/insurance endpoint request -export interface GetFuturesInsuranceReq { - settle: FuturesSettle; - limit?: number; +export interface UnifiedLoanRecord { + id: number; + type: 'borrow' | 'repay'; + repayment_type: 'none' | 'manual_repay' | 'auto_repay' | 'cancel_auto_repay'; + currency_pair: string; + currency: string; + amount: string; + create_time: number; + borrow_type: string; } -⋮---- -export interface UpdateFuturesPriceTriggeredOrderReq { - settle: FuturesSettle; - order_id: number | string; - contract?: string; - size?: number; - /** Same semantics as `size` (decimal contract size) */ - amount?: string; - price?: string; - /** When fully closing in single-position mode, set true */ - close?: boolean; - trigger_price?: string; - price_type?: 0 | 1 | 2; // 0 - Latest trade price, 1 - Mark price, 2 - Index price - auto_size?: string; // Not required in single position mode +export interface UnifiedInterestRecord { + currency: string; + currency_pair: string; + actual_rate: string; + interest: string; + status: number; + type: 'platform' | 'margin'; + create_time: number; } ⋮---- -/** Same semantics as `size` (decimal contract size) */ -⋮---- -/** When fully closing in single-position mode, set true */ +export interface UnifiedRiskUnitDetails { + user_id: number; + spot_hedge: boolean; + risk_units: { + symbol: string; + spot_in_use: string; + maintain_margin: string; + initial_margin: string; + delta: string; + gamma: string; + theta: string; + vega: string; + }[]; +} ⋮---- -price_type?: 0 | 1 | 2; // 0 - Latest trade price, 1 - Mark price, 2 - Index price -auto_size?: string; // Not required in single position mode +export interface UnifiedCurrencyDiscountTiers { + currency: string; + discount_tiers: { + tier: string; + discount: string; + lower_limit: string; + upper_limit: string; + leverage: string; + }[]; +} ⋮---- -/** GET /futures/{settle}/get_leverage/{contract} — v4.106.43: pos_margin_mode and dual_side required */ -export interface GetFuturesContractLeverageReq { - settle: FuturesSettle; - contract: string; - pos_margin_mode: 'isolated' | 'cross'; - dual_side: 'dual_long' | 'dual_short'; +export interface UserCurrencyLeverageConfig { + current_leverage: string; + min_leverage: string; + max_leverage: string; + debit: string; + available_margin: string; + borrowable: string; + except_leverage_borrowable: string; } ⋮---- -/** Trail order (autoorder/v1/trail) request types */ -export interface CreateTrailOrderReq { - settle: 'btc' | 'usdt'; - contract: string; - amount: string; - activation_price?: string; - is_gte?: boolean; - price_type?: 1 | 2 | 3; - price_offset?: string; - reduce_only?: boolean; - position_related?: boolean; - text?: string; - pos_margin_mode?: string; - position_mode?: string; +export interface UnifiedLoanCurrency { + name: string; + prec: string; + min_borrow_amount: string; + user_max_borrow_amount: string; + total_max_borrow_amount: string; + loan_status: string; } ⋮---- -export interface TerminateTrailOrderReq { - settle: 'btc' | 'usdt'; - id?: number; - text?: string; +export interface UnifiedHistoryLendingRate { + currency: string; + tier: string; + tier_up_rate: string; + rates: { + time: number; + rate: string; + }[]; } ⋮---- -export interface BatchTerminateTrailOrdersReq { - settle: 'btc' | 'usdt'; - contract?: string; - related_position?: 1 | 2; +export interface MarginTier { + tier: string; + margin_rate: string; + lower_limit: string; + upper_limit: string; } ⋮---- -export interface GetTrailOrderListReq { - settle: 'btc' | 'usdt'; - contract?: string; - is_finished?: boolean; - start_at?: number; - end_at?: number; - page_num?: number; - page_size?: number; - sort_by?: 1 | 2; - hide_cancel?: boolean; - related_position?: 1 | 2; - sort_by_trigger?: boolean; - reduce_only?: 1 | 2; - side?: 1 | 2; +export interface PortfolioMarginCalculation { + maintain_margin_total: string; + initial_margin_total: string; + calculate_time: number; + risk_unit: { + symbol: string; + spot_in_use: string; + maintain_margin: string; + initial_margin: string; + margin_result: { + type: + | 'original_position' + | 'long_delta_original_position' + | 'short_delta_original_position'; + profit_loss_ranges: { + price_percentage: string; + implied_volatility_percentage: string; + profit_loss: string; + }[]; + max_loss: { + price_percentage: string; + implied_volatility_percentage: string; + profit_loss: string; + }; + mr1: string; + mr2: string; + mr3: string; + mr4: string; + delta: string; + gamma: string; + theta: string; + vega: string; + }[]; + }[]; } ⋮---- -export interface GetTrailOrderDetailReq { - settle: 'btc' | 'usdt'; - id: number; +export interface UnifiedCollateralCurrenciesResp { + is_success: boolean; } ⋮---- -export interface UpdateTrailOrderReq { - settle: 'btc' | 'usdt'; - id: number; - amount?: string; - activation_price?: string; - is_gte_str?: string; - price_type?: 0 | 1 | 2 | 3; - price_offset?: string; +export interface UnifiedQuickRepayDebtItem { + currency?: string; + debt_amount?: string; + estimated_usd?: string; + borrowed?: string; + neg_balance?: string; } ⋮---- -export interface GetTrailOrderChangeLogReq { - settle: 'btc' | 'usdt'; - id: number; - page_num?: number; - page_size?: number; +export interface UnifiedQuickRepayAvailableItem { + currency?: string; + available?: string; + estimated_usd?: string; } ⋮---- -/** Chase limit order (autoorder/v1/chase) request types */ -export interface CreateChaseOrderReq { - settle: FuturesSettle; - contract: string; - amount: string; - price_limit: string; - offset_limit?: string; - reduce_only?: boolean; - text?: string; - is_dual_mode?: boolean; - price_type?: number; - price_gap_type?: number; - price_gap_value?: string; - pos_margin_mode?: 'isolated' | 'cross' | string; - position_mode?: string; +export interface QuickEstimatedRepayment { + debt_currencies?: UnifiedQuickRepayDebtItem[]; + available_currencies?: UnifiedQuickRepayAvailableItem[]; } ⋮---- -export interface StopChaseOrderReq { - settle: FuturesSettle; - id?: string; - text?: string; +export interface QuickRepayRepaidInfo { + currency: string; + repaid: string; + left: string; } ⋮---- -export interface StopAllChaseOrdersReq { - settle: FuturesSettle; - contract?: string; - pos_margin_mode?: 'isolated' | 'cross' | string; +export interface QuickRepayUsedInfo { + currency: string; + used: string; } ⋮---- -export interface GetChaseOrdersReq { - settle: FuturesSettle; - contract?: string; - is_finished?: boolean; - start_at?: number; - end_at?: number; - page_num?: number; - page_size?: number; - /** 1 ORDER_SORT_CREATED_AT, 2 ORDER_SORT_FINISHED_AT */ - sort_by: 1 | 2; - hide_cancel?: boolean; - reduce_only?: 0 | 1 | 2; - side?: 0 | 1 | 2; +export interface QuickRepaymentResp { + order_id: string; + repaid_infos: QuickRepayRepaidInfo[]; + used_infos: QuickRepayUsedInfo[]; } ⋮---- -/** 1 ORDER_SORT_CREATED_AT, 2 ORDER_SORT_FINISHED_AT */ +/** GET/POST /unified/delta_neutral — v4.106.97 */ +export interface DeltaNeutralEnabled { + enabled: boolean; +} ⋮---- -export interface GetChaseOrderDetailReq { - settle: FuturesSettle; - id: string; +/** POST /unified/leverage/user_setting failed currency entry */ +export interface LeverageFailedCurrency { + currency: string; + reason: string; } +================ +File: src/index.ts +================ +// Request Types +⋮---- +// Response Types +⋮---- +// Websockets Types +⋮---- +// Shared Types + ================ File: src/types/response/spot.ts ================ @@ -12885,578 +12824,765 @@ export interface SpotHistoricTradeRecord { trade_quote?: string; } ⋮---- -deal?: string; // v4.105.29: Total Executed Value +deal?: string; // v4.105.29: Total Executed Value +⋮---- +export type SpotPovOrderStatus = + | 'CREATED' + | 'CANCELING' + | 'RUNNING' + | 'COMPLETED' + | 'EXPIRED' + | 'TERMINATED'; +⋮---- +export interface SpotPovOrder { + id?: string; + currency_pair?: string; + side?: string; + amount?: string; + participation_rate?: number; + ttl?: string; + limit_price?: string; + trigger_price?: string; + status?: SpotPovOrderStatus | string; + terminated_as?: string; + start_time_ms?: number; + end_time_ms?: number; + expire_time_ms?: number; + create_time_ms?: number; + update_time_ms?: number; + text?: string; +} + +================ +File: src/lib/BaseRestClient.ts +================ +import axios, { AxiosRequestConfig, AxiosResponse, Method } from 'axios'; +// NOTE: https.Agent is Node.js-only and not available in browser environments +// Browser builds (via webpack) exclude this module - see webpack.config.js fallback settings +import https from 'https'; +⋮---- +import { neverGuard } from './misc-util.js'; +import { + CHANNEL_ID, + getFuturesSizeDecimalHeaders, + getRestBaseUrl, + isFuturesMarketRestEndpoint, + RestClientOptions, + serializeParams, +} from './requestUtils.js'; +import { + checkWebCryptoAPISupported, + hashMessage, + SignAlgorithm, + SignEncodeMethod, + signMessage, +} from './webCryptoAPI.js'; +⋮---- +/** + * Used to switch how authentication/requests work under the hood + */ +⋮---- +export type RestClientType = + (typeof REST_CLIENT_TYPE_ENUM)[keyof typeof REST_CLIENT_TYPE_ENUM]; +⋮---- +interface SignedRequest { + originalParams: T; + paramsWithSign?: T & { sign: string }; + serializedParams: string; + sign: string; + queryParamsWithSign: string; + timestamp: number; + recvWindow: number; +} +⋮---- +interface UnsignedRequest { + originalParams: T; + paramsWithSign: T; +} +⋮---- +type SignMethod = 'gateV4'; +⋮---- +/** + * Some requests require some params to be in the query string and some in the body. Some even support passing params via headers. + * This type anticipates these are possible in any combination. + * + * The request builder will automatically handle where parameters should go. + */ +type ParamsInQueryBodyOrHeader = { + query?: object; + body?: object; + headers?: object; + /** multipart/form-data body; mutually exclusive with `body` */ + multipart?: FormData; +}; +⋮---- +/** multipart/form-data body; mutually exclusive with `body` */ +⋮---- +/** + * Enables: + * - Detailed request/response logging + * - Full request dump in any exceptions thrown from API responses + */ +⋮---- +// request: { +// url: response.config.url, +// method: response.config.method, +// data: response.config.data, +// headers: response.config.headers, +// }, +⋮---- +/** + * Impure, mutates params to remove any values that have a key but are undefined. + */ +function deleteUndefinedValues(params?: any): void +⋮---- +export abstract class BaseRestClient +⋮---- +/** Defines the client type (affecting how requests & signatures behave) */ +abstract getClientType(): RestClientType; +⋮---- +/** + * Create an instance of the REST client. Pass API credentials in the object in the first parameter. + * @param {RestClientOptions} [restClientOptions={}] options to configure REST API connectivity + * @param {AxiosRequestConfig} [networkOptions={}] HTTP networking options for axios + */ +constructor( + restClientOptions: RestClientOptions = {}, + networkOptions: AxiosRequestConfig = {}, +) +⋮---- +/** Throw errors if any request params are empty */ +⋮---- +/** in ms == 5 minutes by default */ +⋮---- +/** inject custom rquest options based on axios specs - see axios docs for more guidance on AxiosRequestConfig: https://github.com/axios/axios#request-config */ +⋮---- +// If enabled, configure a https agent with keepAlive enabled +// NOTE: This is Node.js-only functionality. In browser environments, this code is skipped +// as the 'https' module is excluded via webpack fallback configuration. +// Browser connection pooling is handled automatically by the browser itself. +⋮---- +// Extract existing https agent parameters, if provided, to prevent the keepAlive flag from overwriting an existing https agent completely +⋮---- +// For more advanced configuration, raise an issue on GitHub or use the "networkOptions" +// parameter to define a custom httpsAgent with the desired properties +⋮---- +// Check Web Crypto API support when credentials are provided and no custom sign function is used +⋮---- +// Throw if one of the 3 values is missing, but at least one of them is set +⋮---- +/** + * Timestamp used to sign the request. Override this method to implement your own timestamp/sync mechanism + */ +getSignTimestampMs(): number +⋮---- +protected get(endpoint: string, params?: object) ⋮---- -export type SpotPovOrderStatus = - | 'CREATED' - | 'CANCELING' - | 'RUNNING' - | 'COMPLETED' - | 'EXPIRED' - | 'TERMINATED'; +// GET only supports params in the query string ⋮---- -export interface SpotPovOrder { - id?: string; - currency_pair?: string; - side?: string; - amount?: string; - participation_rate?: number; - ttl?: string; - limit_price?: string; - trigger_price?: string; - status?: SpotPovOrderStatus | string; - terminated_as?: string; - start_time_ms?: number; - end_time_ms?: number; - expire_time_ms?: number; - create_time_ms?: number; - update_time_ms?: number; - text?: string; -} - -================ -File: src/types/response/unified.ts -================ -export interface UnifiedAccountInfo { - mode: 'classic' | 'multi_currency' | 'portfolio' | 'single_currency'; // classic: Classic account; multi_currency: Multi-currency margin; portfolio: Portfolio margin; single_currency: Single-currency margin - user_id: number; - refresh_time: number; - locked: boolean; // Whether the account is locked; valid in cross-currency/combined margin mode, false in other modes such as single-currency margin - balances: { - [key: string]: { - available: string; // Cross available balance, after deducting futures isolated margin occupation and frozen amount (futures isolated occupation = futures isolated balance); effective in single-currency/multi-currency/portfolio margin mode - freeze: string; // Frozen amount; effective in single-currency/multi-currency/portfolio margin mode - borrowed: string; // Borrowed amount; valid in cross-currency/combined margin mode, 0 in other modes such as single-currency margin - negative_liab: string; // Negative balance borrowing; valid in cross-currency/combined margin mode, 0 in other modes such as single-currency margin - futures_pos_liab: string; // Contract opening position borrowing currency (abandoned, to be removed) - equity: string; // Currency equity amount (cross); effective in single-currency/multi-currency/portfolio margin mode - total_freeze: string; // Total frozen (deprecated, to be removed) - total_liab: string; // Total borrowed amount; valid in cross-currency/combined margin mode, 0 in other modes such as single-currency margin - spot_in_use: string; // Spot hedging amount; valid in combined (portfolio) margin mode, 0 in single-currency and cross-currency margin modes - funding: string; // Uniloan / Earn amount; effective when Earn is enabled as unified account margin - funding_version: string; // Funding version - cross_balance: string; // Full margin balance; valid in single-currency margin mode, 0 in cross-currency/combined margin mode - iso_balance: string; // Futures isolated balance; effective in single-currency and multi-currency margin mode, 0 in portfolio margin mode - im: string; // Cross initial margin; only effective for USDT in single-currency margin mode, 0 in multi-currency/portfolio margin mode - mm: string; // Cross maintenance margin; only effective for USDT in single-currency margin mode, 0 in multi-currency/portfolio margin mode - mmr: string; // Cross maintenance margin rate; only effective for USDT in single-currency margin mode, 0 in multi-currency/portfolio margin mode - margin_balance: string; // Cross margin balance; only effective for USDT in single-currency margin mode, 0 in multi-currency/portfolio margin mode - available_margin: string; // Cross available margin; only effective for USDT in single-currency margin mode, 0 in multi-currency/portfolio margin mode - imr?: string; // Cross initial margin rate; only effective for USDT in single-currency margin mode, 0 in multi-currency/portfolio margin mode - enabled_collateral?: boolean; // Currency enabled as margin: true — enabled, false — disabled - balance_version?: number; // Balance version number (int64) - }; - }; - total: string; // Total account assets in USD: sum of (available + freeze) * price per currency (deprecated; use unified_account_total) - borrowed: string; // Total borrowed in USD: sum of borrowed * price (excluding point cards); valid in cross-currency/combined margin mode, 0 in single-currency margin mode - total_initial_margin: string; // Total initial margin (cross); effective in multi-currency/portfolio margin mode, 0 in single-currency margin mode - total_margin_balance: string; // Total margin balance (cross); effective in multi-currency/portfolio margin mode, 0 in single-currency margin mode - total_maintenance_margin: string; // Total maintenance margin (cross); effective in multi-currency/portfolio margin mode, 0 in single-currency margin mode - total_initial_margin_rate: string; // Total initial margin rate (cross); effective in multi-currency/portfolio margin mode, 0 in single-currency margin mode - total_maintenance_margin_rate: string; // Total maintenance margin rate (cross); effective in multi-currency/portfolio margin mode, 0 in single-currency margin mode - total_available_margin: string; // Available margin; valid in cross-currency/combined margin mode, 0 in single-currency margin mode - unified_account_total: string; // Total unified account assets: cross + isolated in single/multi-currency mode; cross only in portfolio margin mode - unified_account_total_liab: string; // Total unified borrowed (cross); effective in multi-currency/portfolio margin mode, 0 in single-currency margin mode - unified_account_total_equity: string; // Total unified equity: cross + isolated in single/multi-currency mode; cross only in portfolio margin mode - leverage: string; // Account leverage; effective in multi-currency/portfolio margin mode (deprecated; prefer GET /unified/leverage/user_currency_setting) - spot_order_loss: string; // Spot pending order loss (USDT); only in cross-currency and portfolio margin mode - options_order_loss?: string; // v4.105.29: Option pending order loss (USDT); only in portfolio margin mode - spot_hedge: boolean; // Spot hedging: true — enabled, false — disabled - margin_mode?: string; - total_balance?: string; - cross_leverage?: string; - portfolio_margin?: string; - risk_level?: string; - is_all_collateral?: boolean; // Whether all currencies are used as margin: true — all as margin, false — not all - borrow_amount?: string; - cross_margin_leverage?: string; - use_funding?: boolean; // Whether Earn funds are used as margin -} +protected post(endpoint: string, params?: ParamsInQueryBodyOrHeader) ⋮---- -mode: 'classic' | 'multi_currency' | 'portfolio' | 'single_currency'; // classic: Classic account; multi_currency: Multi-currency margin; portfolio: Portfolio margin; single_currency: Single-currency margin +protected getPrivate(endpoint: string, params?: object) ⋮---- -locked: boolean; // Whether the account is locked; valid in cross-currency/combined margin mode, false in other modes such as single-currency margin +// GET only supports params in the query string ⋮---- -available: string; // Cross available balance, after deducting futures isolated margin occupation and frozen amount (futures isolated occupation = futures isolated balance); effective in single-currency/multi-currency/portfolio margin mode -freeze: string; // Frozen amount; effective in single-currency/multi-currency/portfolio margin mode -borrowed: string; // Borrowed amount; valid in cross-currency/combined margin mode, 0 in other modes such as single-currency margin -negative_liab: string; // Negative balance borrowing; valid in cross-currency/combined margin mode, 0 in other modes such as single-currency margin -futures_pos_liab: string; // Contract opening position borrowing currency (abandoned, to be removed) -equity: string; // Currency equity amount (cross); effective in single-currency/multi-currency/portfolio margin mode -total_freeze: string; // Total frozen (deprecated, to be removed) -total_liab: string; // Total borrowed amount; valid in cross-currency/combined margin mode, 0 in other modes such as single-currency margin -spot_in_use: string; // Spot hedging amount; valid in combined (portfolio) margin mode, 0 in single-currency and cross-currency margin modes -funding: string; // Uniloan / Earn amount; effective when Earn is enabled as unified account margin -funding_version: string; // Funding version -cross_balance: string; // Full margin balance; valid in single-currency margin mode, 0 in cross-currency/combined margin mode -iso_balance: string; // Futures isolated balance; effective in single-currency and multi-currency margin mode, 0 in portfolio margin mode -im: string; // Cross initial margin; only effective for USDT in single-currency margin mode, 0 in multi-currency/portfolio margin mode -mm: string; // Cross maintenance margin; only effective for USDT in single-currency margin mode, 0 in multi-currency/portfolio margin mode -mmr: string; // Cross maintenance margin rate; only effective for USDT in single-currency margin mode, 0 in multi-currency/portfolio margin mode -margin_balance: string; // Cross margin balance; only effective for USDT in single-currency margin mode, 0 in multi-currency/portfolio margin mode -available_margin: string; // Cross available margin; only effective for USDT in single-currency margin mode, 0 in multi-currency/portfolio margin mode -imr?: string; // Cross initial margin rate; only effective for USDT in single-currency margin mode, 0 in multi-currency/portfolio margin mode -enabled_collateral?: boolean; // Currency enabled as margin: true — enabled, false — disabled -balance_version?: number; // Balance version number (int64) +protected postPrivate(endpoint: string, params?: ParamsInQueryBodyOrHeader) ⋮---- -total: string; // Total account assets in USD: sum of (available + freeze) * price per currency (deprecated; use unified_account_total) -borrowed: string; // Total borrowed in USD: sum of borrowed * price (excluding point cards); valid in cross-currency/combined margin mode, 0 in single-currency margin mode -total_initial_margin: string; // Total initial margin (cross); effective in multi-currency/portfolio margin mode, 0 in single-currency margin mode -total_margin_balance: string; // Total margin balance (cross); effective in multi-currency/portfolio margin mode, 0 in single-currency margin mode -total_maintenance_margin: string; // Total maintenance margin (cross); effective in multi-currency/portfolio margin mode, 0 in single-currency margin mode -total_initial_margin_rate: string; // Total initial margin rate (cross); effective in multi-currency/portfolio margin mode, 0 in single-currency margin mode -total_maintenance_margin_rate: string; // Total maintenance margin rate (cross); effective in multi-currency/portfolio margin mode, 0 in single-currency margin mode -total_available_margin: string; // Available margin; valid in cross-currency/combined margin mode, 0 in single-currency margin mode -unified_account_total: string; // Total unified account assets: cross + isolated in single/multi-currency mode; cross only in portfolio margin mode -unified_account_total_liab: string; // Total unified borrowed (cross); effective in multi-currency/portfolio margin mode, 0 in single-currency margin mode -unified_account_total_equity: string; // Total unified equity: cross + isolated in single/multi-currency mode; cross only in portfolio margin mode -leverage: string; // Account leverage; effective in multi-currency/portfolio margin mode (deprecated; prefer GET /unified/leverage/user_currency_setting) -spot_order_loss: string; // Spot pending order loss (USDT); only in cross-currency and portfolio margin mode -options_order_loss?: string; // v4.105.29: Option pending order loss (USDT); only in portfolio margin mode -spot_hedge: boolean; // Spot hedging: true — enabled, false — disabled +/** POST private endpoint with multipart/form-data (empty body hash for signing) */ +protected postPrivateMultipart( + endpoint: string, + formData: FormData, + query?: object, +) ⋮---- -is_all_collateral?: boolean; // Whether all currencies are used as margin: true — all as margin, false — not all +protected deletePrivate( + endpoint: string, + params?: ParamsInQueryBodyOrHeader, +) ⋮---- -use_funding?: boolean; // Whether Earn funds are used as margin +protected putPrivate(endpoint: string, params?: ParamsInQueryBodyOrHeader) ⋮---- -export interface UnifiedLoan { - currency: string; - currency_pair: string; - amount: string; - type: 'platform' | 'margin'; - create_time: number; - update_time: number; -} +// protected patchPrivate(endpoint: string, params?: any) { +protected patchPrivate(endpoint: string, params?: ParamsInQueryBodyOrHeader) ⋮---- -export interface UnifiedLoanRecord { - id: number; - type: 'borrow' | 'repay'; - repayment_type: 'none' | 'manual_repay' | 'auto_repay' | 'cancel_auto_repay'; - currency_pair: string; - currency: string; - amount: string; - create_time: number; - borrow_type: string; -} -export interface UnifiedInterestRecord { - currency: string; - currency_pair: string; - actual_rate: string; - interest: string; - status: number; - type: 'platform' | 'margin'; - create_time: number; -} +/** + * @private Make a HTTP request to a specific endpoint. Private endpoint API calls are automatically signed. + */ +private async _call( + method: Method, + endpoint: string, + params?: ParamsInQueryBodyOrHeader, + isPublicApi?: boolean, +): Promise ⋮---- -export interface UnifiedRiskUnitDetails { - user_id: number; - spot_hedge: boolean; - risk_units: { - symbol: string; - spot_in_use: string; - maintain_margin: string; - initial_margin: string; - delta: string; - gamma: string; - theta: string; - vega: string; - }[]; -} +// Sanity check to make sure it's only ever prefixed by one forward slash ⋮---- -export interface UnifiedCurrencyDiscountTiers { - currency: string; - discount_tiers: { - tier: string; - discount: string; - lower_limit: string; - upper_limit: string; - leverage: string; - }[]; -} +// Build a request and handle signature process ⋮---- -export interface UserCurrencyLeverageConfig { - current_leverage: string; - min_leverage: string; - max_leverage: string; - debit: string; - available_margin: string; - borrowable: string; - except_leverage_borrowable: string; -} +// Dispatch request ⋮---- -export interface UnifiedLoanCurrency { - name: string; - prec: string; - min_borrow_amount: string; - user_max_borrow_amount: string; - total_max_borrow_amount: string; - loan_status: string; -} +// See: https://www.gate.io/docs/developers/apiv4/en/#return-format ⋮---- -export interface UnifiedHistoryLendingRate { - currency: string; - tier: string; - tier_up_rate: string; - rates: { - time: number; - rate: string; - }[]; -} +// Throw API rejections by parsing the response code from the body ⋮---- -export interface MarginTier { - tier: string; - margin_rate: string; - lower_limit: string; - upper_limit: string; -} +/** + * @private generic handler to parse request exceptions + */ +parseException(e: any, request: AxiosRequestConfig): unknown +⋮---- +// Something happened in setting up the request that triggered an error +⋮---- +// request made but no response received +⋮---- +// The request was made and the server responded with a status code +// that falls out of the range of 2xx +⋮---- +// console.error('err: ', response?.data); +⋮---- +// Prevent credentials from leaking into error messages ⋮---- -export interface PortfolioMarginCalculation { - maintain_margin_total: string; - initial_margin_total: string; - calculate_time: number; - risk_unit: { - symbol: string; - spot_in_use: string; - maintain_margin: string; - initial_margin: string; - margin_result: { - type: - | 'original_position' - | 'long_delta_original_position' - | 'short_delta_original_position'; - profit_loss_ranges: { - price_percentage: string; - implied_volatility_percentage: string; - profit_loss: string; - }[]; - max_loss: { - price_percentage: string; - implied_volatility_percentage: string; - profit_loss: string; - }; - mr1: string; - mr2: string; - mr3: string; - mr4: string; - delta: string; - gamma: string; - theta: string; - vega: string; - }[]; - }[]; -} +/** + * @private sign request and set recv window + */ +private async signRequest< + T extends ParamsInQueryBodyOrHeader | undefined = {}, + >( + data: T, + endpoint: string, + method: Method, + signMethod: SignMethod, +): Promise> ⋮---- -export interface UnifiedCollateralCurrenciesResp { - is_success: boolean; -} +const timestamp = +(this.getSignTimestampMs() / 1000).toFixed(0); // in seconds ⋮---- -export interface UnifiedQuickRepayDebtItem { - currency?: string; - debt_amount?: string; - estimated_usd?: string; - borrowed?: string; - neg_balance?: string; -} +// recvWindow: this.options.recvWindow, ⋮---- -export interface UnifiedQuickRepayAvailableItem { - currency?: string; - available?: string; - estimated_usd?: string; -} +// It's possible to override the recv window on a per rquest level ⋮---- -export interface QuickEstimatedRepayment { - debt_currencies?: UnifiedQuickRepayDebtItem[]; - available_currencies?: UnifiedQuickRepayAvailableItem[]; -} +// console.log('sign params: ', { +// requestBodyToHash, +// paramsStr: toSign, +// url: this.baseUrl, +// urlPath: this.baseUrlPath, +// }); ⋮---- -export interface QuickRepayRepaidInfo { - currency: string; - repaid: string; - left: string; -} +private async signMessage( + paramsStr: string, + secret: string, + method: 'hex' | 'base64', + algorithm: SignAlgorithm, +): Promise ⋮---- -export interface QuickRepayUsedInfo { - currency: string; - used: string; -} +private async prepareSignParams< + TParams extends ParamsInQueryBodyOrHeader | undefined, + >( + method: Method, + endpoint: string, + signMethod: SignMethod, + params?: TParams, + isPublicApi?: true, + ): Promise>; ⋮---- -export interface QuickRepaymentResp { - order_id: string; - repaid_infos: QuickRepayRepaidInfo[]; - used_infos: QuickRepayUsedInfo[]; -} +private async prepareSignParams< + TParams extends ParamsInQueryBodyOrHeader | undefined, + >( + method: Method, + endpoint: string, + signMethod: SignMethod, + params?: TParams, + isPublicApi?: false | undefined, + ): Promise>; ⋮---- -/** GET/POST /unified/delta_neutral — v4.106.97 */ -export interface DeltaNeutralEnabled { - enabled: boolean; -} +private async prepareSignParams< + TParams extends ParamsInQueryBodyOrHeader | undefined, + >( + method: Method, + endpoint: string, + signMethod: SignMethod, + params?: TParams, + isPublicApi?: boolean, +) ⋮---- -/** POST /unified/leverage/user_setting failed currency entry */ -export interface LeverageFailedCurrency { - currency: string; - reason: string; -} +/** Returns an axios request object. Handles signing process automatically if this is a private API call */ +private async buildRequest( + method: Method, + endpoint: string, + url: string, + params?: ParamsInQueryBodyOrHeader, + isPublicApi?: boolean, +): Promise ================ -File: src/lib/BaseRestClient.ts +File: src/types/request/futures.ts ================ -import axios, { AxiosRequestConfig, AxiosResponse, Method } from 'axios'; -// NOTE: https.Agent is Node.js-only and not available in browser environments -// Browser builds (via webpack) exclude this module - see webpack.config.js fallback settings -import https from 'https'; +import { FuturesContractSize } from '../shared.js'; ⋮---- -import { neverGuard } from './misc-util.js'; -import { - CHANNEL_ID, - getRestBaseUrl, - RestClientOptions, - serializeParams, -} from './requestUtils.js'; -import { - checkWebCryptoAPISupported, - hashMessage, - SignAlgorithm, - SignEncodeMethod, - signMessage, -} from './webCryptoAPI.js'; -⋮---- -/** - * Used to switch how authentication/requests work under the hood +/**========================================================================================================================== + * FUTURES + * ========================================================================================================================== */ ⋮---- -export type RestClientType = - (typeof REST_CLIENT_TYPE_ENUM)[keyof typeof REST_CLIENT_TYPE_ENUM]; +export type FuturesSettle = 'btc' | 'usdt' | 'usd' | 'usd1'; ⋮---- -interface SignedRequest { - originalParams: T; - paramsWithSign?: T & { sign: string }; - serializedParams: string; - sign: string; - queryParamsWithSign: string; - timestamp: number; - recvWindow: number; +export interface GetFuturesOrderBookReq { + settle: FuturesSettle; + contract: string; + interval?: string; + limit?: number; + with_id?: boolean; } ⋮---- -interface UnsignedRequest { - originalParams: T; - paramsWithSign: T; +export interface GetFuturesTradesReq { + settle: FuturesSettle; + contract: string; + limit?: number; + offset?: number; + last_id?: string; + from?: number; + to?: number; } ⋮---- -type SignMethod = 'gateV4'; +export interface GetFuturesCandlesReq { + settle: FuturesSettle; + contract: string; + from?: number; + to?: number; + limit?: number; + interval?: string; +} ⋮---- -/** - * Some requests require some params to be in the query string and some in the body. Some even support passing params via headers. - * This type anticipates these are possible in any combination. - * - * The request builder will automatically handle where parameters should go. - */ -type ParamsInQueryBodyOrHeader = { - query?: object; - body?: object; - headers?: object; - /** multipart/form-data body; mutually exclusive with `body` */ - multipart?: FormData; -}; +export interface GetFuturesStatsReq { + settle: FuturesSettle; + contract: string; + from?: number; + interval?: string; + limit?: number; +} ⋮---- -/** multipart/form-data body; mutually exclusive with `body` */ +export interface GetFundingRatesReq { + settle: FuturesSettle; + contract: string; + limit?: number; + from?: number; + to?: number; +} ⋮---- -/** - * Enables: - * - Detailed request/response logging - * - Full request dump in any exceptions thrown from API responses - */ +export interface BatchFundingRatesReq { + settle: 'btc' | 'usdt' | 'usd1'; + contracts: string[]; +} +⋮---- +export interface GetLiquidationHistoryReq { + settle: FuturesSettle; + contract?: string; + from?: number; + to?: number; + limit?: number; +} +⋮---- +export interface GetRiskLimitTiersReq { + settle: FuturesSettle; + contract: string; + limit?: number; + offset?: number; +} +⋮---- +export interface GetRiskLimitTableReq { + settle: FuturesSettle; + table_id: string; +} ⋮---- -// request: { -// url: response.config.url, -// method: response.config.method, -// data: response.config.data, -// headers: response.config.headers, -// }, +export interface GetFuturesAccountBookReq { + settle: FuturesSettle; + contract?: string; + limit?: number; + offset?: number; + from?: number; + to?: number; + type?: + | 'dnw' + | 'pnl' + | 'fee' + | 'refr' + | 'fund' + | 'point_dnw' + | 'point_fee' + | 'point_refr' + | 'bonus_offset'; +} ⋮---- -/** - * Impure, mutates params to remove any values that have a key but are undefined. - */ -function deleteUndefinedValues(params?: any): void +export interface GetFuturesADLRiskStatesReq { + settle: 'btc' | 'usdt' | 'usd1'; +} ⋮---- -export abstract class BaseRestClient +export interface GetFuturesPositionsReq { + settle: FuturesSettle; + holding?: boolean; + limit?: number; // deprecated, use positions_limit instead + positions_limit?: number; // v4.106.104: Replaces limit; omit to return full list, explicit values capped at 1-100 + offset?: number; + position_side?: string; // v4.105.3: Add position_side parameter for hedge mode support + hedge_mode?: boolean; // v4.104.3: Add hedge_mode parameter +} ⋮---- -/** Defines the client type (affecting how requests & signatures behave) */ -abstract getClientType(): RestClientType; +limit?: number; // deprecated, use positions_limit instead +positions_limit?: number; // v4.106.104: Replaces limit; omit to return full list, explicit values capped at 1-100 ⋮---- -/** - * Create an instance of the REST client. Pass API credentials in the object in the first parameter. - * @param {RestClientOptions} [restClientOptions={}] options to configure REST API connectivity - * @param {AxiosRequestConfig} [networkOptions={}] HTTP networking options for axios - */ -constructor( - restClientOptions: RestClientOptions = {}, - networkOptions: AxiosRequestConfig = {}, -) +position_side?: string; // v4.105.3: Add position_side parameter for hedge mode support +hedge_mode?: boolean; // v4.104.3: Add hedge_mode parameter ⋮---- -/** Throw errors if any request params are empty */ +export interface UpdateDualModePositionMarginReq { + settle: FuturesSettle; + contract: string; + change: string; + dual_side: 'dual_long' | 'dual_short'; +} ⋮---- -/** in ms == 5 minutes by default */ +export interface UpdateDualModePositionLeverageReq { + settle: FuturesSettle; + contract: string; + leverage: string; + cross_leverage_limit?: string; +} ⋮---- -/** inject custom rquest options based on axios specs - see axios docs for more guidance on AxiosRequestConfig: https://github.com/axios/axios#request-config */ +export interface SubmitFuturesOrderReq { + xGateExptime?: number; + settle: FuturesSettle; + contract: string; + /** String when `futuresSizeDecimal` is enabled on the client. */ + size: FuturesContractSize; + /** String when `futuresSizeDecimal` is enabled on the client. */ + iceberg?: FuturesContractSize; + price?: string; + close?: boolean; + reduce_only?: boolean; + tif?: string; + text?: string; + auto_size?: string; + stp_act?: string; + action_mode?: 'ACK' | 'RESULT' | 'FULL'; + tpsl_tp_trigger_price?: string; + tpsl_sl_trigger_price?: string; + pos_margin_mode?: 'isolated' | 'cross'; +} ⋮---- -// If enabled, configure a https agent with keepAlive enabled -// NOTE: This is Node.js-only functionality. In browser environments, this code is skipped -// as the 'https' module is excluded via webpack fallback configuration. -// Browser connection pooling is handled automatically by the browser itself. +/** String when `futuresSizeDecimal` is enabled on the client. */ ⋮---- -// Extract existing https agent parameters, if provided, to prevent the keepAlive flag from overwriting an existing https agent completely +/** String when `futuresSizeDecimal` is enabled on the client. */ ⋮---- -// For more advanced configuration, raise an issue on GitHub or use the "networkOptions" -// parameter to define a custom httpsAgent with the desired properties +export interface GetFuturesOrdersReq { + settle: FuturesSettle; + contract?: string; + status: string; + limit?: number; + offset?: number; + last_id?: string; +} ⋮---- -// Check Web Crypto API support when credentials are provided and no custom sign function is used +export interface DeleteAllFuturesOrdersReq { + xGateExptime?: number; + settle: FuturesSettle; + contract: string; + side?: string; + action_mode?: 'ACK' | 'RESULT' | 'FULL'; +} ⋮---- -// Throw if one of the 3 values is missing, but at least one of them is set +export interface GetFuturesOrdersByTimeRangeReq { + settle: FuturesSettle; + contract?: string; + from?: number; + to?: number; + limit?: number; + offset?: number; +} ⋮---- -/** - * Timestamp used to sign the request. Override this method to implement your own timestamp/sync mechanism - */ -getSignTimestampMs(): number +export interface UpdateFuturesOrderReq { + xGateExptime?: number; + settle: FuturesSettle; + order_id: string; + /** String when `futuresSizeDecimal` is enabled on the client. */ + size?: FuturesContractSize; + price?: string; + amend_text?: string; +} ⋮---- -protected get(endpoint: string, params?: object) +/** String when `futuresSizeDecimal` is enabled on the client. */ ⋮---- -// GET only supports params in the query string +export interface GetFuturesTradingHistoryReq { + settle: FuturesSettle; + contract?: string; + order?: number; + limit?: number; + offset?: number; + last_id?: string; +} ⋮---- -protected post(endpoint: string, params?: ParamsInQueryBodyOrHeader) +export interface GetFuturesTradingHistoryByTimeRangeReq { + settle: FuturesSettle; + contract?: string; + from?: number; + to?: number; + limit?: number; + offset?: number; + role?: 'maker' | 'taker'; +} ⋮---- -protected getPrivate(endpoint: string, params?: object) +export interface GetFuturesPositionHistoryReq { + settle: FuturesSettle; + contract?: string; + limit?: number; + offset?: number; + from?: number; + to?: number; + side?: 'long' | 'short'; + pnl?: string; +} ⋮---- -// GET only supports params in the query string +export interface GetFuturesLiquidationHistoryReq { + settle: FuturesSettle; + contract?: string; + limit?: number; + at?: number; +} ⋮---- -protected postPrivate(endpoint: string, params?: ParamsInQueryBodyOrHeader) +export interface SubmitFuturesTriggeredOrderReq { + initial: { + contract: string; + /** String when `futuresSizeDecimal` is enabled on the client. */ + size?: FuturesContractSize; + /** Decimal contract size; if both `size` and `amount` are set, `amount` takes precedence */ + amount?: string; + price: string; // Required: Order price. Set to 0 to use market price + close?: boolean; + tif?: 'gtc' | 'ioc'; + text?: string; + reduce_only?: boolean; + auto_size?: string; + }; + trigger: { + strategy_type?: 0 | 1; + price_type?: 0 | 1 | 2; + price: string; // Required: Price value for price trigger + rule: 1 | 2; // Required: Price Condition Type (1: >=, 2: <=) + expiration?: number; + }; + order_type?: + | 'close-long-order' + | 'close-short-order' + | 'close-long-position' + | 'close-short-position' + | 'plan-close-long-position' + | 'plan-close-short-position'; + settle: FuturesSettle; +} ⋮---- -/** POST private endpoint with multipart/form-data (empty body hash for signing) */ -protected postPrivateMultipart( - endpoint: string, - formData: FormData, - query?: object, -) +/** String when `futuresSizeDecimal` is enabled on the client. */ ⋮---- -protected deletePrivate( - endpoint: string, - params?: ParamsInQueryBodyOrHeader, -) +/** Decimal contract size; if both `size` and `amount` are set, `amount` takes precedence */ ⋮---- -protected putPrivate(endpoint: string, params?: ParamsInQueryBodyOrHeader) +price: string; // Required: Order price. Set to 0 to use market price ⋮---- -// protected patchPrivate(endpoint: string, params?: any) { -protected patchPrivate(endpoint: string, params?: ParamsInQueryBodyOrHeader) +price: string; // Required: Price value for price trigger +rule: 1 | 2; // Required: Price Condition Type (1: >=, 2: <=) +⋮---- +export interface GetFuturesAutoOrdersReq { + settle: FuturesSettle; + status: 'open' | 'finished'; + contract?: string; + limit?: number; + offset?: number; +} ⋮---- /** - * @private Make a HTTP request to a specific endpoint. Private endpoint API calls are automatically signed. - */ -private async _call( - method: Method, - endpoint: string, - params?: ParamsInQueryBodyOrHeader, - isPublicApi?: boolean, -): Promise + * Modify contract order parameters + */ +export interface BatchAmendOrderReq { + order_id?: number; // Order id, order_id and text must contain at least one + text?: string; // User-defined order text, at least one of order_id and text must be passed + /** String when `futuresSizeDecimal` is enabled on the client. */ + size?: FuturesContractSize; // The new order size, including the executed order size + price?: string; // New order price + amend_text?: string; // Custom info during amending order +} ⋮---- -// Sanity check to make sure it's only ever prefixed by one forward slash +order_id?: number; // Order id, order_id and text must contain at least one +text?: string; // User-defined order text, at least one of order_id and text must be passed +/** String when `futuresSizeDecimal` is enabled on the client. */ +size?: FuturesContractSize; // The new order size, including the executed order size +price?: string; // New order price +amend_text?: string; // Custom info during amending order ⋮---- -// Build a request and handle signature process +// v4.105.8: New GET /futures/{settle}/position_close_history endpoint request +export interface GetFuturesPositionCloseHistoryReq { + settle: FuturesSettle; + contract?: string; + limit?: number; + offset?: number; + from?: number; + to?: number; +} +⋮---- +// v4.104.6: New GET /futures/{settle}/insurance endpoint request +export interface GetFuturesInsuranceReq { + settle: FuturesSettle; + limit?: number; +} ⋮---- -// Dispatch request +export interface UpdateFuturesPriceTriggeredOrderReq { + settle: FuturesSettle; + order_id: number | string; + contract?: string; + /** String when `futuresSizeDecimal` is enabled on the client. */ + size?: FuturesContractSize; + /** Same semantics as `size` (decimal contract size) */ + amount?: string; + price?: string; + /** When fully closing in single-position mode, set true */ + close?: boolean; + trigger_price?: string; + price_type?: 0 | 1 | 2; // 0 - Latest trade price, 1 - Mark price, 2 - Index price + auto_size?: string; // Not required in single position mode +} ⋮---- -// See: https://www.gate.io/docs/developers/apiv4/en/#return-format +/** String when `futuresSizeDecimal` is enabled on the client. */ ⋮---- -// Throw API rejections by parsing the response code from the body +/** Same semantics as `size` (decimal contract size) */ ⋮---- -/** - * @private generic handler to parse request exceptions - */ -parseException(e: any, request: AxiosRequestConfig): unknown +/** When fully closing in single-position mode, set true */ ⋮---- -// Something happened in setting up the request that triggered an error +price_type?: 0 | 1 | 2; // 0 - Latest trade price, 1 - Mark price, 2 - Index price +auto_size?: string; // Not required in single position mode ⋮---- -// request made but no response received +/** GET /futures/{settle}/get_leverage/{contract} — v4.106.43: pos_margin_mode and dual_side required */ +export interface GetFuturesContractLeverageReq { + settle: FuturesSettle; + contract: string; + pos_margin_mode: 'isolated' | 'cross'; + dual_side: 'dual_long' | 'dual_short'; +} ⋮---- -// The request was made and the server responded with a status code -// that falls out of the range of 2xx +/** Trail order (autoorder/v1/trail) request types */ +export interface CreateTrailOrderReq { + settle: 'btc' | 'usdt'; + contract: string; + amount: string; + activation_price?: string; + is_gte?: boolean; + price_type?: 1 | 2 | 3; + price_offset?: string; + reduce_only?: boolean; + position_related?: boolean; + text?: string; + pos_margin_mode?: string; + position_mode?: string; +} ⋮---- -// console.error('err: ', response?.data); +export interface TerminateTrailOrderReq { + settle: 'btc' | 'usdt'; + id?: number; + text?: string; +} ⋮---- -// Prevent credentials from leaking into error messages +export interface BatchTerminateTrailOrdersReq { + settle: 'btc' | 'usdt'; + contract?: string; + related_position?: 1 | 2; +} ⋮---- -/** - * @private sign request and set recv window - */ -private async signRequest< - T extends ParamsInQueryBodyOrHeader | undefined = {}, - >( - data: T, - endpoint: string, - method: Method, - signMethod: SignMethod, -): Promise> +export interface GetTrailOrderListReq { + settle: 'btc' | 'usdt'; + contract?: string; + is_finished?: boolean; + start_at?: number; + end_at?: number; + page_num?: number; + page_size?: number; + sort_by?: 1 | 2; + hide_cancel?: boolean; + related_position?: 1 | 2; + sort_by_trigger?: boolean; + reduce_only?: 1 | 2; + side?: 1 | 2; +} ⋮---- -const timestamp = +(this.getSignTimestampMs() / 1000).toFixed(0); // in seconds +export interface GetTrailOrderDetailReq { + settle: 'btc' | 'usdt'; + id: number; +} ⋮---- -// recvWindow: this.options.recvWindow, +export interface UpdateTrailOrderReq { + settle: 'btc' | 'usdt'; + id: number; + amount?: string; + activation_price?: string; + is_gte_str?: string; + price_type?: 0 | 1 | 2 | 3; + price_offset?: string; +} ⋮---- -// It's possible to override the recv window on a per rquest level +export interface GetTrailOrderChangeLogReq { + settle: 'btc' | 'usdt'; + id: number; + page_num?: number; + page_size?: number; +} ⋮---- -// console.log('sign params: ', { -// requestBodyToHash, -// paramsStr: toSign, -// url: this.baseUrl, -// urlPath: this.baseUrlPath, -// }); +/** Chase limit order (autoorder/v1/chase) request types */ +export interface CreateChaseOrderReq { + settle: FuturesSettle; + contract: string; + amount: string; + price_limit: string; + offset_limit?: string; + reduce_only?: boolean; + text?: string; + is_dual_mode?: boolean; + price_type?: number; + price_gap_type?: number; + price_gap_value?: string; + pos_margin_mode?: 'isolated' | 'cross' | string; + position_mode?: string; +} ⋮---- -private async signMessage( - paramsStr: string, - secret: string, - method: 'hex' | 'base64', - algorithm: SignAlgorithm, -): Promise +export interface StopChaseOrderReq { + settle: FuturesSettle; + id?: string; + text?: string; +} ⋮---- -private async prepareSignParams< - TParams extends ParamsInQueryBodyOrHeader | undefined, - >( - method: Method, - endpoint: string, - signMethod: SignMethod, - params?: TParams, - isPublicApi?: true, - ): Promise>; +export interface StopAllChaseOrdersReq { + settle: FuturesSettle; + contract?: string; + pos_margin_mode?: 'isolated' | 'cross' | string; +} ⋮---- -private async prepareSignParams< - TParams extends ParamsInQueryBodyOrHeader | undefined, - >( - method: Method, - endpoint: string, - signMethod: SignMethod, - params?: TParams, - isPublicApi?: false | undefined, - ): Promise>; +export interface GetChaseOrdersReq { + settle: FuturesSettle; + contract?: string; + is_finished?: boolean; + start_at?: number; + end_at?: number; + page_num?: number; + page_size?: number; + /** 1 ORDER_SORT_CREATED_AT, 2 ORDER_SORT_FINISHED_AT */ + sort_by: 1 | 2; + hide_cancel?: boolean; + reduce_only?: 0 | 1 | 2; + side?: 0 | 1 | 2; +} ⋮---- -private async prepareSignParams< - TParams extends ParamsInQueryBodyOrHeader | undefined, - >( - method: Method, - endpoint: string, - signMethod: SignMethod, - params?: TParams, - isPublicApi?: boolean, -) +/** 1 ORDER_SORT_CREATED_AT, 2 ORDER_SORT_FINISHED_AT */ ⋮---- -/** Returns an axios request object. Handles signing process automatically if this is a private API call */ -private async buildRequest( - method: Method, - endpoint: string, - url: string, - params?: ParamsInQueryBodyOrHeader, - isPublicApi?: boolean, -): Promise +export interface GetChaseOrderDetailReq { + settle: FuturesSettle; + id: string; +} ================ File: src/types/response/futures.ts ================ +import { FuturesContractSize } from '../shared.js'; +⋮---- /**========================================================================================================================== * FUTURES * ========================================================================================================================== @@ -13466,8 +13592,8 @@ export interface FuturesOrderBook { id?: number; current: number; update: number; - asks: { p: string; s: number }[]; - bids: { p: string; s: number }[]; + asks: { p: string; s: FuturesContractSize }[]; + bids: { p: string; s: FuturesContractSize }[]; } ⋮---- export interface FuturesTrade { @@ -13475,16 +13601,20 @@ export interface FuturesTrade { create_time: number; create_time_ms: number; contract: string; - size: number; + /** String when `futuresSizeDecimal` is enabled on the client. */ + size: FuturesContractSize; price: string; is_internal?: boolean; // Deprecated } ⋮---- +/** String when `futuresSizeDecimal` is enabled on the client. */ +⋮---- is_internal?: boolean; // Deprecated ⋮---- export interface FuturesCandle { t: number; - v?: number; + /** String when `futuresSizeDecimal` is enabled on the client. */ + v?: FuturesContractSize; c: string; h: string; l: string; @@ -13492,6 +13622,8 @@ export interface FuturesCandle { sum: string; } ⋮---- +/** String when `futuresSizeDecimal` is enabled on the client. */ +⋮---- export interface PremiumIndexKLine { t: number; c: string; @@ -13537,28 +13669,52 @@ export interface FuturesStats { time: number; lsr_taker: number; lsr_account: number; - long_liq_size: number; + /** String when `futuresSizeDecimal` is enabled on the client. */ + long_liq_size: FuturesContractSize; long_liq_amount: number; long_liq_usd: number; long_liq_usd_new?: number; - short_liq_size: number; + /** String when `futuresSizeDecimal` is enabled on the client. */ + short_liq_size: FuturesContractSize; short_liq_amount: number; short_liq_usd: number; short_liq_usd_new?: number; - open_interest: number; + /** String when `futuresSizeDecimal` is enabled on the client. */ + open_interest: FuturesContractSize; open_interest_usd: number; top_lsr_account: number; - top_lsr_size: number; - top_long_size?: number; - top_short_size?: number; - long_taker_size?: number; - short_taker_size?: number; + /** String when `futuresSizeDecimal` is enabled on the client. */ + top_lsr_size: FuturesContractSize; + /** String when `futuresSizeDecimal` is enabled on the client. */ + top_long_size?: FuturesContractSize; + /** String when `futuresSizeDecimal` is enabled on the client. */ + top_short_size?: FuturesContractSize; + /** String when `futuresSizeDecimal` is enabled on the client. */ + long_taker_size?: FuturesContractSize; + /** String when `futuresSizeDecimal` is enabled on the client. */ + short_taker_size?: FuturesContractSize; top_long_account?: number; top_short_account?: number; long_users?: number; short_users?: number; } ⋮---- +/** String when `futuresSizeDecimal` is enabled on the client. */ +⋮---- +/** String when `futuresSizeDecimal` is enabled on the client. */ +⋮---- +/** String when `futuresSizeDecimal` is enabled on the client. */ +⋮---- +/** String when `futuresSizeDecimal` is enabled on the client. */ +⋮---- +/** String when `futuresSizeDecimal` is enabled on the client. */ +⋮---- +/** String when `futuresSizeDecimal` is enabled on the client. */ +⋮---- +/** String when `futuresSizeDecimal` is enabled on the client. */ +⋮---- +/** String when `futuresSizeDecimal` is enabled on the client. */ +⋮---- export interface IndexConstituents { index: string; constituents: { @@ -13570,13 +13726,22 @@ export interface IndexConstituents { export interface LiquidationHistoryRecord { time: number; contract: string; - size: number; - order_size: number; + /** String when `futuresSizeDecimal` is enabled on the client. */ + size: FuturesContractSize; + /** String when `futuresSizeDecimal` is enabled on the client. */ + order_size: FuturesContractSize; order_price: string; fill_price: string; - left: number; + /** String when `futuresSizeDecimal` is enabled on the client. */ + left: FuturesContractSize; } ⋮---- +/** String when `futuresSizeDecimal` is enabled on the client. */ +⋮---- +/** String when `futuresSizeDecimal` is enabled on the client. */ +⋮---- +/** String when `futuresSizeDecimal` is enabled on the client. */ +⋮---- export interface RiskLimitTier { tier: number; risk_limit: string; @@ -13673,8 +13838,10 @@ export interface FuturesOrder { | 'stp'; status?: 'open' | 'finished'; contract: string; - size: number; - iceberg?: number; + /** String when `futuresSizeDecimal` is enabled on the client. */ + size: FuturesContractSize; + /** String when `futuresSizeDecimal` is enabled on the client. */ + iceberg?: FuturesContractSize; price?: string; close?: boolean; is_close?: boolean; @@ -13682,7 +13849,8 @@ export interface FuturesOrder { is_reduce_only?: boolean; is_liq?: boolean; tif?: 'gtc' | 'ioc' | 'poc' | 'fok'; - left?: number; + /** String when `futuresSizeDecimal` is enabled on the client. */ + left?: FuturesContractSize; fill_price?: string; text?: string; tkfr?: string; @@ -13709,6 +13877,12 @@ export interface FuturesOrder { * Final state; **ioc** / **poc** reflect unfilled remainder cancelled by TIF (IOC vs post-only / maker). */ ⋮---- +/** String when `futuresSizeDecimal` is enabled on the client. */ +⋮---- +/** String when `futuresSizeDecimal` is enabled on the client. */ +⋮---- +/** String when `futuresSizeDecimal` is enabled on the client. */ +⋮---- /** Read-only; order notional in settle currency (API response only; omit from order requests). */ ⋮---- /** Read-only; traded value (API response only; omit from order requests). */ @@ -13743,7 +13917,8 @@ export interface FuturesOrderTimerange { export interface FuturesPosition { user?: number; contract?: string; - size?: number; + /** String when `futuresSizeDecimal` is enabled on the client. */ + size?: FuturesContractSize; leverage?: string; // Isolated margin leverage, 0 indicates cross margin mode risk_limit?: string; leverage_max?: string; // Max leverage based on current position size @@ -13785,6 +13960,8 @@ export interface FuturesPosition { unhedged_size?: string; // v4.106.97: Unhedged size under Delta-neutral strategy } ⋮---- +/** String when `futuresSizeDecimal` is enabled on the client. */ +⋮---- leverage?: string; // Isolated margin leverage, 0 indicates cross margin mode ⋮---- leverage_max?: string; // Max leverage based on current position size @@ -13816,15 +13993,21 @@ export interface FuturesTradingHistoryRecord { create_time: number; contract: string; order_id: string; - size: number; + /** String when `futuresSizeDecimal` is enabled on the client. */ + size: FuturesContractSize; price: string; role: 'taker' | 'maker'; text: string; fee: string; point_fee: string; - close_size: number; + /** String when `futuresSizeDecimal` is enabled on the client. */ + close_size: FuturesContractSize; } ⋮---- +/** String when `futuresSizeDecimal` is enabled on the client. */ +⋮---- +/** String when `futuresSizeDecimal` is enabled on the client. */ +⋮---- export interface FuturesPositionHistoryRecord { time: number; contract: string; @@ -13845,7 +14028,8 @@ export interface FuturesLiquidationHistoryRecord { time: number; contract: string; leverage: string; - size: number; + /** String when `futuresSizeDecimal` is enabled on the client. */ + size: FuturesContractSize; margin: string; entry_price: string; liq_price: string; @@ -13853,8 +14037,14 @@ export interface FuturesLiquidationHistoryRecord { order_id: number; order_price: string; fill_price: string; - left: number; + /** String when `futuresSizeDecimal` is enabled on the client. */ + left: FuturesContractSize; } +⋮---- +/** String when `futuresSizeDecimal` is enabled on the client. */ +⋮---- +/** String when `futuresSizeDecimal` is enabled on the client. */ +⋮---- export interface FuturesAutoDeleveragingHistoryRecord { time: number; user: number; @@ -13864,13 +14054,19 @@ export interface FuturesAutoDeleveragingHistoryRecord { cross_leverage_limit: string; // Clarified for better understanding of margin modes entry_price: string; fill_price: string; - trade_size: number; - position_size: number; + /** String when `futuresSizeDecimal` is enabled on the client. */ + trade_size: FuturesContractSize; + /** String when `futuresSizeDecimal` is enabled on the client. */ + position_size: FuturesContractSize; } ⋮---- leverage: string; // Clarified for better understanding of margin modes cross_leverage_limit: string; // Clarified for better understanding of margin modes ⋮---- +/** String when `futuresSizeDecimal` is enabled on the client. */ +⋮---- +/** String when `futuresSizeDecimal` is enabled on the client. */ +⋮---- export interface DeleteFuturesBatchOrdersResp { user_id: number; id: string; @@ -13908,12 +14104,16 @@ export interface FuturesContract { risk_limit_base?: string; risk_limit_step?: string; risk_limit_max?: string; - order_size_min?: string | number; // API returns string e.g. "1" - order_size_max?: string | number; // API returns string e.g. "1000000" + /** String when `futuresSizeDecimal` is enabled on the client. */ + order_size_min?: FuturesContractSize; // API returns string e.g. "1" + /** String when `futuresSizeDecimal` is enabled on the client. */ + order_size_max?: FuturesContractSize; // API returns string e.g. "1000000" orderbook_id?: number; trade_id?: number; - trade_size?: string | number; // API returns string - position_size?: string | number; // API returns string + /** String when `futuresSizeDecimal` is enabled on the client. */ + trade_size?: FuturesContractSize; // API returns string + /** String when `futuresSizeDecimal` is enabled on the client. */ + position_size?: FuturesContractSize; // API returns string short_users?: number; long_users?: number; funding_impact_value?: string; @@ -13948,11 +14148,15 @@ mark_price_round?: string; // Minimum unit of mark price ⋮---- /** Interest rate ratio (string); returned by GET /futures/{settle}/contracts and GET /futures/{settle}/contracts/{contract}. */ ⋮---- -order_size_min?: string | number; // API returns string e.g. "1" -order_size_max?: string | number; // API returns string e.g. "1000000" +/** String when `futuresSizeDecimal` is enabled on the client. */ +order_size_min?: FuturesContractSize; // API returns string e.g. "1" +/** String when `futuresSizeDecimal` is enabled on the client. */ +order_size_max?: FuturesContractSize; // API returns string e.g. "1000000" ⋮---- -trade_size?: string | number; // API returns string -position_size?: string | number; // API returns string +/** String when `futuresSizeDecimal` is enabled on the client. */ +trade_size?: FuturesContractSize; // API returns string +/** String when `futuresSizeDecimal` is enabled on the client. */ +position_size?: FuturesContractSize; // API returns string ⋮---- /** When true, contract supports decimal contract size (size field can use decimal string). When false, size only supports integer type. */ ⋮---- @@ -13994,7 +14198,8 @@ export interface TriggerOrderResponse { export interface FuturesPriceTriggeredOrder { initial: { contract: string; - size?: number; + /** String when `futuresSizeDecimal` is enabled on the client. */ + size?: FuturesContractSize; price?: string; close?: boolean; tif?: 'gtc' | 'ioc'; @@ -14033,6 +14238,8 @@ export interface FuturesPriceTriggeredOrder { me_order_id?: number; // int64 } ⋮---- +/** String when `futuresSizeDecimal` is enabled on the client. */ +⋮---- id?: number; // int64 price-triggered order id /** * Same order as numeric `id`, as decimal string (int64-safe in JS); prefer for display or string keys. @@ -14069,15 +14276,19 @@ export interface FuturesDeliveryContract { risk_limit_base?: string; risk_limit_step?: string; risk_limit_max?: string; - order_size_min?: number; - order_size_max?: number; + /** String when `futuresSizeDecimal` is enabled on the client. */ + order_size_min?: FuturesContractSize; + /** String when `futuresSizeDecimal` is enabled on the client. */ + order_size_max?: FuturesContractSize; order_price_deviate?: string; ref_discount_rate?: string; ref_rebate_rate?: string; orderbook_id?: number; trade_id?: number; - trade_size?: number; - position_size?: number; + /** String when `futuresSizeDecimal` is enabled on the client. */ + trade_size?: FuturesContractSize; + /** String when `futuresSizeDecimal` is enabled on the client. */ + position_size?: FuturesContractSize; config_change_time?: number; in_delisting?: boolean; orders_limit?: number; @@ -14092,6 +14303,14 @@ mark_type?: 'internal' | 'index'; // Deprecated ⋮---- mark_price_round?: string; // Minimum unit of mark price ⋮---- +/** String when `futuresSizeDecimal` is enabled on the client. */ +⋮---- +/** String when `futuresSizeDecimal` is enabled on the client. */ +⋮---- +/** String when `futuresSizeDecimal` is enabled on the client. */ +⋮---- +/** String when `futuresSizeDecimal` is enabled on the client. */ +⋮---- export interface BatchAmendOrderResp { succeeded: boolean; label?: string; @@ -14116,14 +14335,17 @@ export interface BatchAmendOrderResp { | 'stp'; status: 'open' | 'finished'; contract: string; - size: number; - iceberg: number; + /** String when `futuresSizeDecimal` is enabled on the client. */ + size: FuturesContractSize; + /** String when `futuresSizeDecimal` is enabled on the client. */ + iceberg: FuturesContractSize; price: string; is_close: boolean; is_reduce_only: boolean; is_liq: boolean; tif: 'gtc' | 'ioc' | 'poc' | 'fok'; - left: number; + /** String when `futuresSizeDecimal` is enabled on the client. */ + left: FuturesContractSize; fill_price: string; text: string; tkfr: string; @@ -14137,6 +14359,12 @@ export interface BatchAmendOrderResp { * Final state; **ioc** / **poc** reflect unfilled remainder cancelled by TIF (IOC vs post-only / maker). */ ⋮---- +/** String when `futuresSizeDecimal` is enabled on the client. */ +⋮---- +/** String when `futuresSizeDecimal` is enabled on the client. */ +⋮---- +/** String when `futuresSizeDecimal` is enabled on the client. */ +⋮---- /** * @deprecated - Use FuturesAccount instead */ @@ -14968,6 +15196,7 @@ import { CreateChaseOrderReq, CreateTrailOrderReq, DeleteAllFuturesOrdersReq, + FuturesSettle, GetChaseOrderDetailReq, GetChaseOrdersReq, GetFundingRatesReq, @@ -17098,7 +17327,7 @@ submitFlashSwapOrderPreview( * @returns Promise */ getFuturesContracts(params: { - settle: 'btc' | 'usdt' | 'usd' | 'usd1'; + settle: FuturesSettle; limit?: number; offset?: number; }): Promise @@ -17110,7 +17339,7 @@ getFuturesContracts(params: { * @returns Promise */ getFuturesContract(params: { - settle: 'btc' | 'usdt' | 'usd' | 'usd1'; + settle: FuturesSettle; contract: string; }): Promise ⋮---- @@ -17169,7 +17398,7 @@ getPremiumIndexKLines( * @returns Promise */ getFuturesTickers(params: { - settle: 'btc' | 'usdt' | 'usd' | 'usd1'; + settle: FuturesSettle; contract?: string; }): Promise ⋮---- @@ -17211,7 +17440,7 @@ getBatchFundingRates( * }[]> */ getFuturesInsuranceBalanceHistory(params: { - settle: 'btc' | 'usdt' | 'usd' | 'usd1'; + settle: FuturesSettle; limit?: number; }): Promise< { @@ -17237,7 +17466,7 @@ getFuturesStats(params: GetFuturesStatsReq): Promise * @returns Promise */ getIndexConstituents(params: { - settle: 'btc' | 'usdt' | 'usd' | 'usd1'; + settle: FuturesSettle; index: string; }): Promise ⋮---- @@ -17274,7 +17503,7 @@ getRiskLimitTiers(params: GetRiskLimitTiersReq): Promise * @returns Promise */ getFuturesAccount(params: { - settle: 'btc' | 'usdt' | 'usd' | 'usd1'; + settle: FuturesSettle; }): Promise ⋮---- /** @@ -17308,7 +17537,7 @@ getFuturesPositions( * @returns Promise */ getFuturesPosition(params: { - settle: 'btc' | 'usdt' | 'usd' | 'usd1'; + settle: FuturesSettle; contract: string; }): Promise ⋮---- @@ -17321,7 +17550,7 @@ getFuturesPosition(params: { * @returns Promise */ updateFuturesMargin(params: { - settle: 'btc' | 'usdt' | 'usd' | 'usd1'; + settle: FuturesSettle; contract: string; change: string; }): Promise @@ -17344,7 +17573,7 @@ updateFuturesMargin(params: { * @returns Promise */ updateFuturesLeverage(params: { - settle: 'btc' | 'usdt' | 'usd' | 'usd1'; + settle: FuturesSettle; contract: string; leverage: string; cross_leverage_limit?: string; @@ -17382,7 +17611,7 @@ updateFuturesPositionMode(params: { * @returns Promise */ updatePositionRiskLimit(params: { - settle: 'btc' | 'usdt' | 'usd' | 'usd1'; + settle: FuturesSettle; contract: string; risk_limit: string; }): Promise @@ -17396,7 +17625,7 @@ updatePositionRiskLimit(params: { * @returns Promise */ updateFuturesDualMode(params: { - settle: 'btc' | 'usdt' | 'usd' | 'usd1'; + settle: FuturesSettle; dual_mode: boolean; }): Promise ⋮---- @@ -17407,7 +17636,7 @@ updateFuturesDualMode(params: { * @returns Promise */ getDualModePosition(params: { - settle: 'btc' | 'usdt' | 'usd' | 'usd1'; + settle: FuturesSettle; contract: string; }): Promise ⋮---- @@ -17446,7 +17675,7 @@ updateDualModePositionLeverage( * @returns Promise */ updateDualModePositionRiskLimit(params: { - settle: 'btc' | 'usdt' | 'usd' | 'usd1'; + settle: FuturesSettle; contract: string; risk_limit: string; }): Promise @@ -17521,7 +17750,7 @@ getFuturesOrdersByTimeRange( */ submitFuturesBatchOrders(params: { xGateExptime?: number; - settle: 'btc' | 'usdt' | 'usd' | 'usd1'; + settle: FuturesSettle; orders: SubmitFuturesOrderReq[]; }): Promise ⋮---- @@ -17535,7 +17764,7 @@ submitFuturesBatchOrders(params: { * @returns Promise */ getFuturesOrder(params: { - settle: 'btc' | 'usdt' | 'usd' | 'usd1'; + settle: FuturesSettle; order_id: string; }): Promise ⋮---- @@ -17549,7 +17778,7 @@ getFuturesOrder(params: { */ cancelFuturesOrder(params: { xGateExptime?: number; - settle: 'btc' | 'usdt' | 'usd' | 'usd1'; + settle: FuturesSettle; order_id: string; action_mode?: 'ACK' | 'RESULT' | 'FULL'; }): Promise @@ -17629,7 +17858,7 @@ getFuturesAutoDeleveragingHistory( * @returns Promise<{ triggerTime: number }> */ setFuturesOrderCancelCountdown(params: { - settle: 'btc' | 'usdt' | 'usd' | 'usd1'; + settle: FuturesSettle; timeout: number; contract?: string; }): Promise< @@ -17641,7 +17870,7 @@ setFuturesOrderCancelCountdown(params: { * @returns Promise */ getFuturesUserTradingFees(params: { - settle: 'btc' | 'usdt' | 'usd' | 'usd1'; + settle: FuturesSettle; contract?: string; }): Promise ⋮---- @@ -17657,7 +17886,7 @@ getFuturesUserTradingFees(params: { */ batchCancelFuturesOrders(params: { xGateExptime?: number; - settle: 'btc' | 'usdt' | 'usd' | 'usd1'; + settle: FuturesSettle; orderIds: string[]; }): Promise ⋮---- @@ -17674,7 +17903,7 @@ batchCancelFuturesOrders(params: { */ batchUpdateFuturesOrders(params: { xGateExptime?: number; - settle: 'btc' | 'usdt' | 'usd' | 'usd1'; + settle: FuturesSettle; orders: BatchAmendOrderReq[]; }): Promise ⋮---- @@ -17715,7 +17944,7 @@ getFuturesAutoOrders( * @returns Promise */ cancelAllOpenFuturesOrders(params: { - settle: 'btc' | 'usdt' | 'usd' | 'usd1'; + settle: FuturesSettle; contract: string; }): Promise ⋮---- @@ -17726,7 +17955,7 @@ cancelAllOpenFuturesOrders(params: { * @returns Promise */ getFuturesPriceTriggeredOrder(params: { - settle: 'btc' | 'usdt' | 'usd' | 'usd1'; + settle: FuturesSettle; order_id: number; }): Promise ⋮---- @@ -17737,7 +17966,7 @@ getFuturesPriceTriggeredOrder(params: { * @returns Promise */ cancelFuturesPriceTriggeredOrder(params: { - settle: 'btc' | 'usdt' | 'usd' | 'usd1'; + settle: FuturesSettle; order_id: number; }): Promise ⋮---- @@ -20138,7 +20367,7 @@ File: package.json ================ { "name": "gateio-api", - "version": "1.6.4", + "version": "1.7.0", "description": "Complete & Robust Node.js SDK for Gate.com's REST APIs, WebSockets & WebSocket APIs, with TypeScript declarations.", "scripts": { "clean": "rm -rf dist/*", diff --git a/package-lock.json b/package-lock.json index f876e20..ec8fd14 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "gateio-api", - "version": "1.6.4", + "version": "1.7.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "gateio-api", - "version": "1.6.4", + "version": "1.7.0", "license": "MIT", "dependencies": { "@types/ws": "8.18.1", diff --git a/package.json b/package.json index 7df721f..5f2207a 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "gateio-api", - "version": "1.6.4", + "version": "1.7.0", "description": "Complete & Robust Node.js SDK for Gate.com's REST APIs, WebSockets & WebSocket APIs, with TypeScript declarations.", "scripts": { "clean": "rm -rf dist/*", diff --git a/src/WebsocketClient.ts b/src/WebsocketClient.ts index 5da337a..d95092e 100644 --- a/src/WebsocketClient.ts +++ b/src/WebsocketClient.ts @@ -1,6 +1,11 @@ import { BaseWebsocketClient, EmittableEvent } from './lib/BaseWSClient.js'; import { neverGuard } from './lib/misc-util.js'; -import { CHANNEL_ID, MessageEventLike } from './lib/requestUtils.js'; +import { + CHANNEL_ID, + getFuturesSizeDecimalHeaders, + isFuturesMarketWsKey, + MessageEventLike, +} from './lib/requestUtils.js'; import { SignAlgorithm, SignEncodeMethod, @@ -44,6 +49,26 @@ export interface WSAPIRequestFlags { export type WsTopic = string; export class WebsocketClient extends BaseWebsocketClient { + protected getWsConnectRequestHeaders(wsKey: WsKey): Record { + if (!isFuturesMarketWsKey(wsKey)) { + return {}; + } + return getFuturesSizeDecimalHeaders(this.options.futuresSizeDecimal); + } + + private getFuturesWsApiReqHeader(): { + 'X-Gate-Channel-Id': typeof CHANNEL_ID; + 'X-Gate-Size-Decimal'?: '1'; + } { + return { + 'X-Gate-Channel-Id': CHANNEL_ID, + ...getFuturesSizeDecimalHeaders(this.options.futuresSizeDecimal), + } as { + 'X-Gate-Channel-Id': typeof CHANNEL_ID; + 'X-Gate-Size-Decimal'?: '1'; + }; + } + /** * Request connection of all dependent (public & private) websockets, instead of waiting for automatic connection by library. * @@ -197,9 +222,11 @@ export class WebsocketClient extends BaseWebsocketClient { event: 'api', payload: { req_id: this.getNewRequestId(), - req_header: { - 'X-Gate-Channel-Id': CHANNEL_ID, - }, + req_header: isFuturesMarketWsKey(wsKey) + ? this.getFuturesWsApiReqHeader() + : { + 'X-Gate-Channel-Id': CHANNEL_ID, + }, api_key: this.options.apiKey, req_param: params ? params : '', timestamp: `${timeInSeconds}`, @@ -802,9 +829,11 @@ export class WebsocketClient extends BaseWebsocketClient { event: 'api', payload: { req_id: this.getNewRequestId(), - req_header: { - 'X-Gate-Channel-Id': CHANNEL_ID, - }, + req_header: isFuturesMarketWsKey(wsKey) + ? this.getFuturesWsApiReqHeader() + : { + 'X-Gate-Channel-Id': CHANNEL_ID, + }, api_key: this.options.apiKey, req_param: '', timestamp: `${timeInSeconds}`, @@ -844,6 +873,7 @@ export class WebsocketClient extends BaseWebsocketClient { payload: { ...requestEvent.payload, req_header: { + ...requestEvent.payload.req_header, 'X-Gate-Channel-Id': CHANNEL_ID, }, signature: await this.signMessage( diff --git a/src/lib/BaseRestClient.ts b/src/lib/BaseRestClient.ts index 85ba9aa..54bbc2f 100644 --- a/src/lib/BaseRestClient.ts +++ b/src/lib/BaseRestClient.ts @@ -6,7 +6,9 @@ import https from 'https'; import { neverGuard } from './misc-util.js'; import { CHANNEL_ID, + getFuturesSizeDecimalHeaders, getRestBaseUrl, + isFuturesMarketRestEndpoint, RestClientOptions, serializeParams, } from './requestUtils.js'; @@ -517,6 +519,10 @@ export abstract class BaseRestClient { params?: ParamsInQueryBodyOrHeader, isPublicApi?: boolean, ): Promise { + const futuresSizeDecimalHeaders = isFuturesMarketRestEndpoint(endpoint) + ? getFuturesSizeDecimalHeaders(this.options.futuresSizeDecimal) + : {}; + const options: AxiosRequestConfig = { ...this.globalRequestOptions, url: url, @@ -524,6 +530,7 @@ export abstract class BaseRestClient { headers: { ...params?.headers, ...this.globalRequestOptions.headers, + ...futuresSizeDecimalHeaders, }, }; diff --git a/src/lib/BaseWSClient.ts b/src/lib/BaseWSClient.ts index b078621..c2444cb 100644 --- a/src/lib/BaseWSClient.ts +++ b/src/lib/BaseWSClient.ts @@ -173,6 +173,14 @@ export abstract class BaseWebsocketClient< protected abstract getWsUrl(wsKey: TWSKey): string; + /** Optional headers for the WebSocket HTTP upgrade request (e.g. Gate size-decimal mode). */ + protected getWsConnectRequestHeaders( + // eslint-disable-next-line @typescript-eslint/no-unused-vars + _wsKey: TWSKey, + ): Record { + return {}; + } + protected abstract getMaxTopicsPerSubscribeEvent( wsKey: TWSKey, ): number | null; @@ -446,8 +454,24 @@ export abstract class BaseWebsocketClient< wsKey, }); - const { protocols = [], ...wsOptions } = this.options.wsOptions || {}; - const ws = new WebSocket(url, protocols, wsOptions); + const { protocols = [], headers: wsOptionHeaders, ...wsOptions } = + this.options.wsOptions || {}; + const normalizedWsOptionHeaders = + typeof wsOptionHeaders === 'object' && + wsOptionHeaders !== null && + !Array.isArray(wsOptionHeaders) + ? (wsOptionHeaders as Record) + : {}; + const connectHeaders: Record = { + ...normalizedWsOptionHeaders, + ...this.getWsConnectRequestHeaders(wsKey), + }; + const ws = new WebSocket(url, protocols, { + ...wsOptions, + ...(Object.keys(connectHeaders).length + ? { headers: connectHeaders } + : {}), + }); ws.onopen = (event: any) => this.onWsOpen(event, wsKey, url, ws); ws.onmessage = (event: any) => this.onWsMessage(event, wsKey, ws); diff --git a/src/lib/requestUtils.ts b/src/lib/requestUtils.ts index ae40631..49c7562 100644 --- a/src/lib/requestUtils.ts +++ b/src/lib/requestUtils.ts @@ -49,6 +49,37 @@ export interface RestClientOptions { * Look in the examples folder for a demonstration on using node's createHmac instead. */ customSignMessageFn?: (message: string, secret: string) => Promise; + + /** + * When true, sends `X-Gate-Size-Decimal: 1` on futures/delivery REST and WebSocket traffic so size-related fields are returned as decimal strings instead of integers rounded down. + * @default false + */ + futuresSizeDecimal?: boolean; +} + +export const FUTURES_SIZE_DECIMAL_HEADER = 'X-Gate-Size-Decimal'; + +export function isFuturesMarketRestEndpoint(endpoint: string): boolean { + return /^\/futures\//.test(endpoint) || /^\/delivery\//.test(endpoint); +} + +export function isFuturesMarketWsKey(wsKey: string): boolean { + return ( + wsKey === 'perpFuturesUSDTV4' || + wsKey === 'perpFuturesBTCV4' || + wsKey === 'deliveryFuturesUSDTV4' || + wsKey === 'deliveryFuturesBTCV4' + ); +} + +/** Request headers for REST or WS when `futuresSizeDecimal` is enabled. */ +export function getFuturesSizeDecimalHeaders( + futuresSizeDecimal?: boolean, +): Record { + if (!futuresSizeDecimal) { + return {}; + } + return { [FUTURES_SIZE_DECIMAL_HEADER]: '1' }; } export function serializeParams | undefined = {}>( diff --git a/src/types/request/delivery.ts b/src/types/request/delivery.ts index ca621c3..b81189c 100644 --- a/src/types/request/delivery.ts +++ b/src/types/request/delivery.ts @@ -1,3 +1,5 @@ +import { FuturesContractSize } from '../shared.js'; + /**========================================================================================================================== * DELIVERY * ========================================================================================================================== @@ -65,8 +67,10 @@ export interface GetDeliveryBookReq { export interface SubmitDeliveryFuturesOrderReq { settle: 'usdt'; contract: string; - size: number; - iceberg?: number; + /** String when `futuresSizeDecimal` is enabled on the client. */ + size: FuturesContractSize; + /** String when `futuresSizeDecimal` is enabled on the client. */ + iceberg?: FuturesContractSize; price?: string; close?: boolean; reduce_only?: boolean; diff --git a/src/types/request/futures.ts b/src/types/request/futures.ts index 7753669..5da9a21 100644 --- a/src/types/request/futures.ts +++ b/src/types/request/futures.ts @@ -1,3 +1,5 @@ +import { FuturesContractSize } from '../shared.js'; + /**========================================================================================================================== * FUTURES * ========================================================================================================================== @@ -124,8 +126,10 @@ export interface SubmitFuturesOrderReq { xGateExptime?: number; settle: FuturesSettle; contract: string; - size: number; - iceberg?: number; + /** String when `futuresSizeDecimal` is enabled on the client. */ + size: FuturesContractSize; + /** String when `futuresSizeDecimal` is enabled on the client. */ + iceberg?: FuturesContractSize; price?: string; close?: boolean; reduce_only?: boolean; @@ -169,7 +173,8 @@ export interface UpdateFuturesOrderReq { xGateExptime?: number; settle: FuturesSettle; order_id: string; - size?: number; + /** String when `futuresSizeDecimal` is enabled on the client. */ + size?: FuturesContractSize; price?: string; amend_text?: string; } @@ -214,7 +219,8 @@ export interface GetFuturesLiquidationHistoryReq { export interface SubmitFuturesTriggeredOrderReq { initial: { contract: string; - size?: number; + /** String when `futuresSizeDecimal` is enabled on the client. */ + size?: FuturesContractSize; /** Decimal contract size; if both `size` and `amount` are set, `amount` takes precedence */ amount?: string; price: string; // Required: Order price. Set to 0 to use market price @@ -255,7 +261,8 @@ export interface GetFuturesAutoOrdersReq { export interface BatchAmendOrderReq { order_id?: number; // Order id, order_id and text must contain at least one text?: string; // User-defined order text, at least one of order_id and text must be passed - size?: number; // The new order size, including the executed order size + /** String when `futuresSizeDecimal` is enabled on the client. */ + size?: FuturesContractSize; // The new order size, including the executed order size price?: string; // New order price amend_text?: string; // Custom info during amending order } @@ -280,7 +287,8 @@ export interface UpdateFuturesPriceTriggeredOrderReq { settle: FuturesSettle; order_id: number | string; contract?: string; - size?: number; + /** String when `futuresSizeDecimal` is enabled on the client. */ + size?: FuturesContractSize; /** Same semantics as `size` (decimal contract size) */ amount?: string; price?: string; diff --git a/src/types/response/delivery.ts b/src/types/response/delivery.ts index 8f6384d..c70135e 100644 --- a/src/types/response/delivery.ts +++ b/src/types/response/delivery.ts @@ -1,3 +1,5 @@ +import { FuturesContractSize } from '../shared.js'; + /**========================================================================================================================== * DELIVERY * ========================================================================================================================== @@ -7,8 +9,8 @@ export interface DeliveryOrderBook { id?: number; current: number; update: number; - asks: { p: string; s: number }[]; - bids: { p: string; s: number }[]; + asks: { p: string; s: FuturesContractSize }[]; + bids: { p: string; s: FuturesContractSize }[]; } export interface DeliveryTrade { @@ -16,14 +18,16 @@ export interface DeliveryTrade { create_time: number; create_time_ms: number; contract: string; - size: number; + /** String when `futuresSizeDecimal` is enabled on the client. */ + size: FuturesContractSize; price: string; is_internal?: boolean; // Deprecated } export interface DeliveryCandle { t: number; - v?: number; + /** String when `futuresSizeDecimal` is enabled on the client. */ + v?: FuturesContractSize; c: string; h: string; l: string; @@ -116,7 +120,8 @@ export interface DeliveryTradingHistoryRecord { create_time: number; contract: string; order_id: string; - size: number; + /** String when `futuresSizeDecimal` is enabled on the client. */ + size: FuturesContractSize; price: string; role: 'taker' | 'maker'; text: string; @@ -143,7 +148,8 @@ export interface DeliveryLiquidationHistoryRecord { time: number; contract: string; leverage?: string; - size: number; + /** String when `futuresSizeDecimal` is enabled on the client. */ + size: FuturesContractSize; margin?: string; entry_price?: string; liq_price?: string; @@ -151,14 +157,16 @@ export interface DeliveryLiquidationHistoryRecord { order_id?: number; order_price: string; fill_price: string; - left: number; + /** String when `futuresSizeDecimal` is enabled on the client. */ + left: FuturesContractSize; } export interface DeliverySettlementHistoryRecord { time: number; contract: string; leverage: string; - size: number; + /** String when `futuresSizeDecimal` is enabled on the client. */ + size: FuturesContractSize; margin: string; entry_price: string; settle_price: string; diff --git a/src/types/response/futures.ts b/src/types/response/futures.ts index 4a936c8..0c0e529 100644 --- a/src/types/response/futures.ts +++ b/src/types/response/futures.ts @@ -1,3 +1,5 @@ +import { FuturesContractSize } from '../shared.js'; + /**========================================================================================================================== * FUTURES * ========================================================================================================================== @@ -7,8 +9,8 @@ export interface FuturesOrderBook { id?: number; current: number; update: number; - asks: { p: string; s: number }[]; - bids: { p: string; s: number }[]; + asks: { p: string; s: FuturesContractSize }[]; + bids: { p: string; s: FuturesContractSize }[]; } export interface FuturesTrade { @@ -16,14 +18,16 @@ export interface FuturesTrade { create_time: number; create_time_ms: number; contract: string; - size: number; + /** String when `futuresSizeDecimal` is enabled on the client. */ + size: FuturesContractSize; price: string; is_internal?: boolean; // Deprecated } export interface FuturesCandle { t: number; - v?: number; + /** String when `futuresSizeDecimal` is enabled on the client. */ + v?: FuturesContractSize; c: string; h: string; l: string; @@ -74,22 +78,30 @@ export interface FuturesStats { time: number; lsr_taker: number; lsr_account: number; - long_liq_size: number; + /** String when `futuresSizeDecimal` is enabled on the client. */ + long_liq_size: FuturesContractSize; long_liq_amount: number; long_liq_usd: number; long_liq_usd_new?: number; - short_liq_size: number; + /** String when `futuresSizeDecimal` is enabled on the client. */ + short_liq_size: FuturesContractSize; short_liq_amount: number; short_liq_usd: number; short_liq_usd_new?: number; - open_interest: number; + /** String when `futuresSizeDecimal` is enabled on the client. */ + open_interest: FuturesContractSize; open_interest_usd: number; top_lsr_account: number; - top_lsr_size: number; - top_long_size?: number; - top_short_size?: number; - long_taker_size?: number; - short_taker_size?: number; + /** String when `futuresSizeDecimal` is enabled on the client. */ + top_lsr_size: FuturesContractSize; + /** String when `futuresSizeDecimal` is enabled on the client. */ + top_long_size?: FuturesContractSize; + /** String when `futuresSizeDecimal` is enabled on the client. */ + top_short_size?: FuturesContractSize; + /** String when `futuresSizeDecimal` is enabled on the client. */ + long_taker_size?: FuturesContractSize; + /** String when `futuresSizeDecimal` is enabled on the client. */ + short_taker_size?: FuturesContractSize; top_long_account?: number; top_short_account?: number; long_users?: number; @@ -107,11 +119,14 @@ export interface IndexConstituents { export interface LiquidationHistoryRecord { time: number; contract: string; - size: number; - order_size: number; + /** String when `futuresSizeDecimal` is enabled on the client. */ + size: FuturesContractSize; + /** String when `futuresSizeDecimal` is enabled on the client. */ + order_size: FuturesContractSize; order_price: string; fill_price: string; - left: number; + /** String when `futuresSizeDecimal` is enabled on the client. */ + left: FuturesContractSize; } export interface RiskLimitTier { @@ -196,8 +211,10 @@ export interface FuturesOrder { | 'stp'; status?: 'open' | 'finished'; contract: string; - size: number; - iceberg?: number; + /** String when `futuresSizeDecimal` is enabled on the client. */ + size: FuturesContractSize; + /** String when `futuresSizeDecimal` is enabled on the client. */ + iceberg?: FuturesContractSize; price?: string; close?: boolean; is_close?: boolean; @@ -205,7 +222,8 @@ export interface FuturesOrder { is_reduce_only?: boolean; is_liq?: boolean; tif?: 'gtc' | 'ioc' | 'poc' | 'fok'; - left?: number; + /** String when `futuresSizeDecimal` is enabled on the client. */ + left?: FuturesContractSize; fill_price?: string; text?: string; tkfr?: string; @@ -255,7 +273,8 @@ export interface FuturesOrderTimerange { export interface FuturesPosition { user?: number; contract?: string; - size?: number; + /** String when `futuresSizeDecimal` is enabled on the client. */ + size?: FuturesContractSize; leverage?: string; // Isolated margin leverage, 0 indicates cross margin mode risk_limit?: string; leverage_max?: string; // Max leverage based on current position size @@ -302,13 +321,15 @@ export interface FuturesTradingHistoryRecord { create_time: number; contract: string; order_id: string; - size: number; + /** String when `futuresSizeDecimal` is enabled on the client. */ + size: FuturesContractSize; price: string; role: 'taker' | 'maker'; text: string; fee: string; point_fee: string; - close_size: number; + /** String when `futuresSizeDecimal` is enabled on the client. */ + close_size: FuturesContractSize; } export interface FuturesPositionHistoryRecord { @@ -331,7 +352,8 @@ export interface FuturesLiquidationHistoryRecord { time: number; contract: string; leverage: string; - size: number; + /** String when `futuresSizeDecimal` is enabled on the client. */ + size: FuturesContractSize; margin: string; entry_price: string; liq_price: string; @@ -339,7 +361,8 @@ export interface FuturesLiquidationHistoryRecord { order_id: number; order_price: string; fill_price: string; - left: number; + /** String when `futuresSizeDecimal` is enabled on the client. */ + left: FuturesContractSize; } export interface FuturesAutoDeleveragingHistoryRecord { time: number; @@ -350,8 +373,10 @@ export interface FuturesAutoDeleveragingHistoryRecord { cross_leverage_limit: string; // Clarified for better understanding of margin modes entry_price: string; fill_price: string; - trade_size: number; - position_size: number; + /** String when `futuresSizeDecimal` is enabled on the client. */ + trade_size: FuturesContractSize; + /** String when `futuresSizeDecimal` is enabled on the client. */ + position_size: FuturesContractSize; } export interface DeleteFuturesBatchOrdersResp { @@ -391,12 +416,16 @@ export interface FuturesContract { risk_limit_base?: string; risk_limit_step?: string; risk_limit_max?: string; - order_size_min?: string | number; // API returns string e.g. "1" - order_size_max?: string | number; // API returns string e.g. "1000000" + /** String when `futuresSizeDecimal` is enabled on the client. */ + order_size_min?: FuturesContractSize; // API returns string e.g. "1" + /** String when `futuresSizeDecimal` is enabled on the client. */ + order_size_max?: FuturesContractSize; // API returns string e.g. "1000000" orderbook_id?: number; trade_id?: number; - trade_size?: string | number; // API returns string - position_size?: string | number; // API returns string + /** String when `futuresSizeDecimal` is enabled on the client. */ + trade_size?: FuturesContractSize; // API returns string + /** String when `futuresSizeDecimal` is enabled on the client. */ + position_size?: FuturesContractSize; // API returns string short_users?: number; long_users?: number; funding_impact_value?: string; @@ -448,7 +477,8 @@ export interface TriggerOrderResponse { export interface FuturesPriceTriggeredOrder { initial: { contract: string; - size?: number; + /** String when `futuresSizeDecimal` is enabled on the client. */ + size?: FuturesContractSize; price?: string; close?: boolean; tif?: 'gtc' | 'ioc'; @@ -516,15 +546,19 @@ export interface FuturesDeliveryContract { risk_limit_base?: string; risk_limit_step?: string; risk_limit_max?: string; - order_size_min?: number; - order_size_max?: number; + /** String when `futuresSizeDecimal` is enabled on the client. */ + order_size_min?: FuturesContractSize; + /** String when `futuresSizeDecimal` is enabled on the client. */ + order_size_max?: FuturesContractSize; order_price_deviate?: string; ref_discount_rate?: string; ref_rebate_rate?: string; orderbook_id?: number; trade_id?: number; - trade_size?: number; - position_size?: number; + /** String when `futuresSizeDecimal` is enabled on the client. */ + trade_size?: FuturesContractSize; + /** String when `futuresSizeDecimal` is enabled on the client. */ + position_size?: FuturesContractSize; config_change_time?: number; in_delisting?: boolean; orders_limit?: number; @@ -554,14 +588,17 @@ export interface BatchAmendOrderResp { | 'stp'; status: 'open' | 'finished'; contract: string; - size: number; - iceberg: number; + /** String when `futuresSizeDecimal` is enabled on the client. */ + size: FuturesContractSize; + /** String when `futuresSizeDecimal` is enabled on the client. */ + iceberg: FuturesContractSize; price: string; is_close: boolean; is_reduce_only: boolean; is_liq: boolean; tif: 'gtc' | 'ioc' | 'poc' | 'fok'; - left: number; + /** String when `futuresSizeDecimal` is enabled on the client. */ + left: FuturesContractSize; fill_price: string; text: string; tkfr: string; diff --git a/src/types/shared.ts b/src/types/shared.ts index d451367..6eb677e 100644 --- a/src/types/shared.ts +++ b/src/types/shared.ts @@ -3,6 +3,12 @@ export type GateBaseUrlKey = | 'futuresLiveAlternative' | 'futuresTestnet'; +/** + * Futures or delivery contract size (in contracts). + * Integer when the client option `futuresSizeDecimal` is off (default); decimal string when `futuresSizeDecimal` is enabled (`X-Gate-Size-Decimal: 1`). + */ +export type FuturesContractSize = number | string; + // interfaces export interface FromToPageLimit { diff --git a/src/types/websockets/client.ts b/src/types/websockets/client.ts index 7485936..a985f74 100644 --- a/src/types/websockets/client.ts +++ b/src/types/websockets/client.ts @@ -58,6 +58,12 @@ export interface WSClientConfigurableOptions { * If you authenticated the WS API before, automatically try to re-authenticate the WS API if you're disconnected/reconnected for any reason. */ reauthWSAPIOnReconnect?: boolean; + + /** + * When true, sends `X-Gate-Size-Decimal: 1` on futures/delivery WebSocket connections and WS API requests so size-related fields are returned as decimal strings instead of integers rounded down. + * @default false + */ + futuresSizeDecimal?: boolean; } /** diff --git a/src/types/websockets/requests.ts b/src/types/websockets/requests.ts index 97bc39b..e26dada 100644 --- a/src/types/websockets/requests.ts +++ b/src/types/websockets/requests.ts @@ -39,6 +39,7 @@ export interface WSAPIRequest< req_param?: TRequestParams | string; req_header: { 'X-Gate-Channel-Id': typeof CHANNEL_ID; + 'X-Gate-Size-Decimal'?: '1'; }; api_key?: string; signature?: string; diff --git a/src/types/websockets/wsAPI.ts b/src/types/websockets/wsAPI.ts index 2aaf863..fe6da82 100644 --- a/src/types/websockets/wsAPI.ts +++ b/src/types/websockets/wsAPI.ts @@ -1,4 +1,5 @@ import { WsKey } from '../../lib/websocket/websocket-util.js'; +import { FuturesContractSize } from '../shared.js'; export type SpotWSAPITopic = | 'spot.login' @@ -104,8 +105,10 @@ export interface WSAPISpotOrderListReq { export interface WSAPIFuturesOrderPlaceReq { contract: string; - size: number; - iceberg?: number; + /** String when `futuresSizeDecimal` is enabled on the client. */ + size: FuturesContractSize; + /** String when `futuresSizeDecimal` is enabled on the client. */ + iceberg?: FuturesContractSize; price?: string; close?: boolean; reduce_only?: boolean; @@ -127,7 +130,8 @@ export interface WSAPIFuturesOrderCancelCPReq { export interface WSAPIFuturesOrderAmendReq { order_id: string; price?: string; - size?: number; + /** String when `futuresSizeDecimal` is enabled on the client. */ + size?: FuturesContractSize; amend_text?: string; } @@ -203,10 +207,14 @@ export interface WSAPIFuturesOrder { finish_as?: string; status: string; contract: string; - size: number; + /** String when `futuresSizeDecimal` is enabled on the client. */ + size: FuturesContractSize; price: string; tif: string; - left?: number; + /** String when `futuresSizeDecimal` is enabled on the client. */ + left?: FuturesContractSize; + /** String when `futuresSizeDecimal` is enabled on the client. */ + iceberg?: FuturesContractSize; fill_price: string; text: string; tkfr: string; diff --git a/test/lib/futuresSizeDecimal.test.ts b/test/lib/futuresSizeDecimal.test.ts new file mode 100644 index 0000000..2b9e021 --- /dev/null +++ b/test/lib/futuresSizeDecimal.test.ts @@ -0,0 +1,84 @@ +import axios, { AxiosRequestConfig } from 'axios'; + +import { RestClient } from '../../src/RestClient.js'; +import { + FUTURES_SIZE_DECIMAL_HEADER, + getFuturesSizeDecimalHeaders, + isFuturesMarketRestEndpoint, + isFuturesMarketWsKey, +} from '../../src/lib/requestUtils.js'; + +jest.mock('axios', () => ({ + __esModule: true, + default: jest.fn(() => + Promise.resolve({ + status: 200, + data: [], + }), + ), +})); + +const mockedAxios = axios as jest.MockedFunction; + +describe('futuresSizeDecimal', () => { + beforeEach(() => { + mockedAxios.mockClear(); + }); + + describe('getFuturesSizeDecimalHeaders', () => { + it('returns the header only when enabled', () => { + expect(getFuturesSizeDecimalHeaders(false)).toEqual({}); + expect(getFuturesSizeDecimalHeaders(undefined)).toEqual({}); + expect(getFuturesSizeDecimalHeaders(true)).toEqual({ + [FUTURES_SIZE_DECIMAL_HEADER]: '1', + }); + }); + }); + + describe('REST', () => { + it('adds X-Gate-Size-Decimal on futures endpoints when futuresSizeDecimal is true', async () => { + const rest = new RestClient({ futuresSizeDecimal: true }); + await rest.getFuturesContracts({ settle: 'usdt' }); + + expect(mockedAxios).toHaveBeenCalledWith( + expect.objectContaining({ + headers: expect.objectContaining({ + [FUTURES_SIZE_DECIMAL_HEADER]: '1', + }), + }), + ); + }); + + it('does not add X-Gate-Size-Decimal when futuresSizeDecimal is off', async () => { + const rest = new RestClient(); + await rest.getFuturesContracts({ settle: 'usdt' }); + + const config = mockedAxios.mock.calls[0][0] as AxiosRequestConfig; + expect(config.headers?.[FUTURES_SIZE_DECIMAL_HEADER]).toBeUndefined(); + }); + + it('does not add X-Gate-Size-Decimal on non-futures endpoints', async () => { + const rest = new RestClient({ futuresSizeDecimal: true }); + await rest.getSpotTicker(); + + const config = mockedAxios.mock.calls[0][0] as AxiosRequestConfig; + expect(config.headers?.[FUTURES_SIZE_DECIMAL_HEADER]).toBeUndefined(); + }); + }); + + describe('scoping helpers', () => { + it('identifies futures REST paths', () => { + expect(isFuturesMarketRestEndpoint('/futures/usdt/contracts')).toBe(true); + expect(isFuturesMarketRestEndpoint('/delivery/usdt/contracts')).toBe( + true, + ); + expect(isFuturesMarketRestEndpoint('/spot/currency_pairs')).toBe(false); + }); + + it('identifies futures WebSocket keys', () => { + expect(isFuturesMarketWsKey('perpFuturesUSDTV4')).toBe(true); + expect(isFuturesMarketWsKey('deliveryFuturesBTCV4')).toBe(true); + expect(isFuturesMarketWsKey('spotV4')).toBe(false); + }); + }); +});