diff --git a/README.md b/README.md index 4dfcf2e..231477e 100644 --- a/README.md +++ b/README.md @@ -228,6 +228,8 @@ client }); ``` +TestNet REST for spot and futures is `baseUrlKey: 'testnet'` (`https://api-testnet.gateapi.io/api/v4`). `baseUrlKey: 'futuresTestnet'` is that same host, kept so older configs keep working. WebSocket TestNet is `useTestnet: true` on `WebsocketClient`. + See [RestClient](./src/RestClient.ts) for further information, or the [examples](./examples/) for lots of usage examples. ## WebSockets diff --git a/docs/GATE_SDK_QUICKSTART_GUIDE.md b/docs/GATE_SDK_QUICKSTART_GUIDE.md index 5aaf489..e3fa34b 100644 --- a/docs/GATE_SDK_QUICKSTART_GUIDE.md +++ b/docs/GATE_SDK_QUICKSTART_GUIDE.md @@ -1738,11 +1738,12 @@ Gate TestNet is a separate environment with separate credentials. Use it for all | REST API | `https://api-testnet.gateapi.io/api/v4` | | Spot WebSocket | `wss://ws-testnet.gate.com/v4/ws/spot` | | USDT perpetual WebSocket | `wss://ws-testnet.gate.com/v4/ws/futures/usdt` | +| Options WebSocket | `wss://ws-testnet.gate.com/v4/ws/options` | -Set the REST API host with `baseUrl` and the WebSocket host with `wsUrl`. Prefer explicit hosts for TestNet examples: +Set the REST API host with `baseUrl` or `baseUrlKey`, and the WebSocket host with `wsUrl` or `useTestnet: true`. Prefer explicit hosts for TestNet examples: -- Spot WebSocket TestNet is not wired through `useTestnet: true` in this SDK. The Spot testnet map entry is a stub (`NoTestnetForSpotWebsockets!`), so set `wsUrl` to the Spot TestNet host above. -- For Futures-only REST TestNet, the SDK also accepts `baseUrlKey: 'futuresTestnet'`, which resolves to `https://fx-api-testnet.gateio.ws/api/v4`. The Global TestNet REST host in the table is the host used by the Spot and Futures order examples in this guide. +- `baseUrlKey: 'testnet'` uses `https://api-testnet.gateapi.io/api/v4` for spot and futures. `baseUrlKey: 'futuresTestnet'` is the same host, kept so older configs keep working. +- `useTestnet: true` selects the TestNet WebSocket host for that connection, including Spot and Options. BTC perpetual and delivery TestNet hosts stay on the URLs in the current Gate docs (`wss://fx-ws-testnet.gateio.ws/...`). Announcements still have no TestNet host. ```javascript import { RestClient, WebsocketClient } from 'gateio-api'; diff --git a/docs/endpointFunctionList.md b/docs/endpointFunctionList.md index efece8f..ea6ec2e 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#L3557) | :closed_lock_with_key: | PUT | `/futures/{settle}/price_orders/amend/{order_id}` | +| [createTrailOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3575) | :closed_lock_with_key: | POST | `/futures/{settle}/autoorder/v1/trail/create` | +| [terminateTrailOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3593) | :closed_lock_with_key: | POST | `/futures/{settle}/autoorder/v1/trail/stop` | +| [batchTerminateTrailOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3606) | :closed_lock_with_key: | POST | `/futures/{settle}/autoorder/v1/trail/stop_all` | +| [getTrailOrderList()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3621) | :closed_lock_with_key: | GET | `/futures/{settle}/autoorder/v1/trail/list` | +| [getTrailOrderDetail()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3634) | :closed_lock_with_key: | GET | `/futures/{settle}/autoorder/v1/trail/detail` | +| [updateTrailOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3652) | :closed_lock_with_key: | POST | `/futures/{settle}/autoorder/v1/trail/update` | +| [getTrailOrderChangeLog()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3665) | :closed_lock_with_key: | GET | `/futures/{settle}/autoorder/v1/trail/change_log` | +| [createChaseOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3678) | :closed_lock_with_key: | POST | `/futures/{settle}/autoorder/v1/chase/create` | +| [stopChaseOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3688) | :closed_lock_with_key: | POST | `/futures/{settle}/autoorder/v1/chase/stop` | +| [stopAllChaseOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3698) | :closed_lock_with_key: | POST | `/futures/{settle}/autoorder/v1/chase/stop_all` | +| [getChaseOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3710) | :closed_lock_with_key: | GET | `/futures/{settle}/autoorder/v1/chase/list` | +| [getChaseOrderDetail()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3718) | :closed_lock_with_key: | GET | `/futures/{settle}/autoorder/v1/chase/detail` | +| [getFuturesPositionCloseHistory()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3727) | :closed_lock_with_key: | GET | `/futures/{settle}/position_close_history` | +| [getFuturesInsuranceHistory()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3736) | :closed_lock_with_key: | GET | `/futures/{settle}/insurance` | +| [getAllDeliveryContracts()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3753) | | GET | `/delivery/{settle}/contracts` | +| [getDeliveryContract()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3765) | | GET | `/delivery/{settle}/contracts/{contract}` | +| [getDeliveryOrderBook()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3780) | | GET | `/delivery/{settle}/order_book` | +| [getDeliveryTrades()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3793) | | GET | `/delivery/{settle}/trades` | +| [getDeliveryCandles()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3807) | | GET | `/delivery/{settle}/candlesticks` | +| [getDeliveryTickers()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3818) | | GET | `/delivery/{settle}/tickers` | +| [getDeliveryInsuranceBalanceHistory()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3835) | | GET | `/delivery/{settle}/insurance` | +| [getDeliveryAccount()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3854) | :closed_lock_with_key: | GET | `/delivery/{settle}/accounts` | +| [getDeliveryBook()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3865) | :closed_lock_with_key: | GET | `/delivery/{settle}/account_book` | +| [getDeliveryPositions()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3876) | :closed_lock_with_key: | GET | `/delivery/{settle}/positions` | +| [getDeliveryPosition()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3886) | :closed_lock_with_key: | GET | `/delivery/{settle}/positions/{contract}` | +| [updateDeliveryMargin()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3901) | :closed_lock_with_key: | POST | `/delivery/{settle}/positions/{contract}/margin` | +| [updateDeliveryLeverage()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3919) | :closed_lock_with_key: | POST | `/delivery/{settle}/positions/{contract}/leverage` | +| [updateDeliveryRiskLimit()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3937) | :closed_lock_with_key: | POST | `/delivery/{settle}/positions/{contract}/risk_limit` | +| [submitDeliveryOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3957) | :closed_lock_with_key: | POST | `/delivery/{settle}/orders` | +| [getDeliveryOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3972) | :closed_lock_with_key: | GET | `/delivery/{settle}/orders` | +| [cancelAllDeliveryOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L3985) | :closed_lock_with_key: | DELETE | `/delivery/{settle}/orders` | +| [getDeliveryOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4004) | :closed_lock_with_key: | GET | `/delivery/{settle}/orders/{order_id}` | +| [cancelDeliveryOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4019) | :closed_lock_with_key: | DELETE | `/delivery/{settle}/orders/{order_id}` | +| [getDeliveryTradingHistory()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4034) | :closed_lock_with_key: | GET | `/delivery/{settle}/my_trades` | +| [getDeliveryClosedPositions()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4047) | :closed_lock_with_key: | GET | `/delivery/{settle}/position_close` | +| [getDeliveryLiquidationHistory()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4060) | :closed_lock_with_key: | GET | `/delivery/{settle}/liquidates` | +| [getDeliverySettlementHistory()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4073) | :closed_lock_with_key: | GET | `/delivery/{settle}/settlements` | +| [submitDeliveryTriggeredOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4086) | :closed_lock_with_key: | POST | `/delivery/{settle}/price_orders` | +| [getDeliveryAutoOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4101) | :closed_lock_with_key: | GET | `/delivery/{settle}/price_orders` | +| [cancelAllOpenDeliveryOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4114) | :closed_lock_with_key: | DELETE | `/delivery/{settle}/price_orders` | +| [getDeliveryTriggeredOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4130) | :closed_lock_with_key: | GET | `/delivery/{settle}/price_orders/{order_id}` | +| [cancelTriggeredDeliveryOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4145) | :closed_lock_with_key: | DELETE | `/delivery/{settle}/price_orders/{order_id}` | +| [getOptionsUnderlyings()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4164) | | GET | `/options/underlyings` | +| [getOptionsExpirationTimes()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4174) | | GET | `/options/expirations` | +| [getOptionsContracts()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4184) | | GET | `/options/contracts` | +| [getOptionsContract()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4197) | | GET | `/options/contracts/{contract}` | +| [getOptionsSettlementHistory()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4207) | | GET | `/options/settlements` | +| [getOptionsContractSettlement()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4219) | | GET | `/options/settlements/{contract}` | +| [getOptionsMySettlements()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4234) | :closed_lock_with_key: | GET | `/options/my_settlements` | +| [getOptionsOrderBook()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4248) | | GET | `/options/order_book` | +| [getOptionsTickers()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4260) | | GET | `/options/tickers` | +| [getOptionsUnderlyingTicker()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4274) | | GET | `/options/underlying/tickers/{underlying}` | +| [getOptionsCandles()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4288) | | GET | `/options/candlesticks` | +| [getOptionsUnderlyingCandles()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4298) | | GET | `/options/underlying/candlesticks` | +| [getOptionsTrades()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4310) | | GET | `/options/trades` | +| [getOptionsAccount()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4321) | :closed_lock_with_key: | GET | `/options/accounts` | +| [getOptionsAccountChange()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4331) | :closed_lock_with_key: | GET | `/options/account_book` | +| [getOptionsPositionsUnderlying()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4343) | :closed_lock_with_key: | GET | `/options/positions` | +| [getOptionsPositionContract()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4355) | :closed_lock_with_key: | GET | `/options/positions/{contract}` | +| [getOptionsLiquidation()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4367) | :closed_lock_with_key: | GET | `/options/position_close` | +| [submitOptionsOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4380) | :closed_lock_with_key: | POST | `/options/orders` | +| [getOptionsOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4392) | :closed_lock_with_key: | GET | `/options/orders` | +| [cancelAllOpenOptionsOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4404) | :closed_lock_with_key: | DELETE | `/options/orders` | +| [getOptionsOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4418) | :closed_lock_with_key: | GET | `/options/orders/{order_id}` | +| [amendOptionsOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4430) | :closed_lock_with_key: | PUT | `/options/orders/{order_id}` | +| [cancelOptionsOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4445) | :closed_lock_with_key: | DELETE | `/options/orders/{order_id}` | +| [submitOptionsCountdownCancel()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4464) | :closed_lock_with_key: | POST | `/options/countdown_cancel_all` | +| [getOptionsPersonalHistory()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4480) | :closed_lock_with_key: | GET | `/options/my_trades` | +| [setOptionsMMPSettings()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4492) | :closed_lock_with_key: | POST | `/options/mmp` | +| [getOptionsMMPSettings()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4504) | :closed_lock_with_key: | GET | `/options/mmp` | +| [resetOptionsMMPSettings()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4516) | :closed_lock_with_key: | POST | `/options/mmp/reset` | +| [getLendingCurrencies()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4532) | | GET | `/earn/uni/currencies` | +| [getLendingCurrency()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4542) | | GET | `/earn/uni/currencies/{currency}` | +| [submitLendOrRedeemOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4552) | :closed_lock_with_key: | POST | `/earn/uni/lends` | +| [getLendingOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4562) | :closed_lock_with_key: | GET | `/earn/uni/lends` | +| [updateLendingOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4574) | :closed_lock_with_key: | PATCH | `/earn/uni/lends` | +| [getLendingRecords()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4587) | :closed_lock_with_key: | GET | `/earn/uni/lend_records` | +| [getLendingTotalInterest()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4600) | :closed_lock_with_key: | GET | `/earn/uni/interests/{currency}` | +| [getLendingInterestRecords()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4613) | :closed_lock_with_key: | GET | `/earn/uni/interest_records` | +| [updateInterestReinvestment()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4626) | :closed_lock_with_key: | PUT | `/earn/uni/interest_reinvest` | +| [getLendingInterestStatus()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4642) | :closed_lock_with_key: | GET | `/earn/uni/interest_status/{currency}` | +| [getLendingAnnualizedTrendChart()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4657) | :closed_lock_with_key: | GET | `/earn/uni/chart` | +| [getLendingEstimatedRates()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4665) | :closed_lock_with_key: | GET | `/earn/uni/rate` | +| [submitMultiLoanOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4682) | :closed_lock_with_key: | POST | `/loan/multi_collateral/orders` | +| [getMultiLoanOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4694) | :closed_lock_with_key: | GET | `/loan/multi_collateral/orders` | +| [getMultiLoanOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4706) | :closed_lock_with_key: | GET | `/loan/multi_collateral/orders/{order_id}` | +| [repayMultiLoan()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4716) | :closed_lock_with_key: | POST | `/loan/multi_collateral/repay` | +| [getMultiLoanRepayRecords()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4726) | :closed_lock_with_key: | GET | `/loan/multi_collateral/repay` | +| [updateMultiLoan()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4738) | :closed_lock_with_key: | POST | `/loan/multi_collateral/mortgage` | +| [getMultiLoanAdjustmentRecords()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4750) | :closed_lock_with_key: | GET | `/loan/multi_collateral/mortgage` | +| [getMultiLoanCurrencyQuota()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4762) | :closed_lock_with_key: | GET | `/loan/multi_collateral/currency_quota` | +| [getMultiLoanSupportedCurrencies()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4774) | | GET | `/loan/multi_collateral/currencies` | +| [getMultiLoanRatio()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4783) | | GET | `/loan/multi_collateral/ltv` | +| [getMultiLoanFixedRates()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4792) | | GET | `/loan/multi_collateral/fixed_rate` | +| [getMultiLoanCurrentRates()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4805) | | GET | `/loan/multi_collateral/current_rate` | +| [getDualInvestmentProducts()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4827) | | GET | `/earn/dual/investment_plan` | +| [getDualInvestmentOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4838) | :closed_lock_with_key: | GET | `/earn/dual/orders` | +| [submitDualInvestmentOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4850) | :closed_lock_with_key: | POST | `/earn/dual/orders` | +| [getDualOrderRefundPreview()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4859) | :closed_lock_with_key: | GET | `/earn/dual/order-refund-preview` | +| [submitDualOrderRefund()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4868) | :closed_lock_with_key: | POST | `/earn/dual/order-refund` | +| [updateDualOrderReinvest()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4877) | :closed_lock_with_key: | POST | `/earn/dual/modify-order-reinvest` | +| [getDualProjectRecommend()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4888) | :closed_lock_with_key: | GET | `/earn/dual/project-recommend` | +| [getEarnFixedTermProducts()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4897) | | GET | `/earn/fixed-term/product` | +| [getEarnFixedTermProductsByAsset()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4906) | | GET | `/earn/fixed-term/product/{asset}/list` | +| [createEarnFixedTermLend()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4916) | :closed_lock_with_key: | POST | `/earn/fixed-term/user/lend` | +| [getEarnFixedTermLends()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4925) | :closed_lock_with_key: | GET | `/earn/fixed-term/user/lend` | +| [createEarnFixedTermPreRedeem()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4934) | :closed_lock_with_key: | POST | `/earn/fixed-term/user/pre-redeem` | +| [getEarnFixedTermHistory()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4945) | :closed_lock_with_key: | GET | `/earn/fixed-term/user/history` | +| [createAutoInvestPlan()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4954) | :closed_lock_with_key: | POST | `/earn/autoinvest/plans/create` | +| [updateAutoInvestPlan()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4963) | :closed_lock_with_key: | POST | `/earn/autoinvest/plans/update` | +| [stopAutoInvestPlan()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4970) | :closed_lock_with_key: | POST | `/earn/autoinvest/plans/stop` | +| [addAutoInvestPlanPosition()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4977) | :closed_lock_with_key: | POST | `/earn/autoinvest/plans/add_position` | +| [getAutoInvestCoins()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4988) | :closed_lock_with_key: | GET | `/earn/autoinvest/coins` | +| [getAutoInvestMinAmount()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L4997) | :closed_lock_with_key: | POST | `/earn/autoinvest/min_invest_amount` | +| [getAutoInvestPlanRecords()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5008) | :closed_lock_with_key: | GET | `/earn/autoinvest/plans/records` | +| [getAutoInvestOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5017) | :closed_lock_with_key: | GET | `/earn/autoinvest/orders` | +| [getAutoInvestConfig()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5026) | :closed_lock_with_key: | GET | `/earn/autoinvest/config` | +| [getAutoInvestPlanDetail()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5033) | :closed_lock_with_key: | GET | `/earn/autoinvest/plans/detail` | +| [getAutoInvestPlans()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5042) | :closed_lock_with_key: | GET | `/earn/autoinvest/plans/list_info` | +| [getStakingCoins()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5054) | :closed_lock_with_key: | GET | `/earn/staking/coins` | +| [submitStakingSwap()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5067) | :closed_lock_with_key: | POST | `/earn/staking/swap` | +| [getAccountDetail()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5086) | :closed_lock_with_key: | GET | `/account/detail` | +| [getAccountRateLimit()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5095) | :closed_lock_with_key: | GET | `/account/rate_limit` | +| [createStpGroup()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5105) | :closed_lock_with_key: | POST | `/account/stp_groups` | +| [getStpGroups()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5115) | :closed_lock_with_key: | GET | `/account/stp_groups` | +| [getStpGroupUsers()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5125) | :closed_lock_with_key: | GET | `/account/stp_groups/{stp_id}/users` | +| [addUsersToStpGroup()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5135) | :closed_lock_with_key: | POST | `/account/stp_groups/{stp_id}/users` | +| [deleteUserFromStpGroup()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5151) | :closed_lock_with_key: | DELETE | `/account/stp_groups/{stp_id}/users` | +| [setGTDeduction()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5169) | :closed_lock_with_key: | POST | `/account/debit_fee` | +| [getGTDeduction()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5180) | :closed_lock_with_key: | GET | `/account/debit_fee` | +| [getAccountMainKeys()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5189) | :closed_lock_with_key: | GET | `/account/main_keys` | +| [getAgencyTransactionHistory()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5205) | :closed_lock_with_key: | GET | `/rebate/agency/transaction_history` | +| [getAgencyCommissionHistory()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5218) | :closed_lock_with_key: | GET | `/rebate/agency/commission_history` | +| [getPartnerTransactionHistory()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5232) | :closed_lock_with_key: | GET | `/rebate/partner/transaction_history` | +| [getPartnerCommissionHistory()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5247) | :closed_lock_with_key: | GET | `/rebate/partner/commission_history` | +| [getPartnerSubordinateList()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5270) | :closed_lock_with_key: | GET | `/rebate/partner/sub_list` | +| [getPartnerAgentDataAggregated()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5280) | :closed_lock_with_key: | GET | `/rebate/partner/data/aggregated` | +| [getBrokerCommissionHistory()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5293) | :closed_lock_with_key: | GET | `/rebate/broker/commission_history` | +| [getBrokerTransactionHistory()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5306) | :closed_lock_with_key: | GET | `/rebate/broker/transaction_history` | +| [getUserRebateInfo()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5315) | :closed_lock_with_key: | GET | `/rebate/user/info` | +| [createOTCQuote()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5350) | :closed_lock_with_key: | POST | `/otc/quote` | +| [createOTCFiatOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5362) | :closed_lock_with_key: | POST | `/otc/order/create` | +| [createOTCStablecoinOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5376) | :closed_lock_with_key: | POST | `/otc/stable_coin/order/create` | +| [getOTCBankList()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5385) | :closed_lock_with_key: | GET | `/otc/bank/list` | +| [getOTCBankListLegacy()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5392) | :closed_lock_with_key: | GET | `/otc/bank_list` | +| [createOTCUploadPreUpload()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5396) | :closed_lock_with_key: | POST | `/otc/upload/pre_upload` | +| [createOTCBank()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5405) | :closed_lock_with_key: | POST | `/otc/bank/create` | +| [deleteOTCBank()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5419) | :closed_lock_with_key: | POST | `/otc/bank/delete` | +| [setDefaultOTCBank()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5426) | :closed_lock_with_key: | POST | `/otc/bank/set_default` | +| [getOTCBankSupplementChecklist()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5433) | :closed_lock_with_key: | GET | `/otc/bank/bank_supplement_checklist` | +| [submitOTCBankPersonalSupplement()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5442) | :closed_lock_with_key: | POST | `/otc/order/paid` | +| [submitOTCBankEnterpriseSupplement()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5461) | :closed_lock_with_key: | POST | `/otc/order/paid` | +| [markOTCOrderAsPaid()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5497) | :closed_lock_with_key: | POST | `/otc/order/paid` | +| [cancelOTCOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5511) | :closed_lock_with_key: | POST | `/otc/order/cancel` | +| [getOTCFiatOrderList()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5523) | :closed_lock_with_key: | GET | `/otc/order/list` | +| [getOTCStablecoinOrderList()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5537) | :closed_lock_with_key: | GET | `/otc/stable_coin/order/list` | +| [getOTCFiatOrderDetail()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5551) | :closed_lock_with_key: | GET | `/otc/order/detail` | +| [getP2PMerchantUserInfo()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5565) | :closed_lock_with_key: | POST | `/p2p/merchant/account/get_user_info` | +| [getP2PMerchantCounterpartyUserInfo()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5574) | :closed_lock_with_key: | POST | `/p2p/merchant/account/get_counterparty_user_info` | +| [getP2PMerchantMyselfPayment()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5586) | :closed_lock_with_key: | POST | `/p2p/merchant/account/get_myself_payment` | +| [getP2PMerchantSpotBalance()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5599) | :closed_lock_with_key: | POST | `/p2p/merchant/account/set_merchant_work_hours` | +| [setP2PMerchantWorkHours()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5608) | :closed_lock_with_key: | POST | `/p2p/merchant/account/set_merchant_work_hours` | +| [getP2PMerchantPendingTransactionList()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5619) | :closed_lock_with_key: | POST | `/p2p/merchant/transaction/get_pending_transaction_list` | +| [getP2PMerchantCompletedTransactionList()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5631) | :closed_lock_with_key: | POST | `/p2p/merchant/transaction/get_completed_transaction_list` | +| [getP2PMerchantTransactionDetails()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5643) | :closed_lock_with_key: | POST | `/p2p/merchant/transaction/get_transaction_details` | +| [confirmP2PMerchantPayment()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5655) | :closed_lock_with_key: | POST | `/p2p/merchant/transaction/confirm-payment` | +| [confirmP2PMerchantReceipt()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5666) | :closed_lock_with_key: | POST | `/p2p/merchant/transaction/confirm-receipt` | +| [cancelP2PMerchantTransaction()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5677) | :closed_lock_with_key: | POST | `/p2p/merchant/transaction/cancel` | +| [placeP2PMerchantBizPushOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5688) | :closed_lock_with_key: | POST | `/p2p/merchant/books/place_biz_push_order` | +| [updateP2PMerchantAdsStatus()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5699) | :closed_lock_with_key: | POST | `/p2p/merchant/books/ads_update_status` | +| [getP2PMerchantAdsDetail()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5712) | :closed_lock_with_key: | POST | `/p2p/merchant/books/ads_detail` | +| [getP2PMerchantMyAdsList()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5721) | :closed_lock_with_key: | POST | `/p2p/merchant/books/my_ads_list` | +| [getP2PMerchantAdsList()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5732) | :closed_lock_with_key: | POST | `/p2p/merchant/books/ads_list` | +| [getP2PMerchantChatsList()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5741) | :closed_lock_with_key: | POST | `/p2p/merchant/chat/get_chats_list` | +| [sendP2PMerchantChatMessage()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5752) | :closed_lock_with_key: | POST | `/p2p/merchant/chat/send_chat_message` | +| [uploadP2PMerchantChatFile()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5763) | :closed_lock_with_key: | POST | `/p2p/merchant/chat/upload_chat_file` | +| [getCrossExSymbols()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5784) | | GET | `/crossex/rule/symbols` | +| [getCrossExRiskLimits()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5796) | | GET | `/crossex/rule/risk_limits` | +| [getCrossExTransferCoins()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5810) | | GET | `/crossex/transfers/coin` | +| [createCrossExTransfer()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5824) | :closed_lock_with_key: | POST | `/crossex/transfers` | +| [getCrossExTransferHistory()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5838) | :closed_lock_with_key: | GET | `/crossex/transfers` | +| [createCrossExOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5852) | :closed_lock_with_key: | POST | `/crossex/orders` | +| [cancelBatchCrossExOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5866) | :closed_lock_with_key: | POST | `/crossex/batch_cancel_orders` | +| [cancelCrossExOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5880) | :closed_lock_with_key: | DELETE | `/crossex/orders/{order_id}` | +| [modifyCrossExOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5893) | :closed_lock_with_key: | PUT | `/crossex/orders/{order_id}` | +| [getCrossExOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5908) | :closed_lock_with_key: | GET | `/crossex/orders/{order_id}` | +| [createCrossExConvertQuote()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5920) | :closed_lock_with_key: | POST | `/crossex/convert/quote` | +| [createCrossExConvertOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5934) | :closed_lock_with_key: | POST | `/crossex/convert/orders` | +| [updateCrossExAccount()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5948) | :closed_lock_with_key: | PUT | `/crossex/accounts` | +| [getCrossExAccounts()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5962) | :closed_lock_with_key: | GET | `/crossex/accounts` | +| [setCrossExPositionLeverage()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5974) | :closed_lock_with_key: | POST | `/crossex/positions/leverage` | +| [getCrossExPositionLeverage()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L5988) | :closed_lock_with_key: | GET | `/crossex/positions/leverage` | +| [setCrossExMarginPositionLeverage()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6002) | :closed_lock_with_key: | POST | `/crossex/margin_positions/leverage` | +| [getCrossExMarginPositionLeverage()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6018) | :closed_lock_with_key: | GET | `/crossex/margin_positions/leverage` | +| [closeCrossExPosition()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6032) | :closed_lock_with_key: | POST | `/crossex/position` | +| [updateCrossExPositionsMargin()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6038) | :closed_lock_with_key: | POST | `/crossex/positions/margin` | +| [getCrossExInterestRate()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6052) | :closed_lock_with_key: | GET | `/crossex/interest_rate` | +| [getCrossExFeeRate()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6065) | :closed_lock_with_key: | GET | `/crossex/fee` | +| [getCrossExPositions()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6077) | :closed_lock_with_key: | GET | `/crossex/positions` | +| [getCrossExMarginPositions()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6091) | :closed_lock_with_key: | GET | `/crossex/margin_positions` | +| [getCrossExAdlRank()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6105) | :closed_lock_with_key: | GET | `/crossex/adl_rank` | +| [getCrossExOpenOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6117) | :closed_lock_with_key: | GET | `/crossex/open_orders` | +| [getCrossExHistoryOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6131) | :closed_lock_with_key: | GET | `/crossex/history_orders` | +| [getCrossExHistoryPositions()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6145) | :closed_lock_with_key: | GET | `/crossex/history_positions` | +| [getCrossExHistoryMarginPositions()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6159) | :closed_lock_with_key: | GET | `/crossex/history_margin_positions` | +| [getCrossExHistoryMarginInterests()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6173) | :closed_lock_with_key: | GET | `/crossex/history_margin_interests` | +| [getCrossExHistoryTrades()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6187) | :closed_lock_with_key: | GET | `/crossex/history_trades` | +| [getCrossExAccountBook()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6201) | :closed_lock_with_key: | GET | `/crossex/account_book` | +| [getCrossExCoinDiscountRate()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6215) | :closed_lock_with_key: | GET | `/crossex/coin_discount_rate` | +| [getCrossExMarketTickers()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6229) | | GET | `/crossex/market/tickers` | +| [getCrossExMarketFundingInfo()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6243) | | GET | `/crossex/market/funding_info` | +| [getAlphaAccounts()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6261) | :closed_lock_with_key: | GET | `/alpha/accounts` | +| [getAlphaAccountBook()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6273) | :closed_lock_with_key: | GET | `/alpha/account_book` | +| [createAlphaQuote()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6287) | :closed_lock_with_key: | POST | `/alpha/quote` | +| [createAlphaOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6299) | :closed_lock_with_key: | POST | `/alpha/orders` | +| [getAlphaOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6311) | :closed_lock_with_key: | GET | `/alpha/orders` | +| [getAlphaOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6323) | :closed_lock_with_key: | GET | `/alpha/order` | +| [getAlphaCurrencies()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6335) | | GET | `/alpha/currencies` | +| [getAlphaTickers()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6347) | | GET | `/alpha/tickers` | +| [getTradFiMT5Account()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6353) | :closed_lock_with_key: | GET | `/tradfi/users/mt5-account` | +| [getTradFiSymbolCategories()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6357) | | GET | `/tradfi/symbols/categories` | +| [getTradFiSymbols()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6363) | | GET | `/tradfi/symbols` | +| [getTradFiSymbolCommissions()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6375) | :closed_lock_with_key: | GET | `/tradfi/symbols/commissions` | +| [getTradFiSymbolDetail()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6381) | :closed_lock_with_key: | GET | `/tradfi/symbols/detail` | +| [getTradFiKlines()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6387) | | GET | `/tradfi/symbols/{symbol}/klines` | +| [getTradFiTicker()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6394) | | GET | `/tradfi/symbols/{symbol}/tickers` | +| [createTradFiUser()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6398) | :closed_lock_with_key: | POST | `/tradfi/users` | +| [getTradFiAssets()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6402) | :closed_lock_with_key: | GET | `/tradfi/users/assets` | +| [createTradFiTransaction()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6406) | :closed_lock_with_key: | POST | `/tradfi/transactions` | +| [getTradFiTransactions()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6412) | :closed_lock_with_key: | GET | `/tradfi/transactions` | +| [createTradFiOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6418) | :closed_lock_with_key: | POST | `/tradfi/orders` | +| [getTradFiOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6424) | :closed_lock_with_key: | GET | `/tradfi/orders` | +| [modifyTradFiOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6428) | :closed_lock_with_key: | PUT | `/tradfi/orders/{orderId}` | +| [cancelTradFiOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6435) | :closed_lock_with_key: | DELETE | `/tradfi/orders/{orderId}` | +| [getTradFiOrderHistory()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6439) | :closed_lock_with_key: | GET | `/tradfi/orders/history` | +| [getTradFiPositions()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6445) | :closed_lock_with_key: | GET | `/tradfi/positions` | +| [modifyTradFiPosition()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6451) | :closed_lock_with_key: | PUT | `/tradfi/positions/{positionId}` | +| [closeTradFiPosition()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6460) | :closed_lock_with_key: | POST | `/tradfi/positions/{positionId}/close` | +| [getTradFiPositionHistory()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6469) | :closed_lock_with_key: | GET | `/tradfi/positions/history` | +| [getTradFiOrderLog()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6478) | :closed_lock_with_key: | GET | `/tradfi/orders/log/{log_id}` | +| [getStockUserAssets()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6492) | :closed_lock_with_key: | GET | `/stock/users/assets` | +| [getStockSymbols()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6504) | | GET | `/stock/symbols` | +| [getStockSymbolDetail()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6516) | :closed_lock_with_key: | GET | `/stock/symbols/detail` | +| [getStockOrderBook()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6528) | | GET | `/stock/market/{symbol}/orderbook` | +| [getStockOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6538) | :closed_lock_with_key: | GET | `/stock/orders` | +| [createStockOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6552) | :closed_lock_with_key: | POST | `/stock/orders` | +| [cancelAllStockOrders()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6563) | :closed_lock_with_key: | DELETE | `/stock/orders` | +| [getStockOrderHistory()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6573) | :closed_lock_with_key: | GET | `/stock/orders/history` | +| [updateStockOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6586) | :closed_lock_with_key: | PUT | `/stock/orders/{orderId}` | +| [cancelStockOrder()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6599) | :closed_lock_with_key: | DELETE | `/stock/orders/{orderId}` | +| [getStockPositions()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6611) | :closed_lock_with_key: | GET | `/stock/positions` | +| [closeStockPosition()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6623) | :closed_lock_with_key: | POST | `/stock/positions/close` | +| [getStockTransactions()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6635) | :closed_lock_with_key: | GET | `/stock/transactions` | +| [createStockTransaction()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6649) | :closed_lock_with_key: | POST | `/stock/transactions` | +| [getStockExchanges()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6660) | | GET | `/stock/exchanges` | +| [getStockFeeRate()](https://github.com/sieblyio/gateio-api/blob/master/src/RestClient.ts#L6671) | | GET | `/stock/fee-rate` | # WebsocketAPIClient.ts diff --git a/examples/Rest/futures/testnet.ts b/examples/Rest/futures/testnet.ts index 8fb22c4..a2709af 100644 --- a/examples/Rest/futures/testnet.ts +++ b/examples/Rest/futures/testnet.ts @@ -19,8 +19,10 @@ const gateRestClient = new RestClient({ */ /* - * Futures TestNet trading: - * 'https://fx-api-testnet.gateio.ws/api/v4' + * Futures TestNet trading (alias of `testnet`, spot and futures): + * 'https://api-testnet.gateapi.io/api/v4' + * Older host https://fx-api-testnet.gateio.ws/api/v4 now returns 502. + * baseUrlKey: 'testnet' is the same host. */ baseUrlKey: 'futuresTestnet', diff --git a/examples/apidoc/RestClient/updateFuturesPriceTriggeredOrder.js b/examples/apidoc/RestClient/updateFuturesPriceTriggeredOrder.js index a211c1f..48dc1d7 100644 --- a/examples/apidoc/RestClient/updateFuturesPriceTriggeredOrder.js +++ b/examples/apidoc/RestClient/updateFuturesPriceTriggeredOrder.js @@ -4,7 +4,7 @@ import { RestClient } from 'gateio-api'; // This example shows how to call this Gate.io API endpoint with either node.js, javascript (js) or typescript (ts) with the npm module "gateio-api" for Gate.io exchange // This Gate.io API SDK is available on npm via "npm install gateio-api" -// ENDPOINT: /futures/{settle}/price_orders/amend +// ENDPOINT: /futures/{settle}/price_orders/amend/{order_id} // METHOD: PUT // PUBLIC: NO diff --git a/llms.txt b/llms.txt index a13ad5e..5169453 100644 --- a/llms.txt +++ b/llms.txt @@ -196,136 +196,6 @@ Most examples also have minimal typescript, so if you rename them to "js" they s node ./examples/spot/getTickers.js ``` -================ -File: src/lib/websocket/websocket-util.ts -================ -import WebSocket from 'isomorphic-ws'; -⋮---- -import { WSAPIRequest } from '../../types/websockets/requests.js'; -import { - FuturesWSAPITopic, - SpotWSAPITopic, -} from '../../types/websockets/wsAPI.js'; -⋮---- -/** - * Should be one WS key per unique URL. Some URLs may need a suffix. - */ -⋮---- -/** - * Spot & Margin - * https://www.gate.io/docs/developers/apiv4/ws/en/ - */ -⋮---- -/** - * Perpetual futures (USDT) - * https://www.gate.io/docs/developers/futures/ws/en/#gate-io-futures-websocket-v4 - */ -⋮---- -/** - * Perpetual futures (BTC) - * https://www.gate.io/docs/developers/futures/ws/en/#gate-io-futures-websocket-v4 - */ -⋮---- -/** - * Delivery Futures (USDT) - * https://www.gate.io/docs/developers/delivery/ws/en/ - */ -⋮---- -/** - * Delivery Futures (BTC) - * https://www.gate.io/docs/developers/delivery/ws/en/ - */ -⋮---- -/** - * Options - * https://www.gate.io/docs/developers/options/ws/en/ - */ -⋮---- -/** - * Announcements V4 - * https://www.gate.io/docs/developers/options/ws/en/ - */ -⋮---- -/** This is used to differentiate between each of the available websocket streams */ -export type WsKey = (typeof WS_KEY_MAP)[keyof typeof WS_KEY_MAP]; -⋮---- -export type FuturesWsKey = - | typeof WS_KEY_MAP.perpFuturesUSDTV4 - | typeof WS_KEY_MAP.perpFuturesBTCV4 - | typeof WS_KEY_MAP.deliveryFuturesUSDTV4 - | typeof WS_KEY_MAP.deliveryFuturesBTCV4; -⋮---- -export type WsMarket = 'all'; -⋮---- -/** - * Normalised internal format for a request (subscribe/unsubscribe/etc) on a topic, with optional parameters. - * - * - Topic: the topic this event is for - * - Payload: the parameters to include, optional. E.g. auth requires key + sign. Some topics allow configurable parameters. - */ -export interface WsTopicRequest< - TWSTopic extends string = string, - TWSPayload = any, -> { - topic: TWSTopic; - payload?: TWSPayload; -} -⋮---- -/** - * Conveniently allow users to request a topic either as string topics or objects (containing string topic + params) - */ -export type WsTopicRequestOrStringTopic< - TWSTopic extends string, - TWSPayload = any, -> = WsTopicRequest | string; -⋮---- -/** - * Some exchanges have two livenet environments, some have test environments, some dont. This allows easy flexibility for different exchanges. - * Examples: - * - One livenet and one testnet: NetworkMap<'livenet' | 'testnet'> - * - One livenet, sometimes two, one testnet: NetworkMap<'livenet' | 'testnet', 'livenet2'> - * - Only one livenet, no other networks: NetworkMap<'livenet'> - */ -type NetworkMap< - TRequiredKeys extends string, - TOptionalKeys extends string | undefined = undefined, -> = Record & - (TOptionalKeys extends string - ? Record - : Record); -⋮---- -export function neverGuard(x: never, msg: string): Error -⋮---- -/** - * WS API promises are stored using a primary key. This key is constructed using - * properties found in every request & reply. - */ -export function getPromiseRefForWSAPIRequest( - requestEvent: WSAPIRequest, -): string -⋮---- -export function getPrivateSpotTopics(): string[] -⋮---- -// Consumeable channels for spot -⋮---- -// WebSocket API for spot -⋮---- -export function getPrivateFuturesTopics(): string[] -⋮---- -// These are the same for perps vs delivery futures -⋮---- -export function getPrivateOptionsTopics(): string[] -⋮---- -/** - * ws.terminate() is undefined in browsers. - * This only works in node.js, not in browsers. - * Does nothing if `ws` is undefined. Does nothing in browsers. - */ -export function safeTerminateWs( - ws?: WebSocket | any, - fallbackToClose?: boolean, -): boolean - ================ File: src/lib/websocket/WsStore.types.ts ================ @@ -441,118 +311,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 ================ @@ -600,32 +358,12 @@ export interface CreateStpGroupReq { } ================ -File: src/types/request/announcement.ts +File: src/types/request/collateralLoan.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 -================ -/**========================================================================================================================== - * COLLATERAL LOAN - * ========================================================================================================================== - */ +/**========================================================================================================================== + * COLLATERAL LOAN + * ========================================================================================================================== + */ ⋮---- export interface SubmitLoanOrderReq { collateral_amount: string; @@ -1146,44 +884,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 ================ @@ -3034,53 +2734,6 @@ console.error('Error in execution: ', e); // Log any errors that occur ⋮---- // Execute the function to submit a futures order -================ -File: examples/Rest/futures/testnet.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 -⋮---- -/** - * 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() -⋮---- -// Submit a market order for futures 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) -⋮---- -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 - ================ File: examples/Rest/otc/createOTCBank.ts ================ @@ -3714,6 +3367,140 @@ async function start() // 'spotV4', // ); +================ +File: src/lib/websocket/websocket-util.ts +================ +import WebSocket from 'isomorphic-ws'; +⋮---- +import { WSAPIRequest } from '../../types/websockets/requests.js'; +import { + FuturesWSAPITopic, + SpotWSAPITopic, +} from '../../types/websockets/wsAPI.js'; +⋮---- +/** + * Should be one WS key per unique URL. Some URLs may need a suffix. + */ +⋮---- +/** + * Spot & Margin + * https://www.gate.io/docs/developers/apiv4/ws/en/ + */ +⋮---- +/** + * Perpetual futures (USDT) + * https://www.gate.io/docs/developers/futures/ws/en/#gate-io-futures-websocket-v4 + */ +⋮---- +/** + * Perpetual futures (BTC) + * https://www.gate.io/docs/developers/futures/ws/en/#gate-io-futures-websocket-v4 + */ +⋮---- +/** + * Delivery Futures (USDT) + * https://www.gate.io/docs/developers/delivery/ws/en/ + */ +⋮---- +/** + * Delivery Futures (BTC) + * https://www.gate.io/docs/developers/delivery/ws/en/ + */ +⋮---- +/** + * Options + * https://www.gate.io/docs/developers/options/ws/en/ + */ +⋮---- +/** + * Announcements V4 + * https://www.gate.io/docs/developers/options/ws/en/ + */ +⋮---- +/** This is used to differentiate between each of the available websocket streams */ +export type WsKey = (typeof WS_KEY_MAP)[keyof typeof WS_KEY_MAP]; +⋮---- +export type FuturesWsKey = + | typeof WS_KEY_MAP.perpFuturesUSDTV4 + | typeof WS_KEY_MAP.perpFuturesBTCV4 + | typeof WS_KEY_MAP.deliveryFuturesUSDTV4 + | typeof WS_KEY_MAP.deliveryFuturesBTCV4; +⋮---- +export type WsMarket = 'all'; +⋮---- +/** + * Normalised internal format for a request (subscribe/unsubscribe/etc) on a topic, with optional parameters. + * + * - Topic: the topic this event is for + * - Payload: the parameters to include, optional. E.g. auth requires key + sign. Some topics allow configurable parameters. + */ +export interface WsTopicRequest< + TWSTopic extends string = string, + TWSPayload = any, +> { + topic: TWSTopic; + payload?: TWSPayload; +} +⋮---- +/** + * Conveniently allow users to request a topic either as string topics or objects (containing string topic + params) + */ +export type WsTopicRequestOrStringTopic< + TWSTopic extends string, + TWSPayload = any, +> = WsTopicRequest | string; +⋮---- +/** + * Some exchanges have two livenet environments, some have test environments, some dont. This allows easy flexibility for different exchanges. + * Examples: + * - One livenet and one testnet: NetworkMap<'livenet' | 'testnet'> + * - One livenet, sometimes two, one testnet: NetworkMap<'livenet' | 'testnet', 'livenet2'> + * - Only one livenet, no other networks: NetworkMap<'livenet'> + */ +type NetworkMap< + TRequiredKeys extends string, + TOptionalKeys extends string | undefined = undefined, +> = Record & + (TOptionalKeys extends string + ? Record + : Record); +⋮---- +// https://www.gate.com/docs/developers/apiv4/ws/en/ +⋮---- +// https://www.gate.com/docs/developers/options/ws/en/ +⋮---- +export function neverGuard(x: never, msg: string): Error +⋮---- +/** + * WS API promises are stored using a primary key. This key is constructed using + * properties found in every request & reply. + */ +export function getPromiseRefForWSAPIRequest( + requestEvent: WSAPIRequest, +): string +⋮---- +export function getPrivateSpotTopics(): string[] +⋮---- +// Consumeable channels for spot +⋮---- +// WebSocket API for spot +⋮---- +export function getPrivateFuturesTopics(): string[] +⋮---- +// These are the same for perps vs delivery futures +⋮---- +export function getPrivateOptionsTopics(): string[] +⋮---- +/** + * ws.terminate() is undefined in browsers. + * This only works in node.js, not in browsers. + * Does nothing if `ws` is undefined. Does nothing in browsers. + */ +export function safeTerminateWs( + ws?: WebSocket | any, + fallbackToClose?: boolean, +): boolean + ================ File: src/lib/websocket/WsStore.ts ================ @@ -4344,33 +4131,177 @@ export function appendGateMultipartFields( ): void ================ -File: src/types/request/options.ts +File: src/lib/requestUtils.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; -} +import WebSocket from 'isomorphic-ws'; ⋮---- -export interface GetOptionsOrderBookReq { - contract: string; - interval?: '0' | '0.1' | '0.01'; - limit?: number; - with_id?: boolean; +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; + + /** + * Built-in Gate API v4 host. + * `testnet` and `futuresTestnet` both use https://api-testnet.gateapi.io/api/v4 + * (spot and futures). `futuresTestnet` is kept as an alias of `testnet`. + */ + 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' + **/ +⋮---- +/** + * Built-in Gate API v4 host. + * `testnet` and `futuresTestnet` both use https://api-testnet.gateapi.io/api/v4 + * (spot and futures). `futuresTestnet` is kept as an alias of `testnet`. + */ +⋮---- +/** 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 +⋮---- +/** Global TestNet REST host. Gate docs: spot and futures. */ +⋮---- +// Alias of `testnet`. Previously https://fx-api-testnet.gateio.ws/api/v4 (HTTP 502). +⋮---- +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/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/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; +} +⋮---- +export interface GetOptionsOrderBookReq { + contract: string; + interval?: '0' | '0.1' | '0.01'; + limit?: number; + with_id?: boolean; } ⋮---- export interface GetOptionsCandlesReq { @@ -4534,99 +4465,6 @@ export interface GetPartnerAgentDataAggregatedReq { * 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 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; -} -⋮---- -/** 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 UpdateStockOrderReq { - volume: string; - price: string; -} -⋮---- -export interface GetStockPositionsReq { - pnl_calc_type?: number; - pnl_calc_price?: number; - symbol?: string; - exchange?: string; // us | hk | jp -} -⋮---- -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; -} -⋮---- -export interface CreateStockTransactionReq { - asset: string; - change: string; - type: 'deposit' | 'withdraw'; - ref_id: string; -} - ================ File: src/types/response/alpha.ts ================ @@ -4770,10 +4608,48 @@ volume: string; // 24h Trading Volume (USDT) market_cap: string; // Current Token Market Cap ================ -File: src/types/response/autoinvest.ts +File: src/types/response/announcement.ts ================ -/**========================================================================================================================== - * EARN AUTO INVEST +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/autoinvest.ts +================ +/**========================================================================================================================== + * EARN AUTO INVEST * ========================================================================================================================== */ ⋮---- @@ -5213,60 +5089,6 @@ account_type: string; // Description updated to remove "risk" option risk?: string; // Deprecated mmr?: string; // Refined description -================ -File: src/types/response/marginuni.ts -================ -/**========================================================================================================================== - * MARGIN UNI - * ========================================================================================================================== - */ -⋮---- -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 MarginUNILoan { - currency: string; - currency_pair: string; - amount: string; - type: string; // Lending type, margin indicates margin borrowing - create_time: number; - update_time: number; -} -⋮---- -type: string; // Lending type, margin indicates margin borrowing -⋮---- -export interface MarginUNILoanRecord { - type: string; - currency_pair: string; - currency: string; - amount: string; - create_time: number; -} -⋮---- -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; -} -⋮---- -type: string; // Lending type, margin indicates margin borrowing -⋮---- -export interface MarginUNIMaxBorrowable { - currency: string; - currency_pair: string; - borrowable: string; -} - ================ File: src/types/response/multicollateralLoan.ts ================ @@ -5821,388 +5643,151 @@ export interface PartnerDataAggregatedResponse { } ================ -File: src/types/response/stock.ts +File: src/types/response/withdrawal.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 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 StockListData { - list?: T[]; - total?: number; - total_page?: number; -} +/** When `status` is DONE, withdrawal success time (not conditioned on `block_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; -} +| '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: .npmrc +================ +min-release-age=30 +save-exact=true + +================ +File: .nvmrc +================ +v24.18.0 + +================ +File: examples/Rest/futures/testnet.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) ⋮---- -export interface StockSymbolDescI18n { - lang?: string; - value?: string; -} +// Define the account object with API key and secret ⋮---- -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; -} +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 ⋮---- -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; -} +// Initialize the RestClient with the API credentials ⋮---- -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; -} +/** + * 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. + */ ⋮---- -export interface StockCreateOrderResult { - id?: string; -} +/* + * Futures TestNet trading (alias of `testnet`, spot and futures): + * 'https://api-testnet.gateapi.io/api/v4' + * Older host https://fx-api-testnet.gateio.ws/api/v4 now returns 502. + * baseUrlKey: 'testnet' is the same host. + */ ⋮---- -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; -} +/** + * Futures live trading alternative (futures only): + * 'https://fx-api.gateio.ws/api/v4' + */ +// baseUrlKey: 'futuresLiveAlternative' ⋮---- -export interface StockUpdateOrderResult { - order_id?: number; -} +async function submitFuturesOrder() ⋮---- -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; -} +// Submit a market order for futures trading ⋮---- -export interface StockClosePositionResult { - order_id?: number; -} +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) ⋮---- -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('Response: ', result); // Log the response to the console ⋮---- -export interface StockExchangeItem { - exchange?: string; - exchange_desc?: string; - icon_link?: string; - support_transfer?: boolean; -} +console.error('Error in execution: ', e); // Log any errors that occur ⋮---- -export interface StockFeeRateItem { - vip_level?: number; - maker_fee?: string; - taker_fee?: string; -} +// Execute the function to submit a futures order ================ -File: src/types/response/withdrawal.ts +File: examples/Rest/otc/submitOTCBankPersonalSupplement.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; -} +import { readFileSync } from 'fs'; ⋮---- -/** When `status` is DONE, withdrawal success time (not conditioned on `block_number`). */ +import { RestClient } from '../../../src/index.js'; +// import { RestClient } from 'gateio-api'; ⋮---- -| '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 +async function submitOTCBankPersonalSupplementExample() ================ -File: src/types/shared.ts +File: src/types/request/alpha.ts ================ -export type GateBaseUrlKey = - | 'live' - | 'futuresLiveAlternative' - | 'futuresTestnet'; -⋮---- -// interfaces +/**========================================================================================================================== + * ALPHA + * ========================================================================================================================== + */ ⋮---- -export interface FromToPageLimit { - from: number; - to: number; - page: number; - limit: number; +export interface GetAlphaAccountBookReq { + 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 100 items per page } ⋮---- -// 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; -} -⋮---- -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'; -⋮---- -import { RestClient } from '../../../src/index.js'; -// import { RestClient } from 'gateio-api'; -⋮---- -async function submitOTCBankPersonalSupplementExample() - -================ -File: src/types/request/alpha.ts -================ -/**========================================================================================================================== - * ALPHA - * ========================================================================================================================== - */ -⋮---- -export interface GetAlphaAccountBookReq { - 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 100 items per page -} -⋮---- -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 100 items per page +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 100 items per page ⋮---- export interface CreateAlphaQuoteReq { currency: string; // Trading symbol @@ -6539,6 +6124,153 @@ export interface P2PMerchantUploadChatFileReq { base64_img: string; } +================ +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 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; +} +⋮---- +/** 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 UpdateStockOrderReq { + volume: string; + price: string; +} +⋮---- +export interface GetStockPositionsReq { + pnl_calc_type?: number; + pnl_calc_price?: number; + symbol?: string; + exchange?: string; // us | hk | jp +} +⋮---- +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; +} +⋮---- +export interface CreateStockTransactionReq { + asset: string; + change: string; + type: 'deposit' | 'withdraw'; + ref_id: string; +} + +================ +File: src/types/response/marginuni.ts +================ +/**========================================================================================================================== + * MARGIN UNI + * ========================================================================================================================== + */ +⋮---- +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 MarginUNILoan { + currency: string; + currency_pair: string; + amount: string; + type: string; // Lending type, margin indicates margin borrowing + create_time: number; + update_time: number; +} +⋮---- +type: string; // Lending type, margin indicates margin borrowing +⋮---- +export interface MarginUNILoanRecord { + type: string; + currency_pair: string; + currency: string; + amount: string; + create_time: number; +} +⋮---- +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; +} +⋮---- +type: string; // Lending type, margin indicates margin borrowing +⋮---- +export interface MarginUNIMaxBorrowable { + currency: string; + currency_pair: string; + borrowable: string; +} + ================ File: src/types/response/p2pMerchant.ts ================ @@ -6835,3456 +6567,4069 @@ restClientRegex.ts testfile.ts ================ -File: docs/GATE_SDK_QUICKSTART_GUIDE.md +File: src/types/request/earn.ts ================ - - -# Gate API JavaScript Tutorial for Node.js - - - -> [!TIP] -> Read this guide in tutorial format on the Siebly website: [Gate JavaScript REST API and WebSocket Tutorial](https://siebly.io/sdk/gate/javascript/tutorial) - - - -This tutorial uses [`gateio-api`](https://www.npmjs.com/package/gateio-api), Siebly's Node.js, JavaScript, and TypeScript SDK for Gate.com. It covers public and private REST API calls, Spot and Futures TestNet orders, live WebSocket streams, WebSocket API commands, API hosts, and proxies. - -The SDK handles REST API request signing, private WebSocket authentication, product-specific WebSocket routing, heartbeats, reconnects, resubscriptions, and WebSocket API response matching. Request and response types are included for TypeScript users. - -**Key links** - -- Gate JavaScript SDK by Siebly: [`gateio-api`](https://siebly.io/sdk/gate/javascript) -- npm package: [`gateio-api`](https://www.npmjs.com/package/gateio-api) -- GitHub repository: [`sieblyio/gateio-api`](https://github.com/sieblyio/gateio-api) -- SDK examples: [Gate SDK examples](https://siebly.io/examples/Gate) -- SDK endpoint map: [Gate JavaScript endpoint reference](./endpointFunctionList.md) -- Gate REST API documentation: [Gate API v4](https://www.gate.com/docs/developers/apiv4/en/) -- Gate Spot WebSocket documentation: [Spot WebSocket API](https://www.gate.com/docs/developers/apiv4/ws/) -- Gate Futures WebSocket documentation: [Futures WebSocket API](https://www.gate.com/docs/developers/futures/ws/) -- Trading-system terms: [Siebly glossary](https://siebly.io/reference/glossary) -- More JavaScript and TypeScript SDKs: [Siebly.io](https://siebly.io) - -## Why use `gateio-api`? - -The JavaScript SDK handles all the complexities of integrating with Gate's REST APIs & WebSockets, so you can focus on your system without wasting excessive time on plumbing. - -Private Gate REST API requests require a timestamp and HMAC-SHA512 signature. Private WebSocket subscriptions require authentication, and each product family has its own WebSocket connection. A Spot subscription cannot be sent through a USDT perpetual Futures connection. - -`gateio-api` handles those mechanics and gives each job a focused client: - -| Client | Use it for | -| -------------------- | ------------------------------------------------------------ | -| `RestClient` | Public and private REST API calls across Gate product groups | -| `WebsocketClient` | Public and private WebSocket subscriptions | -| `WebsocketAPIClient` | Promise-based Spot and Futures order commands over WebSocket | - -`WebsocketClient` also handles heartbeats, reconnects, cached subscriptions, and resubscription. `WebsocketAPIClient` adds login, request IDs, response matching, and promise resolution. - -## Install the SDK - -```bash -npm install gateio-api -``` - -The package includes CommonJS, ESM, and TypeScript declarations. Every example below is plain JavaScript using ESM imports. - -## Create Gate API keys - -Public market data does not require credentials. Private REST API calls, private streams, and WebSocket API commands require an API key and secret. - -Create and manage keys from the [Gate API key page](https://www.gate.com/myaccount/api_key_manage). Start with the least access your application needs: - -- Use a read-only key while building account views and recovery code. -- Enable Spot read-write access only for Spot order workflows. -- Enable perpetual-contract read-write access only for Futures order workflows. -- Add an IP whitelist when your outbound IP is stable. -- Keep live and TestNet credentials separate. -- Allow a few minutes for API key and permission changes to take effect. -- Do not enable withdrawal permission for anything in this tutorial. - -Set these live credential names in your shell, secret manager, or deployment environment: - -- `GATE_API_KEY` -- `GATE_API_SECRET` - -Use separate names for TestNet: - -- `GATE_TESTNET_API_KEY` -- `GATE_TESTNET_API_SECRET` -- `GATE_PLACE_TESTNET_ORDER=true` - -The order examples check `GATE_PLACE_TESTNET_ORDER` before sending an order. Do not log API keys or secrets, and never put them in browser code. - -## Gate products and request vocabulary - -Several short fields determine where a request goes and what its values mean: - -| Field | Example | Meaning | -| --------------- | ------------------------------ | -------------------------------------------------------------------------------------------------- | -| `currency_pair` | `BTC_USDT` | A Spot or margin market | -| `account` | `spot` | The account used by a Spot order or query | -| `settle` | `usdt` | The settlement currency for a Futures or Delivery REST API request | -| `contract` | `BTC_USDT` | The exact Futures, Delivery, or Options contract | -| `size` | `1` or `-1` | Futures contract count, not a BTC or USDT amount | -| `text` | `t-my-order-123` | Your [custom order ID](https://siebly.io/reference/glossary#custom-order-id) | -| `wsKey` | `WS_KEY_MAP.perpFuturesUSDTV4` | The [WebSocket key](https://siebly.io/reference/glossary#ws-key) that selects a product connection | - -For Spot orders, `account` can be `spot`, `margin`, `cross_margin`, or `unified`, depending on the account and endpoint. This tutorial uses `spot`. - -For USDT perpetual Futures, use `settle: 'usdt'` and a contract such as `BTC_USDT`. The `size` is a number of contracts. In one-way mode, a positive size buys and a negative size sells. The contract's `quanto_multiplier` tells you how much underlying currency one contract represents. - -Keep these routing values visible in code and logs. They are part of the request, not interchangeable labels. - - - -## Start building: first calls and streams - -Run each example on its own. Start with public data, then add authenticated account state and live streams. - -### 1. Make public REST API calls - -Public calls need no API key. Gate response bodies are endpoint-specific: server time and order books are objects, tickers are arrays, and candles are tuple arrays. - - - -```javascript -import { RestClient } from 'gateio-api'; - -const client = new RestClient(); - -async function main() { - try { - const time = await client.getServerTime(); - console.log('Server time:', time.server_time); - } catch (error) { - console.error('Server time request failed:', error); - } - - try { - const pair = await client.getSpotCurrencyPair({ - currency_pair: 'BTC_USDT', - }); - console.log('BTC_USDT metadata:', pair); - } catch (error) { - console.error('Currency pair request failed:', error); - } - - try { - const tickers = await client.getSpotTicker({ - currency_pair: 'BTC_USDT', - }); - console.log('BTC_USDT ticker:', tickers[0]); - } catch (error) { - console.error('Ticker request failed:', error); - } - - try { - const orderBook = await client.getSpotOrderBook({ - currency_pair: 'BTC_USDT', - limit: 5, - }); - console.log('Best bid:', orderBook.bids[0]); - console.log('Best ask:', orderBook.asks[0]); - } catch (error) { - console.error('Order book request failed:', error); - } - - try { - const candles = await client.getSpotCandles({ - currency_pair: 'BTC_USDT', - interval: '1h', - limit: 10, - }); - console.log('Latest candle:', candles[0]); - } catch (error) { - console.error('Candles request failed:', error); - } -} - -main(); -``` - -The SDK returns the endpoint body directly. There is no shared result wrapper to unwrap. - -Each Spot candle is a tuple: - -```text -[ - timestamp, - quoteVolume, - close, - high, - low, - open, - baseVolume, - closed -] -``` - -Use the [SDK endpoint map](./endpointFunctionList.md) or the official endpoint documentation when reading tuple positions and endpoint-specific objects. - -### 2. Make private REST API calls - -Private calls use the same `RestClient`. Add your key and secret, then call private methods normally. The SDK adds the required timestamp and signature. - - - -```javascript -import { RestClient } from 'gateio-api'; - -const client = new RestClient({ - apiKey: process.env.GATE_API_KEY, - apiSecret: process.env.GATE_API_SECRET, -}); - -async function main() { - try { - const balances = await client.getSpotAccounts(); - console.log('Spot balances:', balances); - } catch (error) { - console.error('Balance request failed:', error); - } - - try { - const openOrders = await client.getSpotOpenOrders({ - account: 'spot', - }); - console.log('Open Spot orders grouped by pair:', openOrders); - } catch (error) { - console.error('Open-order request failed:', error); - } - - try { - const recentOrders = await client.getSpotOrders({ - currency_pair: 'BTC_USDT', - status: 'finished', - account: 'spot', - limit: 20, - }); - console.log('Recent BTC_USDT orders:', recentOrders); - } catch (error) { - console.error('Order-history request failed:', error); - } - - try { - const trades = await client.getSpotTradingHistory({ - currency_pair: 'BTC_USDT', - account: 'spot', - limit: 20, - }); - console.log('Recent BTC_USDT trades:', trades); - } catch (error) { - console.error('Trade-history request failed:', error); - } -} - -main(); -``` - -`getSpotAccounts()`, `getSpotOrders()`, and `getSpotTradingHistory()` return arrays. `getSpotOpenOrders()` returns an array whose entries group open orders by currency pair. Other private endpoints return objects or different array shapes, so check the [SDK endpoint map](./endpointFunctionList.md) instead of assuming a common format. - -### 3. Subscribe to public WebSocket streams - -Every subscription includes both a topic and an explicit `wsKey`. The key tells the SDK which Gate connection should carry the subscription. - - - -```javascript -import { WebsocketClient, WS_KEY_MAP } from 'gateio-api'; - -const ws = new WebsocketClient(); - -ws.on('response', (response) => { - console.log('Subscription response:', response); -}); - -ws.on('update', (update) => { - console.log('WebSocket update:', update); -}); - -ws.on('reconnect', ({ wsKey }) => { - console.log('Reconnecting:', wsKey); -}); - -ws.on('reconnected', (event) => { - console.log('Reconnected:', event.wsKey); -}); - -ws.on('exception', (error) => { - console.error('WebSocket exception:', error); -}); - -try { - ws.subscribe( - { - topic: 'spot.tickers', - payload: ['BTC_USDT'], - }, - WS_KEY_MAP.spotV4, - ); -} catch (error) { - console.error('Spot subscription failed:', error); -} - -try { - ws.subscribe( - { - topic: 'futures.tickers', - payload: ['BTC_USDT'], - }, - WS_KEY_MAP.perpFuturesUSDTV4, - ); -} catch (error) { - console.error('Futures subscription failed:', error); -} - -process.once('SIGINT', () => { - ws.closeAll(); -}); -``` - -Gate sends Spot ticker data as an object in `result`, while a Futures ticker update can contain an array. The SDK adds `wsKey` to each update so one event handler can identify the source connection. - -The main WebSocket events are: - -| Event | Meaning | -| --------------- | ------------------------------------------------------------- | -| `open` | A connection opened for the reported `wsKey` | -| `response` | Subscription, unsubscription, or request response | -| `update` | Market or account data | -| `authenticated` | A private connection authenticated successfully | -| `reconnect` | The connection dropped and a reconnect is starting | -| `reconnected` | The connection is open and cached subscriptions were restored | -| `close` | A connection closed for the reported `wsKey` | -| `exception` | The client or connection reported an error | - -A successful `response` event confirms the [subscription acknowledgement](https://siebly.io/reference/glossary#subscription-acknowledgement). It does not mean that a market update has arrived yet. - -### 4. Subscribe to private Spot streams - -Private streams use the same client with credentials. This example follows Spot balances, orders, and user trades. - - - -```javascript -import { WebsocketClient, WS_KEY_MAP } from 'gateio-api'; - -const ws = new WebsocketClient({ - apiKey: process.env.GATE_API_KEY, - apiSecret: process.env.GATE_API_SECRET, -}); - -ws.on('authenticated', ({ wsKey }) => { - console.log('Authenticated:', wsKey); -}); - -ws.on('response', (response) => { - console.log('Subscription response:', response); -}); - -ws.on('update', (update) => { - console.log('Private Spot update:', update); -}); - -ws.on('reconnected', (event) => { - console.log('Reconnected:', event.wsKey); -}); - -ws.on('exception', (error) => { - console.error('WebSocket exception:', error); -}); - -try { - ws.subscribe( - { - topic: 'spot.balances', - }, - WS_KEY_MAP.spotV4, - ); -} catch (error) { - console.error('Balance subscription failed:', error); -} - -try { - ws.subscribe( - { - topic: 'spot.orders', - payload: ['BTC_USDT'], - }, - WS_KEY_MAP.spotV4, - ); -} catch (error) { - console.error('Order subscription failed:', error); -} - -try { - ws.subscribe( - { - topic: 'spot.usertrades', - payload: ['BTC_USDT'], - }, - WS_KEY_MAP.spotV4, - ); -} catch (error) { - console.error('Trade subscription failed:', error); -} - -process.once('SIGINT', () => { - ws.closeAll(); -}); -``` - -Use the `authenticated` event as a connection-level signal. Use private updates as [private stream confirmation](https://siebly.io/reference/glossary#private-stream-confirmation) of account and order changes. - -Other private Spot topics include `spot.margin_balances` and `spot.cross_balances`. Check each channel's payload rules before subscribing. - -### 5. Subscribe to private Futures streams - -Futures private channels use your Gate user ID. Contract-specific channels also include the contract. Retrieve the user ID once from the REST API, then use the payload required by each channel. - -```javascript -import { RestClient, WebsocketClient, WS_KEY_MAP } from 'gateio-api'; - -const rest = new RestClient({ - apiKey: process.env.GATE_API_KEY, - apiSecret: process.env.GATE_API_SECRET, -}); - -const ws = new WebsocketClient({ - apiKey: process.env.GATE_API_KEY, - apiSecret: process.env.GATE_API_SECRET, -}); - -ws.on('authenticated', ({ wsKey }) => { - console.log('Authenticated:', wsKey); -}); - -ws.on('response', (response) => { - console.log('Subscription response:', response); -}); - -ws.on('update', (update) => { - console.log('Private Futures update:', update); -}); - -ws.on('exception', (error) => { - console.error('WebSocket exception:', error); -}); - -async function main() { - let account; - - try { - account = await rest.getAccountDetail(); - console.log('Gate user ID:', account.user_id); - } catch (error) { - console.error('Account detail request failed:', error); - return; - } - - const userId = String(account.user_id); - const payload = [userId, 'BTC_USDT']; - const wsKey = WS_KEY_MAP.perpFuturesUSDTV4; - - try { - ws.subscribe( - { - topic: 'futures.orders', - payload, - }, - wsKey, - ); - } catch (error) { - console.error('Order subscription failed:', error); - } - - try { - ws.subscribe( - { - topic: 'futures.usertrades', - payload, - }, - wsKey, - ); - } catch (error) { - console.error('Trade subscription failed:', error); - } - - try { - ws.subscribe( - { - topic: 'futures.balances', - payload: [userId], - }, - wsKey, - ); - } catch (error) { - console.error('Balance subscription failed:', error); - } - - try { - ws.subscribe( - { - topic: 'futures.positions', - payload, - }, - wsKey, - ); - } catch (error) { - console.error('Position subscription failed:', error); - } -} - -process.once('SIGINT', () => { - ws.closeAll(); -}); - -main(); -``` - -Keep the `wsKey` aligned with the settlement currency and product. USDT perpetual Futures use `WS_KEY_MAP.perpFuturesUSDTV4`; BTC perpetual Futures use `WS_KEY_MAP.perpFuturesBTCV4`. - -Gate also provides private Futures channels such as `futures.autoorders`. Use the payload documented for that specific channel. - -### 6. Place and cancel a Spot order in TestNet - -Gate TestNet uses separate credentials and API hosts. This example: - -1. Checks the explicit order opt-in. -2. Loads current `BTC_USDT` trading rules and the order book. -3. Calculates an amount that meets the pair's base and quote minimums. -4. Places a post-only limit buy at the current best bid. -5. Queries the order and cancels it if it remains open. - -The order uses `time_in_force: 'poc'`, Gate's post-only setting. A fast market can move before the request arrives, in which case Gate can reject or finish the order instead of leaving it on the book. - - - -```javascript -import { RestClient } from 'gateio-api'; - -const client = new RestClient({ - apiKey: process.env.GATE_TESTNET_API_KEY, - apiSecret: process.env.GATE_TESTNET_API_SECRET, - baseUrl: 'https://api-testnet.gateapi.io/api/v4', -}); - -async function main() { - if (process.env.GATE_PLACE_TESTNET_ORDER !== 'true') { - console.error('Set GATE_PLACE_TESTNET_ORDER=true to run this example.'); - return; - } - - if ( - !process.env.GATE_TESTNET_API_KEY || - !process.env.GATE_TESTNET_API_SECRET - ) { - console.error('Set GATE_TESTNET_API_KEY and GATE_TESTNET_API_SECRET.'); - return; - } - - let pair; - - try { - pair = await client.getSpotCurrencyPair({ - currency_pair: 'BTC_USDT', - }); - } catch (error) { - console.error('Currency pair request failed:', error); - return; - } - - let orderBook; - - try { - orderBook = await client.getSpotOrderBook({ - currency_pair: 'BTC_USDT', - limit: 5, - }); - } catch (error) { - console.error('Order book request failed:', error); - return; - } - - if (pair.trade_status !== 'tradable' && pair.trade_status !== 'buyable') { - console.error('BTC_USDT is not currently buyable.'); - return; - } - - const price = orderBook.bids[0]?.[0]; - const amountPrecision = pair.amount_precision; - const minBase = Number(pair.min_base_amount); - const minQuote = Number(pair.min_quote_amount); - const priceNumber = Number(price); - - if ( - !price || - amountPrecision === undefined || - !Number.isFinite(minBase) || - !Number.isFinite(minQuote) || - !Number.isFinite(priceNumber) || - priceNumber <= 0 - ) { - console.error('Required market metadata is unavailable.'); - return; - } - - const amountStep = 10 ** -amountPrecision; - const minimumAmount = Math.max(minBase, minQuote / priceNumber); - const amountNumber = (Math.ceil(minimumAmount / amountStep) + 1) * amountStep; - const amount = amountNumber.toFixed(amountPrecision); - - if (amountNumber < minBase || amountNumber * priceNumber < minQuote) { - console.error('Could not derive a valid TestNet order.'); - return; - } - - const maxBase = Number(pair.max_base_amount); - const maxQuote = Number(pair.max_quote_amount); - - if ( - (Number.isFinite(maxBase) && amountNumber > maxBase) || - (Number.isFinite(maxQuote) && amountNumber * priceNumber > maxQuote) - ) { - console.error('Derived amount exceeds the pair limits.'); - return; - } - - const text = `t-siebly${Date.now().toString().slice(-12)}`; - let placedOrder; - - try { - placedOrder = await client.submitSpotOrder({ - currency_pair: 'BTC_USDT', - account: 'spot', - side: 'buy', - type: 'limit', - amount, - price, - time_in_force: 'poc', - text, - }); - console.log('Placed Spot order:', placedOrder); - } catch (error) { - console.error('Spot order placement failed:', error); - return; - } - - if (!placedOrder.id) { - console.error('Gate did not return an order ID.'); - return; - } - - let currentOrder; - - try { - currentOrder = await client.getSpotOrder({ - order_id: placedOrder.id, - currency_pair: 'BTC_USDT', - account: 'spot', - }); - console.log('Current Spot order:', currentOrder); - } catch (error) { - console.error('Spot order query failed:', error); - } - - if (currentOrder && currentOrder.status !== 'open') { - console.log('Order is no longer open:', currentOrder.status); - return; - } - - try { - const cancelledOrder = await client.cancelSpotOrder({ - order_id: placedOrder.id, - currency_pair: 'BTC_USDT', - account: 'spot', - }); - console.log('Cancelled Spot order:', cancelledOrder); - } catch (error) { - console.error('Spot order cancellation failed:', error); - } -} - -main(); -``` - -The extra amount increment avoids falling just below the quote minimum after decimal rounding. Before using another pair, read its `amount_precision`, `precision`, minimums, maximums, and `trade_status`. - -### 7. Place and cancel a USDT perpetual order in TestNet - -A Futures `size` is a contract count. It is not an amount of BTC or USDT. This example reads the contract's minimum size and current price, and it only runs when the account is in one-way mode. It does not change account or position settings. - - - -```javascript -import { RestClient } from 'gateio-api'; - -const client = new RestClient({ - apiKey: process.env.GATE_TESTNET_API_KEY, - apiSecret: process.env.GATE_TESTNET_API_SECRET, - baseUrl: 'https://api-testnet.gateapi.io/api/v4', -}); - -async function main() { - if (process.env.GATE_PLACE_TESTNET_ORDER !== 'true') { - console.error('Set GATE_PLACE_TESTNET_ORDER=true to run this example.'); - return; - } - - if ( - !process.env.GATE_TESTNET_API_KEY || - !process.env.GATE_TESTNET_API_SECRET - ) { - console.error('Set GATE_TESTNET_API_KEY and GATE_TESTNET_API_SECRET.'); - return; - } - - let contract; - - try { - contract = await client.getFuturesContract({ - settle: 'usdt', - contract: 'BTC_USDT', - }); - } catch (error) { - console.error('Contract request failed:', error); - return; - } - - let orderBook; - - try { - orderBook = await client.getFuturesOrderBook({ - settle: 'usdt', - contract: 'BTC_USDT', - limit: 5, - }); - } catch (error) { - console.error('Order book request failed:', error); - return; - } - - let account; - - try { - account = await client.getFuturesAccount({ - settle: 'usdt', - }); - } catch (error) { - console.error('Futures account request failed:', error); - return; - } - - const oneWayMode = account.position_mode - ? account.position_mode === 'single' - : !account.in_dual_mode; - - if (!oneWayMode) { - console.error('This example requires one-way Futures position mode.'); - return; - } - - if (contract.status && contract.status !== 'trading') { - console.error('BTC_USDT Futures is not currently trading.'); - return; - } - - const price = orderBook.bids[0]?.p; - const size = Number(contract.order_size_min); - - if ( - !price || - !Number.isFinite(Number(price)) || - Number(price) <= 0 || - !Number.isFinite(size) || - size <= 0 || - (contract.enable_decimal === false && !Number.isInteger(size)) - ) { - console.error('Required contract metadata is unavailable.'); - return; - } - - console.log('One contract represents:', contract.quanto_multiplier, 'BTC'); - console.log('Price increment:', contract.order_price_round); - - const text = `t-siebly${Date.now().toString().slice(-12)}`; - let placedOrder; - - try { - placedOrder = await client.submitFuturesOrder({ - settle: 'usdt', - contract: 'BTC_USDT', - size, - price, - tif: 'poc', - text, - }); - console.log('Placed Futures order:', placedOrder); - } catch (error) { - console.error('Futures order placement failed:', error); - return; - } - - if (placedOrder.id === undefined) { - console.error('Gate did not return an order ID.'); - return; - } - - const orderId = String(placedOrder.id); - let currentOrder; - - try { - currentOrder = await client.getFuturesOrder({ - settle: 'usdt', - order_id: orderId, - }); - console.log('Current Futures order:', currentOrder); - } catch (error) { - console.error('Futures order query failed:', error); - } - - if (currentOrder && currentOrder.status !== 'open') { - console.log('Order is no longer open:', currentOrder.status); - return; - } - - try { - const cancelledOrder = await client.cancelFuturesOrder({ - settle: 'usdt', - order_id: orderId, - }); - console.log('Cancelled Futures order:', cancelledOrder); - } catch (error) { - console.error('Futures order cancellation failed:', error); - } -} - -main(); -``` - -In one-way mode, a positive `size` buys and a negative `size` sells. Dual-side mode uses different position semantics, so handle it in account-specific code after reading the [official Gate API v4 documentation](https://www.gate.com/docs/developers/apiv4/en/). - -The contract metadata supplies the size and price rules: - -- `order_size_min`: minimum contract count -- `order_price_round`: permitted price increment -- `quanto_multiplier`: underlying amount represented by one contract -- `enable_decimal`: whether fractional contract sizes are supported - -Do not derive a Futures order size from Spot precision rules. - -### 8. Send a Spot order through the WebSocket API - -`WebsocketAPIClient` turns Gate WebSocket API commands into promises. It connects and authenticates automatically on the first private command, adds a request ID, matches the response, and resolves the promise. - -This TestNet example uses the REST API only to read current market rules and the order book. The order, query, and cancellation use the WebSocket API. - - - -```javascript -import { RestClient, WebsocketAPIClient, WS_KEY_MAP } from 'gateio-api'; - -const rest = new RestClient({ - baseUrl: 'https://api-testnet.gateapi.io/api/v4', -}); - -const wsApi = new WebsocketAPIClient({ - apiKey: process.env.GATE_TESTNET_API_KEY, - apiSecret: process.env.GATE_TESTNET_API_SECRET, - wsUrl: 'wss://ws-testnet.gate.com/v4/ws/spot', -}); - -async function main() { - if (process.env.GATE_PLACE_TESTNET_ORDER !== 'true') { - console.error('Set GATE_PLACE_TESTNET_ORDER=true to run this example.'); - return; - } - - if ( - !process.env.GATE_TESTNET_API_KEY || - !process.env.GATE_TESTNET_API_SECRET - ) { - console.error('Set GATE_TESTNET_API_KEY and GATE_TESTNET_API_SECRET.'); - return; - } - - let pair; - - try { - pair = await rest.getSpotCurrencyPair({ - currency_pair: 'BTC_USDT', - }); - } catch (error) { - console.error('Currency pair request failed:', error); - return; - } - - let orderBook; - - try { - orderBook = await rest.getSpotOrderBook({ - currency_pair: 'BTC_USDT', - limit: 5, - }); - } catch (error) { - console.error('Order book request failed:', error); - return; - } - - if (pair.trade_status !== 'tradable' && pair.trade_status !== 'buyable') { - console.error('BTC_USDT is not currently buyable.'); - return; - } - - const price = orderBook.bids[0]?.[0]; - const amountPrecision = pair.amount_precision; - const minBase = Number(pair.min_base_amount); - const minQuote = Number(pair.min_quote_amount); - const priceNumber = Number(price); - - if ( - !price || - amountPrecision === undefined || - !Number.isFinite(minBase) || - !Number.isFinite(minQuote) || - !Number.isFinite(priceNumber) || - priceNumber <= 0 - ) { - console.error('Required market metadata is unavailable.'); - return; - } - - const amountStep = 10 ** -amountPrecision; - const minimumAmount = Math.max(minBase, minQuote / priceNumber); - const amountNumber = (Math.ceil(minimumAmount / amountStep) + 1) * amountStep; - const amount = amountNumber.toFixed(amountPrecision); - - if (amountNumber < minBase || amountNumber * priceNumber < minQuote) { - console.error('Could not derive a valid TestNet order.'); - return; - } - - const maxBase = Number(pair.max_base_amount); - const maxQuote = Number(pair.max_quote_amount); - - if ( - (Number.isFinite(maxBase) && amountNumber > maxBase) || - (Number.isFinite(maxQuote) && amountNumber * priceNumber > maxQuote) - ) { - console.error('Derived amount exceeds the pair limits.'); - return; - } - - const text = `t-siebly${Date.now().toString().slice(-12)}`; - const wsKey = WS_KEY_MAP.spotV4; - - try { - let placedResponse; - - try { - placedResponse = await wsApi.submitNewSpotOrder( - { - currency_pair: 'BTC_USDT', - account: 'spot', - side: 'buy', - type: 'limit', - amount, - price, - time_in_force: 'poc', - text, - }, - wsKey, - ); - console.log('Command status:', placedResponse.header.status); - console.log('Placed Spot order:', placedResponse.data.result); - } catch (error) { - console.error('Spot WebSocket API placement failed:', error); - return; - } - - const orderId = placedResponse.data.result.id; - let statusResponse; - - try { - statusResponse = await wsApi.getSpotOrderStatus( - { - order_id: orderId, - currency_pair: 'BTC_USDT', - account: 'spot', - }, - wsKey, - ); - console.log('Current Spot order:', statusResponse.data.result); - } catch (error) { - console.error('Spot WebSocket API query failed:', error); - } - - if (statusResponse && statusResponse.data.result.status !== 'open') { - console.log( - 'Order is no longer open:', - statusResponse.data.result.status, - ); - return; - } - - try { - const cancelledResponse = await wsApi.cancelSpotOrder( - { - order_id: orderId, - currency_pair: 'BTC_USDT', - account: 'spot', - }, - wsKey, - ); - console.log('Cancelled Spot order:', cancelledResponse.data.result); - } catch (error) { - console.error('Spot WebSocket API cancellation failed:', error); - } - } finally { - wsApi.getWSClient().closeAll(); - } +/**========================================================================================================================== + * EARN + * ========================================================================================================================== + */ +⋮---- +/** GET /earn/dual/investment_plan */ +export interface GetDualInvestmentPlansReq { + plan_id?: number | string; + coin?: string; + type?: string; + quote_currency?: string; + /** `apy` | `short-period` | `multiple` */ + sort?: string; + page?: number; + page_size?: number; } +⋮---- +/** `apy` | `short-period` | `multiple` */ +⋮---- +/** GET /earn/dual/orders */ +export interface GetDualInvestmentOrdersReq { + from?: number; + to?: number; + type?: string; + status?: string; + coin?: string; + page?: number; + limit?: number; +} +⋮---- +/** GET /earn/dual/order-refund-preview */ +export interface GetDualOrderRefundPreviewReq { + order_id: string; +} +⋮---- +/** POST /earn/dual/order-refund */ +export interface SubmitDualOrderRefundParams { + order_id: string; + /** From order-refund-preview */ + req_id: string; +} +⋮---- +/** From order-refund-preview */ +⋮---- +/** POST /earn/dual/modify-order-reinvest */ +export interface UpdateDualOrderReinvestParams { + order_id?: number; + /** 0 off, 1 on */ + status?: number; + /** Effective duration in seconds; default 86400 */ + effective_time_duration?: number; +} +⋮---- +/** 0 off, 1 on */ +⋮---- +/** Effective duration in seconds; default 86400 */ +⋮---- +/** GET /earn/dual/project-recommend */ +export interface GetDualProjectRecommendReq { + mode?: string; + coin?: string; + type?: string; + /** Comma-separated project IDs to exclude */ + history_pids?: string; +} +⋮---- +/** Comma-separated project IDs to exclude */ +⋮---- +/** Request params for POST /earn/dual/orders */ +export interface PlaceDualInvestmentOrderParams { + plan_id: string; + /** Subscription amount. Mutually exclusive with copies. */ + amount: string; + /** Units. Mutually exclusive with amount. */ + copies?: string; + /** Custom order info, must start with t- */ + text?: string; +} +⋮---- +/** Subscription amount. Mutually exclusive with copies. */ +⋮---- +/** Units. Mutually exclusive with amount. */ +⋮---- +/** Custom order info, must start with t- */ +⋮---- +/**========================================================================================================================== + * EARN FIXED-TERM + * ========================================================================================================================== + */ +⋮---- +export interface GetEarnFixedTermProductsReq { + asset?: string; + type?: number; // 1 regular, 2 VIP + page: number; + limit: number; +} +⋮---- +type?: number; // 1 regular, 2 VIP +⋮---- +export interface GetEarnFixedTermProductsByAssetReq { + /** Product type: "" or 1 regular, 2 VIP, 0 all */ + type?: string; +} +⋮---- +/** Product type: "" or 1 regular, 2 VIP, 0 all */ +⋮---- +export interface CreateEarnFixedTermLendReq { + product_id: number; + amount: string; + year_rate?: string; + reinvest_status?: number; // 0 off, 1 on + redeem_account_type?: number; // 1 spot + financial_rate_id?: number; // interest boost coupon id, 0 = none + sub_business?: number; +} +⋮---- +reinvest_status?: number; // 0 off, 1 on +redeem_account_type?: number; // 1 spot +financial_rate_id?: number; // interest boost coupon id, 0 = none +⋮---- +export interface GetEarnFixedTermLendsReq { + product_id?: number; + order_id?: number; + asset?: string; + order_type: '1' | '2'; // 1 current, 2 historical + page: number; + limit: number; + sub_business?: number; + business_filter?: string; +} +⋮---- +order_type: '1' | '2'; // 1 current, 2 historical +⋮---- +export interface EarnFixedTermPreRedeemReq { + order_id: string; +} +⋮---- +export interface GetEarnFixedTermHistoryReq { + product_id?: number; + order_id?: string; + asset?: string; + type: '1' | '2' | '3' | '4'; // 1 subscribe, 2 redeem, 3 interest, 4 bonus + page: number; + limit: number; + start_at?: number; + end_at?: number; + sub_business?: number; + business_filter?: string; +} +⋮---- +type: '1' | '2' | '3' | '4'; // 1 subscribe, 2 redeem, 3 interest, 4 bonus -main(); -``` - -### 9. Send a USDT perpetual order through the WebSocket API - -Futures WebSocket API commands use a product-specific WebSocket key. Pass it explicitly so the contract and connection remain clear. - - - -```javascript -import { RestClient, WebsocketAPIClient, WS_KEY_MAP } from 'gateio-api'; - -const rest = new RestClient({ - apiKey: process.env.GATE_TESTNET_API_KEY, - apiSecret: process.env.GATE_TESTNET_API_SECRET, - baseUrl: 'https://api-testnet.gateapi.io/api/v4', -}); - -const wsApi = new WebsocketAPIClient({ - apiKey: process.env.GATE_TESTNET_API_KEY, - apiSecret: process.env.GATE_TESTNET_API_SECRET, - wsUrl: 'wss://ws-testnet.gate.com/v4/ws/futures/usdt', -}); - -async function main() { - if (process.env.GATE_PLACE_TESTNET_ORDER !== 'true') { - console.error('Set GATE_PLACE_TESTNET_ORDER=true to run this example.'); - return; - } - - if ( - !process.env.GATE_TESTNET_API_KEY || - !process.env.GATE_TESTNET_API_SECRET - ) { - console.error('Set GATE_TESTNET_API_KEY and GATE_TESTNET_API_SECRET.'); - return; - } - - let contract; - - try { - contract = await rest.getFuturesContract({ - settle: 'usdt', - contract: 'BTC_USDT', - }); - } catch (error) { - console.error('Contract request failed:', error); - return; - } - - let orderBook; - - try { - orderBook = await rest.getFuturesOrderBook({ - settle: 'usdt', - contract: 'BTC_USDT', - limit: 5, - }); - } catch (error) { - console.error('Order book request failed:', error); - return; - } - - let account; - - try { - account = await rest.getFuturesAccount({ - settle: 'usdt', - }); - } catch (error) { - console.error('Futures account request failed:', error); - return; - } - - const oneWayMode = account.position_mode - ? account.position_mode === 'single' - : !account.in_dual_mode; - - if (!oneWayMode) { - console.error('This example requires one-way Futures position mode.'); - return; - } - - if (contract.status && contract.status !== 'trading') { - console.error('BTC_USDT Futures is not currently trading.'); - return; - } - - const price = orderBook.bids[0]?.p; - const size = Number(contract.order_size_min); - - if ( - !price || - !Number.isFinite(Number(price)) || - Number(price) <= 0 || - !Number.isFinite(size) || - size <= 0 || - (contract.enable_decimal === false && !Number.isInteger(size)) - ) { - console.error('Required contract metadata is unavailable.'); - return; - } - - const text = `t-siebly${Date.now().toString().slice(-12)}`; - const wsKey = WS_KEY_MAP.perpFuturesUSDTV4; - - try { - let placedResponse; - - try { - placedResponse = await wsApi.submitNewFuturesOrder( - { - contract: 'BTC_USDT', - size, - price, - tif: 'poc', - text, - }, - wsKey, - ); - console.log('Command status:', placedResponse.header.status); - console.log('Placed Futures order:', placedResponse.data.result); - } catch (error) { - console.error('Futures WebSocket API placement failed:', error); - return; - } - - const orderId = String(placedResponse.data.result.id); - let statusResponse; - - try { - statusResponse = await wsApi.getFuturesOrderStatus( - { - order_id: orderId, - }, - wsKey, - ); - console.log('Current Futures order:', statusResponse.data.result); - } catch (error) { - console.error('Futures WebSocket API query failed:', error); - } +================ +File: src/types/request/unified.ts +================ +export interface SubmitUnifiedBorrowOrRepayReq { + currency: string; + type: 'borrow' | 'repay'; + amount: string; + repaid_all?: boolean; + text?: string; +} +⋮---- +export interface GetUnifiedLoansReq { + currency?: string; + page?: number; + limit?: number; + type?: 'platform' | 'margin'; +} +⋮---- +export interface GetUnifiedLoanRecordsReq { + type?: 'borrow' | 'repay'; + currency?: string; + page?: number; + limit?: number; +} +export interface GetUnifiedInterestRecordsReq { + currency?: string; + page?: number; + limit?: number; + from?: number; + to?: number; + type?: 'platform' | 'margin'; +} +⋮---- +export interface SetUnifiedAccountModeReq { + mode: 'classic' | 'multi_currency' | 'portfolio' | 'single_currency'; + settings?: { + usdt_futures?: boolean; + spot_hedge?: boolean; + use_funding?: boolean; + options?: boolean; + }; +} +⋮---- +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 GetUnifiedHistoryLendingRateReq { + currency: string; + tier?: string; + page?: number; + limit?: number; +} +⋮---- +export interface SubmitUnifiedLoanRepayReq { + 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[]; +} +⋮---- +/** POST /unified/delta_neutral — v4.106.97 */ +export interface SetUnifiedDeltaNeutralReq { + enabled: boolean; +} +⋮---- +/** POST /unified/leverage/user_setting — set leverage for all borrowed currencies */ +export interface SetUserLeverageReq { + leverage?: string; +} - if (statusResponse && statusResponse.data.result.status !== 'open') { - console.log( - 'Order is no longer open:', - statusResponse.data.result.status, - ); - return; - } +================ +File: src/types/request/wallet.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 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; +} +⋮---- +export interface GetMainSubTransfersReq { + sub_uid?: string; + from?: number; + to?: number; + limit?: number; + offset?: number; +} +⋮---- +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 +} +⋮---- +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; +} +⋮---- +export interface ListPushOrdersReq { + id?: number; + from?: number; + to?: number; + limit?: number; + offset?: number; + transaction_type?: string; +} +⋮---- +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; +} +⋮---- +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'; +} +⋮---- +/** GET /wallet/transfers */ +export interface GetTransferReq { + tx_id: string; +} - try { - const cancelledResponse = await wsApi.cancelFuturesOrder( - { - order_id: orderId, - }, - wsKey, - ); - console.log('Cancelled Futures order:', cancelledResponse.data.result); - } catch (error) { - console.error('Futures WebSocket API cancellation failed:', error); - } - } finally { - wsApi.getWSClient().closeAll(); - } +================ +File: src/types/response/stock.ts +================ +export type StockCategory = + | 'CS' + | 'ETF' + | 'ADRC' + | 'ADR' + | 'ETV' + | 'PFD' + | 'ETS' + | 'ETN' + | 'FUND'; +⋮---- +export type StockAssetType = 'STOCK' | 'ETF'; +⋮---- +/** v4.106.159: `closed` and `gt_lp` removed. */ +export type StockTradeStatus = 'pre_market' | 'open' | 'post_market'; +⋮---- +/** + * v4.106.148. + * 0 disabled, 1 buy only, 2 sell only, 4 buy and sell, + * 5 manual suspension, 6 strategy exception, 7 stock halt, 8 circuit breaker halt. + */ +export type StockTradeMode = 0 | 1 | 2 | 4 | 5 | 6 | 7 | 8; +⋮---- +/** + * `GET /stock/orders` and `GET /stock/orders/history`. JSON stays an integer. + * 0 unknown, 1 new, 2 partial, 3 filled, 4 canceled, 5 rejected, + * 6 cancel rejected, 7 update succeeded, 8 update rejected. + */ +export type StockOrderStatus = 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8; +⋮---- +/** + * `GET /stock/orders/history`. JSON stays an integer. + * 0 unknown, 1 no quote, 2 no match, 3 trigger price exceeded, + * 4 order value exceeds limit, 5 unknown rejection, 6 unknown cancellation, + * 7 canceled by user, 8 time in force expired, 9 session unsupported, + * 13 canceled due to corporate action. + */ +export type StockOrderFinishAs = 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 13; +⋮---- +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?: StockTradeStatus; + trade_mode?: StockTradeMode; + 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?: StockTradeStatus; + trade_mode?: StockTradeMode; + 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?: StockTradeStatus; + trade_mode?: StockTradeMode; + price_type?: string; + side?: number; + status?: StockOrderStatus; + 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?: StockOrderStatus; + status_desc?: string; + status_detail?: { title?: string; message?: string } | null; + finish_as?: StockOrderFinishAs; + 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; } - -main(); -``` - -Successful commands have `header.status === '200'`, and the endpoint result is in `data.result`. The SDK rejects a command promise when Gate returns a non-success status. - -An accepted command is not proof that an order later filled, remained open, or was cancelled. Treat the response as [pending confirmation](https://siebly.io/reference/glossary#pending-confirmation), then confirm the final state through the private order stream or a REST API query. - - - -## Work with the Gate REST API - -`RestClient` covers Gate's product groups through named methods. Public methods work without credentials. Private methods use the API key and secret passed to the client. - -### Understand response shapes - -The client resolves to the endpoint's response body: - -```javascript -import { RestClient } from 'gateio-api'; - -const client = new RestClient(); - -async function main() { - try { - const result = await client.getSpotOrderBook({ - currency_pair: 'BTC_USDT', - }); - console.log(result); - } catch (error) { - console.error('Order book request failed:', error); - } +⋮---- +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?: StockTradeStatus; + 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 StockFeeRateItem { + vip_level?: number; + maker_fee?: string; + taker_fee?: string; } -main(); -``` - -There is no shared response envelope. Check the [SDK endpoint map](./endpointFunctionList.md) before deciding how to handle `result`. - -| Method | Response shape | -| ----------------------- | ------------------------------------------ | -| `getServerTime()` | Object with `server_time` | -| `getSpotCurrencyPair()` | Currency-pair object | -| `getSpotTicker()` | Array of ticker objects | -| `getSpotOrderBook()` | Object with tuple-array `bids` and `asks` | -| `getSpotCandles()` | Array of candle tuples | -| `getFuturesContract()` | Contract object | -| `getFuturesTickers()` | Array of ticker objects | -| `getFuturesOrderBook()` | Object with `{ p, s }` bid and ask entries | -| `getFuturesAccount()` | Account object | -| `getFuturesPositions()` | Array of position objects | - -Prices and quantities are commonly returned as strings. Keep them as strings while passing them between Gate API methods. Convert them deliberately when doing calculations, and round the result back to the product's required precision. - -### Read account state - -An authenticated integration usually needs these views: - -| State | Spot method | USDT perpetual method | -| ------------------- | ------------------------- | ---------------------------------------------------------- | -| Balances or account | `getSpotAccounts()` | `getFuturesAccount({ settle: 'usdt' })` | -| Positions | Not applicable | `getFuturesPositions({ settle: 'usdt' })` | -| Open orders | `getSpotOpenOrders()` | `getFuturesOrders({ settle: 'usdt', status: 'open' })` | -| Recent orders | `getSpotOrders()` | `getFuturesOrders({ settle: 'usdt', status: 'finished' })` | -| Trades | `getSpotTradingHistory()` | `getFuturesTradingHistory({ settle: 'usdt' })` | - -These REST API views form a reliable [account state](https://siebly.io/reference/glossary#accountstate) baseline before stream updates are applied. - -### Explore other Gate product groups - -The same `RestClient` also covers the following APIs. Start with read methods and check account eligibility, permissions, and product-specific rules before using any write method. - -| Product group | Representative SDK methods | -| ----------------------- | --------------------------------------------------------------------------- | -| Margin and cross margin | `getMarginAccounts()`, `getCrossMarginAccount()`, `getMarginUserAccounts()` | -| Universal margin loans | `getMarginUNILoans()`, `getMarginUNIMaxBorrow()` | -| Unified Account | `getUnifiedAccountInfo()`, `getUnifiedAccountMode()`, `getUnifiedLoans()` | -| Delivery | `getAllDeliveryContracts()`, `getDeliveryAccount()`, `getDeliveryOrders()` | -| Options | `getOptionsContracts()`, `getOptionsAccount()`, `getOptionsOrders()` | -| Wallet and transfers | `getBalances()`, `submitTransfer()`, `getTransferStatus()` | -| Multi-collateral loans | `getMultiLoanOrders()`, `getMultiLoanSupportedCurrencies()` | -| Flash Swap | `getFlashSwapCurrencyPairs()`, `getFlashSwapOrders()` | -| Earn and lending | `getEarnFixedTermProducts()`, `getEarnFixedTermLends()` | -| Auto Invest | `getAutoInvestCoins()`, `getAutoInvestPlans()`, `getAutoInvestOrders()` | -| Subaccounts | `getSubAccounts()`, `getSubBalance()`, `getSubFuturesBalances()` | -| Rebates and partners | `getPartnerTransactionHistory()`, `getPartnerCommissionHistory()` | -| OTC | `getOTCBankList()`, `getOTCFiatOrderList()` | -| P2P Merchant | `getP2PMerchantUserInfo()`, `getP2PMerchantPendingTransactionList()` | -| CrossEx | `getCrossExSymbols()`, `getCrossExAccounts()`, `getCrossExPositions()` | -| Alpha | `getAlphaCurrencies()`, `getAlphaTickers()`, `getAlphaOrders()` | -| TradFi | `getTradFiSymbols()`, `getTradFiAssets()`, `getTradFiOrders()` | - -See the [complete SDK endpoint map](./endpointFunctionList.md) for every supported method, its authentication requirement, HTTP method, and Gate path. - - - -## Build with WebSocket streams - -Use `WebsocketClient` for ongoing market and account updates. A subscription request has two independent parts: - -- `topic` and `payload` select the Gate channel and its data. -- `wsKey` selects the product connection that carries the subscription. - -One `subscribe()` call can contain several topics when they share the same `wsKey`. Use separate calls for topics on different product connections. - -### Choose the correct WebSocket key - -| Product connection | SDK key | -| ---------------------- | ---------------------------------- | -| Spot | `WS_KEY_MAP.spotV4` | -| USDT perpetual Futures | `WS_KEY_MAP.perpFuturesUSDTV4` | -| BTC perpetual Futures | `WS_KEY_MAP.perpFuturesBTCV4` | -| USDT Delivery | `WS_KEY_MAP.deliveryFuturesUSDTV4` | -| BTC Delivery | `WS_KEY_MAP.deliveryFuturesBTCV4` | -| Options | `WS_KEY_MAP.optionsV4` | -| Announcements | `WS_KEY_MAP.announcementsV4` | - -Do not infer the connection from a symbol alone. `BTC_USDT` can appear in more than one product family. - -Useful public topics include: - -| Product | Starting topics | -| ------- | -------------------------------------------------------------------------------------------------------------- | -| Spot | `spot.tickers`, `spot.trades`, `spot.order_book`, `spot.order_book_update`, `spot.candlesticks` | -| Futures | `futures.tickers`, `futures.trades`, `futures.order_book`, `futures.order_book_update`, `futures.candlesticks` | -| Options | `options.tickers`, `options.trades`, `options.order_book`, `options.ul_tickers` | - -### Treat responses and updates differently - -The `response` event tells you whether Gate accepted a subscribe, unsubscribe, or request message. Check its `error` and `result`. - -The `update` event carries channel data. Inspect `channel`, `event`, `result`, and the SDK-added `wsKey` before updating local state. A subscription response and a data update can have different result shapes. - -### Recover after a reconnect - -The SDK reconnects and restores cached subscriptions. A stream gap can still hide balance, order, trade, or position changes. Reload the affected state from the REST API after `reconnected`. - -This Spot example reloads balances, open orders, and recent trades in sequence: - -```javascript -import { RestClient, WebsocketClient, WS_KEY_MAP } from 'gateio-api'; - -const rest = new RestClient({ - apiKey: process.env.GATE_API_KEY, - apiSecret: process.env.GATE_API_SECRET, -}); - -const ws = new WebsocketClient({ - apiKey: process.env.GATE_API_KEY, - apiSecret: process.env.GATE_API_SECRET, -}); - -let recoveryRunning = false; -let spotState; - -async function recoverSpotState() { - if (recoveryRunning) { - return; - } - - recoveryRunning = true; - - try { - let balances; - - try { - balances = await rest.getSpotAccounts(); - } catch (error) { - console.error('Balance recovery failed:', error); - return; - } - - let openOrders; - - try { - openOrders = await rest.getSpotOpenOrders({ - account: 'spot', - }); - } catch (error) { - console.error('Open-order recovery failed:', error); - return; - } - - let trades; - - try { - trades = await rest.getSpotTradingHistory({ - currency_pair: 'BTC_USDT', - account: 'spot', - limit: 100, - }); - } catch (error) { - console.error('Trade recovery failed:', error); - return; - } - - spotState = { - balances, - openOrders, - trades, - recoveredAt: Date.now(), +================ +File: src/types/response/wallet.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; +} +⋮---- +/** GET /wallet/sub_account_balances item */ +export interface SubAccountBalance { + uid: string; + available: { [key: string]: string }; + /** Locked amount per currency */ + locking?: { [key: string]: string }; +} +⋮---- +/** Locked amount per currency */ +⋮---- +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'; +} +⋮---- +| '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 +⋮---- +export interface CreateDepositAddressResp { + currency: string; + address: string; + multichain_addresses: { + chain: string; + address: string; + payment_id: string; + payment_name: string; + obtain_failed: number; + }[]; +} +⋮---- +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 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 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 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; + }; }; - - console.log('Recovered Spot state:', spotState); - } finally { - recoveryRunning = false; - } + }; } - -ws.on('reconnected', async ({ wsKey }) => { - if (wsKey !== WS_KEY_MAP.spotV4) { - return; - } - - await recoverSpotState(); -}); - -ws.on('update', (update) => { - console.log('Private Spot update:', update); -}); - -ws.on('exception', (error) => { - console.error('WebSocket exception:', error); -}); - -try { - ws.subscribe( - { - topic: 'spot.balances', - }, - WS_KEY_MAP.spotV4, - ); -} catch (error) { - console.error('Balance subscription failed:', error); +⋮---- +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 SavedAddress { + currency: string; + chain: string; + address: string; + name: string; + tag: string; + verified: string; +} +⋮---- +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 GetBalancesResp { + total: { + amount: string; + currency: string; + unrealised_pnl?: string; + borrowed?: string; + }; + details: { + [key: string]: { + amount: string; + currency: string; + unrealised_pnl?: string; + borrowed?: string; + }; + }; } - -try { - ws.subscribe( - { - topic: 'spot.orders', - payload: ['BTC_USDT'], - }, - WS_KEY_MAP.spotV4, - ); -} catch (error) { - console.error('Order subscription failed:', error); +⋮---- +export interface SmallBalanceRecord { + currency: string; + available_balance: string; + estimated_as_btc: string; + convertible_to_gt: string; } - -try { - ws.subscribe( - { - topic: 'spot.usertrades', - payload: ['BTC_USDT'], - }, - WS_KEY_MAP.spotV4, - ); -} catch (error) { - console.error('Trade subscription failed:', error); +⋮---- +export interface SmallBalanceHistoryRecord { + id: string; + currency: string; + amount: string; + gt_amount: string; + create_time: number; +} +⋮---- +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; +} +⋮---- +/** 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; } -process.once('SIGINT', () => { - ws.closeAll(); -}); -``` - -This is [REST API hydration](https://siebly.io/reference/glossary#rest-hydration) applied as [scoped recovery](https://siebly.io/reference/glossary#scoped-recovery). The example replaces `spotState` only after all three reads succeed. Reload only the state that may have changed on the affected connection, then reconcile it before trusting new updates. - -For a wider recovery design, see [Exchange State](https://siebly.io/reference/exchange-state) and [Runtime Workflows](https://siebly.io/reference/runtime-workflows). - - - -## Use the Gate WebSocket API - -`WebsocketAPIClient` is for request and response commands over WebSocket. It is not the same as a subscription stream. +================ +File: src/types/websockets/client.ts +================ +import type { ClientRequestArgs } from 'http'; +import WebSocket from 'isomorphic-ws'; +⋮---- +/** + * Event args for subscribing/unsubscribing + */ +⋮---- +// export type WsTopicSubscribePrivateArgsV2 = +// | WsTopicSubscribePrivateInstIdArgsV2 +// | WsTopicSubscribePrivateCoinArgsV2; +⋮---- +// export type WsTopicSubscribeEventArgsV2 = +// | WsTopicSubscribePublicArgsV2 +// | WsTopicSubscribePrivateArgsV2; +⋮---- +/** General configuration for the WebsocketClient */ +export interface WSClientConfigurableOptions { + /** Your API key */ + apiKey?: string; -The client: + /** Your API secret */ + apiSecret?: string; -1. Opens the selected WebSocket connection. -2. Authenticates automatically. -3. Adds a unique request ID. -4. Sends the command. -5. Matches Gate's response to the pending promise. -6. Resolves with `header`, `data.result`, `request_id`, and `wsKey`. + useTestnet?: boolean; -Authentication happens automatically on the first command. `connectWSAPI(wsKey)` is available when an application wants to open and authenticate the connection early. Automatic WebSocket API reauthentication after a reconnect is enabled by default. + /** Define a recv window when preparing a private websocket signature. This is in milliseconds, so 5000 == 5 seconds */ + recvWindow?: number; -Spot methods include: + /** How often to check if the connection is alive */ + pingInterval?: number; -- `submitNewSpotOrder()` -- `getSpotOrderStatus()` -- `getSpotOrders()` -- `updateSpotOrder()` -- `cancelSpotOrder()` -- `cancelSpotOrderById()` -- `cancelSpotOrderForSymbol()` + /** How long to wait for a pong (heartbeat reply) before assuming the connection is dead */ + pongTimeout?: number; -Futures methods include: + /** Delay in milliseconds before respawning the connection */ + reconnectTimeout?: number; -- `submitNewFuturesOrder()` -- `submitNewFuturesBatchOrder()` -- `getFuturesOrderStatus()` -- `getFuturesOrders()` -- `updateFuturesOrder()` -- `cancelFuturesOrder()` + requestOptions?: {}; -Pass a Futures `wsKey` explicitly. This keeps the settlement connection visible: + wsUrl?: string; -```javascript -import { WebsocketAPIClient, WS_KEY_MAP } from 'gateio-api'; + wsOptions?: { + protocols?: string[]; + agent?: any; + } & ( + | Omit, 'agent'> + | Omit, 'agent'> + ); -const wsApi = new WebsocketAPIClient({ - apiKey: process.env.GATE_API_KEY, - apiSecret: process.env.GATE_API_SECRET, -}); + /** + * 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; -async function main() { - try { - const response = await wsApi.getFuturesOrders( - { - contract: 'BTC_USDT', - status: 'open', - limit: 20, - }, - WS_KEY_MAP.perpFuturesUSDTV4, - ); + /** + * If you authenticated the WS API before, automatically try to re-authenticate the WS API if you're disconnected/reconnected for any reason. + */ + reauthWSAPIOnReconnect?: boolean; +} +⋮---- +/** Your API key */ +⋮---- +/** Your API secret */ +⋮---- +/** Define a recv window when preparing a private websocket signature. This is in milliseconds, so 5000 == 5 seconds */ +⋮---- +/** How often to check if the connection is alive */ +⋮---- +/** How long to wait for a pong (heartbeat reply) before assuming the connection is dead */ +⋮---- +/** Delay in milliseconds before respawning the connection */ +⋮---- +/** + * Allows you to provide a custom "signMessage" function, e.g. to use node's much faster createHmac method + * + * Look in the examples folder for a demonstration on using node's createHmac instead. + */ +⋮---- +/** + * If you authenticated the WS API before, automatically try to re-authenticate the WS API if you're disconnected/reconnected for any reason. + */ +⋮---- +/** + * WS configuration that's always defined, regardless of user configuration + * (usually comes from defaults if there's no user-provided values) + */ +export interface WebsocketClientOptions extends WSClientConfigurableOptions { + pingInterval: number; + pongTimeout: number; + reconnectTimeout: number; + recvWindow: number; + authPrivateConnectionsOnConnect: boolean; + authPrivateRequests: boolean; + reauthWSAPIOnReconnect: boolean; +} - console.log(response.header.status); - console.log(response.data.result); - } catch (error) { - console.error('WebSocket API order request failed:', error); - } finally { - wsApi.getWSClient().closeAll(); - } +================ +File: src/types/shared.ts +================ +/** + * Built-in Gate API v4 hosts. + * `testnet` is the global TestNet host (spot and futures). + * `futuresTestnet` is the same host, kept so older `baseUrlKey` values keep working. + */ +export type GateBaseUrlKey = + | 'live' + | 'futuresLiveAlternative' + | 'testnet' + | 'futuresTestnet'; +⋮---- +// interfaces +⋮---- +export interface FromToPageLimit { + from: number; + to: number; + 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; } +⋮---- +up_rate?: string; // v4.106.4: Maximum price increase percentage +down_rate?: string; // v4.106.4: Maximum price decrease percentage -main(); -``` - -The response confirms the command outcome. Use private order streams or a REST API query to confirm the resulting exchange state. - - - -## Use Gate TestNet +================ +File: webpack/webpack.config.cjs +================ +function generateConfig(name) +⋮---- +// Add '.ts' and '.tsx' as resolvable extensions. +⋮---- +// 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 +⋮---- +// Code is already transpiled from TypeScript, no additional loaders needed -Gate TestNet is a separate environment with separate credentials. Use it for all order examples while learning the SDK. +================ +File: docs/GATE_SDK_QUICKSTART_GUIDE.md +================ + -| Interface | Current TestNet host | -| ------------------------ | ---------------------------------------------- | -| REST API | `https://api-testnet.gateapi.io/api/v4` | -| Spot WebSocket | `wss://ws-testnet.gate.com/v4/ws/spot` | -| USDT perpetual WebSocket | `wss://ws-testnet.gate.com/v4/ws/futures/usdt` | +# Gate API JavaScript Tutorial for Node.js -Set the REST API host with `baseUrl` and the WebSocket host with `wsUrl`. Prefer explicit hosts for TestNet examples: + -- Spot WebSocket TestNet is not wired through `useTestnet: true` in this SDK. The Spot testnet map entry is a stub (`NoTestnetForSpotWebsockets!`), so set `wsUrl` to the Spot TestNet host above. -- For Futures-only REST TestNet, the SDK also accepts `baseUrlKey: 'futuresTestnet'`, which resolves to `https://fx-api-testnet.gateio.ws/api/v4`. The Global TestNet REST host in the table is the host used by the Spot and Futures order examples in this guide. +> [!TIP] +> Read this guide in tutorial format on the Siebly website: [Gate JavaScript REST API and WebSocket Tutorial](https://siebly.io/sdk/gate/javascript/tutorial) -```javascript -import { RestClient, WebsocketClient } from 'gateio-api'; + -const rest = new RestClient({ - apiKey: process.env.GATE_TESTNET_API_KEY, - apiSecret: process.env.GATE_TESTNET_API_SECRET, - baseUrl: 'https://api-testnet.gateapi.io/api/v4', -}); +This tutorial uses [`gateio-api`](https://www.npmjs.com/package/gateio-api), Siebly's Node.js, JavaScript, and TypeScript SDK for Gate.com. It covers public and private REST API calls, Spot and Futures TestNet orders, live WebSocket streams, WebSocket API commands, API hosts, and proxies. -const spotWs = new WebsocketClient({ - apiKey: process.env.GATE_TESTNET_API_KEY, - apiSecret: process.env.GATE_TESTNET_API_SECRET, - wsUrl: 'wss://ws-testnet.gate.com/v4/ws/spot', -}); -``` +The SDK handles REST API request signing, private WebSocket authentication, product-specific WebSocket routing, heartbeats, reconnects, resubscriptions, and WebSocket API response matching. Request and response types are included for TypeScript users. -Do not send live credentials to TestNet or TestNet credentials to live hosts. TestNet balances, liquidity, and available products can differ from live trading. +**Key links** -Fund the required Spot or Futures TestNet account with test assets before running an order example. +- Gate JavaScript SDK by Siebly: [`gateio-api`](https://siebly.io/sdk/gate/javascript) +- npm package: [`gateio-api`](https://www.npmjs.com/package/gateio-api) +- GitHub repository: [`sieblyio/gateio-api`](https://github.com/sieblyio/gateio-api) +- SDK examples: [Gate SDK examples](https://siebly.io/examples/Gate) +- SDK endpoint map: [Gate JavaScript endpoint reference](./endpointFunctionList.md) +- Gate REST API documentation: [Gate API v4](https://www.gate.com/docs/developers/apiv4/en/) +- Gate Spot WebSocket documentation: [Spot WebSocket API](https://www.gate.com/docs/developers/apiv4/ws/) +- Gate Futures WebSocket documentation: [Futures WebSocket API](https://www.gate.com/docs/developers/futures/ws/) +- Trading-system terms: [Siebly glossary](https://siebly.io/reference/glossary) +- More JavaScript and TypeScript SDKs: [Siebly.io](https://siebly.io) - +## Why use `gateio-api`? -## Connect to Global and regional REST API hosts +The JavaScript SDK handles all the complexities of integrating with Gate's REST APIs & WebSockets, so you can focus on your system without wasting excessive time on plumbing. -Use the API host associated with the Gate account and product you are integrating. Credentials and product availability are not interchangeable across account regions. +Private Gate REST API requests require a timestamp and HMAC-SHA512 signature. Private WebSocket subscriptions require authentication, and each product family has its own WebSocket connection. A Spot subscription cannot be sent through a USDT perpetual Futures connection. -| Environment or account | REST API base URL | Official reference | -| ------------------------ | --------------------------------------- | -------------------------------------------------------------------- | -| Global live | `https://api.gateio.ws/api/v4` | [Global Gate API v4](https://www.gate.com/docs/developers/apiv4/en/) | -| Global TestNet | `https://api-testnet.gateapi.io/api/v4` | [Global Gate API v4](https://www.gate.com/docs/developers/apiv4/en/) | -| Futures live alternative | `https://fx-api.gateio.ws/api/v4` | [Global Gate API v4](https://www.gate.com/docs/developers/apiv4/en/) | -| Gate US live | `https://api.gate.us/api/v4` | [Gate US API v4](https://us.gate.com/en-us/docs/developers/apiv4/) | -| Gate EU live | `https://api.gateeu.com/api/v4` | [Gate EU API v4](https://eu.gate.com/docs/developers/apiv4/en/) | +`gateio-api` handles those mechanics and gives each job a focused client: -Global live is the SDK default. Set `baseUrl` for another supported account host: +| Client | Use it for | +| -------------------- | ------------------------------------------------------------ | +| `RestClient` | Public and private REST API calls across Gate product groups | +| `WebsocketClient` | Public and private WebSocket subscriptions | +| `WebsocketAPIClient` | Promise-based Spot and Futures order commands over WebSocket | -```javascript -import { RestClient } from 'gateio-api'; +`WebsocketClient` also handles heartbeats, reconnects, cached subscriptions, and resubscription. `WebsocketAPIClient` adds login, request IDs, response matching, and promise resolution. -const gateUs = new RestClient({ - apiKey: process.env.GATE_API_KEY, - apiSecret: process.env.GATE_API_SECRET, - baseUrl: 'https://api.gate.us/api/v4', -}); +## Install the SDK -const gateEu = new RestClient({ - apiKey: process.env.GATE_API_KEY, - apiSecret: process.env.GATE_API_SECRET, - baseUrl: 'https://api.gateeu.com/api/v4', -}); +```bash +npm install gateio-api ``` -Use only the client that matches the account. Regional APIs can expose different products and endpoint sets. Check the regional documentation before calling a method, and use the region's own credentials. - -This guide does not assign regional WebSocket URLs. Use a regional WebSocket host only when the official documentation for that account region provides it. - - - -## Use a proxy with the REST API and WebSockets - -`gateio-api` accepts standard Node.js agents. Configure the agent in both places when all Gate traffic must use the proxy: - -- Pass `httpsAgent` in the second `RestClient` argument and set `proxy: false`. -- Pass the same agent as `wsOptions.agent` to `WebsocketClient` or `WebsocketAPIClient`. - -See [Using proxies with Siebly SDKs](https://siebly.io/blog/using-proxy-with-siebly-sdks) for deployment and troubleshooting guidance. - -### HTTP and HTTPS proxy - -Install the proxy agent: +The package includes CommonJS, ESM, and TypeScript declarations. Every example below is plain JavaScript using ESM imports. -```bash -npm install https-proxy-agent -``` +## Create Gate API keys -Set `GATE_PROXY_URL` to an `http://` or `https://` proxy URL. The example does not print the value because it may contain credentials. +Public market data does not require credentials. Private REST API calls, private streams, and WebSocket API commands require an API key and secret. -```javascript -import { HttpsProxyAgent } from 'https-proxy-agent'; -import { RestClient, WebsocketClient, WS_KEY_MAP } from 'gateio-api'; +Create and manage keys from the [Gate API key page](https://www.gate.com/myaccount/api_key_manage). Start with the least access your application needs: -async function main() { - const proxyUrl = process.env.GATE_PROXY_URL; +- Use a read-only key while building account views and recovery code. +- Enable Spot read-write access only for Spot order workflows. +- Enable perpetual-contract read-write access only for Futures order workflows. +- Add an IP whitelist when your outbound IP is stable. +- Keep live and TestNet credentials separate. +- Allow a few minutes for API key and permission changes to take effect. +- Do not enable withdrawal permission for anything in this tutorial. - if (!proxyUrl) { - console.error('Set GATE_PROXY_URL.'); - return; - } +Set these live credential names in your shell, secret manager, or deployment environment: - const agent = new HttpsProxyAgent(proxyUrl); +- `GATE_API_KEY` +- `GATE_API_SECRET` - const rest = new RestClient( - {}, - { - httpsAgent: agent, - proxy: false, - }, - ); +Use separate names for TestNet: - const ws = new WebsocketClient({ - wsOptions: { - agent, - }, - }); +- `GATE_TESTNET_API_KEY` +- `GATE_TESTNET_API_SECRET` +- `GATE_PLACE_TESTNET_ORDER=true` - ws.on('open', ({ wsKey }) => { - console.log('WebSocket connected through proxy:', wsKey); - }); +The order examples check `GATE_PLACE_TESTNET_ORDER` before sending an order. Do not log API keys or secrets, and never put them in browser code. - ws.on('response', (response) => { - console.log('Subscription response:', response); - }); +## Gate products and request vocabulary - ws.on('update', (update) => { - console.log('Ticker update through proxy:', update); - ws.closeAll(); - }); +Several short fields determine where a request goes and what its values mean: - ws.on('exception', () => { - console.error('WebSocket proxy connection failed.'); - }); +| Field | Example | Meaning | +| --------------- | ------------------------------ | -------------------------------------------------------------------------------------------------- | +| `currency_pair` | `BTC_USDT` | A Spot or margin market | +| `account` | `spot` | The account used by a Spot order or query | +| `settle` | `usdt` | The settlement currency for a Futures or Delivery REST API request | +| `contract` | `BTC_USDT` | The exact Futures, Delivery, or Options contract | +| `size` | `1` or `-1` | Futures contract count, not a BTC or USDT amount | +| `text` | `t-my-order-123` | Your [custom order ID](https://siebly.io/reference/glossary#custom-order-id) | +| `wsKey` | `WS_KEY_MAP.perpFuturesUSDTV4` | The [WebSocket key](https://siebly.io/reference/glossary#ws-key) that selects a product connection | - try { - const time = await rest.getServerTime(); - console.log('Server time through proxy:', time.server_time); - } catch { - console.error('REST API proxy request failed.'); - } +For Spot orders, `account` can be `spot`, `margin`, `cross_margin`, or `unified`, depending on the account and endpoint. This tutorial uses `spot`. - try { - ws.subscribe( - { - topic: 'spot.tickers', - payload: ['BTC_USDT'], - }, - WS_KEY_MAP.spotV4, - ); - } catch { - console.error('WebSocket proxy subscription failed.'); - } +For USDT perpetual Futures, use `settle: 'usdt'` and a contract such as `BTC_USDT`. The `size` is a number of contracts. In one-way mode, a positive size buys and a negative size sells. The contract's `quanto_multiplier` tells you how much underlying currency one contract represents. - process.once('SIGINT', () => { - ws.closeAll(); - }); -} +Keep these routing values visible in code and logs. They are part of the request, not interchangeable labels. -main(); -``` + -For an authenticated HTTP or HTTPS proxy, include the username and password in `GATE_PROXY_URL`. Percent-encode reserved characters in each credential component. +## Start building: first calls and streams -### SOCKS5 proxy +Run each example on its own. Start with public data, then add authenticated account state and live streams. -Install the SOCKS agent: +### 1. Make public REST API calls -```bash -npm install socks-proxy-agent -``` +Public calls need no API key. Gate response bodies are endpoint-specific: server time and order books are objects, tickers are arrays, and candles are tuple arrays. -Set `GATE_SOCKS_PROXY_URL` to a `socks5://` URL: + ```javascript -import { SocksProxyAgent } from 'socks-proxy-agent'; -import { RestClient, WebsocketClient, WS_KEY_MAP } from 'gateio-api'; +import { RestClient } from 'gateio-api'; -async function main() { - const proxyUrl = process.env.GATE_SOCKS_PROXY_URL; +const client = new RestClient(); - if (!proxyUrl) { - console.error('Set GATE_SOCKS_PROXY_URL.'); - return; +async function main() { + try { + const time = await client.getServerTime(); + console.log('Server time:', time.server_time); + } catch (error) { + console.error('Server time request failed:', error); } - const agent = new SocksProxyAgent(proxyUrl); - - const rest = new RestClient( - {}, - { - httpsAgent: agent, - proxy: false, - }, - ); - - const ws = new WebsocketClient({ - wsOptions: { - agent, - }, - }); - - ws.on('open', ({ wsKey }) => { - console.log('WebSocket connected through SOCKS5:', wsKey); - }); - - ws.on('response', (response) => { - console.log('Subscription response:', response); - }); - - ws.on('update', (update) => { - console.log('Ticker update through SOCKS5:', update); - ws.closeAll(); - }); - - ws.on('exception', () => { - console.error('SOCKS5 WebSocket connection failed.'); - }); + try { + const pair = await client.getSpotCurrencyPair({ + currency_pair: 'BTC_USDT', + }); + console.log('BTC_USDT metadata:', pair); + } catch (error) { + console.error('Currency pair request failed:', error); + } try { - const time = await rest.getServerTime(); - console.log('Server time through SOCKS5:', time.server_time); - } catch { - console.error('SOCKS5 REST API request failed.'); + const tickers = await client.getSpotTicker({ + currency_pair: 'BTC_USDT', + }); + console.log('BTC_USDT ticker:', tickers[0]); + } catch (error) { + console.error('Ticker request failed:', error); } try { - ws.subscribe( - { - topic: 'spot.tickers', - payload: ['BTC_USDT'], - }, - WS_KEY_MAP.spotV4, - ); - } catch { - console.error('SOCKS5 WebSocket subscription failed.'); + const orderBook = await client.getSpotOrderBook({ + currency_pair: 'BTC_USDT', + limit: 5, + }); + console.log('Best bid:', orderBook.bids[0]); + console.log('Best ask:', orderBook.asks[0]); + } catch (error) { + console.error('Order book request failed:', error); } - process.once('SIGINT', () => { - ws.closeAll(); - }); + try { + const candles = await client.getSpotCandles({ + currency_pair: 'BTC_USDT', + interval: '1h', + limit: 10, + }); + console.log('Latest candle:', candles[0]); + } catch (error) { + console.error('Candles request failed:', error); + } } main(); ``` -### Private REST API, stream, and WebSocket API traffic - -Use the same agent and credentials for private REST API calls, private subscriptions, and WebSocket API connections: - -```javascript -import { HttpsProxyAgent } from 'https-proxy-agent'; -import { - RestClient, - WebsocketAPIClient, - WebsocketClient, - WS_KEY_MAP, -} from 'gateio-api'; - -async function main() { - const proxyUrl = process.env.GATE_PROXY_URL; +The SDK returns the endpoint body directly. There is no shared result wrapper to unwrap. - if (!proxyUrl) { - console.error('Set GATE_PROXY_URL.'); - return; - } +Each Spot candle is a tuple: - const agent = new HttpsProxyAgent(proxyUrl); +```text +[ + timestamp, + quoteVolume, + close, + high, + low, + open, + baseVolume, + closed +] +``` - const rest = new RestClient( - { - apiKey: process.env.GATE_API_KEY, - apiSecret: process.env.GATE_API_SECRET, - }, - { - httpsAgent: agent, - proxy: false, - }, - ); +Use the [SDK endpoint map](./endpointFunctionList.md) or the official endpoint documentation when reading tuple positions and endpoint-specific objects. - const streams = new WebsocketClient({ - apiKey: process.env.GATE_API_KEY, - apiSecret: process.env.GATE_API_SECRET, - wsOptions: { - agent, - }, - }); +### 2. Make private REST API calls - const wsApi = new WebsocketAPIClient({ - apiKey: process.env.GATE_API_KEY, - apiSecret: process.env.GATE_API_SECRET, - wsOptions: { - agent, - }, - }); +Private calls use the same `RestClient`. Add your key and secret, then call private methods normally. The SDK adds the required timestamp and signature. - streams.on('authenticated', ({ wsKey }) => { - console.log('Private stream authenticated:', wsKey); - }); + - streams.on('update', (update) => { - console.log('Private update through proxy:', update); - }); +```javascript +import { RestClient } from 'gateio-api'; - streams.on('exception', () => { - console.error('Private stream proxy connection failed.'); - }); +const client = new RestClient({ + apiKey: process.env.GATE_API_KEY, + apiSecret: process.env.GATE_API_SECRET, +}); +async function main() { try { - const balances = await rest.getSpotAccounts(); - console.log('Spot balances through proxy:', balances); - } catch { - console.error('Private REST API proxy request failed.'); + const balances = await client.getSpotAccounts(); + console.log('Spot balances:', balances); + } catch (error) { + console.error('Balance request failed:', error); } try { - streams.subscribe( - { - topic: 'spot.balances', - }, - WS_KEY_MAP.spotV4, - ); - } catch { - console.error('Private stream subscription failed.'); + const openOrders = await client.getSpotOpenOrders({ + account: 'spot', + }); + console.log('Open Spot orders grouped by pair:', openOrders); + } catch (error) { + console.error('Open-order request failed:', error); } try { - await wsApi.getWSClient().connectWSAPI(WS_KEY_MAP.spotV4); - console.log('WebSocket API authenticated through proxy.'); - } catch { - console.error('WebSocket API proxy connection failed.'); + const recentOrders = await client.getSpotOrders({ + currency_pair: 'BTC_USDT', + status: 'finished', + account: 'spot', + limit: 20, + }); + console.log('Recent BTC_USDT orders:', recentOrders); + } catch (error) { + console.error('Order-history request failed:', error); } - process.once('SIGINT', () => { - streams.closeAll(); - wsApi.getWSClient().closeAll(); - }); + try { + const trades = await client.getSpotTradingHistory({ + currency_pair: 'BTC_USDT', + account: 'spot', + limit: 20, + }); + console.log('Recent BTC_USDT trades:', trades); + } catch (error) { + console.error('Trade-history request failed:', error); + } } main(); ``` -To combine a proxy with TestNet or a regional API, keep `baseUrl` or `wsUrl` in the first client argument and the agent in the same positions shown above. +`getSpotAccounts()`, `getSpotOrders()`, and `getSpotTradingHistory()` return arrays. `getSpotOpenOrders()` returns an array whose entries group open orders by currency pair. Other private endpoints return objects or different array shapes, so check the [SDK endpoint map](./endpointFunctionList.md) instead of assuming a common format. -The proxy's egress IP is the address Gate sees. Add that address to the API key whitelist when whitelisting is enabled. Use a stable proxy endpoint, monitor its latency, and never use a proxy to bypass account or regional restrictions. +### 3. Subscribe to public WebSocket streams -A proxy changes the network path, not request signing, account eligibility, or regional product access. Test public REST API and WebSocket traffic first. Treat HTTP 407 responses, TLS failures, and repeated reconnects as network faults. The SDK does not rotate proxy endpoints. +Every subscription includes both a topic and an explicit `wsKey`. The key tells the SDK which Gate connection should carry the subscription. - + -## Production checklist +```javascript +import { WebsocketClient, WS_KEY_MAP } from 'gateio-api'; -### Keep request time accurate +const ws = new WebsocketClient(); -Gate private requests and WebSocket authentication depend on timestamp checks. The gap between request time and server time must not exceed 60 seconds. +ws.on('response', (response) => { + console.log('Subscription response:', response); +}); + +ws.on('update', (update) => { + console.log('WebSocket update:', update); +}); + +ws.on('reconnect', ({ wsKey }) => { + console.log('Reconnecting:', wsKey); +}); + +ws.on('reconnected', (event) => { + console.log('Reconnected:', event.wsKey); +}); + +ws.on('exception', (error) => { + console.error('WebSocket exception:', error); +}); + +try { + ws.subscribe( + { + topic: 'spot.tickers', + payload: ['BTC_USDT'], + }, + WS_KEY_MAP.spotV4, + ); +} catch (error) { + console.error('Spot subscription failed:', error); +} + +try { + ws.subscribe( + { + topic: 'futures.tickers', + payload: ['BTC_USDT'], + }, + WS_KEY_MAP.perpFuturesUSDTV4, + ); +} catch (error) { + console.error('Futures subscription failed:', error); +} + +process.once('SIGINT', () => { + ws.closeAll(); +}); +``` + +Gate sends Spot ticker data as an object in `result`, while a Futures ticker update can contain an array. The SDK adds `wsKey` to each update so one event handler can identify the source connection. + +The main WebSocket events are: + +| Event | Meaning | +| --------------- | ------------------------------------------------------------- | +| `open` | A connection opened for the reported `wsKey` | +| `response` | Subscription, unsubscription, or request response | +| `update` | Market or account data | +| `authenticated` | A private connection authenticated successfully | +| `reconnect` | The connection dropped and a reconnect is starting | +| `reconnected` | The connection is open and cached subscriptions were restored | +| `close` | A connection closed for the reported `wsKey` | +| `exception` | The client or connection reported an error | + +A successful `response` event confirms the [subscription acknowledgement](https://siebly.io/reference/glossary#subscription-acknowledgement). It does not mean that a market update has arrived yet. -Synchronize the host clock with NTP. Use `getServerTime()` for diagnosis, but fix the system clock rather than adding a permanent application offset for a drifting machine. +### 4. Subscribe to private Spot streams -### Respect rate limits +Private streams use the same client with credentials. This example follows Spot balances, orders, and user trades. -Rate limits vary by product and endpoint. Read the current [Gate API rate-limit documentation](https://www.gate.com/docs/developers/apiv4/en/#frequency-limit-rule) and monitor rejection labels. + -Retry temporary network failures and rate-limit responses with bounded exponential backoff and jitter. Do not blindly retry an order command after an ambiguous timeout. First reconcile by the order's `text` value or query current order state. +```javascript +import { WebsocketClient, WS_KEY_MAP } from 'gateio-api'; -### Use custom order IDs +const ws = new WebsocketClient({ + apiKey: process.env.GATE_API_KEY, + apiSecret: process.env.GATE_API_SECRET, +}); -Set a unique `text` value beginning with `t-` on each application-owned order. Store it with your local request record. This gives retries, restarts, stream updates, and REST API recovery a common identifier. +ws.on('authenticated', ({ wsKey }) => { + console.log('Authenticated:', wsKey); +}); -### Apply product metadata +ws.on('response', (response) => { + console.log('Subscription response:', response); +}); -Before placing an order: +ws.on('update', (update) => { + console.log('Private Spot update:', update); +}); -- Check that the pair or contract is tradable. -- Apply minimum and maximum amounts. -- Round prices and quantities to the permitted increments. -- Treat Futures `size` as a contract count. -- Read `quanto_multiplier` before translating contract size into underlying exposure. -- Keep one-way, dual-side, and split position modes explicit. +ws.on('reconnected', (event) => { + console.log('Reconnected:', event.wsKey); +}); -Refresh metadata regularly and when Gate rejects an order for a precision or size rule. +ws.on('exception', (error) => { + console.error('WebSocket exception:', error); +}); -### Confirm final state +try { + ws.subscribe( + { + topic: 'spot.balances', + }, + WS_KEY_MAP.spotV4, + ); +} catch (error) { + console.error('Balance subscription failed:', error); +} -A REST API response or WebSocket API response can arrive before later fills, cancellations, or amendments. Record the command response, then confirm final state through private streams or a REST API query. +try { + ws.subscribe( + { + topic: 'spot.orders', + payload: ['BTC_USDT'], + }, + WS_KEY_MAP.spotV4, + ); +} catch (error) { + console.error('Order subscription failed:', error); +} -After a reconnect, restore the affected [exchange state](https://siebly.io/reference/exchange-state) before resuming state-dependent actions. +try { + ws.subscribe( + { + topic: 'spot.usertrades', + payload: ['BTC_USDT'], + }, + WS_KEY_MAP.spotV4, + ); +} catch (error) { + console.error('Trade subscription failed:', error); +} -### Scope credentials and network access +process.once('SIGINT', () => { + ws.closeAll(); +}); +``` -- Use separate keys for live and TestNet. -- Grant only the product permissions the process needs. -- Use read-only keys for monitoring services. -- Do not grant withdrawal permission. -- Add IP whitelists when egress addresses are stable. -- Keep secrets in a server-side secret manager or deployment environment. -- Monitor proxy availability and egress IP changes. +Use the `authenticated` event as a connection-level signal. Use private updates as [private stream confirmation](https://siebly.io/reference/glossary#private-stream-confirmation) of account and order changes. -### Shut down connections +Other private Spot topics include `spot.margin_balances` and `spot.cross_balances`. Check each channel's payload rules before subscribing. -Call `closeAll()` on each WebSocket client when the process is ending. An unsubscribe request is unnecessary when the connection is about to close. +### 5. Subscribe to private Futures streams -## FAQ +Futures private channels use your Gate user ID. Contract-specific channels also include the contract. Retrieve the user ID once from the REST API, then use the payload required by each channel. -### Does `gateio-api` work with plain JavaScript? +```javascript +import { RestClient, WebsocketClient, WS_KEY_MAP } from 'gateio-api'; -Yes. Every example in this guide is plain JavaScript. The examples use ESM imports, so save them as `.mjs` files or set `"type": "module"` in `package.json`. The package also includes a CommonJS build and TypeScript declarations. +const rest = new RestClient({ + apiKey: process.env.GATE_API_KEY, + apiSecret: process.env.GATE_API_SECRET, +}); -### Which client should I use? +const ws = new WebsocketClient({ + apiKey: process.env.GATE_API_KEY, + apiSecret: process.env.GATE_API_SECRET, +}); -Use `RestClient` for public and private REST API calls, `WebsocketClient` for ongoing subscriptions, and `WebsocketAPIClient` for awaitable Spot and Futures commands over WebSocket. +ws.on('authenticated', ({ wsKey }) => { + console.log('Authenticated:', wsKey); +}); -### Do public Gate API calls need credentials? +ws.on('response', (response) => { + console.log('Subscription response:', response); +}); -No. Public market data works without an API key. Account data, private streams, and order commands require credentials with the relevant product permission. +ws.on('update', (update) => { + console.log('Private Futures update:', update); +}); -### Why did a REST API call return an object when another returned an array? +ws.on('exception', (error) => { + console.error('WebSocket exception:', error); +}); -Gate response bodies are endpoint-specific. The SDK returns the endpoint body directly. Check the [endpoint map](./endpointFunctionList.md) before reading the result. +async function main() { + let account; -### Why does `getSpotTicker()` return an array for one pair? + try { + account = await rest.getAccountDetail(); + console.log('Gate user ID:', account.user_id); + } catch (error) { + console.error('Account detail request failed:', error); + return; + } -That is Gate's endpoint response shape. Read the first entry after checking that the array is not empty. + const userId = String(account.user_id); + const payload = [userId, 'BTC_USDT']; + const wsKey = WS_KEY_MAP.perpFuturesUSDTV4; -### How are Spot candles structured? + try { + ws.subscribe( + { + topic: 'futures.orders', + payload, + }, + wsKey, + ); + } catch (error) { + console.error('Order subscription failed:', error); + } -Spot candles are tuple arrays containing timestamp, quote volume, close, high, low, open, base volume, and a closed-window flag in that order. + try { + ws.subscribe( + { + topic: 'futures.usertrades', + payload, + }, + wsKey, + ); + } catch (error) { + console.error('Trade subscription failed:', error); + } -### Why does Gate use `BTC_USDT`? + try { + ws.subscribe( + { + topic: 'futures.balances', + payload: [userId], + }, + wsKey, + ); + } catch (error) { + console.error('Balance subscription failed:', error); + } -Gate uses underscore-separated currency pairs and contract names. Pass the exact identifier returned by the relevant market or contract metadata endpoint. + try { + ws.subscribe( + { + topic: 'futures.positions', + payload, + }, + wsKey, + ); + } catch (error) { + console.error('Position subscription failed:', error); + } +} -### What do `account` and `settle` change? +process.once('SIGINT', () => { + ws.closeAll(); +}); -`account` selects the account used by a Spot order or query. `settle` selects the settlement currency and REST API path for Futures or Delivery requests. +main(); +``` -### What is the `text` order field? +Keep the `wsKey` aligned with the settlement currency and product. USDT perpetual Futures use `WS_KEY_MAP.perpFuturesUSDTV4`; BTC perpetual Futures use `WS_KEY_MAP.perpFuturesBTCV4`. -`text` is Gate's custom order ID field. Use a unique value beginning with `t-` to reconcile requests, stream updates, and order queries. +Gate also provides private Futures channels such as `futures.autoorders`. Use the payload documented for that specific channel. -### Why am I not receiving WebSocket updates? +### 6. Place and cancel a Spot order in TestNet -Check the topic payload, `wsKey`, API host, credentials, and permissions. Then inspect `response`, `authenticated`, and `exception` events. A successful subscription response confirms registration, but an update only arrives when the subscribed data changes. +Gate TestNet uses separate credentials and API hosts. This example: -### Which `WS_KEY_MAP` value should I use? +1. Checks the explicit order opt-in. +2. Loads current `BTC_USDT` trading rules and the order book. +3. Calculates an amount that meets the pair's base and quote minimums. +4. Places a post-only limit buy at the current best bid. +5. Queries the order and cancels it if it remains open. -Choose the key for the exact product connection. For example, Spot uses `spotV4` and USDT perpetual Futures uses `perpFuturesUSDTV4`. +The order uses `time_in_force: 'poc'`, Gate's post-only setting. A fast market can move before the request arrives, in which case Gate can reject or finish the order instead of leaving it on the book. -### Why do private Futures topics use my Gate user ID? + -It is part of the payload required by those channels. Retrieve it with `getAccountDetail()` instead of hardcoding it. +```javascript +import { RestClient } from 'gateio-api'; -### What is the difference between a stream and the WebSocket API? +const client = new RestClient({ + apiKey: process.env.GATE_TESTNET_API_KEY, + apiSecret: process.env.GATE_TESTNET_API_SECRET, + baseUrl: 'https://api-testnet.gateapi.io/api/v4', +}); -Streams push subscribed market or account updates. The WebSocket API sends a command and resolves a promise with Gate's matching response. +async function main() { + if (process.env.GATE_PLACE_TESTNET_ORDER !== 'true') { + console.error('Set GATE_PLACE_TESTNET_ORDER=true to run this example.'); + return; + } -### Does a successful WebSocket API response mean the order filled? + if ( + !process.env.GATE_TESTNET_API_KEY || + !process.env.GATE_TESTNET_API_SECRET + ) { + console.error('Set GATE_TESTNET_API_KEY and GATE_TESTNET_API_SECRET.'); + return; + } -No. It confirms the command result. Confirm later order and fill state through private streams or a REST API query. + let pair; -### Why was a post-only order rejected or immediately finished? + try { + pair = await client.getSpotCurrencyPair({ + currency_pair: 'BTC_USDT', + }); + } catch (error) { + console.error('Currency pair request failed:', error); + return; + } -The best bid or ask can move between the order-book request and order placement. Gate will not let a post-only order take liquidity. Read the returned status and `finish_as`, then decide whether to refresh the book and submit a new order with a new `text`. + let orderBook; -### Why does a Futures order size look too small? + try { + orderBook = await client.getSpotOrderBook({ + currency_pair: 'BTC_USDT', + limit: 5, + }); + } catch (error) { + console.error('Order book request failed:', error); + return; + } -Futures `size` is the number of contracts. Use `quanto_multiplier` to find the underlying amount represented by one contract. + if (pair.trade_status !== 'tradable' && pair.trade_status !== 'buyable') { + console.error('BTC_USDT is not currently buyable.'); + return; + } -### Can live credentials be used in TestNet? + const price = orderBook.bids[0]?.[0]; + const amountPrecision = pair.amount_precision; + const minBase = Number(pair.min_base_amount); + const minQuote = Number(pair.min_quote_amount); + const priceNumber = Number(price); -No. TestNet and live trading use separate API keys and balances. Use the current TestNet `baseUrl` or `wsUrl` with TestNet credentials. + if ( + !price || + amountPrecision === undefined || + !Number.isFinite(minBase) || + !Number.isFinite(minQuote) || + !Number.isFinite(priceNumber) || + priceNumber <= 0 + ) { + console.error('Required market metadata is unavailable.'); + return; + } -### Can I use Gate US or Gate EU with the SDK? + const amountStep = 10 ** -amountPrecision; + const minimumAmount = Math.max(minBase, minQuote / priceNumber); + const amountNumber = (Math.ceil(minimumAmount / amountStep) + 1) * amountStep; + const amount = amountNumber.toFixed(amountPrecision); -Yes, for endpoints available to that account region. Set the documented regional `baseUrl`, use credentials from the same region, and check its official API documentation for product coverage. + if (amountNumber < minBase || amountNumber * priceNumber < minQuote) { + console.error('Could not derive a valid TestNet order.'); + return; + } -### Can REST API and WebSocket traffic use the same proxy? + const maxBase = Number(pair.max_base_amount); + const maxQuote = Number(pair.max_quote_amount); -Yes. Create one compatible agent, pass it as `httpsAgent` to `RestClient`, and pass it as `wsOptions.agent` to the WebSocket clients. + if ( + (Number.isFinite(maxBase) && amountNumber > maxBase) || + (Number.isFinite(maxQuote) && amountNumber * priceNumber > maxQuote) + ) { + console.error('Derived amount exceeds the pair limits.'); + return; + } -### Does a proxy change signing or account eligibility? + const text = `t-siebly${Date.now().toString().slice(-12)}`; + let placedOrder; -No. The SDK signs the same requests through the proxy. The Gate account, API host, product permissions, and regional availability still apply. + try { + placedOrder = await client.submitSpotOrder({ + currency_pair: 'BTC_USDT', + account: 'spot', + side: 'buy', + type: 'limit', + amount, + price, + time_in_force: 'poc', + text, + }); + console.log('Placed Spot order:', placedOrder); + } catch (error) { + console.error('Spot order placement failed:', error); + return; + } -### What causes `INVALID_SIGNATURE` or `REQUEST_EXPIRED`? + if (!placedOrder.id) { + console.error('Gate did not return an order ID.'); + return; + } -Common causes are a drifting system clock, the wrong API secret, credentials from another environment, or an API request reaching the wrong host. Verify the clock, credential source, and API host without logging the secret. + let currentOrder; -## Next steps + try { + currentOrder = await client.getSpotOrder({ + order_id: placedOrder.id, + currency_pair: 'BTC_USDT', + account: 'spot', + }); + console.log('Current Spot order:', currentOrder); + } catch (error) { + console.error('Spot order query failed:', error); + } -- Browse the [Gate SDK examples](https://siebly.io/examples/Gate). -- Find methods in the [complete endpoint map](./endpointFunctionList.md). -- Review the [Gate SDK page](https://siebly.io/sdk/gate/javascript). -- Install or update [`gateio-api` from npm](https://www.npmjs.com/package/gateio-api). -- Browse the [`gateio-api` source repository](https://github.com/sieblyio/gateio-api). -- Read the official [Gate REST API documentation](https://www.gate.com/docs/developers/apiv4/en/). -- Read the official [Gate Spot WebSocket documentation](https://www.gate.com/docs/developers/apiv4/ws/). -- Read the official [Gate Futures WebSocket documentation](https://www.gate.com/docs/developers/futures/ws/). -- Review [Exchange State](https://siebly.io/reference/exchange-state) before building private state management. -- Use [Runtime Workflows](https://siebly.io/reference/runtime-workflows) when designing startup, reconnect, and reconciliation behavior. -- Open the [Siebly glossary](https://siebly.io/reference/glossary) for order, stream, and recovery terms. -- Report SDK issues in the [`gateio-api` GitHub repository](https://github.com/sieblyio/gateio-api/issues). + if (currentOrder && currentOrder.status !== 'open') { + console.log('Order is no longer open:', currentOrder.status); + return; + } -================ -File: src/types/request/earn.ts -================ -/**========================================================================================================================== - * EARN - * ========================================================================================================================== - */ -⋮---- -/** GET /earn/dual/investment_plan */ -export interface GetDualInvestmentPlansReq { - plan_id?: number | string; - coin?: string; - type?: string; - quote_currency?: string; - /** `apy` | `short-period` | `multiple` */ - sort?: string; - page?: number; - page_size?: number; -} -⋮---- -/** `apy` | `short-period` | `multiple` */ -⋮---- -/** GET /earn/dual/orders */ -export interface GetDualInvestmentOrdersReq { - from?: number; - to?: number; - type?: string; - status?: string; - coin?: string; - page?: number; - limit?: number; -} -⋮---- -/** GET /earn/dual/order-refund-preview */ -export interface GetDualOrderRefundPreviewReq { - order_id: string; -} -⋮---- -/** POST /earn/dual/order-refund */ -export interface SubmitDualOrderRefundParams { - order_id: string; - /** From order-refund-preview */ - req_id: string; -} -⋮---- -/** From order-refund-preview */ -⋮---- -/** POST /earn/dual/modify-order-reinvest */ -export interface UpdateDualOrderReinvestParams { - order_id?: number; - /** 0 off, 1 on */ - status?: number; - /** Effective duration in seconds; default 86400 */ - effective_time_duration?: number; -} -⋮---- -/** 0 off, 1 on */ -⋮---- -/** Effective duration in seconds; default 86400 */ -⋮---- -/** GET /earn/dual/project-recommend */ -export interface GetDualProjectRecommendReq { - mode?: string; - coin?: string; - type?: string; - /** Comma-separated project IDs to exclude */ - history_pids?: string; -} -⋮---- -/** Comma-separated project IDs to exclude */ -⋮---- -/** Request params for POST /earn/dual/orders */ -export interface PlaceDualInvestmentOrderParams { - plan_id: string; - /** Subscription amount. Mutually exclusive with copies. */ - amount: string; - /** Units. Mutually exclusive with amount. */ - copies?: string; - /** Custom order info, must start with t- */ - text?: string; -} -⋮---- -/** Subscription amount. Mutually exclusive with copies. */ -⋮---- -/** Units. Mutually exclusive with amount. */ -⋮---- -/** Custom order info, must start with t- */ -⋮---- -/**========================================================================================================================== - * EARN FIXED-TERM - * ========================================================================================================================== - */ -⋮---- -export interface GetEarnFixedTermProductsReq { - asset?: string; - type?: number; // 1 regular, 2 VIP - page: number; - limit: number; -} -⋮---- -type?: number; // 1 regular, 2 VIP -⋮---- -export interface GetEarnFixedTermProductsByAssetReq { - /** Product type: "" or 1 regular, 2 VIP, 0 all */ - type?: string; -} -⋮---- -/** Product type: "" or 1 regular, 2 VIP, 0 all */ -⋮---- -export interface CreateEarnFixedTermLendReq { - product_id: number; - amount: string; - year_rate?: string; - reinvest_status?: number; // 0 off, 1 on - redeem_account_type?: number; // 1 spot - financial_rate_id?: number; // interest boost coupon id, 0 = none - sub_business?: number; -} -⋮---- -reinvest_status?: number; // 0 off, 1 on -redeem_account_type?: number; // 1 spot -financial_rate_id?: number; // interest boost coupon id, 0 = none -⋮---- -export interface GetEarnFixedTermLendsReq { - product_id?: number; - order_id?: number; - asset?: string; - order_type: '1' | '2'; // 1 current, 2 historical - page: number; - limit: number; - sub_business?: number; - business_filter?: string; -} -⋮---- -order_type: '1' | '2'; // 1 current, 2 historical -⋮---- -export interface EarnFixedTermPreRedeemReq { - order_id: string; -} -⋮---- -export interface GetEarnFixedTermHistoryReq { - product_id?: number; - order_id?: string; - asset?: string; - type: '1' | '2' | '3' | '4'; // 1 subscribe, 2 redeem, 3 interest, 4 bonus - page: number; - limit: number; - start_at?: number; - end_at?: number; - sub_business?: number; - business_filter?: string; + try { + const cancelledOrder = await client.cancelSpotOrder({ + order_id: placedOrder.id, + currency_pair: 'BTC_USDT', + account: 'spot', + }); + console.log('Cancelled Spot order:', cancelledOrder); + } catch (error) { + console.error('Spot order cancellation failed:', error); + } } -⋮---- -type: '1' | '2' | '3' | '4'; // 1 subscribe, 2 redeem, 3 interest, 4 bonus -================ -File: src/types/request/otc.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 -} -⋮---- -order_id: string; // Order ID -⋮---- -export interface OTCBankIdReq { - bank_id: string; -} -⋮---- -export interface GetOTCBankSupplementChecklistReq { - bank_id: 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 SubmitOTCBankPersonalSupplementReq { - bank_id: string; - id_document_front: GateMultipartFile; - id_document_back: GateMultipartFile; - address_proof: GateMultipartFile; +main(); +``` + +The extra amount increment avoids falling just below the quote minimum after decimal rounding. Before using another pair, read its `amount_precision`, `precision`, minimums, maximums, and `trade_status`. + +### 7. Place and cancel a USDT perpetual order in TestNet + +A Futures `size` is a contract count. It is not an amount of BTC or USDT. This example reads the contract's minimum size and current price, and it only runs when the account is in one-way mode. It does not change account or position settings. + + + +```javascript +import { RestClient } from 'gateio-api'; + +const client = new RestClient({ + apiKey: process.env.GATE_TESTNET_API_KEY, + apiSecret: process.env.GATE_TESTNET_API_SECRET, + baseUrl: 'https://api-testnet.gateapi.io/api/v4', +}); + +async function main() { + if (process.env.GATE_PLACE_TESTNET_ORDER !== 'true') { + console.error('Set GATE_PLACE_TESTNET_ORDER=true to run this example.'); + return; + } + + if ( + !process.env.GATE_TESTNET_API_KEY || + !process.env.GATE_TESTNET_API_SECRET + ) { + console.error('Set GATE_TESTNET_API_KEY and GATE_TESTNET_API_SECRET.'); + return; + } + + let contract; + + try { + contract = await client.getFuturesContract({ + settle: 'usdt', + contract: 'BTC_USDT', + }); + } catch (error) { + console.error('Contract request failed:', error); + return; + } + + let orderBook; + + try { + orderBook = await client.getFuturesOrderBook({ + settle: 'usdt', + contract: 'BTC_USDT', + limit: 5, + }); + } catch (error) { + console.error('Order book request failed:', error); + return; + } + + let account; + + try { + account = await client.getFuturesAccount({ + settle: 'usdt', + }); + } catch (error) { + console.error('Futures account request failed:', error); + return; + } + + const oneWayMode = account.position_mode + ? account.position_mode === 'single' + : !account.in_dual_mode; + + if (!oneWayMode) { + console.error('This example requires one-way Futures position mode.'); + return; + } + + if (contract.status && contract.status !== 'trading') { + console.error('BTC_USDT Futures is not currently trading.'); + return; + } + + const price = orderBook.bids[0]?.p; + const size = Number(contract.order_size_min); + + if ( + !price || + !Number.isFinite(Number(price)) || + Number(price) <= 0 || + !Number.isFinite(size) || + size <= 0 || + (contract.enable_decimal === false && !Number.isInteger(size)) + ) { + console.error('Required contract metadata is unavailable.'); + return; + } + + console.log('One contract represents:', contract.quanto_multiplier, 'BTC'); + console.log('Price increment:', contract.order_price_round); + + const text = `t-siebly${Date.now().toString().slice(-12)}`; + let placedOrder; + + try { + placedOrder = await client.submitFuturesOrder({ + settle: 'usdt', + contract: 'BTC_USDT', + size, + price, + tif: 'poc', + text, + }); + console.log('Placed Futures order:', placedOrder); + } catch (error) { + console.error('Futures order placement failed:', error); + return; + } + + if (placedOrder.id === undefined) { + console.error('Gate did not return an order ID.'); + return; + } + + const orderId = String(placedOrder.id); + let currentOrder; + + try { + currentOrder = await client.getFuturesOrder({ + settle: 'usdt', + order_id: orderId, + }); + console.log('Current Futures order:', currentOrder); + } catch (error) { + console.error('Futures order query failed:', error); + } + + if (currentOrder && currentOrder.status !== 'open') { + console.log('Order is no longer open:', currentOrder.status); + return; + } + + try { + const cancelledOrder = await client.cancelFuturesOrder({ + settle: 'usdt', + order_id: orderId, + }); + console.log('Cancelled Futures order:', cancelledOrder); + } catch (error) { + console.error('Futures order cancellation failed:', error); + } } -⋮---- -export interface SubmitOTCBankEnterpriseSupplementReq { - bank_id: string; - certificate: GateMultipartFile; - share_holders: GateMultipartFile; - passport: GateMultipartFile; - share_holding_structure: GateMultipartFile; - uid?: string; - funds_statement?: GateMultipartFile; - additional?: GateMultipartFile; + +main(); +``` + +In one-way mode, a positive `size` buys and a negative `size` sells. Dual-side mode uses different position semantics, so handle it in account-specific code after reading the [official Gate API v4 documentation](https://www.gate.com/docs/developers/apiv4/en/). + +The contract metadata supplies the size and price rules: + +- `order_size_min`: minimum contract count +- `order_price_round`: permitted price increment +- `quanto_multiplier`: underlying amount represented by one contract +- `enable_decimal`: whether fractional contract sizes are supported + +Do not derive a Futures order size from Spot precision rules. + +### 8. Send a Spot order through the WebSocket API + +`WebsocketAPIClient` turns Gate WebSocket API commands into promises. It connects and authenticates automatically on the first private command, adds a request ID, matches the response, and resolves the promise. + +This TestNet example uses the REST API only to read current market rules and the order book. The order, query, and cancellation use the WebSocket API. + + + +```javascript +import { RestClient, WebsocketAPIClient, WS_KEY_MAP } from 'gateio-api'; + +const rest = new RestClient({ + baseUrl: 'https://api-testnet.gateapi.io/api/v4', +}); + +const wsApi = new WebsocketAPIClient({ + apiKey: process.env.GATE_TESTNET_API_KEY, + apiSecret: process.env.GATE_TESTNET_API_SECRET, + wsUrl: 'wss://ws-testnet.gate.com/v4/ws/spot', +}); + +async function main() { + if (process.env.GATE_PLACE_TESTNET_ORDER !== 'true') { + console.error('Set GATE_PLACE_TESTNET_ORDER=true to run this example.'); + return; + } + + if ( + !process.env.GATE_TESTNET_API_KEY || + !process.env.GATE_TESTNET_API_SECRET + ) { + console.error('Set GATE_TESTNET_API_KEY and GATE_TESTNET_API_SECRET.'); + return; + } + + let pair; + + try { + pair = await rest.getSpotCurrencyPair({ + currency_pair: 'BTC_USDT', + }); + } catch (error) { + console.error('Currency pair request failed:', error); + return; + } + + let orderBook; + + try { + orderBook = await rest.getSpotOrderBook({ + currency_pair: 'BTC_USDT', + limit: 5, + }); + } catch (error) { + console.error('Order book request failed:', error); + return; + } + + if (pair.trade_status !== 'tradable' && pair.trade_status !== 'buyable') { + console.error('BTC_USDT is not currently buyable.'); + return; + } + + const price = orderBook.bids[0]?.[0]; + const amountPrecision = pair.amount_precision; + const minBase = Number(pair.min_base_amount); + const minQuote = Number(pair.min_quote_amount); + const priceNumber = Number(price); + + if ( + !price || + amountPrecision === undefined || + !Number.isFinite(minBase) || + !Number.isFinite(minQuote) || + !Number.isFinite(priceNumber) || + priceNumber <= 0 + ) { + console.error('Required market metadata is unavailable.'); + return; + } + + const amountStep = 10 ** -amountPrecision; + const minimumAmount = Math.max(minBase, minQuote / priceNumber); + const amountNumber = (Math.ceil(minimumAmount / amountStep) + 1) * amountStep; + const amount = amountNumber.toFixed(amountPrecision); + + if (amountNumber < minBase || amountNumber * priceNumber < minQuote) { + console.error('Could not derive a valid TestNet order.'); + return; + } + + const maxBase = Number(pair.max_base_amount); + const maxQuote = Number(pair.max_quote_amount); + + if ( + (Number.isFinite(maxBase) && amountNumber > maxBase) || + (Number.isFinite(maxQuote) && amountNumber * priceNumber > maxQuote) + ) { + console.error('Derived amount exceeds the pair limits.'); + return; + } + + const text = `t-siebly${Date.now().toString().slice(-12)}`; + const wsKey = WS_KEY_MAP.spotV4; + + try { + let placedResponse; + + try { + placedResponse = await wsApi.submitNewSpotOrder( + { + currency_pair: 'BTC_USDT', + account: 'spot', + side: 'buy', + type: 'limit', + amount, + price, + time_in_force: 'poc', + text, + }, + wsKey, + ); + console.log('Command status:', placedResponse.header.status); + console.log('Placed Spot order:', placedResponse.data.result); + } catch (error) { + console.error('Spot WebSocket API placement failed:', error); + return; + } + + const orderId = placedResponse.data.result.id; + let statusResponse; + + try { + statusResponse = await wsApi.getSpotOrderStatus( + { + order_id: orderId, + currency_pair: 'BTC_USDT', + account: 'spot', + }, + wsKey, + ); + console.log('Current Spot order:', statusResponse.data.result); + } catch (error) { + console.error('Spot WebSocket API query failed:', error); + } + + if (statusResponse && statusResponse.data.result.status !== 'open') { + console.log( + 'Order is no longer open:', + statusResponse.data.result.status, + ); + return; + } + + try { + const cancelledResponse = await wsApi.cancelSpotOrder( + { + order_id: orderId, + currency_pair: 'BTC_USDT', + account: 'spot', + }, + wsKey, + ); + console.log('Cancelled Spot order:', cancelledResponse.data.result); + } catch (error) { + console.error('Spot WebSocket API cancellation failed:', error); + } + } finally { + wsApi.getWSClient().closeAll(); + } } -⋮---- -export interface CreateOTCUploadPreUploadReq { - content_type: string; - scene: 'general' | 'bank' | 'assessment' | 'credit'; + +main(); +``` + +### 9. Send a USDT perpetual order through the WebSocket API + +Futures WebSocket API commands use a product-specific WebSocket key. Pass it explicitly so the contract and connection remain clear. + + + +```javascript +import { RestClient, WebsocketAPIClient, WS_KEY_MAP } from 'gateio-api'; + +const rest = new RestClient({ + apiKey: process.env.GATE_TESTNET_API_KEY, + apiSecret: process.env.GATE_TESTNET_API_SECRET, + baseUrl: 'https://api-testnet.gateapi.io/api/v4', +}); + +const wsApi = new WebsocketAPIClient({ + apiKey: process.env.GATE_TESTNET_API_KEY, + apiSecret: process.env.GATE_TESTNET_API_SECRET, + wsUrl: 'wss://ws-testnet.gate.com/v4/ws/futures/usdt', +}); + +async function main() { + if (process.env.GATE_PLACE_TESTNET_ORDER !== 'true') { + console.error('Set GATE_PLACE_TESTNET_ORDER=true to run this example.'); + return; + } + + if ( + !process.env.GATE_TESTNET_API_KEY || + !process.env.GATE_TESTNET_API_SECRET + ) { + console.error('Set GATE_TESTNET_API_KEY and GATE_TESTNET_API_SECRET.'); + return; + } + + let contract; + + try { + contract = await rest.getFuturesContract({ + settle: 'usdt', + contract: 'BTC_USDT', + }); + } catch (error) { + console.error('Contract request failed:', error); + return; + } + + let orderBook; + + try { + orderBook = await rest.getFuturesOrderBook({ + settle: 'usdt', + contract: 'BTC_USDT', + limit: 5, + }); + } catch (error) { + console.error('Order book request failed:', error); + return; + } + + let account; + + try { + account = await rest.getFuturesAccount({ + settle: 'usdt', + }); + } catch (error) { + console.error('Futures account request failed:', error); + return; + } + + const oneWayMode = account.position_mode + ? account.position_mode === 'single' + : !account.in_dual_mode; + + if (!oneWayMode) { + console.error('This example requires one-way Futures position mode.'); + return; + } + + if (contract.status && contract.status !== 'trading') { + console.error('BTC_USDT Futures is not currently trading.'); + return; + } + + const price = orderBook.bids[0]?.p; + const size = Number(contract.order_size_min); + + if ( + !price || + !Number.isFinite(Number(price)) || + Number(price) <= 0 || + !Number.isFinite(size) || + size <= 0 || + (contract.enable_decimal === false && !Number.isInteger(size)) + ) { + console.error('Required contract metadata is unavailable.'); + return; + } + + const text = `t-siebly${Date.now().toString().slice(-12)}`; + const wsKey = WS_KEY_MAP.perpFuturesUSDTV4; + + try { + let placedResponse; + + try { + placedResponse = await wsApi.submitNewFuturesOrder( + { + contract: 'BTC_USDT', + size, + price, + tif: 'poc', + text, + }, + wsKey, + ); + console.log('Command status:', placedResponse.header.status); + console.log('Placed Futures order:', placedResponse.data.result); + } catch (error) { + console.error('Futures WebSocket API placement failed:', error); + return; + } + + const orderId = String(placedResponse.data.result.id); + let statusResponse; + + try { + statusResponse = await wsApi.getFuturesOrderStatus( + { + order_id: orderId, + }, + wsKey, + ); + console.log('Current Futures order:', statusResponse.data.result); + } catch (error) { + console.error('Futures WebSocket API query failed:', error); + } + + if (statusResponse && statusResponse.data.result.status !== 'open') { + console.log( + 'Order is no longer open:', + statusResponse.data.result.status, + ); + return; + } + + try { + const cancelledResponse = await wsApi.cancelFuturesOrder( + { + order_id: orderId, + }, + wsKey, + ); + console.log('Cancelled Futures order:', cancelledResponse.data.result); + } catch (error) { + console.error('Futures WebSocket API cancellation failed:', error); + } + } finally { + wsApi.getWSClient().closeAll(); + } +} + +main(); +``` + +Successful commands have `header.status === '200'`, and the endpoint result is in `data.result`. The SDK rejects a command promise when Gate returns a non-success status. + +An accepted command is not proof that an order later filled, remained open, or was cancelled. Treat the response as [pending confirmation](https://siebly.io/reference/glossary#pending-confirmation), then confirm the final state through the private order stream or a REST API query. + + + +## Work with the Gate REST API + +`RestClient` covers Gate's product groups through named methods. Public methods work without credentials. Private methods use the API key and secret passed to the client. + +### Understand response shapes + +The client resolves to the endpoint's response body: + +```javascript +import { RestClient } from 'gateio-api'; + +const client = new RestClient(); + +async function main() { + try { + const result = await client.getSpotOrderBook({ + currency_pair: 'BTC_USDT', + }); + console.log(result); + } catch (error) { + console.error('Order book request failed:', error); + } } -================ -File: src/types/request/spot.ts -================ -/**========================================================================================================================== - * SPOT - * ========================================================================================================================== - */ -⋮---- -/** Limit-order take-profit / stop-loss on create */ -export interface SpotOrderTPSL { - trigger_price: string; - order_price: string; -} -⋮---- -/** Limit-order take-profit / stop-loss on amend; `{}` cancels, `null` leaves unchanged */ -export type PatchSpotOrderTPSL = SpotOrderTPSL | {} | null; -⋮---- -export interface GetSpotOrderBookReq { - currency_pair: string; - interval?: string; - limit?: number; - with_id?: boolean; +main(); +``` + +There is no shared response envelope. Check the [SDK endpoint map](./endpointFunctionList.md) before deciding how to handle `result`. + +| Method | Response shape | +| ----------------------- | ------------------------------------------ | +| `getServerTime()` | Object with `server_time` | +| `getSpotCurrencyPair()` | Currency-pair object | +| `getSpotTicker()` | Array of ticker objects | +| `getSpotOrderBook()` | Object with tuple-array `bids` and `asks` | +| `getSpotCandles()` | Array of candle tuples | +| `getFuturesContract()` | Contract object | +| `getFuturesTickers()` | Array of ticker objects | +| `getFuturesOrderBook()` | Object with `{ p, s }` bid and ask entries | +| `getFuturesAccount()` | Account object | +| `getFuturesPositions()` | Array of position objects | + +Prices and quantities are commonly returned as strings. Keep them as strings while passing them between Gate API methods. Convert them deliberately when doing calculations, and round the result back to the product's required precision. + +### Read account state + +An authenticated integration usually needs these views: + +| State | Spot method | USDT perpetual method | +| ------------------- | ------------------------- | ---------------------------------------------------------- | +| Balances or account | `getSpotAccounts()` | `getFuturesAccount({ settle: 'usdt' })` | +| Positions | Not applicable | `getFuturesPositions({ settle: 'usdt' })` | +| Open orders | `getSpotOpenOrders()` | `getFuturesOrders({ settle: 'usdt', status: 'open' })` | +| Recent orders | `getSpotOrders()` | `getFuturesOrders({ settle: 'usdt', status: 'finished' })` | +| Trades | `getSpotTradingHistory()` | `getFuturesTradingHistory({ settle: 'usdt' })` | + +These REST API views form a reliable [account state](https://siebly.io/reference/glossary#accountstate) baseline before stream updates are applied. + +### Explore other Gate product groups + +The same `RestClient` also covers the following APIs. Start with read methods and check account eligibility, permissions, and product-specific rules before using any write method. + +| Product group | Representative SDK methods | +| ----------------------- | --------------------------------------------------------------------------- | +| Margin and cross margin | `getMarginAccounts()`, `getCrossMarginAccount()`, `getMarginUserAccounts()` | +| Universal margin loans | `getMarginUNILoans()`, `getMarginUNIMaxBorrow()` | +| Unified Account | `getUnifiedAccountInfo()`, `getUnifiedAccountMode()`, `getUnifiedLoans()` | +| Delivery | `getAllDeliveryContracts()`, `getDeliveryAccount()`, `getDeliveryOrders()` | +| Options | `getOptionsContracts()`, `getOptionsAccount()`, `getOptionsOrders()` | +| Wallet and transfers | `getBalances()`, `submitTransfer()`, `getTransferStatus()` | +| Multi-collateral loans | `getMultiLoanOrders()`, `getMultiLoanSupportedCurrencies()` | +| Flash Swap | `getFlashSwapCurrencyPairs()`, `getFlashSwapOrders()` | +| Earn and lending | `getEarnFixedTermProducts()`, `getEarnFixedTermLends()` | +| Auto Invest | `getAutoInvestCoins()`, `getAutoInvestPlans()`, `getAutoInvestOrders()` | +| Subaccounts | `getSubAccounts()`, `getSubBalance()`, `getSubFuturesBalances()` | +| Rebates and partners | `getPartnerTransactionHistory()`, `getPartnerCommissionHistory()` | +| OTC | `getOTCBankList()`, `getOTCFiatOrderList()` | +| P2P Merchant | `getP2PMerchantUserInfo()`, `getP2PMerchantPendingTransactionList()` | +| CrossEx | `getCrossExSymbols()`, `getCrossExAccounts()`, `getCrossExPositions()` | +| Alpha | `getAlphaCurrencies()`, `getAlphaTickers()`, `getAlphaOrders()` | +| TradFi | `getTradFiSymbols()`, `getTradFiAssets()`, `getTradFiOrders()` | + +See the [complete SDK endpoint map](./endpointFunctionList.md) for every supported method, its authentication requirement, HTTP method, and Gate path. + + + +## Build with WebSocket streams + +Use `WebsocketClient` for ongoing market and account updates. A subscription request has two independent parts: + +- `topic` and `payload` select the Gate channel and its data. +- `wsKey` selects the product connection that carries the subscription. + +One `subscribe()` call can contain several topics when they share the same `wsKey`. Use separate calls for topics on different product connections. + +### Choose the correct WebSocket key + +| Product connection | SDK key | +| ---------------------- | ---------------------------------- | +| Spot | `WS_KEY_MAP.spotV4` | +| USDT perpetual Futures | `WS_KEY_MAP.perpFuturesUSDTV4` | +| BTC perpetual Futures | `WS_KEY_MAP.perpFuturesBTCV4` | +| USDT Delivery | `WS_KEY_MAP.deliveryFuturesUSDTV4` | +| BTC Delivery | `WS_KEY_MAP.deliveryFuturesBTCV4` | +| Options | `WS_KEY_MAP.optionsV4` | +| Announcements | `WS_KEY_MAP.announcementsV4` | + +Do not infer the connection from a symbol alone. `BTC_USDT` can appear in more than one product family. + +Useful public topics include: + +| Product | Starting topics | +| ------- | -------------------------------------------------------------------------------------------------------------- | +| Spot | `spot.tickers`, `spot.trades`, `spot.order_book`, `spot.order_book_update`, `spot.candlesticks` | +| Futures | `futures.tickers`, `futures.trades`, `futures.order_book`, `futures.order_book_update`, `futures.candlesticks` | +| Options | `options.tickers`, `options.trades`, `options.order_book`, `options.ul_tickers` | + +### Treat responses and updates differently + +The `response` event tells you whether Gate accepted a subscribe, unsubscribe, or request message. Check its `error` and `result`. + +The `update` event carries channel data. Inspect `channel`, `event`, `result`, and the SDK-added `wsKey` before updating local state. A subscription response and a data update can have different result shapes. + +### Recover after a reconnect + +The SDK reconnects and restores cached subscriptions. A stream gap can still hide balance, order, trade, or position changes. Reload the affected state from the REST API after `reconnected`. + +This Spot example reloads balances, open orders, and recent trades in sequence: + +```javascript +import { RestClient, WebsocketClient, WS_KEY_MAP } from 'gateio-api'; + +const rest = new RestClient({ + apiKey: process.env.GATE_API_KEY, + apiSecret: process.env.GATE_API_SECRET, +}); + +const ws = new WebsocketClient({ + apiKey: process.env.GATE_API_KEY, + apiSecret: process.env.GATE_API_SECRET, +}); + +let recoveryRunning = false; +let spotState; + +async function recoverSpotState() { + if (recoveryRunning) { + return; + } + + recoveryRunning = true; + + try { + let balances; + + try { + balances = await rest.getSpotAccounts(); + } catch (error) { + console.error('Balance recovery failed:', error); + return; + } + + let openOrders; + + try { + openOrders = await rest.getSpotOpenOrders({ + account: 'spot', + }); + } catch (error) { + console.error('Open-order recovery failed:', error); + return; + } + + let trades; + + try { + trades = await rest.getSpotTradingHistory({ + currency_pair: 'BTC_USDT', + account: 'spot', + limit: 100, + }); + } catch (error) { + console.error('Trade recovery failed:', error); + return; + } + + spotState = { + balances, + openOrders, + trades, + recoveredAt: Date.now(), + }; + + console.log('Recovered Spot state:', spotState); + } finally { + recoveryRunning = false; + } } -⋮---- -export interface GetSpotTradesReq { - currency_pair: string; - limit?: number; - last_id?: string; - reverse?: boolean; - from?: number; - to?: number; - page?: number; + +ws.on('reconnected', async ({ wsKey }) => { + if (wsKey !== WS_KEY_MAP.spotV4) { + return; + } + + await recoverSpotState(); +}); + +ws.on('update', (update) => { + console.log('Private Spot update:', update); +}); + +ws.on('exception', (error) => { + console.error('WebSocket exception:', error); +}); + +try { + ws.subscribe( + { + topic: 'spot.balances', + }, + WS_KEY_MAP.spotV4, + ); +} catch (error) { + console.error('Balance subscription failed:', error); } -⋮---- -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'; + +try { + ws.subscribe( + { + topic: 'spot.orders', + payload: ['BTC_USDT'], + }, + WS_KEY_MAP.spotV4, + ); +} catch (error) { + console.error('Order subscription failed:', error); } -⋮---- -export interface GetSpotAccountBookReq { - 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; + +try { + ws.subscribe( + { + topic: 'spot.usertrades', + payload: ['BTC_USDT'], + }, + WS_KEY_MAP.spotV4, + ); +} catch (error) { + console.error('Trade subscription failed:', error); } -⋮---- -/** - * 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; - amount: string; - price: string; - action_mode?: 'ACK' | 'RESULT' | 'FULL'; + +process.once('SIGINT', () => { + ws.closeAll(); +}); +``` + +This is [REST API hydration](https://siebly.io/reference/glossary#rest-hydration) applied as [scoped recovery](https://siebly.io/reference/glossary#scoped-recovery). The example replaces `spotState` only after all three reads succeed. Reload only the state that may have changed on the affected connection, then reconcile it before trusting new updates. + +For a wider recovery design, see [Exchange State](https://siebly.io/reference/exchange-state) and [Runtime Workflows](https://siebly.io/reference/runtime-workflows). + + + +## Use the Gate WebSocket API + +`WebsocketAPIClient` is for request and response commands over WebSocket. It is not the same as a subscription stream. + +The client: + +1. Opens the selected WebSocket connection. +2. Authenticates automatically. +3. Adds a unique request ID. +4. Sends the command. +5. Matches Gate's response to the pending promise. +6. Resolves with `header`, `data.result`, `request_id`, and `wsKey`. + +Authentication happens automatically on the first command. `connectWSAPI(wsKey)` is available when an application wants to open and authenticate the connection early. Automatic WebSocket API reauthentication after a reconnect is enabled by default. + +Spot methods include: + +- `submitNewSpotOrder()` +- `getSpotOrderStatus()` +- `getSpotOrders()` +- `updateSpotOrder()` +- `cancelSpotOrder()` +- `cancelSpotOrderById()` +- `cancelSpotOrderForSymbol()` + +Futures methods include: + +- `submitNewFuturesOrder()` +- `submitNewFuturesBatchOrder()` +- `getFuturesOrderStatus()` +- `getFuturesOrders()` +- `updateFuturesOrder()` +- `cancelFuturesOrder()` + +Pass a Futures `wsKey` explicitly. This keeps the settlement connection visible: + +```javascript +import { WebsocketAPIClient, WS_KEY_MAP } from 'gateio-api'; + +const wsApi = new WebsocketAPIClient({ + apiKey: process.env.GATE_API_KEY, + apiSecret: process.env.GATE_API_SECRET, +}); + +async function main() { + try { + const response = await wsApi.getFuturesOrders( + { + contract: 'BTC_USDT', + status: 'open', + limit: 20, + }, + WS_KEY_MAP.perpFuturesUSDTV4, + ); + + console.log(response.header.status); + console.log(response.data.result); + } catch (error) { + console.error('WebSocket API order request failed:', error); + } finally { + wsApi.getWSClient().closeAll(); + } } -⋮---- -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'; + +main(); +``` + +The response confirms the command outcome. Use private order streams or a REST API query to confirm the resulting exchange state. + + + +## Use Gate TestNet + +Gate TestNet is a separate environment with separate credentials. Use it for all order examples while learning the SDK. + +| Interface | Current TestNet host | +| ------------------------ | ---------------------------------------------- | +| REST API | `https://api-testnet.gateapi.io/api/v4` | +| Spot WebSocket | `wss://ws-testnet.gate.com/v4/ws/spot` | +| USDT perpetual WebSocket | `wss://ws-testnet.gate.com/v4/ws/futures/usdt` | +| Options WebSocket | `wss://ws-testnet.gate.com/v4/ws/options` | + +Set the REST API host with `baseUrl` or `baseUrlKey`, and the WebSocket host with `wsUrl` or `useTestnet: true`. Prefer explicit hosts for TestNet examples: + +- `baseUrlKey: 'testnet'` uses `https://api-testnet.gateapi.io/api/v4` for spot and futures. `baseUrlKey: 'futuresTestnet'` is the same host, kept so older configs keep working. +- `useTestnet: true` selects the TestNet WebSocket host for that connection, including Spot and Options. BTC perpetual and delivery TestNet hosts stay on the URLs in the current Gate docs (`wss://fx-ws-testnet.gateio.ws/...`). Announcements still have no TestNet host. + +```javascript +import { RestClient, WebsocketClient } from 'gateio-api'; + +const rest = new RestClient({ + apiKey: process.env.GATE_TESTNET_API_KEY, + apiSecret: process.env.GATE_TESTNET_API_SECRET, + baseUrl: 'https://api-testnet.gateapi.io/api/v4', +}); + +const spotWs = new WebsocketClient({ + apiKey: process.env.GATE_TESTNET_API_KEY, + apiSecret: process.env.GATE_TESTNET_API_SECRET, + wsUrl: 'wss://ws-testnet.gate.com/v4/ws/spot', +}); +``` + +Do not send live credentials to TestNet or TestNet credentials to live hosts. TestNet balances, liquidity, and available products can differ from live trading. + +Fund the required Spot or Futures TestNet account with test assets before running an order example. + + + +## Connect to Global and regional REST API hosts + +Use the API host associated with the Gate account and product you are integrating. Credentials and product availability are not interchangeable across account regions. + +| Environment or account | REST API base URL | Official reference | +| ------------------------ | --------------------------------------- | -------------------------------------------------------------------- | +| Global live | `https://api.gateio.ws/api/v4` | [Global Gate API v4](https://www.gate.com/docs/developers/apiv4/en/) | +| Global TestNet | `https://api-testnet.gateapi.io/api/v4` | [Global Gate API v4](https://www.gate.com/docs/developers/apiv4/en/) | +| Futures live alternative | `https://fx-api.gateio.ws/api/v4` | [Global Gate API v4](https://www.gate.com/docs/developers/apiv4/en/) | +| Gate US live | `https://api.gate.us/api/v4` | [Gate US API v4](https://us.gate.com/en-us/docs/developers/apiv4/) | +| Gate EU live | `https://api.gateeu.com/api/v4` | [Gate EU API v4](https://eu.gate.com/docs/developers/apiv4/en/) | + +Global live is the SDK default. Set `baseUrl` for another supported account host: + +```javascript +import { RestClient } from 'gateio-api'; + +const gateUs = new RestClient({ + apiKey: process.env.GATE_API_KEY, + apiSecret: process.env.GATE_API_SECRET, + baseUrl: 'https://api.gate.us/api/v4', +}); + +const gateEu = new RestClient({ + apiKey: process.env.GATE_API_KEY, + apiSecret: process.env.GATE_API_SECRET, + baseUrl: 'https://api.gateeu.com/api/v4', +}); +``` + +Use only the client that matches the account. Regional APIs can expose different products and endpoint sets. Check the regional documentation before calling a method, and use the region's own credentials. + +This guide does not assign regional WebSocket URLs. Use a regional WebSocket host only when the official documentation for that account region provides it. + + + +## Use a proxy with the REST API and WebSockets + +`gateio-api` accepts standard Node.js agents. Configure the agent in both places when all Gate traffic must use the proxy: + +- Pass `httpsAgent` in the second `RestClient` argument and set `proxy: false`. +- Pass the same agent as `wsOptions.agent` to `WebsocketClient` or `WebsocketAPIClient`. + +See [Using proxies with Siebly SDKs](https://siebly.io/blog/using-proxy-with-siebly-sdks) for deployment and troubleshooting guidance. + +### HTTP and HTTPS proxy + +Install the proxy agent: + +```bash +npm install https-proxy-agent +``` + +Set `GATE_PROXY_URL` to an `http://` or `https://` proxy URL. The example does not print the value because it may contain credentials. + +```javascript +import { HttpsProxyAgent } from 'https-proxy-agent'; +import { RestClient, WebsocketClient, WS_KEY_MAP } from 'gateio-api'; + +async function main() { + const proxyUrl = process.env.GATE_PROXY_URL; + + if (!proxyUrl) { + console.error('Set GATE_PROXY_URL.'); + return; + } + + const agent = new HttpsProxyAgent(proxyUrl); + + const rest = new RestClient( + {}, + { + httpsAgent: agent, + proxy: false, + }, + ); + + const ws = new WebsocketClient({ + wsOptions: { + agent, + }, + }); + + ws.on('open', ({ wsKey }) => { + console.log('WebSocket connected through proxy:', wsKey); + }); + + ws.on('response', (response) => { + console.log('Subscription response:', response); + }); + + ws.on('update', (update) => { + console.log('Ticker update through proxy:', update); + ws.closeAll(); + }); + + ws.on('exception', () => { + console.error('WebSocket proxy connection failed.'); + }); + + try { + const time = await rest.getServerTime(); + console.log('Server time through proxy:', time.server_time); + } catch { + console.error('REST API proxy request failed.'); + } + + try { + ws.subscribe( + { + topic: 'spot.tickers', + payload: ['BTC_USDT'], + }, + WS_KEY_MAP.spotV4, + ); + } catch { + console.error('WebSocket proxy subscription failed.'); + } + + process.once('SIGINT', () => { + ws.closeAll(); + }); } -⋮---- -export interface CancelSpotBatchOrdersReq { - currency_pair: string; - id: string; - account?: 'cross_margin'; - action_mode?: 'ACK' | 'RESULT' | 'FULL'; + +main(); +``` + +For an authenticated HTTP or HTTPS proxy, include the username and password in `GATE_PROXY_URL`. Percent-encode reserved characters in each credential component. + +### SOCKS5 proxy + +Install the SOCKS agent: + +```bash +npm install socks-proxy-agent +``` + +Set `GATE_SOCKS_PROXY_URL` to a `socks5://` URL: + +```javascript +import { SocksProxyAgent } from 'socks-proxy-agent'; +import { RestClient, WebsocketClient, WS_KEY_MAP } from 'gateio-api'; + +async function main() { + const proxyUrl = process.env.GATE_SOCKS_PROXY_URL; + + if (!proxyUrl) { + console.error('Set GATE_SOCKS_PROXY_URL.'); + return; + } + + const agent = new SocksProxyAgent(proxyUrl); + + const rest = new RestClient( + {}, + { + httpsAgent: agent, + proxy: false, + }, + ); + + const ws = new WebsocketClient({ + wsOptions: { + agent, + }, + }); + + ws.on('open', ({ wsKey }) => { + console.log('WebSocket connected through SOCKS5:', wsKey); + }); + + ws.on('response', (response) => { + console.log('Subscription response:', response); + }); + + ws.on('update', (update) => { + console.log('Ticker update through SOCKS5:', update); + ws.closeAll(); + }); + + ws.on('exception', () => { + console.error('SOCKS5 WebSocket connection failed.'); + }); + + try { + const time = await rest.getServerTime(); + console.log('Server time through SOCKS5:', time.server_time); + } catch { + console.error('SOCKS5 REST API request failed.'); + } + + try { + ws.subscribe( + { + topic: 'spot.tickers', + payload: ['BTC_USDT'], + }, + WS_KEY_MAP.spotV4, + ); + } catch { + console.error('SOCKS5 WebSocket subscription failed.'); + } + + process.once('SIGINT', () => { + ws.closeAll(); + }); } -⋮---- -export interface DeleteSpotOrderReq { - order_id: string; - currency_pair: string; - account?: 'spot' | 'margin' | 'cross_margin' | 'unified'; - action_mode?: 'ACK' | 'RESULT' | 'FULL'; - xGateExptime?: number; + +main(); +``` + +### Private REST API, stream, and WebSocket API traffic + +Use the same agent and credentials for private REST API calls, private subscriptions, and WebSocket API connections: + +```javascript +import { HttpsProxyAgent } from 'https-proxy-agent'; +import { + RestClient, + WebsocketAPIClient, + WebsocketClient, + WS_KEY_MAP, +} from 'gateio-api'; + +async function main() { + const proxyUrl = process.env.GATE_PROXY_URL; + + if (!proxyUrl) { + console.error('Set GATE_PROXY_URL.'); + return; + } + + const agent = new HttpsProxyAgent(proxyUrl); + + const rest = new RestClient( + { + apiKey: process.env.GATE_API_KEY, + apiSecret: process.env.GATE_API_SECRET, + }, + { + httpsAgent: agent, + proxy: false, + }, + ); + + const streams = new WebsocketClient({ + apiKey: process.env.GATE_API_KEY, + apiSecret: process.env.GATE_API_SECRET, + wsOptions: { + agent, + }, + }); + + const wsApi = new WebsocketAPIClient({ + apiKey: process.env.GATE_API_KEY, + apiSecret: process.env.GATE_API_SECRET, + wsOptions: { + agent, + }, + }); + + streams.on('authenticated', ({ wsKey }) => { + console.log('Private stream authenticated:', wsKey); + }); + + streams.on('update', (update) => { + console.log('Private update through proxy:', update); + }); + + streams.on('exception', () => { + console.error('Private stream proxy connection failed.'); + }); + + try { + const balances = await rest.getSpotAccounts(); + console.log('Spot balances through proxy:', balances); + } catch { + console.error('Private REST API proxy request failed.'); + } + + try { + streams.subscribe( + { + topic: 'spot.balances', + }, + WS_KEY_MAP.spotV4, + ); + } catch { + console.error('Private stream subscription failed.'); + } + + try { + await wsApi.getWSClient().connectWSAPI(WS_KEY_MAP.spotV4); + console.log('WebSocket API authenticated through proxy.'); + } catch { + console.error('WebSocket API proxy connection failed.'); + } + + process.once('SIGINT', () => { + streams.closeAll(); + wsApi.getWSClient().closeAll(); + }); } + +main(); +``` + +To combine a proxy with TestNet or a regional API, keep `baseUrl` or `wsUrl` in the first client argument and the agent in the same positions shown above. + +The proxy's egress IP is the address Gate sees. Add that address to the API key whitelist when whitelisting is enabled. Use a stable proxy endpoint, monitor its latency, and never use a proxy to bypass account or regional restrictions. + +A proxy changes the network path, not request signing, account eligibility, or regional product access. Test public REST API and WebSocket traffic first. Treat HTTP 407 responses, TLS failures, and repeated reconnects as network faults. The SDK does not rotate proxy endpoints. + + + +## Production checklist + +### Keep request time accurate + +Gate private requests and WebSocket authentication depend on timestamp checks. The gap between request time and server time must not exceed 60 seconds. + +Synchronize the host clock with NTP. Use `getServerTime()` for diagnosis, but fix the system clock rather than adding a permanent application offset for a drifting machine. + +### Respect rate limits + +Rate limits vary by product and endpoint. Read the current [Gate API rate-limit documentation](https://www.gate.com/docs/developers/apiv4/en/#frequency-limit-rule) and monitor rejection labels. + +Retry temporary network failures and rate-limit responses with bounded exponential backoff and jitter. Do not blindly retry an order command after an ambiguous timeout. First reconcile by the order's `text` value or query current order state. + +### Use custom order IDs + +Set a unique `text` value beginning with `t-` on each application-owned order. Store it with your local request record. This gives retries, restarts, stream updates, and REST API recovery a common identifier. + +### Apply product metadata + +Before placing an order: + +- Check that the pair or contract is tradable. +- Apply minimum and maximum amounts. +- Round prices and quantities to the permitted increments. +- Treat Futures `size` as a contract count. +- Read `quanto_multiplier` before translating contract size into underlying exposure. +- Keep one-way, dual-side, and split position modes explicit. + +Refresh metadata regularly and when Gate rejects an order for a precision or size rule. + +### Confirm final state + +A REST API response or WebSocket API response can arrive before later fills, cancellations, or amendments. Record the command response, then confirm final state through private streams or a REST API query. + +After a reconnect, restore the affected [exchange state](https://siebly.io/reference/exchange-state) before resuming state-dependent actions. + +### Scope credentials and network access + +- Use separate keys for live and TestNet. +- Grant only the product permissions the process needs. +- Use read-only keys for monitoring services. +- Do not grant withdrawal permission. +- Add IP whitelists when egress addresses are stable. +- Keep secrets in a server-side secret manager or deployment environment. +- Monitor proxy availability and egress IP changes. + +### Shut down connections + +Call `closeAll()` on each WebSocket client when the process is ending. An unsubscribe request is unnecessary when the connection is about to close. + +## FAQ + +### Does `gateio-api` work with plain JavaScript? + +Yes. Every example in this guide is plain JavaScript. The examples use ESM imports, so save them as `.mjs` files or set `"type": "module"` in `package.json`. The package also includes a CommonJS build and TypeScript declarations. + +### Which client should I use? + +Use `RestClient` for public and private REST API calls, `WebsocketClient` for ongoing subscriptions, and `WebsocketAPIClient` for awaitable Spot and Futures commands over WebSocket. + +### Do public Gate API calls need credentials? + +No. Public market data works without an API key. Account data, private streams, and order commands require credentials with the relevant product permission. + +### Why did a REST API call return an object when another returned an array? + +Gate response bodies are endpoint-specific. The SDK returns the endpoint body directly. Check the [endpoint map](./endpointFunctionList.md) before reading the result. + +### Why does `getSpotTicker()` return an array for one pair? + +That is Gate's endpoint response shape. Read the first entry after checking that the array is not empty. + +### How are Spot candles structured? + +Spot candles are tuple arrays containing timestamp, quote volume, close, high, low, open, base volume, and a closed-window flag in that order. + +### Why does Gate use `BTC_USDT`? + +Gate uses underscore-separated currency pairs and contract names. Pass the exact identifier returned by the relevant market or contract metadata endpoint. + +### What do `account` and `settle` change? + +`account` selects the account used by a Spot order or query. `settle` selects the settlement currency and REST API path for Futures or Delivery requests. + +### What is the `text` order field? + +`text` is Gate's custom order ID field. Use a unique value beginning with `t-` to reconcile requests, stream updates, and order queries. + +### Why am I not receiving WebSocket updates? + +Check the topic payload, `wsKey`, API host, credentials, and permissions. Then inspect `response`, `authenticated`, and `exception` events. A successful subscription response confirms registration, but an update only arrives when the subscribed data changes. + +### Which `WS_KEY_MAP` value should I use? + +Choose the key for the exact product connection. For example, Spot uses `spotV4` and USDT perpetual Futures uses `perpFuturesUSDTV4`. + +### Why do private Futures topics use my Gate user ID? + +It is part of the payload required by those channels. Retrieve it with `getAccountDetail()` instead of hardcoding it. + +### What is the difference between a stream and the WebSocket API? + +Streams push subscribed market or account updates. The WebSocket API sends a command and resolves a promise with Gate's matching response. + +### Does a successful WebSocket API response mean the order filled? + +No. It confirms the command result. Confirm later order and fill state through private streams or a REST API query. + +### Why was a post-only order rejected or immediately finished? + +The best bid or ask can move between the order-book request and order placement. Gate will not let a post-only order take liquidity. Read the returned status and `finish_as`, then decide whether to refresh the book and submit a new order with a new `text`. + +### Why does a Futures order size look too small? + +Futures `size` is the number of contracts. Use `quanto_multiplier` to find the underlying amount represented by one contract. + +### Can live credentials be used in TestNet? + +No. TestNet and live trading use separate API keys and balances. Use the current TestNet `baseUrl` or `wsUrl` with TestNet credentials. + +### Can I use Gate US or Gate EU with the SDK? + +Yes, for endpoints available to that account region. Set the documented regional `baseUrl`, use credentials from the same region, and check its official API documentation for product coverage. + +### Can REST API and WebSocket traffic use the same proxy? + +Yes. Create one compatible agent, pass it as `httpsAgent` to `RestClient`, and pass it as `wsOptions.agent` to the WebSocket clients. + +### Does a proxy change signing or account eligibility? + +No. The SDK signs the same requests through the proxy. The Gate account, API host, product permissions, and regional availability still apply. + +### What causes `INVALID_SIGNATURE` or `REQUEST_EXPIRED`? + +Common causes are a drifting system clock, the wrong API secret, credentials from another environment, or an API request reaching the wrong host. Verify the clock, credential source, and API host without logging the secret. + +## Next steps + +- Browse the [Gate SDK examples](https://siebly.io/examples/Gate). +- Find methods in the [complete endpoint map](./endpointFunctionList.md). +- Review the [Gate SDK page](https://siebly.io/sdk/gate/javascript). +- Install or update [`gateio-api` from npm](https://www.npmjs.com/package/gateio-api). +- Browse the [`gateio-api` source repository](https://github.com/sieblyio/gateio-api). +- Read the official [Gate REST API documentation](https://www.gate.com/docs/developers/apiv4/en/). +- Read the official [Gate Spot WebSocket documentation](https://www.gate.com/docs/developers/apiv4/ws/). +- Read the official [Gate Futures WebSocket documentation](https://www.gate.com/docs/developers/futures/ws/). +- Review [Exchange State](https://siebly.io/reference/exchange-state) before building private state management. +- Use [Runtime Workflows](https://siebly.io/reference/runtime-workflows) when designing startup, reconnect, and reconciliation behavior. +- Open the [Siebly glossary](https://siebly.io/reference/glossary) for order, stream, and recovery terms. +- Report SDK issues in the [`gateio-api` GitHub repository](https://github.com/sieblyio/gateio-api/issues). + +================ +File: src/types/request/otc.ts +================ +import { GateMultipartFile } from '../../lib/multipartUtil.js'; ⋮---- -export interface GetSpotOrderReq { - order_id: string; - currency_pair: string; - account?: 'spot' | 'margin' | 'cross_margin' | 'unified'; -} +/**========================================================================================================================== + * OTC + * ========================================================================================================================== + */ ⋮---- -export interface GetSpotTradingHistoryReq { - currency_pair?: string; - limit?: number; - page?: number; - order_id?: string; - account?: 'spot' | 'margin' | 'cross_margin' | 'unified'; - from?: number; - to?: number; +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) } ⋮---- -export interface UpdateSpotBatchOrdersReq { - order_id?: string; - currency_pair?: string; - amount?: string; - price?: string; - amend_text?: string; - stop_loss?: PatchSpotOrderTPSL; - stop_profit?: PatchSpotOrderTPSL; -} +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 GetSpotInsuranceHistoryReq { - business: 'margin' | 'unified'; - currency: string; - from: number; - to: number; - page?: number; - limit?: number; +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; } ⋮---- -export interface GetSpotAutoOrdersReq { - status: 'open' | 'finished'; - market?: string; - account?: 'normal' | 'margin' | 'cross_margin' | 'unified'; - limit?: number; - offset?: number; -} +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 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; +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 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; -} +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) ⋮---- -/** GET /spot/pov_orders */ -export interface GetSpotPovOrdersReq { - status: 'open' | 'finished'; - currency_pair?: string; - side?: 'buy' | 'sell'; - page?: number; - limit?: number; +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 } ⋮---- -/** 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; -} +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 ⋮---- -/** DELETE /spot/pov_orders */ -export interface CancelSpotPovOrdersReq { - currency_pair?: string; +export interface CancelOTCOrderReq { + order_id: string; // Order ID } - -================ -File: src/types/request/tradfi.ts -================ -/** TradFi API request types */ ⋮---- -export interface TradFiGetSymbolDetailParams { - symbols: string; -} +order_id: string; // Order ID ⋮---- -export interface TradFiGetKlinesParams { - kline_type: '1m' | '15m' | '1h' | '4h' | '1d' | '7d' | '30d'; - begin_time?: number; - end_time?: number; - limit?: number; +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 TradFiCreateTransactionReq { - asset: string; - change: string; - type: 'deposit' | 'withdraw'; -} +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 TradFiGetTransactionsParams { - begin_time?: number; - end_time?: number; - type?: 'deposit' | 'withdraw' | 'dividend' | 'fill_negative'; - page?: number; - page_size?: number; +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 TradFiCreateOrderReq { - price: string; - price_type: 'trigger' | 'market'; - side: 1 | 2; - symbol: string; - volume: string; - price_tp?: string; - price_sl?: string; - leverage?: number; +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 TradFiModifyOrderReq { - price: string; - price_tp?: string | null; - price_sl?: string | null; +order_id: string; // Order ID +⋮---- +export interface OTCBankIdReq { + bank_id: string; } ⋮---- -export interface TradFiModifyPositionReq { - price_tp?: string | null; - price_sl?: string | null; +export interface GetOTCBankSupplementChecklistReq { + bank_id: string; } ⋮---- -export interface TradFiClosePositionReq { - close_type: 1 | 2; - close_volume?: string | null; +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 TradFiGetOrderHistoryParams { - begin_time?: number; - end_time?: number; - symbol?: string; - side?: 1 | 2; +export interface SubmitOTCBankPersonalSupplementReq { + bank_id: string; + id_document_front: GateMultipartFile; + id_document_back: GateMultipartFile; + address_proof: GateMultipartFile; } ⋮---- -export interface TradFiGetPositionHistoryParams { - begin_time?: number; - end_time?: number; - symbol?: string; - position_dir?: 'Long' | 'Short'; - page?: number; - page_size?: number; +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 /tradfi/symbols/commissions */ -export interface TradFiGetSymbolCommissionsParams { - symbols?: string; - category_code?: string; +export interface CreateOTCUploadPreUploadReq { + content_type: string; + scene: 'general' | 'bank' | 'assessment' | 'credit'; } ================ -File: src/types/request/unified.ts +File: src/types/request/spot.ts ================ -export interface SubmitUnifiedBorrowOrRepayReq { - currency: string; - type: 'borrow' | 'repay'; - amount: string; - repaid_all?: boolean; - text?: string; -} +/**========================================================================================================================== + * SPOT + * ========================================================================================================================== + */ ⋮---- -export interface GetUnifiedLoansReq { - currency?: string; - page?: number; - limit?: number; - type?: 'platform' | 'margin'; +/** Limit-order take-profit / stop-loss on create */ +export interface SpotOrderTPSL { + trigger_price: string; + order_price: string; } ⋮---- -export interface GetUnifiedLoanRecordsReq { - type?: 'borrow' | 'repay'; - currency?: string; - page?: number; +/** Limit-order take-profit / stop-loss on amend; `{}` cancels, `null` leaves unchanged */ +export type PatchSpotOrderTPSL = SpotOrderTPSL | {} | null; +⋮---- +export interface GetSpotOrderBookReq { + currency_pair: string; + interval?: string; limit?: number; + with_id?: boolean; } -export interface GetUnifiedInterestRecordsReq { - currency?: string; - page?: number; +⋮---- +export interface GetSpotTradesReq { + currency_pair: string; limit?: number; + last_id?: string; + reverse?: boolean; from?: number; to?: number; - type?: 'platform' | 'margin'; -} -⋮---- -export interface SetUnifiedAccountModeReq { - mode: 'classic' | 'multi_currency' | 'portfolio' | 'single_currency'; - settings?: { - usdt_futures?: boolean; - spot_hedge?: boolean; - use_funding?: boolean; - options?: boolean; - }; + page?: number; } ⋮---- -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 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 GetUnifiedHistoryLendingRateReq { - currency: string; - tier?: string; +export interface GetSpotAccountBookReq { + 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; } ⋮---- -export interface SubmitUnifiedLoanRepayReq { - 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[]; -} -⋮---- -/** POST /unified/delta_neutral — v4.106.97 */ -export interface SetUnifiedDeltaNeutralReq { - enabled: boolean; -} +/** + * BizType / business type filter. Sub-account transfer internal BizType values include + * 150215, 150216, 150217, 150218, 150219 (Subaccount Transfer); see Gate BizType reference. + */ ⋮---- -/** POST /unified/leverage/user_setting — set leverage for all borrowed currencies */ -export interface SetUserLeverageReq { - leverage?: string; +export interface SubmitSpotClosePosCrossDisabledReq { + text?: string; + currency_pair: string; + amount: string; + price: string; + action_mode?: 'ACK' | 'RESULT' | 'FULL'; } - -================ -File: src/types/request/wallet.ts -================ -/** GET /wallet/sub_account_balances */ -export interface GetSubAccountBalancesReq { - sub_uid?: string; +⋮---- +export interface GetSpotOrdersReq { + currency_pair: string; + status: 'open' | 'finished'; page?: number; limit?: number; -} -⋮---- -export interface GetWithdrawalDepositRecordsReq { - currency?: string; + account?: 'spot' | 'margin' | 'cross_margin' | 'unified'; from?: number; to?: number; - limit?: number; - offset?: number; + side?: 'buy' | 'sell'; } ⋮---- -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; +export interface CancelSpotBatchOrdersReq { + currency_pair: string; + id: string; + account?: 'cross_margin'; + action_mode?: 'ACK' | 'RESULT' | 'FULL'; } ⋮---- -export interface GetMainSubTransfersReq { - sub_uid?: string; - from?: number; - to?: number; - limit?: number; - offset?: number; +export interface DeleteSpotOrderReq { + order_id: string; + currency_pair: string; + account?: 'spot' | 'margin' | 'cross_margin' | 'unified'; + action_mode?: 'ACK' | 'RESULT' | 'FULL'; + xGateExptime?: number; } ⋮---- -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 GetSpotOrderReq { + order_id: string; + currency_pair: string; + account?: 'spot' | 'margin' | 'cross_margin' | 'unified'; } ⋮---- -currency?: string; // v4.106.94: Optional filter by currency +export interface GetSpotTradingHistoryReq { + currency_pair?: string; + limit?: number; + 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; +} ⋮---- -export interface GetSmallBalanceHistoryReq { - currency?: string; +export interface GetSpotInsuranceHistoryReq { + business: 'margin' | 'unified'; + currency: string; + from: number; + to: number; page?: number; limit?: number; } ⋮---- -export interface ListPushOrdersReq { - id?: number; - from?: number; - to?: number; +export interface GetSpotAutoOrdersReq { + status: 'open' | 'finished'; + market?: string; + account?: 'normal' | 'margin' | 'cross_margin' | 'unified'; limit?: number; offset?: number; - transaction_type?: string; -} -⋮---- -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; } ⋮---- -export interface SubmitMainSubTransferReq { - currency: string; - sub_account: string; - direction: 'to' | 'from'; +export interface SubmitSpotOrderReq { + xGateExptime?: number; + side: 'buy' | 'sell'; amount: string; - client_order_id?: string; - sub_account_type?: 'spot' | 'futures' | 'cross_margin' | 'delivery'; + 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; } ⋮---- -/** GET /wallet/transfers */ -export interface GetTransferReq { - tx_id: string; -} - -================ -File: src/types/response/wallet.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; +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 /wallet/sub_account_balances item */ -export interface SubAccountBalance { - uid: string; - available: { [key: string]: string }; - /** Locked amount per currency */ - locking?: { [key: string]: string }; +/** GET /spot/pov_orders */ +export interface GetSpotPovOrdersReq { + status: 'open' | 'finished'; + currency_pair?: string; + side?: 'buy' | 'sell'; + page?: number; + limit?: number; } ⋮---- -/** Locked amount per currency */ -⋮---- -export interface DepositRecord { - id: string; - txid: string; - timestamp: string; +/** POST /spot/pov_orders */ +export interface CreateSpotPovOrderReq { + currency_pair: string; + side: 'buy' | 'sell'; 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'; + 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; } ⋮---- -| '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 +/** DELETE /spot/pov_orders */ +export interface CancelSpotPovOrdersReq { + currency_pair?: string; +} + +================ +File: src/types/request/tradfi.ts +================ +/** TradFi API request types */ ⋮---- -export interface CreateDepositAddressResp { - currency: string; - address: string; - multichain_addresses: { - chain: string; - address: string; - payment_id: string; - payment_name: string; - obtain_failed: number; - }[]; +export interface TradFiGetSymbolDetailParams { + symbols: string; } ⋮---- -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 TradFiGetKlinesParams { + kline_type: '1m' | '15m' | '1h' | '4h' | '1d' | '7d' | '30d'; + begin_time?: number; + end_time?: number; + limit?: 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 }; +export interface TradFiCreateTransactionReq { + asset: string; + change: string; + type: 'deposit' | 'withdraw'; } ⋮---- -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 TradFiGetTransactionsParams { + begin_time?: number; + end_time?: number; + type?: 'deposit' | 'withdraw' | 'dividend' | 'fill_negative'; + page?: number; + page_size?: number; } ⋮---- -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 TradFiCreateOrderReq { + price: string; + price_type: 'trigger' | 'market'; + side: 1 | 2; + symbol: string; + volume: string; + price_tp?: string; + price_sl?: string; + leverage?: 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 TradFiModifyOrderReq { + price: string; + price_tp?: string | null; + price_sl?: string | null; } ⋮---- -export interface SavedAddress { - currency: string; - chain: string; - address: string; - name: string; - tag: string; - verified: string; +export interface TradFiModifyPositionReq { + price_tp?: string | null; + price_sl?: string | null; } ⋮---- -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 TradFiClosePositionReq { + close_type: 1 | 2; + close_volume?: string | null; } ⋮---- -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 TradFiGetOrderHistoryParams { + begin_time?: number; + end_time?: number; + symbol?: string; + side?: 1 | 2; } ⋮---- -export interface SmallBalanceRecord { - currency: string; - available_balance: string; - estimated_as_btc: string; - convertible_to_gt: string; +export interface TradFiGetPositionHistoryParams { + begin_time?: number; + end_time?: number; + symbol?: string; + position_dir?: 'Long' | 'Short'; + page?: number; + page_size?: number; } ⋮---- -export interface SmallBalanceHistoryRecord { - id: string; - currency: string; - amount: string; - gt_amount: string; - create_time: number; +/** GET /tradfi/symbols/commissions */ +export interface TradFiGetSymbolCommissionsParams { + symbols?: string; + category_code?: string; } + +================ +File: src/types/response/earn.ts +================ +/**========================================================================================================================== + * EARN + * ========================================================================================================================== + */ ⋮---- -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 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'; } ⋮---- -/** 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; +/** @deprecated */ +⋮---- +/** 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; } - -================ -File: src/types/websockets/client.ts -================ -import type { ClientRequestArgs } from 'http'; -import WebSocket from 'isomorphic-ws'; ⋮---- -/** - * Event args for subscribing/unsubscribing - */ +/** 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; +} ⋮---- -// export type WsTopicSubscribePrivateArgsV2 = -// | WsTopicSubscribePrivateInstIdArgsV2 -// | WsTopicSubscribePrivateCoinArgsV2; +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; +} ⋮---- -// export type WsTopicSubscribeEventArgsV2 = -// | WsTopicSubscribePublicArgsV2 -// | WsTopicSubscribePrivateArgsV2; +/**========================================================================================================================== + * EARN FIXED-TERM + * ========================================================================================================================== + */ ⋮---- -/** 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; +export interface FixedTermLadderApr { + apr: string; + left: string; + right: string; } ⋮---- -/** Your API key */ +export interface FixedTermProductInfo { + pre_redeem: number; + reinvest: number; + redeem_account: number; + min_vip: number; + max_vip: number; +} ⋮---- -/** Your API secret */ +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; +} ⋮---- -/** Define a recv window when preparing a private websocket signature. This is in milliseconds, so 5000 == 5 seconds */ +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; +} ⋮---- -/** How often to check if the connection is alive */ +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; +} ⋮---- -/** How long to wait for a pong (heartbeat reply) before assuming the connection is dead */ +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; +} ⋮---- -/** Delay in milliseconds before respawning the connection */ +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; +} ⋮---- -/** - * 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 GetEarnFixedTermProductsResponse { + code: number; + message: string; + data: { + list: FixedTermProduct[]; + total: number; + }; + timestamp: 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 GetEarnFixedTermProductsByAssetResponse { + code: number; + message: string; + data: { + list: FixedTermProductSimple[]; + }; + timestamp: number; +} +⋮---- +export interface CreateEarnFixedTermLendResponse { + code?: number; + message?: string; + data?: { + order_id?: number; + }; + timestamp?: number; +} ⋮---- -/** - * 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 GetEarnFixedTermLendsResponse { + code: number; + message: string; + data: { + list: FixedTermLendOrder[]; + total: number; + }; + timestamp: number; } - -================ -File: webpack/webpack.config.cjs -================ -function generateConfig(name) ⋮---- -// Add '.ts' and '.tsx' as resolvable extensions. +export interface CreateEarnFixedTermPreRedeemResponse { + code?: number; + message?: string; + data?: Record; + timestamp?: 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 +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; +} ⋮---- -// Code is already transpiled from TypeScript, no additional loaders needed +export interface GetEarnFixedTermHistoryResponse { + code?: number; + message?: string; + data?: { + list?: FixedTermHistoryRecord[]; + total?: number; + }; + timestamp?: number; +} ================ File: src/types/request/crossex.ts @@ -10776,1346 +11121,1041 @@ export interface CreateCrossExConvertQuoteResp { to_coin: string; // Asset Bought from_amount: string; // Amount to sell to_amount: string; // Amount to buy - price: string; // Price -} -⋮---- -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 CreateCrossExConvertOrderResp { - order_id: string; // Order ID - text: string; // User-defined order ID text -} -⋮---- -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) -} -⋮---- -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 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) -} -⋮---- -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 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[]; -} -⋮---- -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 SetCrossExPositionLeverageResp { - symbol: string; // Currency pair - leverage: string; // Requested Modified Leverage -} -⋮---- -symbol: string; // Currency pair -leverage: string; // Requested Modified Leverage -⋮---- -export interface CrossExPositionLeverage { - symbol: string; // Currency pair - leverage: number | string; -} -⋮---- -symbol: string; // Currency pair -⋮---- -export interface SetCrossExMarginPositionLeverageResp { - symbol: string; // Currency pair - leverage: string; // Requested Modified Leverage -} -⋮---- -symbol: string; // Currency pair -leverage: string; // Requested Modified Leverage -⋮---- -export interface CrossExMarginPositionLeverage { - symbol: string; // Currency pair - leverage: number | string; -} -⋮---- -symbol: string; // Currency pair -⋮---- -export interface CloseCrossExPositionResp { - order_id: string; // Order ID - text: string; // User-defined Order ID -} -⋮---- -order_id: string; // Order ID -text: string; // User-defined Order ID -⋮---- -export interface CrossExInterestRate { - coin: string; // Currency - exchange_type: string; // Exchange - hour_interest_rate: string; // Hourly Interest Rate - time: string; // Millisecond Timestamp -} -⋮---- -coin: string; // Currency -exchange_type: string; // Exchange -hour_interest_rate: string; // Hourly Interest Rate -time: string; // Millisecond Timestamp -⋮---- -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 -} -⋮---- -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[]; -} -⋮---- -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; -} -⋮---- -export interface CrossExMarketFundingInfo { - symbol: string; - funding_rate: string; - funding_interval: string; - funding_time: string; // Next funding time + price: string; // Price } ⋮---- -funding_time: string; // Next funding time +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 CancelBatchCrossExOrdersResp { - order_id: string; - text: string; - accepted: string; // "true" | "false" - label: string; - message: string; +export interface CreateCrossExConvertOrderResp { + order_id: string; // Order ID + text: string; // User-defined order ID text } ⋮---- -accepted: string; // "true" | "false" +order_id: string; // Order ID +text: string; // User-defined order ID text ⋮---- -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 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) } ⋮---- -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 +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 CrossExMarginPosition { +export interface CrossExAccountAsset { 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 + coin: string; // Currency + exchange_type: string; // Exchange + balance: string; // Balance 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 + 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) } ⋮---- 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 +coin: string; // Currency +exchange_type: string; // Exchange +balance: string; // Balance 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) -} -⋮---- -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) +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 CrossExHistoryPosition { - position_id: string; // Position ID +export interface CrossExAccount { 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 + 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[]; } ⋮---- -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 -⋮---- -business_type: string; // Business Type +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 CrossExHistoryMarginPosition { - position_id: string; // Position ID - user_id: string; // User ID +export interface SetCrossExPositionLeverageResp { 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 + leverage: string; // Requested Modified Leverage } ⋮---- -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 +leverage: string; // Requested Modified Leverage ⋮---- -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 CrossExPositionLeverage { + symbol: string; // Currency pair + leverage: number | string; +} +⋮---- +symbol: string; // Currency pair +⋮---- +export interface SetCrossExMarginPositionLeverageResp { + symbol: string; // Currency pair + leverage: string; // Requested Modified Leverage } ⋮---- -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 +symbol: string; // Currency pair +leverage: string; // Requested Modified Leverage ⋮---- -export interface CrossExHistoryTrade { - user_id: string; // User ID - transaction_id: string; // filled records ID - order_id: string; // Order ID - text: string; // User Order ID +export interface CrossExMarginPositionLeverage { 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 + leverage: number | 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 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 CloseCrossExPositionResp { + order_id: string; // Order ID + text: string; // User-defined Order ID } ⋮---- -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 +order_id: string; // Order ID +text: string; // User-defined Order ID ⋮---- -export interface CrossExCoinDiscountRate { +export interface CrossExInterestRate { 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 + hour_interest_rate: string; // Hourly Interest Rate + time: string; // Millisecond Timestamp } ⋮---- 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 +hour_interest_rate: string; // Hourly Interest Rate +time: string; // Millisecond Timestamp ⋮---- -export interface UpdateCrossExPositionsMarginResp { - symbol?: string; - margin?: string; - position_side?: 'NONE' | 'LONG' | 'SHORT'; +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 } - -================ -File: src/types/response/earn.ts -================ -/**========================================================================================================================== - * EARN - * ========================================================================================================================== - */ ⋮---- -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'; +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[]; } ⋮---- -/** @deprecated */ +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 ⋮---- -/** 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 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; } ⋮---- -/** 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; +export interface CrossExMarketFundingInfo { + symbol: string; + funding_rate: string; + funding_interval: string; + funding_time: string; // Next funding time } ⋮---- -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; +funding_time: string; // Next funding time +⋮---- +export interface CancelBatchCrossExOrdersResp { + order_id: string; text: string; + accepted: string; // "true" | "false" + label: string; + message: string; } ⋮---- -/**========================================================================================================================== - * EARN FIXED-TERM - * ========================================================================================================================== - */ +accepted: string; // "true" | "false" ⋮---- -export interface FixedTermLadderApr { - apr: string; - left: string; - right: string; +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 FixedTermProductInfo { - pre_redeem: number; - reinvest: number; - redeem_account: number; - min_vip: number; - max_vip: number; -} +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 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 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 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; -} +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 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 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 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; -} +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 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 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 GetEarnFixedTermProductsResponse { - code: number; - message: string; - data: { - list: FixedTermProduct[]; - total: number; - }; - timestamp: number; +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 +⋮---- +business_type: string; // Business Type +create_time: string; // Created time +update_time: string; // Update time +⋮---- +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 GetEarnFixedTermProductsByAssetResponse { - code: number; - message: string; - data: { - list: FixedTermProductSimple[]; - }; - timestamp: number; -} +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 CreateEarnFixedTermLendResponse { - code?: number; - message?: string; - data?: { - order_id?: number; - }; - timestamp?: number; +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 GetEarnFixedTermLendsResponse { - code: number; - message: string; - data: { - list: FixedTermLendOrder[]; - total: number; - }; - timestamp: number; -} +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 CreateEarnFixedTermPreRedeemResponse { - code?: number; - message?: string; - data?: Record; - timestamp?: number; +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 } ⋮---- -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; -} +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 GetEarnFixedTermHistoryResponse { - code?: number; - message?: string; - data?: { - list?: FixedTermHistoryRecord[]; - total?: number; - }; - timestamp?: number; +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 } - -================ -File: src/types/response/otc.ts -================ -/**========================================================================================================================== - * OTC - * ========================================================================================================================== - */ ⋮---- -export interface OTCActionResp { - code: number; - message: string; - timestamp: number; -} +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 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; +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 } ⋮---- -type: string; // BUY (on-ramp) or SELL (off-ramp) -⋮---- -rate_reci: string; // Reciprocal of the exchange rate -⋮---- -order_type: string; // FIAT or STABLE -quote_token: string; // Quote token required when placing an order -⋮---- -export type CreateOTCFiatOrderResp = OTCActionResp; +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 CreateOTCStablecoinOrderResp { - code: number; - message: string; - timestamp: number; +export interface UpdateCrossExPositionsMarginResp { + symbol?: string; + margin?: string; + position_side?: 'NONE' | 'LONG' | 'SHORT'; } + +================ +File: src/types/response/tradfi.ts +================ +/** TradFi API response types */ ⋮---- -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; +export interface TradFiApiResp { + timestamp?: number; + data?: T; + code?: number; + message?: string; + label?: string; } ⋮---- -id: string; // Bank ID (required for order placement) -⋮---- -/** 1 = default bank card, 0 = not default */ -⋮---- -export interface GetOTCBankListResp { - code: number; - message: string; - data: { - lists: OTCBankListItem[]; - }; - timestamp: number; +export interface TradFiListData { + list?: T[]; + total?: number; + total_page?: number; } ⋮---- -export interface CreateOTCBankResp { - code: number; - message: string; - data: { - bank_id: number; - status: number; - }; - 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 OTCBankSupplementChecklistItem { - description: string; - code?: string; - zh?: string; - en?: string; - required?: boolean; +mt5_uid?: number; // Removed from API in v4.106.132; kept optional for compatibility +⋮---- +export interface TradFiCategoryItem { + category_id?: number; + is_favorite?: boolean; + category_name?: string; } ⋮---- -export interface GetOTCBankSupplementChecklistResp { - code: number; - message: string; - data: { - user_type: 'personal' | 'enterprise'; - items: OTCBankSupplementChecklistItem[]; - }; - timestamp?: number; +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 type MarkOTCOrderAsPaidResp = OTCActionResp; +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 CancelOTCOrderResp = OTCActionResp; +export interface TradFiKlineItem { + o?: string; + c?: string; + h?: string; + l?: string; + t?: number; +} ⋮---- -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 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; } ⋮---- -time: string; // Current time -timestamp: number; // Current timestamp +export interface TradFiCreateUserResult { + status?: number; + leverage?: number; + mt5_uid?: string; // Removed from API in v4.106.132; kept optional for compatibility +} ⋮---- -trade_no: string; // Trade number -type: string; // Quote direction buy/sell/all -status: string; // Order Status (includes DISBURSED) +mt5_uid?: string; // Removed from API in v4.106.132; kept optional for compatibility ⋮---- -fiat_currency: string; // Fiat type +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 +} ⋮---- -fiat_amount: string; // Fiat amount -crypto_currency: string; // Stablecoin +mt5_uid?: string; // Removed from API in v4.106.132; kept optional for compatibility ⋮---- -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 TradFiTransactionRecord { + asset?: string; + type?: string; + type_desc?: string; + change?: string; + balance?: string; + time?: number; +} ⋮---- -export interface GetOTCFiatOrderListResp { - code: number; - message: string; - data: { - pn: number; - ps: number; - total_pn: number; - count: number; - list: OTCFiatOrderListItem[]; - }; +export interface TradFiTransactionListData { + total?: number; + total_page?: number; + list?: TradFiTransactionRecord[]; } ⋮---- -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 TradFiCreateOrderResult { + id?: 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 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 GetOTCStablecoinOrderListResp { - code: number; - message: string; - data: { - total: number; - page_size: number; - page_number: number; - total_page: number; - list: OTCStablecoinOrderListItem[]; - }; +export interface TradFiOrderListData { + list?: TradFiOrderItem[]; + timestamp?: number; } ⋮---- -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 +export interface TradFiModifyOrderResult { + order_id?: number; + symbol?: string; + state?: string; + volume?: string; + price?: string; + price_tp?: string; + price_sl?: string; } ⋮---- -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 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; +} ⋮---- -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 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 GetOTCFiatOrderDetailResp { - message: string; - code: number; - data: OTCFiatOrderDetail; +export interface TradFiPositionListData { + list?: TradFiPositionItem[]; + timestamp?: number; } ⋮---- -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; +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 CreateOTCUploadPreUploadData { - file_key?: string; - url?: string; - fields?: CreateOTCUploadPreUploadFields; - expires_in?: 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 CreateOTCUploadPreUploadResp { - code?: number; - message?: string; - timestamp?: number; - data?: CreateOTCUploadPreUploadData; +export interface TradFiSymbolCommissionItem { + category_code?: string; + symbol?: string; + fee_per_lot?: string; } ================ -File: src/types/response/tradfi.ts +File: src/types/response/unified.ts ================ -/** TradFi API response types */ -⋮---- -export interface TradFiApiResp { - timestamp?: number; - data?: T; - code?: number; - message?: string; - label?: string; +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 } ⋮---- -export interface TradFiListData { - list?: T[]; - total?: number; - total_page?: number; -} +mode: 'classic' | 'multi_currency' | 'portfolio' | 'single_currency'; // classic: Classic account; multi_currency: Multi-currency margin; portfolio: Portfolio margin; single_currency: Single-currency margin ⋮---- -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; -} +locked: boolean; // Whether the account is locked; valid in cross-currency/combined margin mode, false in other modes such as single-currency margin ⋮---- -mt5_uid?: number; // Removed from API in v4.106.132; kept optional for compatibility +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 TradFiCategoryItem { - category_id?: number; - is_favorite?: boolean; - category_name?: string; -} +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 ⋮---- -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; -} +is_all_collateral?: boolean; // Whether all currencies are used as margin: true — all as margin, false — not all +⋮---- +use_funding?: boolean; // Whether Earn funds are used as margin ⋮---- -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 UnifiedLoan { + currency: string; + currency_pair: string; + amount: string; + type: 'platform' | 'margin'; + create_time: number; + update_time: number; } ⋮---- -export interface TradFiKlineItem { - o?: string; - c?: string; - h?: string; - l?: string; - t?: 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 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 UnifiedInterestRecord { + currency: string; + currency_pair: string; + actual_rate: string; + interest: string; + status: number; + type: 'platform' | 'margin'; + create_time: number; } ⋮---- -export interface TradFiCreateUserResult { - status?: number; - leverage?: number; - mt5_uid?: string; // Removed from API in v4.106.132; kept optional for compatibility +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; + }[]; } ⋮---- -mt5_uid?: string; // Removed from API in v4.106.132; kept optional for compatibility +export interface UnifiedCurrencyDiscountTiers { + currency: string; + discount_tiers: { + tier: string; + discount: string; + lower_limit: string; + upper_limit: string; + leverage: string; + }[]; +} ⋮---- -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 UserCurrencyLeverageConfig { + current_leverage: string; + min_leverage: string; + max_leverage: string; + debit: string; + available_margin: string; + borrowable: string; + except_leverage_borrowable: string; } ⋮---- -mt5_uid?: string; // Removed from API in v4.106.132; kept optional for compatibility +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 TradFiTransactionRecord { - asset?: string; - type?: string; - type_desc?: string; - change?: string; - balance?: string; - time?: number; +export interface UnifiedHistoryLendingRate { + currency: string; + tier: string; + tier_up_rate: string; + rates: { + time: number; + rate: string; + }[]; } ⋮---- -export interface TradFiTransactionListData { - total?: number; - total_page?: number; - list?: TradFiTransactionRecord[]; +export interface MarginTier { + tier: string; + margin_rate: string; + lower_limit: string; + upper_limit: string; } ⋮---- -export interface TradFiCreateOrderResult { - id?: string; +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 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 UnifiedCollateralCurrenciesResp { + is_success: boolean; } ⋮---- -export interface TradFiOrderListData { - list?: TradFiOrderItem[]; - timestamp?: number; +export interface UnifiedQuickRepayDebtItem { + currency?: string; + debt_amount?: string; + estimated_usd?: string; + borrowed?: string; + neg_balance?: string; } ⋮---- -export interface TradFiModifyOrderResult { - order_id?: number; - symbol?: string; - state?: string; - volume?: string; - price?: string; - price_tp?: string; - price_sl?: string; +export interface UnifiedQuickRepayAvailableItem { + currency?: string; + available?: string; + estimated_usd?: string; } ⋮---- -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; +export interface QuickEstimatedRepayment { + debt_currencies?: UnifiedQuickRepayDebtItem[]; + available_currencies?: UnifiedQuickRepayAvailableItem[]; } ⋮---- -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 QuickRepayRepaidInfo { + currency: string; + repaid: string; + left: string; } ⋮---- -export interface TradFiPositionListData { - list?: TradFiPositionItem[]; - timestamp?: number; +export interface QuickRepayUsedInfo { + currency: string; + used: 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 QuickRepaymentResp { + order_id: string; + repaid_infos: QuickRepayRepaidInfo[]; + used_infos: QuickRepayUsedInfo[]; } ⋮---- -/** 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; +/** GET/POST /unified/delta_neutral — v4.106.97 */ +export interface DeltaNeutralEnabled { + enabled: boolean; } ⋮---- -export interface TradFiSymbolCommissionItem { - category_code?: string; - symbol?: string; - fee_per_lot?: string; +/** POST /unified/leverage/user_setting failed currency entry */ +export interface LeverageFailedCurrency { + currency: string; + reason: string; } ================ @@ -12130,1329 +12170,1360 @@ File: src/index.ts // Shared Types ================ -File: src/types/request/futures.ts +File: src/lib/BaseRestClient.ts ================ -/**========================================================================================================================== - * FUTURES - * ========================================================================================================================== - */ -⋮---- -export type FuturesSettle = 'btc' | 'usdt' | 'usd' | 'usd1'; -⋮---- -export interface GetFuturesOrderBookReq { - settle: FuturesSettle; - contract: string; - interval?: string; - limit?: number; - with_id?: boolean; -} -⋮---- -export interface GetFuturesTradesReq { - settle: FuturesSettle; - contract: string; - limit?: number; - offset?: number; - last_id?: string; - from?: number; - to?: number; -} -⋮---- -export interface GetFuturesCandlesReq { - settle: FuturesSettle; - contract: string; - from?: number; - to?: number; - limit?: number; - interval?: string; -} +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'; ⋮---- -export interface GetFuturesStatsReq { - settle: FuturesSettle; - contract: string; - from?: number; - interval?: string; - limit?: number; -} +import { neverGuard } from './misc-util.js'; +import { + CHANNEL_ID, + getRestBaseUrl, + RestClientOptions, + serializeParams, +} from './requestUtils.js'; +import { + checkWebCryptoAPISupported, + hashMessage, + SignAlgorithm, + SignEncodeMethod, + signMessage, +} from './webCryptoAPI.js'; ⋮---- -export interface GetFundingRatesReq { - settle: FuturesSettle; - contract: string; - limit?: number; - from?: number; - to?: number; -} +/** + * Used to switch how authentication/requests work under the hood + */ ⋮---- -export interface BatchFundingRatesReq { - settle: 'btc' | 'usdt' | 'usd1'; - contracts: string[]; -} +export type RestClientType = + (typeof REST_CLIENT_TYPE_ENUM)[keyof typeof REST_CLIENT_TYPE_ENUM]; ⋮---- -export interface GetLiquidationHistoryReq { - settle: FuturesSettle; - contract?: string; - from?: number; - to?: number; - limit?: number; +interface SignedRequest { + originalParams: T; + paramsWithSign?: T & { sign: string }; + serializedParams: string; + sign: string; + queryParamsWithSign: string; + timestamp: number; + recvWindow: number; } ⋮---- -export interface GetRiskLimitTiersReq { - settle: FuturesSettle; - contract: string; - limit?: number; - offset?: number; +interface UnsignedRequest { + originalParams: T; + paramsWithSign: T; } ⋮---- -export interface GetRiskLimitTableReq { - settle: FuturesSettle; - table_id: string; -} +type SignMethod = 'gateV4'; ⋮---- -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'; -} +/** + * 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 GetFuturesADLRiskStatesReq { - settle: 'btc' | 'usdt' | 'usd1'; -} +/** multipart/form-data body; mutually exclusive with `body` */ ⋮---- -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 -} +/** + * Enables: + * - Detailed request/response logging + * - Full request dump in any exceptions thrown from API responses + */ ⋮---- -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 +// request: { +// url: response.config.url, +// method: response.config.method, +// data: response.config.data, +// headers: response.config.headers, +// }, ⋮---- -position_side?: string; // v4.105.3: Add position_side parameter for hedge mode support -hedge_mode?: boolean; // v4.104.3: Add hedge_mode parameter +/** + * Impure, mutates params to remove any values that have a key but are undefined. + */ +function deleteUndefinedValues(params?: any): void ⋮---- -export interface UpdateDualModePositionMarginReq { - settle: FuturesSettle; - contract: string; - change: string; - dual_side: 'dual_long' | 'dual_short'; -} +export abstract class BaseRestClient ⋮---- -export interface UpdateDualModePositionLeverageReq { - settle: FuturesSettle; - contract: string; - leverage: string; - cross_leverage_limit?: string; -} +/** Defines the client type (affecting how requests & signatures behave) */ +abstract getClientType(): RestClientType; ⋮---- -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'; -} +/** + * 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 = {}, +) ⋮---- -export interface GetFuturesOrdersReq { - settle: FuturesSettle; - contract?: string; - status: string; - limit?: number; - offset?: number; - last_id?: string; -} +/** Throw errors if any request params are empty */ ⋮---- -export interface DeleteAllFuturesOrdersReq { - xGateExptime?: number; - settle: FuturesSettle; - contract: string; - side?: string; - action_mode?: 'ACK' | 'RESULT' | 'FULL'; -} +/** in ms == 5 minutes by default */ ⋮---- -export interface GetFuturesOrdersByTimeRangeReq { - settle: FuturesSettle; - contract?: string; - from?: number; - to?: number; - limit?: number; - offset?: number; -} +/** 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 UpdateFuturesOrderReq { - xGateExptime?: number; - settle: FuturesSettle; - order_id: string; - size?: number; - price?: string; - amend_text?: string; -} +// 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. ⋮---- -export interface GetFuturesTradingHistoryReq { - settle: FuturesSettle; - contract?: string; - order?: number; - limit?: number; - offset?: number; - last_id?: string; -} +// Extract existing https agent parameters, if provided, to prevent the keepAlive flag from overwriting an existing https agent completely ⋮---- -export interface GetFuturesTradingHistoryByTimeRangeReq { - settle: FuturesSettle; - contract?: string; - from?: number; - to?: number; - limit?: number; - offset?: number; - role?: 'maker' | 'taker'; -} +// 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 GetFuturesPositionHistoryReq { - settle: FuturesSettle; - contract?: string; - limit?: number; - offset?: number; - from?: number; - to?: number; - side?: 'long' | 'short'; - pnl?: string; -} +// Check Web Crypto API support when credentials are provided and no custom sign function is used ⋮---- -export interface GetFuturesLiquidationHistoryReq { - settle: FuturesSettle; - contract?: string; - limit?: number; - at?: number; -} +// Throw if one of the 3 values is missing, but at least one of them is set ⋮---- -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; - }; - order_type?: - | 'close-long-order' - | 'close-short-order' - | 'close-long-position' - | 'close-short-position' - | 'plan-close-long-position' - | 'plan-close-short-position'; - settle: FuturesSettle; -} +/** + * Timestamp used to sign the request. Override this method to implement your own timestamp/sync mechanism + */ +getSignTimestampMs(): number ⋮---- -/** Decimal contract size; if both `size` and `amount` are set, `amount` takes precedence */ +protected get(endpoint: string, params?: object) ⋮---- -price: string; // Required: Order price. Set to 0 to use market price +// GET only supports params in the query string ⋮---- -price: string; // Required: Price value for price trigger -rule: 1 | 2; // Required: Price Condition Type (1: >=, 2: <=) +protected post(endpoint: string, params?: ParamsInQueryBodyOrHeader) ⋮---- -export interface GetFuturesAutoOrdersReq { - settle: FuturesSettle; - status: 'open' | 'finished'; - contract?: string; - limit?: number; - offset?: number; -} +protected getPrivate(endpoint: string, params?: object) ⋮---- -/** - * 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 -} +// GET only supports params in the query string ⋮---- -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 +protected postPrivate(endpoint: string, params?: ParamsInQueryBodyOrHeader) ⋮---- -// 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; -} +/** POST private endpoint with multipart/form-data (empty body hash for signing) */ +protected postPrivateMultipart( + endpoint: string, + formData: FormData, + query?: object, +) ⋮---- -// v4.104.6: New GET /futures/{settle}/insurance endpoint request -export interface GetFuturesInsuranceReq { - settle: FuturesSettle; - limit?: number; -} +protected deletePrivate( + endpoint: string, + params?: ParamsInQueryBodyOrHeader, +) ⋮---- -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 -} +protected putPrivate(endpoint: string, params?: ParamsInQueryBodyOrHeader) ⋮---- -/** Same semantics as `size` (decimal contract size) */ +// protected patchPrivate(endpoint: string, params?: any) { +protected patchPrivate(endpoint: string, params?: ParamsInQueryBodyOrHeader) ⋮---- -/** When fully closing in single-position mode, set true */ +/** + * @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 ⋮---- -price_type?: 0 | 1 | 2; // 0 - Latest trade price, 1 - Mark price, 2 - Index price -auto_size?: string; // Not required in single position mode +// Sanity check to make sure it's only ever prefixed by one forward slash ⋮---- -/** 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'; -} +// Build a request and handle signature process ⋮---- -/** 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; -} +// Dispatch request ⋮---- -export interface TerminateTrailOrderReq { - settle: 'btc' | 'usdt'; - id?: number; - text?: string; -} +// See: https://www.gate.io/docs/developers/apiv4/en/#return-format ⋮---- -export interface BatchTerminateTrailOrdersReq { - settle: 'btc' | 'usdt'; - contract?: string; - related_position?: 1 | 2; -} +// Throw API rejections by parsing the response code from the body ⋮---- -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; -} +/** + * @private generic handler to parse request exceptions + */ +parseException(e: any, request: AxiosRequestConfig): unknown ⋮---- -export interface GetTrailOrderDetailReq { - settle: 'btc' | 'usdt'; - id: number; -} +// Something happened in setting up the request that triggered an error ⋮---- -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; -} +// request made but no response received ⋮---- -export interface GetTrailOrderChangeLogReq { - settle: 'btc' | 'usdt'; - id: number; - page_num?: number; - page_size?: number; -} +// The request was made and the server responded with a status code +// that falls out of the range of 2xx ⋮---- -/** 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; -} +// console.error('err: ', response?.data); ⋮---- -export interface StopChaseOrderReq { - settle: FuturesSettle; - id?: string; - text?: string; -} +// Prevent credentials from leaking into error messages ⋮---- -export interface StopAllChaseOrdersReq { - settle: FuturesSettle; - contract?: string; - pos_margin_mode?: 'isolated' | 'cross' | 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 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; -} +const timestamp = +(this.getSignTimestampMs() / 1000).toFixed(0); // in seconds ⋮---- -/** 1 ORDER_SORT_CREATED_AT, 2 ORDER_SORT_FINISHED_AT */ +// recvWindow: this.options.recvWindow, ⋮---- -export interface GetChaseOrderDetailReq { - settle: FuturesSettle; - id: string; -} +// It's possible to override the recv window on a per rquest level +⋮---- +// console.log('sign params: ', { +// requestBodyToHash, +// paramsStr: toSign, +// url: this.baseUrl, +// urlPath: this.baseUrlPath, +// }); +⋮---- +private async signMessage( + paramsStr: string, + secret: string, + method: 'hex' | 'base64', + algorithm: SignAlgorithm, +): Promise +⋮---- +private async prepareSignParams< + TParams extends ParamsInQueryBodyOrHeader | undefined, + >( + method: Method, + endpoint: string, + signMethod: SignMethod, + params?: TParams, + isPublicApi?: true, + ): Promise>; +⋮---- +private async prepareSignParams< + TParams extends ParamsInQueryBodyOrHeader | undefined, + >( + method: Method, + endpoint: string, + signMethod: SignMethod, + params?: TParams, + isPublicApi?: false | undefined, + ): Promise>; +⋮---- +private async prepareSignParams< + TParams extends ParamsInQueryBodyOrHeader | undefined, + >( + method: Method, + endpoint: string, + signMethod: SignMethod, + params?: TParams, + isPublicApi?: boolean, +) +⋮---- +/** Returns an axios request object. Handles signing process automatically if this is a private API call */ +private async buildRequest( + method: Method, + endpoint: string, + url: string, + params?: ParamsInQueryBodyOrHeader, + isPublicApi?: boolean, +): Promise ================ -File: src/types/response/spot.ts +File: src/types/response/otc.ts ================ /**========================================================================================================================== - * SPOT + * OTC * ========================================================================================================================== */ ⋮---- -/** Limit-order take-profit / stop-loss on order responses (not re-exported; use request types for submits) */ -interface SpotOrderTPSL { - trigger_price: string; - order_price: string; +export interface OTCActionResp { + code: number; + message: string; + timestamp: number; } ⋮---- -/** `{}` cancels TP/SL; `null` leaves unchanged */ -type PatchSpotOrderTPSL = SpotOrderTPSL | {} | null; -⋮---- -export interface SpotCurrencyChain { - name: string; - addr?: string; - withdraw_disabled: boolean; - withdraw_delayed: boolean; - deposit_disabled: boolean; +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; } ⋮---- -export interface SpotCurrency { - currency: string; - name: string; - delisted: boolean; - withdraw_disabled: boolean; - withdraw_delayed: boolean; - deposit_disabled: boolean; - trade_disabled: boolean; - chain: string; - chains: SpotCurrencyChain[]; - /** Asset categories (e.g. stocks, metals, indices, forex, commodities). */ - category?: string[]; -} +type: string; // BUY (on-ramp) or SELL (off-ramp) ⋮---- -/** Asset categories (e.g. stocks, metals, indices, forex, commodities). */ +rate_reci: string; // Reciprocal of the exchange rate ⋮---- -export interface SpotTicker { - currency_pair: string; - last: string; - lowest_ask: string; - lowest_size: string; - highest_bid: string; - highest_size: string; - change_percentage: string; - change_utc0: string; - change_utc8: string; - base_volume: string; - quote_volume: string; - high_24h: string; - low_24h: string; - etf_net_value: string; - etf_pre_net_value: string | null; - etf_pre_timestamp: number | null; - etf_leverage: string | null; -} +order_type: string; // FIAT or STABLE +quote_token: string; // Quote token required when placing an order ⋮---- -export interface SpotOrderBook { - id?: number; - current: number; - update: number; - asks: [string, string][]; - bids: [string, string][]; +export type CreateOTCFiatOrderResp = OTCActionResp; +⋮---- +export interface CreateOTCStablecoinOrderResp { + code: number; + message: string; + timestamp: number; } ⋮---- -export interface SpotTrade { - id: string; - create_time: string; - create_time_ms: string; - currency_pair: string; - side: 'buy' | 'sell'; - role: 'taker' | 'maker'; - amount: string; - price: string; - order_id: string; - fee: string; - fee_currency: string; - point_fee: string; - gt_fee: string; - amend_text: string; - sequence_id: string; - text: string; - trade_quote?: string; +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; } ⋮---- -export type SpotCandle = [ - string, // Unix timestamp with second precision - string, // Trading volume in quote currency - string, // Closing price - string, // Highest price - string, // Lowest price - string, // Opening price - string, // Trading volume in base currency - boolean, // Whether the window is closed -]; +id: string; // Bank ID (required for order placement) ⋮---- -string, // Unix timestamp with second precision -string, // Trading volume in quote currency -string, // Closing price -string, // Highest price -string, // Lowest price -string, // Opening price -string, // Trading volume in base currency -boolean, // Whether the window is closed +/** 1 = default bank card, 0 = not default */ ⋮---- -export interface SpotFeeRates { - user_id: number; - taker_fee: string; // For spot trading - maker_fee: string; // For spot trading - gt_discount: boolean; - gt_taker_fee: string; - gt_maker_fee: string; - loan_fee: string; - point_type: string; - currency_pair: string; - debit_fee: number; +export interface GetOTCBankListResp { + code: number; + message: string; + data: { + lists: OTCBankListItem[]; + }; + timestamp: number; } ⋮---- -taker_fee: string; // For spot trading -maker_fee: string; // For spot trading -⋮---- -export interface SpotAccount { - currency: string; - available: string; - locked: string; - update_id: number; - refresh_time: number; - last_update_time?: number; - trading_fee_rate?: string; +export interface CreateOTCBankResp { + code: number; + message: string; + data: { + bank_id: number; + status: number; + }; + timestamp?: number; } ⋮---- -export interface SpotAccountBook { - id: string; - time: number; - currency: string; - change: string; - balance: string; - type: string; - code: string; - text: string; +export interface OTCBankSupplementChecklistItem { + description: string; + code?: string; + zh?: string; + en?: string; + required?: boolean; } ⋮---- -export interface SubmitSpotBatchOrdersResp { - order_id: string; - amend_text: string; - text: string; - succeeded: boolean; - label: string; +export interface GetOTCBankSupplementChecklistResp { + code: number; message: string; - id: string; - create_time: string; - update_time: string; - create_time_ms: number; - update_time_ms: number; - status: 'open' | 'closed' | 'cancelled'; - currency_pair: string; - type: 'limit' | 'market'; - account: 'spot' | 'margin' | 'cross_margin' | 'unified'; - side: 'buy' | 'sell'; - amount: string; - price: string; - time_in_force: 'gtc' | 'ioc' | 'poc' | 'fok'; - iceberg: string; - auto_repay: boolean; - left: string; - filled_amount: string; - fill_price: string; - filled_total: string; - avg_deal_price: string; - fee: string; - fee_currency: string; - point_fee: string; - gt_fee: string; - gt_discount: boolean; - rebated_fee: string; - rebated_fee_currency: string; - stp_id: number; - stp_act: 'cn' | 'co' | 'cb' | '-'; - /** - * Final state; **ioc** / **poc** reflect unfilled remainder cancelled by TIF (IOC vs post-only / maker). - */ - finish_as: 'open' | 'filled' | 'cancelled' | 'ioc' | 'poc' | 'stp'; + data: { + user_type: 'personal' | 'enterprise'; + items: OTCBankSupplementChecklistItem[]; + }; + timestamp?: number; } ⋮---- -/** - * Final state; **ioc** / **poc** reflect unfilled remainder cancelled by TIF (IOC vs post-only / maker). - */ +export type MarkOTCOrderAsPaidResp = OTCActionResp; ⋮---- -export interface SpotOrder { - id?: string; - text?: string; - amend_text?: string; - create_time?: string; - update_time?: string; - create_time_ms?: number; - update_time_ms?: number; - status?: 'open' | 'closed' | 'cancelled'; - currency_pair: string; - type?: 'limit' | 'market'; - account?: 'spot' | 'margin' | 'cross_margin' | 'unified'; - side: 'buy' | 'sell'; - amount: string; - price?: string; - time_in_force?: 'gtc' | 'ioc' | 'poc' | 'fok'; - iceberg?: string; - auto_borrow?: boolean; - auto_repay?: boolean; - left?: string; - filled_amount?: string; - fill_price?: 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?: 'cn' | 'co' | 'cb' | '-'; - /** - * Final state; **ioc** / **poc** reflect unfilled remainder cancelled by TIF (IOC vs post-only / maker). - */ - finish_as?: 'open' | 'filled' | 'cancelled' | 'ioc' | 'poc' | 'stp'; - action_mode?: 'ACK' | 'RESULT' | 'FULL'; - stop_loss?: PatchSpotOrderTPSL; - stop_profit?: PatchSpotOrderTPSL; - trade_quote?: string; +export type CancelOTCOrderResp = OTCActionResp; +⋮---- +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 } ⋮---- -/** - * Final state; **ioc** / **poc** reflect unfilled remainder cancelled by TIF (IOC vs post-only / maker). - */ +time: string; // Current time +timestamp: number; // Current timestamp ⋮---- -export interface SpotInsuranceHistory { - currency: string; - balance: string; - time: number; -} +trade_no: string; // Trade number +type: string; // Quote direction buy/sell/all +status: string; // Order Status (includes DISBURSED) ⋮---- -export interface SpotPriceTriggeredOrder { - trigger: { - price: string; - rule: '>=' | '<='; - expiration?: number; - }; - put: { - type?: 'limit' | 'market'; - side: 'buy' | 'sell'; - price: string; - amount: string; - account: 'normal' | 'margin' | 'cross_margin'; - time_in_force: 'gtc' | 'ioc'; - text?: string; +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; + /** v4.106.158: was `list` */ + lists: OTCFiatOrderListItem[]; }; - id?: number; - user?: number; - market: string; - ctime?: number; - ftime?: number; - fired_order_id?: number; - status?: 'open' | 'cancelled' | 'finish' | 'failed' | 'expired'; - reason?: string; } ⋮---- -export interface GetSpotOpenOrdersResp { - currency_pair: string; - total: number; - orders: SpotOrder[]; +/** v4.106.158: was `list` */ +⋮---- +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 DeleteSpotBatchOrdersResp { - currency_pair: string; - id: string; - succeeded: boolean; - label: 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; - account: string; - text: string; + data: { + total: number; + page_size: number; + page_number: number; + total_page: number; + /** v4.106.158: was `list` */ + lists: OTCStablecoinOrderListItem[]; + }; } ⋮---- -export interface SpotHistoricTradeRecord { - id: string; - create_time: string; - create_time_ms: string; - currency_pair: string; - side: 'buy' | 'sell'; - role: 'taker' | 'maker'; - amount: string; - price: string; - order_id: string; - fee: string; - fee_currency: string; - point_fee: string; - gt_fee: string; - amend_text: string; - sequence_id: string; - text: string; - deal?: string; // v4.105.29: Total Executed Value - trade_quote?: string; +/** v4.106.158: was `list` */ +⋮---- +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 } ⋮---- -deal?: string; // v4.105.29: Total Executed Value +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 type SpotPovOrderStatus = - | 'CREATED' - | 'CANCELING' - | 'RUNNING' - | 'COMPLETED' - | 'EXPIRED' - | 'TERMINATED'; +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 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 +export interface GetOTCFiatOrderDetailResp { + message: string; + code: number; + data: OTCFiatOrderDetail; } ⋮---- -mode: 'classic' | 'multi_currency' | 'portfolio' | 'single_currency'; // classic: Classic account; multi_currency: Multi-currency margin; portfolio: Portfolio margin; single_currency: Single-currency margin -⋮---- -locked: boolean; // Whether the account is locked; valid in cross-currency/combined margin mode, false in other modes such as single-currency margin +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; +} ⋮---- -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 CreateOTCUploadPreUploadData { + file_key?: string; + url?: string; + fields?: CreateOTCUploadPreUploadFields; + expires_in?: 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 +export interface CreateOTCUploadPreUploadResp { + code?: number; + message?: string; + timestamp?: number; + data?: CreateOTCUploadPreUploadData; +} + +================ +File: src/types/response/spot.ts +================ +/**========================================================================================================================== + * SPOT + * ========================================================================================================================== + */ ⋮---- -is_all_collateral?: boolean; // Whether all currencies are used as margin: true — all as margin, false — not all +/** Limit-order take-profit / stop-loss on order responses (not re-exported; use request types for submits) */ +interface SpotOrderTPSL { + trigger_price: string; + order_price: string; +} ⋮---- -use_funding?: boolean; // Whether Earn funds are used as margin +/** `{}` cancels TP/SL; `null` leaves unchanged */ +type PatchSpotOrderTPSL = SpotOrderTPSL | {} | null; ⋮---- -export interface UnifiedLoan { - currency: string; - currency_pair: string; - amount: string; - type: 'platform' | 'margin'; - create_time: number; - update_time: number; +export interface SpotCurrencyChain { + name: string; + addr?: string; + withdraw_disabled: boolean; + withdraw_delayed: boolean; + deposit_disabled: boolean; } ⋮---- -export interface UnifiedLoanRecord { - id: number; - type: 'borrow' | 'repay'; - repayment_type: 'none' | 'manual_repay' | 'auto_repay' | 'cancel_auto_repay'; - currency_pair: string; +export interface SpotCurrency { currency: string; - amount: string; - create_time: number; - borrow_type: string; + name: string; + delisted: boolean; + withdraw_disabled: boolean; + withdraw_delayed: boolean; + deposit_disabled: boolean; + trade_disabled: boolean; + chain: string; + chains: SpotCurrencyChain[]; + /** Asset categories (e.g. stocks, metals, indices, forex, commodities). */ + category?: string[]; } -export interface UnifiedInterestRecord { - currency: string; +⋮---- +/** Asset categories (e.g. stocks, metals, indices, forex, commodities). */ +⋮---- +export interface SpotTicker { currency_pair: string; - actual_rate: string; - interest: string; - status: number; - type: 'platform' | 'margin'; - create_time: number; + last: string; + lowest_ask: string; + lowest_size: string; + highest_bid: string; + highest_size: string; + change_percentage: string; + change_utc0: string; + change_utc8: string; + base_volume: string; + quote_volume: string; + high_24h: string; + low_24h: string; + etf_net_value: string; + etf_pre_net_value: string | null; + etf_pre_timestamp: number | null; + etf_leverage: string | null; } ⋮---- -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; - }[]; +export interface SpotOrderBook { + id?: number; + current: number; + update: number; + asks: [string, string][]; + bids: [string, string][]; } ⋮---- -export interface UnifiedCurrencyDiscountTiers { - currency: string; - discount_tiers: { - tier: string; - discount: string; - lower_limit: string; - upper_limit: string; - leverage: string; - }[]; +export interface SpotTrade { + id: string; + create_time: string; + create_time_ms: string; + currency_pair: string; + side: 'buy' | 'sell'; + role: 'taker' | 'maker'; + amount: string; + price: string; + order_id: string; + fee: string; + fee_currency: string; + point_fee: string; + gt_fee: string; + amend_text: string; + sequence_id: string; + text: string; + trade_quote?: string; } ⋮---- -export interface UserCurrencyLeverageConfig { - current_leverage: string; - min_leverage: string; - max_leverage: string; - debit: string; - available_margin: string; - borrowable: string; - except_leverage_borrowable: string; -} +export type SpotCandle = [ + string, // Unix timestamp with second precision + string, // Trading volume in quote currency + string, // Closing price + string, // Highest price + string, // Lowest price + string, // Opening price + string, // Trading volume in base currency + boolean, // Whether the window is closed +]; ⋮---- -export interface UnifiedLoanCurrency { - name: string; - prec: string; - min_borrow_amount: string; - user_max_borrow_amount: string; - total_max_borrow_amount: string; - loan_status: string; +string, // Unix timestamp with second precision +string, // Trading volume in quote currency +string, // Closing price +string, // Highest price +string, // Lowest price +string, // Opening price +string, // Trading volume in base currency +boolean, // Whether the window is closed +⋮---- +export interface SpotFeeRates { + user_id: number; + taker_fee: string; // For spot trading + maker_fee: string; // For spot trading + gt_discount: boolean; + gt_taker_fee: string; + gt_maker_fee: string; + loan_fee: string; + point_type: string; + currency_pair: string; + debit_fee: number; } ⋮---- -export interface UnifiedHistoryLendingRate { +taker_fee: string; // For spot trading +maker_fee: string; // For spot trading +⋮---- +export interface SpotAccount { currency: string; - tier: string; - tier_up_rate: string; - rates: { - time: number; - rate: string; - }[]; + available: string; + locked: string; + update_id: number; + refresh_time: number; + last_update_time?: number; + trading_fee_rate?: string; } ⋮---- -export interface MarginTier { - tier: string; - margin_rate: string; - lower_limit: string; - upper_limit: string; +export interface SpotAccountBook { + id: string; + time: number; + currency: string; + change: string; + balance: string; + type: string; + code: string; + text: string; } ⋮---- -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 SubmitSpotBatchOrdersResp { + order_id: string; + amend_text: string; + text: string; + succeeded: boolean; + label: string; + message: string; + id: string; + create_time: string; + update_time: string; + create_time_ms: number; + update_time_ms: number; + status: 'open' | 'closed' | 'cancelled'; + currency_pair: string; + type: 'limit' | 'market'; + account: 'spot' | 'margin' | 'cross_margin' | 'unified'; + side: 'buy' | 'sell'; + amount: string; + price: string; + time_in_force: 'gtc' | 'ioc' | 'poc' | 'fok'; + iceberg: string; + auto_repay: boolean; + left: string; + filled_amount: string; + fill_price: string; + filled_total: string; + avg_deal_price: string; + fee: string; + fee_currency: string; + point_fee: string; + gt_fee: string; + gt_discount: boolean; + rebated_fee: string; + rebated_fee_currency: string; + stp_id: number; + stp_act: 'cn' | 'co' | 'cb' | '-'; + /** + * Final state; **ioc** / **poc** reflect unfilled remainder cancelled by TIF (IOC vs post-only / maker). + */ + finish_as: 'open' | 'filled' | 'cancelled' | 'ioc' | 'poc' | 'stp'; } ⋮---- -export interface UnifiedCollateralCurrenciesResp { - is_success: boolean; -} +/** + * Final state; **ioc** / **poc** reflect unfilled remainder cancelled by TIF (IOC vs post-only / maker). + */ ⋮---- -export interface UnifiedQuickRepayDebtItem { - currency?: string; - debt_amount?: string; - estimated_usd?: string; - borrowed?: string; - neg_balance?: string; +export interface SpotOrder { + id?: string; + text?: string; + amend_text?: string; + create_time?: string; + update_time?: string; + create_time_ms?: number; + update_time_ms?: number; + status?: 'open' | 'closed' | 'cancelled'; + currency_pair: string; + type?: 'limit' | 'market'; + account?: 'spot' | 'margin' | 'cross_margin' | 'unified'; + side: 'buy' | 'sell'; + amount: string; + price?: string; + time_in_force?: 'gtc' | 'ioc' | 'poc' | 'fok'; + iceberg?: string; + auto_borrow?: boolean; + auto_repay?: boolean; + left?: string; + filled_amount?: string; + fill_price?: 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?: 'cn' | 'co' | 'cb' | '-'; + /** + * Final state; **ioc** / **poc** reflect unfilled remainder cancelled by TIF (IOC vs post-only / maker). + */ + finish_as?: 'open' | 'filled' | 'cancelled' | 'ioc' | 'poc' | 'stp'; + action_mode?: 'ACK' | 'RESULT' | 'FULL'; + stop_loss?: PatchSpotOrderTPSL; + stop_profit?: PatchSpotOrderTPSL; + trade_quote?: string; } ⋮---- -export interface UnifiedQuickRepayAvailableItem { - currency?: string; - available?: string; - estimated_usd?: string; +/** + * Final state; **ioc** / **poc** reflect unfilled remainder cancelled by TIF (IOC vs post-only / maker). + */ +⋮---- +export interface SpotInsuranceHistory { + currency: string; + balance: string; + time: number; } ⋮---- -export interface QuickEstimatedRepayment { - debt_currencies?: UnifiedQuickRepayDebtItem[]; - available_currencies?: UnifiedQuickRepayAvailableItem[]; +export interface SpotPriceTriggeredOrder { + trigger: { + price: string; + rule: '>=' | '<='; + expiration?: number; + }; + put: { + type?: 'limit' | 'market'; + side: 'buy' | 'sell'; + price: string; + amount: string; + account: 'normal' | 'margin' | 'cross_margin'; + time_in_force: 'gtc' | 'ioc'; + text?: string; + }; + id?: number; + user?: number; + market: string; + ctime?: number; + ftime?: number; + fired_order_id?: number; + status?: 'open' | 'cancelled' | 'finish' | 'failed' | 'expired'; + reason?: string; } ⋮---- -export interface QuickRepayRepaidInfo { - currency: string; - repaid: string; - left: string; +export interface GetSpotOpenOrdersResp { + currency_pair: string; + total: number; + orders: SpotOrder[]; } ⋮---- -export interface QuickRepayUsedInfo { - currency: string; - used: string; +export interface DeleteSpotBatchOrdersResp { + currency_pair: string; + id: string; + succeeded: boolean; + label: string; + message: string; + account: string; + text: string; } ⋮---- -export interface QuickRepaymentResp { +export interface SpotHistoricTradeRecord { + id: string; + create_time: string; + create_time_ms: string; + currency_pair: string; + side: 'buy' | 'sell'; + role: 'taker' | 'maker'; + amount: string; + price: string; order_id: string; - repaid_infos: QuickRepayRepaidInfo[]; - used_infos: QuickRepayUsedInfo[]; + fee: string; + fee_currency: string; + point_fee: string; + gt_fee: string; + amend_text: string; + sequence_id: string; + text: string; + deal?: string; // v4.105.29: Total Executed Value + trade_quote?: string; } ⋮---- -/** GET/POST /unified/delta_neutral — v4.106.97 */ -export interface DeltaNeutralEnabled { - enabled: boolean; -} +deal?: string; // v4.105.29: Total Executed Value ⋮---- -/** POST /unified/leverage/user_setting failed currency entry */ -export interface LeverageFailedCurrency { - currency: string; - reason: string; +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 +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'; +/**========================================================================================================================== + * FUTURES + * ========================================================================================================================== + */ ⋮---- -import { neverGuard } from './misc-util.js'; -import { - CHANNEL_ID, - getRestBaseUrl, - RestClientOptions, - serializeParams, -} from './requestUtils.js'; -import { - checkWebCryptoAPISupported, - hashMessage, - SignAlgorithm, - SignEncodeMethod, - signMessage, -} from './webCryptoAPI.js'; +export type FuturesSettle = 'btc' | 'usdt' | 'usd' | 'usd1'; ⋮---- -/** - * Used to switch how authentication/requests work under the hood - */ +export interface GetFuturesOrderBookReq { + settle: FuturesSettle; + contract: string; + interval?: string; + limit?: number; + with_id?: boolean; +} ⋮---- -export type RestClientType = - (typeof REST_CLIENT_TYPE_ENUM)[keyof typeof REST_CLIENT_TYPE_ENUM]; +export interface GetFuturesTradesReq { + settle: FuturesSettle; + contract: string; + limit?: number; + offset?: number; + last_id?: string; + from?: number; + to?: number; +} ⋮---- -interface SignedRequest { - originalParams: T; - paramsWithSign?: T & { sign: string }; - serializedParams: string; - sign: string; - queryParamsWithSign: string; - timestamp: number; - recvWindow: number; +export interface GetFuturesCandlesReq { + settle: FuturesSettle; + contract: string; + from?: number; + to?: number; + limit?: number; + interval?: string; +} +⋮---- +export interface GetFuturesStatsReq { + settle: FuturesSettle; + contract: string; + from?: number; + interval?: string; + limit?: number; } ⋮---- -interface UnsignedRequest { - originalParams: T; - paramsWithSign: T; +export interface GetFundingRatesReq { + settle: FuturesSettle; + contract: string; + limit?: number; + from?: number; + to?: number; } ⋮---- -type SignMethod = 'gateV4'; +export interface BatchFundingRatesReq { + settle: 'btc' | 'usdt' | 'usd1'; + contracts: 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 GetLiquidationHistoryReq { + settle: FuturesSettle; + contract?: string; + from?: number; + to?: number; + limit?: number; +} ⋮---- -/** multipart/form-data body; mutually exclusive with `body` */ +export interface GetRiskLimitTiersReq { + settle: FuturesSettle; + contract: string; + limit?: number; + offset?: number; +} ⋮---- -/** - * Enables: - * - Detailed request/response logging - * - Full request dump in any exceptions thrown from API responses - */ +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, -// }, +/** Change types for `GET /futures/{settle}/account_book`. */ +export type FuturesAccountBookType = + | 'dnw' + | 'pnl' + | 'fee' + | 'refr' + | 'fund' + | 'point_dnw' + | 'point_fee' + | 'point_refr' + | 'bonus_offset' + | 'dividend'; // v4.106.147: dividend payout ⋮---- -/** - * Impure, mutates params to remove any values that have a key but are undefined. - */ -function deleteUndefinedValues(params?: any): void +| 'dividend'; // v4.106.147: dividend payout ⋮---- -export abstract class BaseRestClient +export interface GetFuturesAccountBookReq { + settle: FuturesSettle; + contract?: string; + limit?: number; + offset?: number; + from?: number; + to?: number; + type?: FuturesAccountBookType; +} ⋮---- -/** Defines the client type (affecting how requests & signatures behave) */ -abstract getClientType(): RestClientType; +export interface GetFuturesADLRiskStatesReq { + settle: 'btc' | 'usdt' | 'usd1'; +} ⋮---- -/** - * 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 = {}, -) +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 +} ⋮---- -/** Throw errors if any request params are empty */ +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 ⋮---- -/** in ms == 5 minutes by default */ +position_side?: string; // v4.105.3: Add position_side parameter for hedge mode support +hedge_mode?: boolean; // v4.104.3: Add hedge_mode parameter ⋮---- -/** 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 UpdateDualModePositionMarginReq { + settle: FuturesSettle; + contract: string; + change: string; + dual_side: 'dual_long' | 'dual_short'; +} ⋮---- -// 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. +export interface UpdateDualModePositionLeverageReq { + settle: FuturesSettle; + contract: string; + leverage: string; + cross_leverage_limit?: string; +} ⋮---- -// Extract existing https agent parameters, if provided, to prevent the keepAlive flag from overwriting an existing https agent completely +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; + /** BBO price type for the take-profit leg */ + tpsl_tp_bbo_type?: string; + /** BBO price type for the stop-loss leg */ + tpsl_sl_bbo_type?: string; + pos_margin_mode?: 'isolated' | 'cross'; +} ⋮---- -// For more advanced configuration, raise an issue on GitHub or use the "networkOptions" -// parameter to define a custom httpsAgent with the desired properties +/** BBO price type for the take-profit leg */ ⋮---- -// Check Web Crypto API support when credentials are provided and no custom sign function is used +/** BBO price type for the stop-loss leg */ ⋮---- -// Throw if one of the 3 values is missing, but at least one of them is set +export interface GetFuturesOrdersReq { + settle: FuturesSettle; + contract?: string; + status: string; + limit?: number; + offset?: number; + last_id?: string; +} ⋮---- -/** - * Timestamp used to sign the request. Override this method to implement your own timestamp/sync mechanism - */ -getSignTimestampMs(): number +export interface DeleteAllFuturesOrdersReq { + xGateExptime?: number; + settle: FuturesSettle; + contract: string; + side?: string; + action_mode?: 'ACK' | 'RESULT' | 'FULL'; +} ⋮---- -protected get(endpoint: string, params?: object) +export interface GetFuturesOrdersByTimeRangeReq { + settle: FuturesSettle; + contract?: string; + from?: number; + to?: number; + limit?: number; + offset?: number; +} ⋮---- -// GET only supports params in the query string +export interface UpdateFuturesOrderReq { + xGateExptime?: number; + settle: FuturesSettle; + order_id: string; + size?: number; + price?: string; + amend_text?: string; +} ⋮---- -protected post(endpoint: string, params?: ParamsInQueryBodyOrHeader) +export interface GetFuturesTradingHistoryReq { + settle: FuturesSettle; + contract?: string; + order?: number; + limit?: number; + offset?: number; + last_id?: string; +} ⋮---- -protected getPrivate(endpoint: string, params?: object) +export interface GetFuturesTradingHistoryByTimeRangeReq { + settle: FuturesSettle; + contract?: string; + from?: number; + to?: number; + limit?: number; + offset?: number; + role?: 'maker' | 'taker'; +} ⋮---- -// GET only supports params in the query string +export interface GetFuturesPositionHistoryReq { + settle: FuturesSettle; + contract?: string; + limit?: number; + offset?: number; + from?: number; + to?: number; + side?: 'long' | 'short'; + pnl?: string; +} ⋮---- -protected postPrivate(endpoint: string, params?: ParamsInQueryBodyOrHeader) +export interface GetFuturesLiquidationHistoryReq { + settle: FuturesSettle; + contract?: string; + limit?: number; + at?: number; +} ⋮---- -/** POST private endpoint with multipart/form-data (empty body hash for signing) */ -protected postPrivateMultipart( - endpoint: string, - formData: FormData, - query?: object, -) +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; + }; + order_type?: + | 'close-long-order' + | 'close-short-order' + | 'close-long-position' + | 'close-short-position' + | 'plan-close-long-position' + | 'plan-close-short-position'; + settle: FuturesSettle; +} ⋮---- -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 +⋮---- +price: string; // Required: Price value for price trigger +rule: 1 | 2; // Required: Price Condition Type (1: >=, 2: <=) ⋮---- -// protected patchPrivate(endpoint: string, params?: any) { -protected patchPrivate(endpoint: string, params?: ParamsInQueryBodyOrHeader) +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 + size?: number; // 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 +size?: number; // 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; +} ⋮---- -// Dispatch request +// v4.104.6: New GET /futures/{settle}/insurance endpoint request +export interface GetFuturesInsuranceReq { + settle: FuturesSettle; + limit?: number; +} ⋮---- -// See: https://www.gate.io/docs/developers/apiv4/en/#return-format +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 +} ⋮---- -// 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 @@ -13462,6 +13533,8 @@ File: src/types/response/futures.ts * ========================================================================================================================== */ ⋮---- +import type { FuturesAccountBookType } from '../request/futures.js'; +⋮---- export interface FuturesOrderBook { id?: number; current: number; @@ -13646,13 +13719,16 @@ export interface FuturesAccountBookRecord { time: number; change: string; balance: string; - type: string; + /** v4.106.147: includes `dividend` (dividend payout) */ + type: FuturesAccountBookType; text: string; contract?: string; trade_id: string; id: string; } ⋮---- +/** v4.106.147: includes `dividend` (dividend payout) */ +⋮---- export interface FuturesOrder { id?: number; user?: number; @@ -14530,6 +14606,8 @@ client }); ``` +TestNet REST for spot and futures is `baseUrlKey: 'testnet'` (`https://api-testnet.gateapi.io/api/v4`). `baseUrlKey: 'futuresTestnet'` is that same host, kept so older configs keep working. WebSocket TestNet is `useTestnet: true` on `WebsocketClient`. + See [RestClient](./src/RestClient.ts) for further information, or the [examples](./examples/) for lots of usage examples. ## WebSockets @@ -14968,6 +15046,7 @@ import { CreateChaseOrderReq, CreateTrailOrderReq, DeleteAllFuturesOrdersReq, + FuturesSettle, GetChaseOrderDetailReq, GetChaseOrdersReq, GetFundingRatesReq, @@ -17098,7 +17177,7 @@ submitFlashSwapOrderPreview( * @returns Promise */ getFuturesContracts(params: { - settle: 'btc' | 'usdt' | 'usd' | 'usd1'; + settle: FuturesSettle; limit?: number; offset?: number; }): Promise @@ -17110,7 +17189,7 @@ getFuturesContracts(params: { * @returns Promise */ getFuturesContract(params: { - settle: 'btc' | 'usdt' | 'usd' | 'usd1'; + settle: FuturesSettle; contract: string; }): Promise ⋮---- @@ -17169,7 +17248,7 @@ getPremiumIndexKLines( * @returns Promise */ getFuturesTickers(params: { - settle: 'btc' | 'usdt' | 'usd' | 'usd1'; + settle: FuturesSettle; contract?: string; }): Promise ⋮---- @@ -17211,7 +17290,7 @@ getBatchFundingRates( * }[]> */ getFuturesInsuranceBalanceHistory(params: { - settle: 'btc' | 'usdt' | 'usd' | 'usd1'; + settle: FuturesSettle; limit?: number; }): Promise< { @@ -17237,7 +17316,7 @@ getFuturesStats(params: GetFuturesStatsReq): Promise * @returns Promise */ getIndexConstituents(params: { - settle: 'btc' | 'usdt' | 'usd' | 'usd1'; + settle: FuturesSettle; index: string; }): Promise ⋮---- @@ -17274,7 +17353,7 @@ getRiskLimitTiers(params: GetRiskLimitTiersReq): Promise * @returns Promise */ getFuturesAccount(params: { - settle: 'btc' | 'usdt' | 'usd' | 'usd1'; + settle: FuturesSettle; }): Promise ⋮---- /** @@ -17308,7 +17387,7 @@ getFuturesPositions( * @returns Promise */ getFuturesPosition(params: { - settle: 'btc' | 'usdt' | 'usd' | 'usd1'; + settle: FuturesSettle; contract: string; }): Promise ⋮---- @@ -17321,7 +17400,7 @@ getFuturesPosition(params: { * @returns Promise */ updateFuturesMargin(params: { - settle: 'btc' | 'usdt' | 'usd' | 'usd1'; + settle: FuturesSettle; contract: string; change: string; }): Promise @@ -17344,7 +17423,7 @@ updateFuturesMargin(params: { * @returns Promise */ updateFuturesLeverage(params: { - settle: 'btc' | 'usdt' | 'usd' | 'usd1'; + settle: FuturesSettle; contract: string; leverage: string; cross_leverage_limit?: string; @@ -17382,7 +17461,7 @@ updateFuturesPositionMode(params: { * @returns Promise */ updatePositionRiskLimit(params: { - settle: 'btc' | 'usdt' | 'usd' | 'usd1'; + settle: FuturesSettle; contract: string; risk_limit: string; }): Promise @@ -17396,7 +17475,7 @@ updatePositionRiskLimit(params: { * @returns Promise */ updateFuturesDualMode(params: { - settle: 'btc' | 'usdt' | 'usd' | 'usd1'; + settle: FuturesSettle; dual_mode: boolean; }): Promise ⋮---- @@ -17407,7 +17486,7 @@ updateFuturesDualMode(params: { * @returns Promise */ getDualModePosition(params: { - settle: 'btc' | 'usdt' | 'usd' | 'usd1'; + settle: FuturesSettle; contract: string; }): Promise ⋮---- @@ -17446,7 +17525,7 @@ updateDualModePositionLeverage( * @returns Promise */ updateDualModePositionRiskLimit(params: { - settle: 'btc' | 'usdt' | 'usd' | 'usd1'; + settle: FuturesSettle; contract: string; risk_limit: string; }): Promise @@ -17521,7 +17600,7 @@ getFuturesOrdersByTimeRange( */ submitFuturesBatchOrders(params: { xGateExptime?: number; - settle: 'btc' | 'usdt' | 'usd' | 'usd1'; + settle: FuturesSettle; orders: SubmitFuturesOrderReq[]; }): Promise ⋮---- @@ -17535,7 +17614,7 @@ submitFuturesBatchOrders(params: { * @returns Promise */ getFuturesOrder(params: { - settle: 'btc' | 'usdt' | 'usd' | 'usd1'; + settle: FuturesSettle; order_id: string; }): Promise ⋮---- @@ -17549,7 +17628,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 +17708,7 @@ getFuturesAutoDeleveragingHistory( * @returns Promise<{ triggerTime: number }> */ setFuturesOrderCancelCountdown(params: { - settle: 'btc' | 'usdt' | 'usd' | 'usd1'; + settle: FuturesSettle; timeout: number; contract?: string; }): Promise< @@ -17641,7 +17720,7 @@ setFuturesOrderCancelCountdown(params: { * @returns Promise */ getFuturesUserTradingFees(params: { - settle: 'btc' | 'usdt' | 'usd' | 'usd1'; + settle: FuturesSettle; contract?: string; }): Promise ⋮---- @@ -17657,7 +17736,7 @@ getFuturesUserTradingFees(params: { */ batchCancelFuturesOrders(params: { xGateExptime?: number; - settle: 'btc' | 'usdt' | 'usd' | 'usd1'; + settle: FuturesSettle; orderIds: string[]; }): Promise ⋮---- @@ -17674,7 +17753,7 @@ batchCancelFuturesOrders(params: { */ batchUpdateFuturesOrders(params: { xGateExptime?: number; - settle: 'btc' | 'usdt' | 'usd' | 'usd1'; + settle: FuturesSettle; orders: BatchAmendOrderReq[]; }): Promise ⋮---- @@ -17715,7 +17794,7 @@ getFuturesAutoOrders( * @returns Promise */ cancelAllOpenFuturesOrders(params: { - settle: 'btc' | 'usdt' | 'usd' | 'usd1'; + settle: FuturesSettle; contract: string; }): Promise ⋮---- @@ -17726,7 +17805,7 @@ cancelAllOpenFuturesOrders(params: { * @returns Promise */ getFuturesPriceTriggeredOrder(params: { - settle: 'btc' | 'usdt' | 'usd' | 'usd1'; + settle: FuturesSettle; order_id: number; }): Promise ⋮---- @@ -17737,13 +17816,16 @@ getFuturesPriceTriggeredOrder(params: { * @returns Promise */ cancelFuturesPriceTriggeredOrder(params: { - settle: 'btc' | 'usdt' | 'usd' | 'usd1'; + settle: FuturesSettle; order_id: number; }): Promise ⋮---- /** * Update a single price-triggered order * + * v4.106.160: `PUT /futures/{settle}/price_orders/amend/{order_id}`. + * `order_id` is required in the path and is still sent in the JSON body. + * * @param params Parameters for updating a price-triggered order * @returns Promise */ @@ -20138,7 +20220,7 @@ File: package.json ================ { "name": "gateio-api", - "version": "1.6.4", + "version": "1.6.5", "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..78c0677 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "gateio-api", - "version": "1.6.4", + "version": "1.6.5", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "gateio-api", - "version": "1.6.4", + "version": "1.6.5", "license": "MIT", "dependencies": { "@types/ws": "8.18.1", diff --git a/package.json b/package.json index 7df721f..e527c0d 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "gateio-api", - "version": "1.6.4", + "version": "1.6.5", "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/RestClient.ts b/src/RestClient.ts index 66d6c04..aba932c 100644 --- a/src/RestClient.ts +++ b/src/RestClient.ts @@ -3548,16 +3548,22 @@ export class RestClient extends BaseRestClient { /** * Update a single price-triggered order * + * v4.106.160: `PUT /futures/{settle}/price_orders/amend/{order_id}`. + * `order_id` is required in the path and is still sent in the JSON body. + * * @param params Parameters for updating a price-triggered order * @returns Promise */ updateFuturesPriceTriggeredOrder( params: UpdateFuturesPriceTriggeredOrderReq, ): Promise { - const { settle, ...body } = params; - return this.putPrivate(`/futures/${settle}/price_orders/amend`, { - body: body, - }); + const { settle, order_id, ...rest } = params; + return this.putPrivate( + `/futures/${settle}/price_orders/amend/${order_id}`, + { + body: { order_id, ...rest }, + }, + ); } /** diff --git a/src/lib/requestUtils.ts b/src/lib/requestUtils.ts index ae40631..ac2eae6 100644 --- a/src/lib/requestUtils.ts +++ b/src/lib/requestUtils.ts @@ -24,7 +24,11 @@ export interface RestClientOptions { **/ baseUrl?: string; - // manually override with one of the known base URLs in the library + /** + * Built-in Gate API v4 host. + * `testnet` and `futuresTestnet` both use https://api-testnet.gateapi.io/api/v4 + * (spot and futures). `futuresTestnet` is kept as an alias of `testnet`. + */ baseUrlKey?: GateBaseUrlKey; /** Default: true. whether to try and post-process request exceptions (and throw them). */ @@ -79,10 +83,15 @@ export function serializeParams | undefined = {}>( return queryString ? prefixWith + queryString : queryString; } +/** Global TestNet REST host. Gate docs: spot and futures. */ +const GATE_TESTNET_REST_URL = 'https://api-testnet.gateapi.io/api/v4'; + const GATE_BASE_URLS: Record = { live: 'https://api.gateio.ws/api/v4', futuresLiveAlternative: 'https://fx-api.gateio.ws/api/v4', - futuresTestnet: 'https://fx-api-testnet.gateio.ws/api/v4', + testnet: GATE_TESTNET_REST_URL, + // Alias of `testnet`. Previously https://fx-api-testnet.gateio.ws/api/v4 (HTTP 502). + futuresTestnet: GATE_TESTNET_REST_URL, }; export function getRestBaseUrl(restClientOptions: RestClientOptions): string { diff --git a/src/lib/websocket/websocket-util.ts b/src/lib/websocket/websocket-util.ts index e6d1dab..3f938b4 100644 --- a/src/lib/websocket/websocket-util.ts +++ b/src/lib/websocket/websocket-util.ts @@ -101,7 +101,8 @@ export const WS_BASE_URL_MAP: Record< > = { spotV4: { livenet: 'wss://api.gateio.ws/ws/v4/', - testnet: 'NoTestnetForSpotWebsockets!', + // https://www.gate.com/docs/developers/apiv4/ws/en/ + testnet: 'wss://ws-testnet.gate.com/v4/ws/spot', }, perpFuturesUSDTV4: { livenet: 'wss://fx-ws.gateio.ws/v4/ws/usdt', @@ -121,7 +122,8 @@ export const WS_BASE_URL_MAP: Record< }, optionsV4: { livenet: 'wss://op-ws.gateio.live/v4/ws', - testnet: 'wss://op-ws-testnet.gateio.live/v4/ws', + // https://www.gate.com/docs/developers/options/ws/en/ + testnet: 'wss://ws-testnet.gate.com/v4/ws/options', }, announcementsV4: { livenet: 'wss://api.gateio.ws/ws/v4/ann', diff --git a/src/types/request/futures.ts b/src/types/request/futures.ts index 7753669..1007c36 100644 --- a/src/types/request/futures.ts +++ b/src/types/request/futures.ts @@ -73,6 +73,19 @@ export interface GetRiskLimitTableReq { table_id: string; } +/** Change types for `GET /futures/{settle}/account_book`. */ +export type FuturesAccountBookType = + | 'dnw' + | 'pnl' + | 'fee' + | 'refr' + | 'fund' + | 'point_dnw' + | 'point_fee' + | 'point_refr' + | 'bonus_offset' + | 'dividend'; // v4.106.147: dividend payout + export interface GetFuturesAccountBookReq { settle: FuturesSettle; contract?: string; @@ -80,16 +93,7 @@ export interface GetFuturesAccountBookReq { offset?: number; from?: number; to?: number; - type?: - | 'dnw' - | 'pnl' - | 'fee' - | 'refr' - | 'fund' - | 'point_dnw' - | 'point_fee' - | 'point_refr' - | 'bonus_offset'; + type?: FuturesAccountBookType; } export interface GetFuturesADLRiskStatesReq { @@ -136,6 +140,10 @@ export interface SubmitFuturesOrderReq { action_mode?: 'ACK' | 'RESULT' | 'FULL'; tpsl_tp_trigger_price?: string; tpsl_sl_trigger_price?: string; + /** BBO price type for the take-profit leg */ + tpsl_tp_bbo_type?: string; + /** BBO price type for the stop-loss leg */ + tpsl_sl_bbo_type?: string; pos_margin_mode?: 'isolated' | 'cross'; } diff --git a/src/types/response/futures.ts b/src/types/response/futures.ts index 4a936c8..46d330c 100644 --- a/src/types/response/futures.ts +++ b/src/types/response/futures.ts @@ -165,11 +165,25 @@ export interface FuturesAccount { funding_balance?: string; } +/** v4.106.147: includes `dividend` (dividend payout) */ +export type FuturesAccountBookRecordType = + | 'dnw' + | 'pnl' + | 'fee' + | 'refr' + | 'fund' + | 'point_dnw' + | 'point_fee' + | 'point_refr' + | 'bonus_offset' + | 'dividend'; + export interface FuturesAccountBookRecord { time: number; change: string; balance: string; - type: string; + /** v4.106.147: includes `dividend` (dividend payout) */ + type: FuturesAccountBookRecordType; text: string; contract?: string; trade_id: string; diff --git a/src/types/response/otc.ts b/src/types/response/otc.ts index ce6319f..c022716 100644 --- a/src/types/response/otc.ts +++ b/src/types/response/otc.ts @@ -147,7 +147,8 @@ export interface GetOTCFiatOrderListResp { ps: number; total_pn: number; count: number; - list: OTCFiatOrderListItem[]; + /** v4.106.158: was `list` */ + lists: OTCFiatOrderListItem[]; }; } @@ -175,7 +176,8 @@ export interface GetOTCStablecoinOrderListResp { page_size: number; page_number: number; total_page: number; - list: OTCStablecoinOrderListItem[]; + /** v4.106.158: was `list` */ + lists: OTCStablecoinOrderListItem[]; }; } diff --git a/src/types/response/stock.ts b/src/types/response/stock.ts index 3770646..4b8058a 100644 --- a/src/types/response/stock.ts +++ b/src/types/response/stock.ts @@ -11,6 +11,32 @@ export type StockCategory = export type StockAssetType = 'STOCK' | 'ETF'; +/** v4.106.159: `closed` and `gt_lp` removed. */ +export type StockTradeStatus = 'pre_market' | 'open' | 'post_market'; + +/** + * v4.106.148. + * 0 disabled, 1 buy only, 2 sell only, 4 buy and sell, + * 5 manual suspension, 6 strategy exception, 7 stock halt, 8 circuit breaker halt. + */ +export type StockTradeMode = 0 | 1 | 2 | 4 | 5 | 6 | 7 | 8; + +/** + * `GET /stock/orders` and `GET /stock/orders/history`. JSON stays an integer. + * 0 unknown, 1 new, 2 partial, 3 filled, 4 canceled, 5 rejected, + * 6 cancel rejected, 7 update succeeded, 8 update rejected. + */ +export type StockOrderStatus = 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8; + +/** + * `GET /stock/orders/history`. JSON stays an integer. + * 0 unknown, 1 no quote, 2 no match, 3 trigger price exceeded, + * 4 order value exceeds limit, 5 unknown rejection, 6 unknown cancellation, + * 7 canceled by user, 8 time in force expired, 9 session unsupported, + * 13 canceled due to corporate action. + */ +export type StockOrderFinishAs = 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 13; + export interface StockApiResp { timestamp?: number; data?: T; @@ -53,8 +79,8 @@ export interface StockSymbolItem { symbol_desc?: string; category?: StockCategory | string; asset_type?: StockAssetType; - trade_status?: string; - trade_mode?: number; + trade_status?: StockTradeStatus; + trade_mode?: StockTradeMode; order_fill_timing?: number; icon_link?: string; quote_currency_symbol?: string; @@ -91,8 +117,8 @@ export interface StockSymbolDetailItem { buy_price_protection?: string; slippage_rate?: string; commission_rate?: string; - trade_status?: string; - trade_mode?: number; + trade_status?: StockTradeStatus; + trade_mode?: StockTradeMode; order_fill_timing?: number; symbol_descs?: StockSymbolDescI18n[]; [key: string]: unknown; @@ -118,11 +144,11 @@ export interface StockOrderItem { quote_currency?: string; fx_rate?: string; symbol_desc?: string; - trade_status?: string; - trade_mode?: number; + trade_status?: StockTradeStatus; + trade_mode?: StockTradeMode; price_type?: string; side?: number; - status?: number; + status?: StockOrderStatus; volume?: string; fill_volume?: string; price?: string; @@ -152,10 +178,10 @@ export interface StockOrderHistoryItem { fx_rate?: string; symbol_desc?: string; price_type?: string; - status?: number; + status?: StockOrderStatus; status_desc?: string; status_detail?: { title?: string; message?: string } | null; - finish_as?: number; + finish_as?: StockOrderFinishAs; side?: number; time_in_force?: string; volume?: string; @@ -178,7 +204,7 @@ export interface StockPositionItem { quote_currency?: string; quote_currency_precision?: number; fx_rate?: string; - trade_status?: string; + trade_status?: StockTradeStatus; symbol_desc?: string; position_pnl?: string; today_pnl?: string; diff --git a/src/types/shared.ts b/src/types/shared.ts index d451367..c4c095e 100644 --- a/src/types/shared.ts +++ b/src/types/shared.ts @@ -1,6 +1,12 @@ +/** + * Built-in Gate API v4 hosts. + * `testnet` is the global TestNet host (spot and futures). + * `futuresTestnet` is the same host, kept so older `baseUrlKey` values keep working. + */ export type GateBaseUrlKey = | 'live' | 'futuresLiveAlternative' + | 'testnet' | 'futuresTestnet'; // interfaces diff --git a/test/REST/baseUrl.test.ts b/test/REST/baseUrl.test.ts new file mode 100644 index 0000000..007a5d1 --- /dev/null +++ b/test/REST/baseUrl.test.ts @@ -0,0 +1,24 @@ +import { getRestBaseUrl } from '../../src/lib/requestUtils.js'; + +const GATE_TESTNET_REST_URL = 'https://api-testnet.gateapi.io/api/v4'; + +describe('REST base URL', () => { + it('uses the global testnet host for testnet and futuresTestnet', () => { + expect(getRestBaseUrl({ baseUrlKey: 'testnet' })).toBe( + GATE_TESTNET_REST_URL, + ); + expect(getRestBaseUrl({ baseUrlKey: 'futuresTestnet' })).toBe( + GATE_TESTNET_REST_URL, + ); + }); + + it('keeps live as the default and prefers an explicit baseUrl', () => { + expect(getRestBaseUrl({})).toBe('https://api.gateio.ws/api/v4'); + expect( + getRestBaseUrl({ + baseUrl: 'https://example.test/api/v4', + baseUrlKey: 'testnet', + }), + ).toBe('https://example.test/api/v4'); + }); +}); diff --git a/test/REST/priceOrderAmend.test.ts b/test/REST/priceOrderAmend.test.ts new file mode 100644 index 0000000..8e68480 --- /dev/null +++ b/test/REST/priceOrderAmend.test.ts @@ -0,0 +1,32 @@ +import { RestClient } from '../../src/index.js'; + +class CapturingRestClient extends RestClient { + public lastCall?: { endpoint: string; params?: unknown }; + + protected putPrivate(endpoint: string, params?: unknown): Promise { + this.lastCall = { endpoint, params }; + return Promise.resolve({ id: 1, id_string: '1' }); + } +} + +describe('updateFuturesPriceTriggeredOrder', () => { + it('puts order_id in the path and the body', async () => { + const rest = new CapturingRestClient(); + + await rest.updateFuturesPriceTriggeredOrder({ + settle: 'usdt', + order_id: 42, + price: '1', + }); + + expect(rest.lastCall).toEqual({ + endpoint: '/futures/usdt/price_orders/amend/42', + params: { + body: { + order_id: 42, + price: '1', + }, + }, + }); + }); +});