From 94c8b40ab5f32840419d70cde931596b0af5bc35 Mon Sep 17 00:00:00 2001 From: Jerko J <83344666+JJ-Cro@users.noreply.github.com> Date: Thu, 16 May 2024 23:53:11 +0200 Subject: [PATCH 01/36] feat(): Added Enpoints for "Withdrawal" and "Wallet" --- src/RestClient.ts | 731 +++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 728 insertions(+), 3 deletions(-) diff --git a/src/RestClient.ts b/src/RestClient.ts index b2019c6..43c8f0d 100644 --- a/src/RestClient.ts +++ b/src/RestClient.ts @@ -33,9 +33,6 @@ export class RestClient extends BaseRestClient { * * It is not recommended to use its result for any trading calculation. */ - getBalances(params?: { currency: string }): Promise> { - return this.getPrivate('/wallet/total_balance', params); - } getSpotBalances(params?: { currency: string; @@ -60,4 +57,732 @@ export class RestClient extends BaseRestClient { }): Promise> { return this.getPrivate('/wallet/sub_account_balances', params); } + + /** + * WITHDRAW + */ + + /** + * Withdraw + * + * Withdrawals to Gate addresses do not incur transaction fees. + * + * @param params Withdrawal parameters + * @returns Promise> + */ + withdraw(params: { + withdraw_order_id?: string; + amount: string; + currency: string; + address?: string; + memo?: string; + chain: string; + }): Promise< + APIResponse<{ + id: string; + txid: string; + withdraw_order_id: string; + timestamp: string; + amount: string; + currency: string; + address: string; + memo?: string; + status: + | 'DONE' + | 'CANCEL' + | 'REQUEST' + | 'MANUAL' + | 'BCODE' + | 'EXTPEND' + | 'FAIL' + | 'INVALID' + | 'VERIFY' + | 'PROCES' + | 'PEND' + | 'DMOVE' + | 'SPLITPEND'; + chain: string; + }> + > { + return this.postPrivate('/withdrawals', params); + } + + /** + * Cancel withdrawal with specified ID + * + * @param params Parameters containing the withdrawal ID + * @returns Promise> + */ + cancelWithdrawal(params: { withdrawal_id: string }): Promise< + APIResponse<{ + id: string; + txid: string; + withdraw_order_id: string; + timestamp: string; + amount: string; + currency: string; + address: string; + memo?: string; + status: + | 'DONE' + | 'CANCEL' + | 'REQUEST' + | 'MANUAL' + | 'BCODE' + | 'EXTPEND' + | 'FAIL' + | 'INVALID' + | 'VERIFY' + | 'PROCES' + | 'PEND' + | 'DMOVE' + | 'SPLITPEND'; + chain: string; + }> + > { + return this.deletePrivate(`/withdrawals/${params.withdrawal_id}`); + } + + /** + * WALLET + */ + + /** + * List chains supported for specified currency + * + * @param params Parameters containing the currency name + * @returns Promise> + */ + listCurrencyChains(params: { currency: string }): Promise< + APIResponse< + { + chain: string; + name_cn: string; + name_en: string; + contract_address: string; + is_disabled: number; + is_deposit_disabled: number; + is_withdraw_disabled: number; + decimal: string; + }[] + > + > { + return this.get('/wallet/currency_chains', params); + } + + /** + * Generate currency deposit address + * + * @param params Parameters containing the currency name + * @returns Promise> + */ + generateDepositAddress(params: { currency: string }): Promise< + APIResponse<{ + currency: string; + address: string; + multichain_addresses: { + chain: string; + address: string; + payment_id: string; + payment_name: string; + obtain_failed: number; + }[]; + }> + > { + return this.getPrivate('/wallet/deposit_address', params); + } + + /** + * Retrieve withdrawal records + * + * Record time range cannot exceed 30 days + * + * @param params Parameters for filtering withdrawal records + * @returns Promise> + */ + retrieveWithdrawalRecords(params?: { + currency?: string; + from?: number; + to?: number; + limit?: number; + offset?: number; + }): Promise< + APIResponse< + { + id: string; + txid: string; + withdraw_order_id: string; + timestamp: string; + amount: string; + fee: string; + currency: string; + address: string; + memo?: string; + status: + | 'DONE' + | 'CANCEL' + | 'REQUEST' + | 'MANUAL' + | 'BCODE' + | 'EXTPEND' + | 'FAIL' + | 'INVALID' + | 'VERIFY' + | 'PROCES' + | 'PEND' + | 'DMOVE' + | 'SPLITPEND'; + chain: string; + }[] + > + > { + return this.getPrivate('/wallet/withdrawals', params); + } + + /** + * Retrieve deposit records + * + * Record time range cannot exceed 30 days + * + * @param params Parameters for filtering deposit records + * @returns Promise> + */ + retrieveDepositRecords(params?: { + currency?: string; + from?: number; + to?: number; + limit?: number; + offset?: number; + }): Promise< + APIResponse< + { + id: string; + txid: string; + withdraw_order_id: string; + timestamp: string; + amount: string; + currency: string; + address: string; + memo?: string; + status: + | 'DONE' + | 'CANCEL' + | 'REQUEST' + | 'MANUAL' + | 'BCODE' + | 'EXTPEND' + | 'FAIL' + | 'INVALID' + | 'VERIFY' + | 'PROCES' + | 'PEND' + | 'DMOVE' + | 'SPLITPEND'; + chain: string; + }[] + > + > { + return this.getPrivate('/wallet/deposits', params); + } + + /** + * Transfer between trading accounts + * + * Transfer between different accounts. Currently support transfers between the following: + * - spot - margin + * - spot - futures(perpetual) + * - spot - delivery + * - spot - cross margin + * - spot - options + * + * @param params Transfer parameters + * @returns Promise> + */ + transferBetweenAccounts(params: { + 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; + }): Promise< + APIResponse<{ + tx_id: number; + }> + > { + return this.postPrivate('/wallet/transfers', params); + } + + /** + * Transfer between main and sub accounts + * + * Support transferring with sub user's spot or futures account. Note that only main user's spot account is used no matter which sub user's account is operated. + * + * @param params Transfer parameters + * @returns Promise> + */ + transferBetweenMainAndSubAccounts(params: { + currency: string; + sub_account: string; + direction: 'to' | 'from'; + amount: string; + client_order_id?: string; + sub_account_type?: 'spot' | 'futures' | 'cross_margin' | 'delivery'; + }): Promise> { + return this.postPrivate('/wallet/sub_account_transfers', params); + } + + /** + * Retrieve transfer records between main and sub accounts + * + * Record time range cannot exceed 30 days + * + * Note: only records after 2020-04-10 can be retrieved + * + * @param params Parameters for filtering transfer records + * @returns Promise> + */ + retrieveSubAccountTransferRecords(params?: { + sub_uid?: string; + from?: number; + to?: number; + limit?: number; + offset?: number; + }): Promise< + APIResponse< + { + 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'; + }[] + > + > { + return this.getPrivate('/wallet/sub_account_transfers', params); + } + + /** + * Sub-account transfers to sub-account + * + * It is possible to perform balance transfers between two sub-accounts under the same main account. You can use either the API Key of the main account or the API Key of the sub-account to initiate the transfer. + * + * @param params Transfer parameters + * @returns Promise> + */ + subAccountTransfersToSubAccount(params: { + currency: string; + sub_account_type?: 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; + }): Promise> { + return this.postPrivate('/wallet/sub_account_to_sub_account', params); + } + + /** + * Retrieve withdrawal status + * + * @param params Parameters for retrieving withdrawal status + * @returns Promise> + */ + retrieveWithdrawalStatus(params?: { currency?: string }): Promise< + APIResponse< + { + 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 }; + }[] + > + > { + return this.getPrivate('/wallet/withdraw_status', params); + } + + /** + * Retrieve sub account balances + * + * @param params Parameters for retrieving sub account balances + * @returns Promise> + */ + retrieveSubAccountBalances(params?: { sub_uid?: string }): Promise< + APIResponse< + { + uid: string; + available: { [key: string]: string }; + }[] + > + > { + return this.getPrivate('/wallet/sub_account_balances', params); + } + + /** + * Query sub accounts' margin balances + * + * @param params Parameters for querying sub accounts' margin balances + * @returns Promise> + */ + querySubAccountMarginBalances(params?: { sub_uid?: string }): Promise< + APIResponse< + { + uid: string; + available: { + 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; + }; + }[]; + }[] + > + > { + return this.getPrivate('/wallet/sub_account_margin_balances', params); + } + + /** + * Query sub accounts' futures account balances + * + * @param params Parameters for querying sub accounts' futures account balances + * @returns Promise> + */ + querySubAccountFuturesBalances(params?: { + sub_uid?: string; + settle?: string; + }): Promise< + APIResponse< + { + 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; + 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; + }; + }; + }; + }[] + > + > { + return this.getPrivate('/wallet/sub_account_futures_balances', params); + } + + /** + * Query subaccount's cross_margin account info + * + * @param params Parameters for querying subaccount's cross_margin account info + * @returns Promise> + */ + querySubAccountCrossMarginBalances(params?: { sub_uid?: string }): Promise< + APIResponse< + { + 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; + }; + }[] + > + > { + return this.getPrivate('/wallet/sub_account_cross_margin_balances', params); + } + + /** + * Query saved address + * + * @param params Parameters for querying saved address + * @returns Promise> + */ + querySavedAddress(params: { + currency: string; + chain?: string; + limit?: string; + page?: number; + }): Promise< + APIResponse< + { + currency: string; + chain: string; + address: string; + name: string; + tag: string; + verified: string; + }[] + > + > { + return this.getPrivate('/wallet/saved_address', params); + } + + /** + * Retrieve personal trading fee + * + * @param params Parameters for retrieving personal trading fee + * @returns Promise> + */ + retrievePersonalTradingFee(params?: { + currency_pair?: string; + settle?: 'BTC' | 'USDT' | 'USD'; + }): Promise< + APIResponse<{ + 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; + }> + > { + return this.getPrivate('/wallet/fee', params); + } + + /** + * Retrieve user's total balances + * + * This endpoint returns an approximate sum of exchanged amount from all currencies to input currency for each account. + * The exchange rate and account balance could have been cached for at most 1 minute. It is not recommended to use its result for any trading calculation. + * + * For trading calculation, use the corresponding account query endpoint for each account type. For example: + * - GET /spot/accounts to query spot account balance + * - GET /margin/accounts to query margin account balance + * - GET /futures/{settle}/accounts to query futures account balance + * + * @param params Parameters for retrieving total balances + * @returns Promise> + */ + getBalances(params?: { currency?: string }): Promise< + APIResponse<{ + total: { + amount: string; + currency: string; + unrealised_pnl?: string; + borrowed?: string; + }; + details: { + [key: string]: { + amount: string; + currency: string; + unrealised_pnl?: string; + borrowed?: string; + }; + }; + }> + > { + return this.getPrivate('/wallet/total_balance', params); + } + + /** + * List small balance + * + * @returns Promise> + */ + listSmallBalance(): Promise< + APIResponse<{ + currency: string; + available_balance: string; + estimated_as_btc: string; + convertible_to_gt: string; + }> + > { + return this.getPrivate('/wallet/small_balance'); + } + + /** + * Convert small balance + * + * @param params Parameters for converting small balance + * @returns Promise> + */ + convertSmallBalance(params: { + currency?: string[]; + }): Promise> { + return this.postPrivate('/wallet/small_balance', params); + } + + /** + * List small balance history + * + * @param params Parameters for listing small balance history + * @returns Promise> + */ + listSmallBalanceHistory(params?: { + currency?: string; + page?: number; + limit?: number; + }): Promise< + APIResponse< + { + id: string; + currency: string; + amount: string; + gt_amount: string; + create_time: number; + }[] + > + > { + return this.getPrivate('/wallet/small_balance_history', params); + } + + /** + * + */ /** + * + */ /** + * + */ /** + * + */ } From c62799f2731728ec8f54f5ca80602d730e5f83b2 Mon Sep 17 00:00:00 2001 From: Jerko J <83344666+JJ-Cro@users.noreply.github.com> Date: Sat, 18 May 2024 20:59:59 +0200 Subject: [PATCH 02/36] feat(): Added subaccount and Margin endpoints --- src/RestClient.ts | 3330 +++++++++++++++++++++++++++++++++++-- src/lib/BaseRestClient.ts | 8 + 2 files changed, 3184 insertions(+), 154 deletions(-) diff --git a/src/RestClient.ts b/src/RestClient.ts index 43c8f0d..5dc7217 100644 --- a/src/RestClient.ts +++ b/src/RestClient.ts @@ -8,6 +8,380 @@ import { import { RestClientOptions } from './lib/requestUtils.js'; import { APIResponse } from './types/response/shared.types.js'; +// interfaces + +interface SubAccountKey { + user_id?: string; + mode?: number; + name?: string; + perms?: { + name?: + | 'wallet' + | 'spot' + | 'futures' + | 'delivery' + | 'earn' + | 'options' + | 'account' + | 'unified' + | 'loan'; + read_only?: boolean; + }[]; + ip_whitelist?: string[]; + key?: string; + state?: number; + created_at?: number; + updated_at?: number; + last_access?: number; +} + +interface EstimateRate { + [key: string]: string; +} + +interface CurrencyPair { + id?: string; + base?: string; + quote?: string; + 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; +} + +interface Order { + 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' | '-'; + finish_as?: 'open' | 'filled' | 'cancelled' | 'ioc' | 'stp'; + action_mode?: 'ACK' | 'RESULT' | 'FULL'; +} + +interface CancelBatchOrder { + currency_pair: string; + id: string; + account?: 'cross_margin'; + action_mode?: 'ACK' | 'RESULT' | 'FULL'; +} + +interface Loan { + id?: string; + create_time?: string; + expire_time?: string; + status?: 'open' | 'loaned' | 'finished' | 'auto_repaid'; + side: 'lend' | 'borrow'; + currency: string; + rate?: string; + amount: string; + days?: number; + auto_renew?: boolean; + currency_pair?: string; + left?: string; + repaid?: string; + paid_interest?: string; + unpaid_interest?: string; + fee_rate?: string; + orig_id?: string; + text?: string; +} + +interface LoanRecord { + id?: string; + loan_id?: string; + create_time?: string; + expire_time?: string; + status?: 'loaned' | 'finished'; + borrow_user_id?: string; + currency?: string; + rate?: string; + amount?: string; + days?: number; + auto_renew?: boolean; + repaid?: string; + paid_interest?: string; + unpaid_interest?: string; +} + +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; +} + +interface Contract { + name?: string; + type?: 'inverse' | 'direct'; + quanto_multiplier?: string; + leverage_min?: string; + leverage_max?: string; + maintenance_rate?: string; + mark_type?: 'internal' | 'index'; + mark_price?: string; + index_price?: string; + last_price?: string; + maker_fee_rate?: string; + taker_fee_rate?: string; + order_price_round?: string; + mark_price_round?: string; + funding_rate?: string; + funding_interval?: number; + funding_next_apply?: number; + risk_limit_base?: string; + risk_limit_step?: string; + risk_limit_max?: string; + order_size_min?: number; + order_size_max?: number; + order_price_deviate?: string; + ref_discount_rate?: string; + ref_rebate_rate?: string; + orderbook_id?: number; + trade_id?: number; + trade_size?: number; + position_size?: number; + config_change_time?: number; + in_delisting?: boolean; + orders_limit?: number; + enable_bonus?: boolean; + enable_credit?: boolean; + create_time?: number; + funding_cap_ratio?: string; +} + +interface Position { + user?: number; + contract?: string; + size?: number; + leverage?: string; + risk_limit?: string; + leverage_max?: string; + maintenance_rate?: string; + value?: string; + margin?: string; + entry_price?: string; + liq_price?: string; + mark_price?: string; + initial_margin?: string; + maintenance_margin?: string; + unrealised_pnl?: string; + realised_pnl?: string; + pnl_pnl?: string; + pnl_fund?: string; + pnl_fee?: string; + history_pnl?: string; + last_close_pnl?: string; + realised_point?: string; + history_point?: string; + adl_ranking?: number; + pending_orders?: number; + close_order?: { + id?: number; + price?: string; + is_liq?: boolean; + } | null; + mode?: 'single' | 'dual_long' | 'dual_short'; + cross_leverage_limit?: string; + update_time?: number; + open_time?: number; +} + +interface FuturesOrder { + id?: number; + user?: number; + create_time?: number; + finish_time?: number; + finish_as?: + | 'filled' + | 'cancelled' + | 'liquidated' + | 'ioc' + | 'auto_deleveraged' + | 'reduce_only' + | 'position_closed' + | 'stp'; + status?: 'open' | 'finished'; + contract: string; + size: number; + iceberg?: number; + price?: string; + close?: boolean; + is_close?: boolean; + reduce_only?: boolean; + is_reduce_only?: boolean; + is_liq?: boolean; + tif?: 'gtc' | 'ioc' | 'poc' | 'fok'; + left?: number; + fill_price?: string; + text?: string; + tkfr?: string; + mkfr?: string; + refu?: number; + auto_size?: 'close_long' | 'close_short'; + stp_id?: number; + stp_act?: 'cn' | 'co' | 'cb' | '-'; + amend_text?: string; + biz_info?: string; +} + +interface FuturesPriceTriggeredOrder { + initial: { + contract: string; + size?: number; + price?: string; + close?: boolean; + tif?: 'gtc' | 'ioc'; + text?: string; + reduce_only?: boolean; + auto_size?: string; + is_reduce_only?: boolean; + is_close?: boolean; + }; + trigger: { + strategy_type?: 0 | 1; + price_type?: 0 | 1 | 2; + price?: string; + rule?: 1 | 2; + expiration?: number; + }; + id?: number; + user?: number; + create_time?: number; + finish_time?: number; + trade_id?: number; + status?: 'open' | 'finished' | 'inactive' | 'invalid'; + finish_as?: 'cancelled' | 'succeeded' | 'failed' | 'expired'; + reason?: string; + order_type?: + | 'close-long-order' + | 'close-short-order' + | 'close-long-position' + | 'close-short-position' + | 'plan-close-long-position' + | 'plan-close-short-position'; + me_order_id?: number; +} + +interface DeliveryContract { + name?: string; + underlying?: string; + cycle?: 'WEEKLY' | 'BI-WEEKLY' | 'QUARTERLY' | 'BI-QUARTERLY'; + type?: 'inverse' | 'direct'; + quanto_multiplier?: string; + leverage_min?: string; + leverage_max?: string; + maintenance_rate?: string; + mark_type?: 'internal' | 'index'; + mark_price?: string; + index_price?: string; + last_price?: string; + maker_fee_rate?: string; + taker_fee_rate?: string; + order_price_round?: string; + mark_price_round?: string; + basis_rate?: string; + basis_value?: string; + basis_impact_value?: string; + settle_price?: string; + settle_price_interval?: number; + settle_price_duration?: number; + expire_time?: number; + risk_limit_base?: string; + risk_limit_step?: string; + risk_limit_max?: string; + order_size_min?: number; + order_size_max?: number; + order_price_deviate?: string; + ref_discount_rate?: string; + ref_rebate_rate?: string; + orderbook_id?: number; + trade_id?: number; + trade_size?: number; + position_size?: number; + config_change_time?: number; + in_delisting?: boolean; + orders_limit?: number; +} + +interface Withdraw { + id: string; + txid: string; + withdraw_order_id: string; + timestamp: string; + amount: string; + currency: string; + address: string; + memo?: string; + status: + | 'DONE' + | 'CANCEL' + | 'REQUEST' + | 'MANUAL' + | 'BCODE' + | 'EXTPEND' + | 'FAIL' + | 'INVALID' + | 'VERIFY' + | 'PROCES' + | 'PEND' + | 'DMOVE' + | 'SPLITPEND'; + chain: string; +} /** * Unified REST API client for all of Gate's REST APIs */ @@ -28,38 +402,9 @@ export class RestClient extends BaseRestClient { return this.get('/v1/public/system_info'); } - /** - * This endpoint returns an approximate sum of exchanged amount from all currencies to input currency for each account.The exchange rate and account balance could have been cached for at most 1 minute. - * - * It is not recommended to use its result for any trading calculation. - */ - - getSpotBalances(params?: { - currency: string; - }): Promise> { - return this.getPrivate('/spot/accounts', params); - } - - getMarginBalances(params?: { - currency: string; - }): Promise> { - return this.getPrivate('/margin/accounts', params); - } - - getFuturesBalances(params?: { - settle: string; - }): Promise> { - return this.getPrivate(`/futures/${params?.settle}/accounts`, params); - } - - getSubAccountBalances(params?: { - sub_uid: string; - }): Promise> { - return this.getPrivate('/wallet/sub_account_balances', params); - } - - /** + /**================================================================================================================================ * WITHDRAW + * ========================================================================================================================== */ /** @@ -68,7 +413,7 @@ export class RestClient extends BaseRestClient { * Withdrawals to Gate addresses do not incur transaction fees. * * @param params Withdrawal parameters - * @returns Promise> + * @returns Promise> */ withdraw(params: { withdraw_order_id?: string; @@ -77,33 +422,7 @@ export class RestClient extends BaseRestClient { address?: string; memo?: string; chain: string; - }): Promise< - APIResponse<{ - id: string; - txid: string; - withdraw_order_id: string; - timestamp: string; - amount: string; - currency: string; - address: string; - memo?: string; - status: - | 'DONE' - | 'CANCEL' - | 'REQUEST' - | 'MANUAL' - | 'BCODE' - | 'EXTPEND' - | 'FAIL' - | 'INVALID' - | 'VERIFY' - | 'PROCES' - | 'PEND' - | 'DMOVE' - | 'SPLITPEND'; - chain: string; - }> - > { + }): Promise> { return this.postPrivate('/withdrawals', params); } @@ -111,47 +430,33 @@ export class RestClient extends BaseRestClient { * Cancel withdrawal with specified ID * * @param params Parameters containing the withdrawal ID - * @returns Promise> + * @returns Promise> */ - cancelWithdrawal(params: { withdrawal_id: string }): Promise< - APIResponse<{ - id: string; - txid: string; - withdraw_order_id: string; - timestamp: string; - amount: string; - currency: string; - address: string; - memo?: string; - status: - | 'DONE' - | 'CANCEL' - | 'REQUEST' - | 'MANUAL' - | 'BCODE' - | 'EXTPEND' - | 'FAIL' - | 'INVALID' - | 'VERIFY' - | 'PROCES' - | 'PEND' - | 'DMOVE' - | 'SPLITPEND'; - chain: string; - }> - > { + cancelWithdrawal(params: { + withdrawal_id: string; + }): Promise> { return this.deletePrivate(`/withdrawals/${params.withdrawal_id}`); } - /** + /**========================================================================================================================== * WALLET + * ========================================================================================================================== */ /** * List chains supported for specified currency * * @param params Parameters containing the currency name - * @returns Promise> + * @returns Promise> */ listCurrencyChains(params: { currency: string }): Promise< APIResponse< @@ -174,7 +479,17 @@ export class RestClient extends BaseRestClient { * Generate currency deposit address * * @param params Parameters containing the currency name - * @returns Promise> + * @returns Promise> */ generateDepositAddress(params: { currency: string }): Promise< APIResponse<{ @@ -198,7 +513,7 @@ export class RestClient extends BaseRestClient { * Record time range cannot exceed 30 days * * @param params Parameters for filtering withdrawal records - * @returns Promise> + * @returns Promise> */ retrieveWithdrawalRecords(params?: { currency?: string; @@ -206,36 +521,7 @@ export class RestClient extends BaseRestClient { to?: number; limit?: number; offset?: number; - }): Promise< - APIResponse< - { - id: string; - txid: string; - withdraw_order_id: string; - timestamp: string; - amount: string; - fee: string; - currency: string; - address: string; - memo?: string; - status: - | 'DONE' - | 'CANCEL' - | 'REQUEST' - | 'MANUAL' - | 'BCODE' - | 'EXTPEND' - | 'FAIL' - | 'INVALID' - | 'VERIFY' - | 'PROCES' - | 'PEND' - | 'DMOVE' - | 'SPLITPEND'; - chain: string; - }[] - > - > { + }): Promise> { return this.getPrivate('/wallet/withdrawals', params); } @@ -245,7 +531,7 @@ export class RestClient extends BaseRestClient { * Record time range cannot exceed 30 days * * @param params Parameters for filtering deposit records - * @returns Promise> + * @returns Promise> */ retrieveDepositRecords(params?: { currency?: string; @@ -253,35 +539,7 @@ export class RestClient extends BaseRestClient { to?: number; limit?: number; offset?: number; - }): Promise< - APIResponse< - { - id: string; - txid: string; - withdraw_order_id: string; - timestamp: string; - amount: string; - currency: string; - address: string; - memo?: string; - status: - | 'DONE' - | 'CANCEL' - | 'REQUEST' - | 'MANUAL' - | 'BCODE' - | 'EXTPEND' - | 'FAIL' - | 'INVALID' - | 'VERIFY' - | 'PROCES' - | 'PEND' - | 'DMOVE' - | 'SPLITPEND'; - chain: string; - }[] - > - > { + }): Promise> { return this.getPrivate('/wallet/deposits', params); } @@ -378,7 +636,7 @@ export class RestClient extends BaseRestClient { * It is possible to perform balance transfers between two sub-accounts under the same main account. You can use either the API Key of the main account or the API Key of the sub-account to initiate the transfer. * * @param params Transfer parameters - * @returns Promise> + * @returns Promise> */ subAccountTransfersToSubAccount(params: { currency: string; @@ -396,7 +654,20 @@ export class RestClient extends BaseRestClient { * Retrieve withdrawal status * * @param params Parameters for retrieving withdrawal status - * @returns Promise> + * @returns Promise> */ retrieveWithdrawalStatus(params?: { currency?: string }): Promise< APIResponse< @@ -423,7 +694,10 @@ export class RestClient extends BaseRestClient { * Retrieve sub account balances * * @param params Parameters for retrieving sub account balances - * @returns Promise> + * @returns Promise> */ retrieveSubAccountBalances(params?: { sub_uid?: string }): Promise< APIResponse< @@ -776,6 +1050,2754 @@ export class RestClient extends BaseRestClient { return this.getPrivate('/wallet/small_balance_history', params); } + /**========================================================================================================================== + * SUBACCOUNT + * ========================================================================================================================== + */ + + /** + * Create a new sub-account + * + * @param params Parameters for creating a new sub-account + * @returns Promise> + */ + createSubAccount(params: { + remark?: string; + login_name: string; + password?: string; + email?: string; + }): Promise< + APIResponse<{ + remark?: string; + login_name: string; + password?: string; + email?: string; + state: number; + type: number; + user_id: number; + create_time: number; + }> + > { + return this.postPrivate('/sub_accounts', params); + } + + /** + * List sub-accounts + * + * @param params Parameters for listing sub-accounts + * @returns Promise> + */ + listSubAccounts(params?: { type?: string }): Promise< + APIResponse< + { + remark?: string; + login_name: string; + password?: string; + email?: string; + state: number; + type: number; + user_id: number; + create_time: number; + }[] + > + > { + return this.getPrivate('/sub_accounts', params); + } + + /** + * Get the sub-account + * + * @param params Parameters containing the sub-account user ID + * @returns Promise> + */ + getSubAccount(params: { user_id: number }): Promise< + APIResponse<{ + remark?: string; + login_name: string; + password?: string; + email?: string; + state: number; + type: number; + user_id: number; + create_time: number; + }> + > { + return this.getPrivate(`/sub_accounts/${params.user_id}`); + } + + /** + * Create API Key of the sub-account + * + * @param params Parameters for creating API Key of the sub-account + * @returns Promise> + */ + createSubAccountApiKey(params: { + user_id: number; + mode?: number; + name?: string; + perms?: { + name?: + | 'wallet' + | 'spot' + | 'futures' + | 'delivery' + | 'earn' + | 'options' + | 'account' + | 'unified' + | 'loan'; + read_only?: boolean; + }[]; + ip_whitelist?: string[]; + }): Promise< + APIResponse<{ + user_id: string; + mode?: number; + name?: string; + perms?: { + name?: + | 'wallet' + | 'spot' + | 'futures' + | 'delivery' + | 'earn' + | 'options' + | 'account' + | 'unified' + | 'loan'; + read_only?: boolean; + }[]; + ip_whitelist?: string[]; + key: string; + state: number; + created_at: number; + updated_at: number; + last_access: number; + }> + > { + return this.postPrivate(`/sub_accounts/${params.user_id}/keys`, params); + } + + /** + * List all API Key of the sub-account + * + * @param params Parameters containing the sub-account user ID + * @returns Promise> + */ + listSubAccountApiKeys(params: { + user_id: number; + }): Promise> { + return this.getPrivate(`/sub_accounts/${params.user_id}/keys`); + } + + /** + * Update API key of the sub-account + * + * @param params Parameters for updating API key of the sub-account + * @returns Promise> + */ + updateSubAccountApiKey(params: { + user_id: number; + key: string; + mode?: number; + name?: string; + perms?: { + name?: + | 'wallet' + | 'spot' + | 'futures' + | 'delivery' + | 'earn' + | 'options' + | 'account' + | 'unified' + | 'loan'; + read_only?: boolean; + }[]; + ip_whitelist?: string[]; + }): Promise> { + return this.putPrivate( + `/sub_accounts/${params.user_id}/keys/${params.key}`, + params, + ); + } + + /** + * Delete API key of the sub-account + * + * @param params Parameters for deleting API key of the sub-account + * @returns Promise> + */ + deleteSubAccountApiKey(params: { + user_id: number; + key: string; + }): Promise> { + return this.deletePrivate( + `/sub_accounts/${params.user_id}/keys/${params.key}`, + ); + } + + /** + * Get the API Key of the sub-account + * + * @param params Parameters containing the sub-account user ID and API key + * @returns Promise> + */ + getSubAccountApiKey(params: { + user_id: number; + key: string; + }): Promise> { + return this.getPrivate( + `/sub_accounts/${params.user_id}/keys/${params.key}`, + ); + } + + /** + * Lock the sub-account + * + * @param params Parameters containing the sub-account user ID + * @returns Promise> + */ + lockSubAccount(params: { user_id: number }): Promise> { + return this.postPrivate(`/sub_accounts/${params.user_id}/lock`); + } + + /** + * Unlock the sub-account + * + * @param params Parameters containing the sub-account user ID + * @returns Promise> + */ + unlockSubAccount(params: { user_id: number }): Promise> { + return this.postPrivate(`/sub_accounts/${params.user_id}/unlock`); + } + /**========================================================================================================================== + * UNIFIED + * ========================================================================================================================== + */ + + /** + * Get unified account information + * + * The assets of each currency in the account will be adjusted according to their liquidity, defined by corresponding adjustment coefficients, and then uniformly converted to USD to calculate the total asset value and position value of the account. + * + * @param params Parameters for retrieving unified account information + * @returns Promise> + */ + getUnifiedAccountInfo(params?: { currency?: string }): Promise< + APIResponse<{ + user_id: number; + refresh_time: number; + locked: boolean; + balances: { + [key: string]: { + available: string; + freeze: string; + borrowed: string; + negative_liab: string; + futures_pos_liab: string; + equity: string; + total_freeze: string; + total_liab: string; + spot_in_use: string; + }; + }; + total: string; + borrowed: 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; + unified_account_total: string; + unified_account_total_liab: string; + unified_account_total_equity: string; + leverage: string; + spot_order_loss: string; + spot_hedge: boolean; + }> + > { + return this.getPrivate('/unified/accounts', params); + } + + /** + * Query about the maximum borrowing for the unified account + * + * @param params Parameters for querying the maximum borrowing for the unified account + * @returns Promise> + */ + queryUnifiedAccountMaxBorrowing(params: { currency: string }): Promise< + APIResponse<{ + currency: string; + amount: string; + }> + > { + return this.getPrivate('/unified/borrowable', params); + } + + /** + * Query about the maximum transferable for the unified account + * + * @param params Parameters for querying the maximum transferable for the unified account + * @returns Promise> + */ + queryUnifiedAccountMaxTransferable(params: { currency: string }): Promise< + APIResponse<{ + currency: string; + amount: string; + }> + > { + return this.getPrivate('/unified/transferable', params); + } + + /** + * Borrow or repay + * + * When borrowing, it is essential to ensure that the borrowed amount is not below the minimum borrowing threshold for the specific cryptocurrency and does not exceed the maximum borrowing limit set by the platform and the user. + * + * The interest on the loan will be automatically deducted from the account at regular intervals. It is the user's responsibility to manage the repayment of the borrowed amount. + * + * For repayment, the option to repay the entire borrowed amount is available by setting the parameter repaid_all=true + * + * @param params Parameters for borrowing or repaying + * @returns Promise> + */ + borrowOrRepay(params: { + currency: string; + type: 'borrow' | 'repay'; + amount: string; + repaid_all?: boolean; + text?: string; + }): Promise> { + return this.postPrivate('/unified/loans', params); + } + + /** + * List loans + * + * @param params Parameters for listing loans + * @returns Promise> + */ + listLoans(params?: { + currency?: string; + page?: number; + limit?: number; + type?: 'platform' | 'margin'; + }): Promise< + APIResponse< + { + currency: string; + currency_pair: string; + amount: string; + type: 'platform' | 'margin'; + create_time: number; + update_time: number; + }[] + > + > { + return this.getPrivate('/unified/loans', params); + } + + /** + * Get loan records + * + * @param params Parameters for getting loan records + * @returns Promise> + */ + getLoanRecords(params?: { + type?: 'borrow' | 'repay'; + currency?: string; + page?: number; + limit?: number; + }): Promise< + APIResponse< + { + 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; + }[] + > + > { + return this.getPrivate('/unified/loan_records', params); + } + + /** + * List interest records + * + * @param params Parameters for listing interest records + * @returns Promise> + */ + listInterestRecords(params?: { + currency?: string; + page?: number; + limit?: number; + type?: 'platform' | 'margin'; + }): Promise< + APIResponse< + { + currency: string; + currency_pair: string; + actual_rate: string; + interest: string; + status: number; + type: 'platform' | 'margin'; + create_time: number; + }[] + > + > { + return this.getPrivate('/unified/interest_records', params); + } + + /** + * Retrieve user risk unit details, only valid in portfolio margin mode + * + * @returns Promise> + */ + retrieveUserRiskUnitDetails(): Promise< + APIResponse<{ + 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; + }[]; + }> + > { + return this.getPrivate('/unified/risk_units'); + } + + /** + * Set mode of the unified account + * + * Switching between different account modes requires only passing the parameters corresponding to the target account mode. It also supports opening or closing configuration switches for the corresponding account mode when switching. + * + * @param params Parameters for setting the mode of the unified account + * @returns Promise> + */ + setUnifiedAccountMode(params: { + mode: 'classic' | 'multi_currency' | 'portfolio'; + settings?: { + usdt_futures?: boolean; + spot_hedge?: boolean; + }; + }): Promise> { + return this.putPrivate('/unified/unified_mode', params); + } + + /** + * Query mode of the unified account + * + * @returns Promise> + */ + queryUnifiedAccountMode(): Promise< + APIResponse<{ + mode: 'classic' | 'multi_currency' | 'portfolio'; + settings: { + usdt_futures?: boolean; + spot_hedge?: boolean; + }; + }> + > { + return this.getPrivate('/unified/unified_mode'); + } + + /** + * Get unified estimate rate + * + * Due to fluctuations in lending depth, hourly interest rates may vary, and thus, I cannot provide exact rates. When a currency is not supported, the interest rate returned will be an empty string. + * + * @param params Parameters for querying estimate rates + * @returns Promise> + */ + getUnifiedEstimateRate(params: { + currencies: string[]; + }): Promise> { + return this.getPrivate('/unified/estimate_rate', params); + } + + /** + * List currency discount tiers + * + * @returns Promise> + */ + listCurrencyDiscountTiers(): Promise< + APIResponse< + { + currency: string; + discount_tiers: { + tier: string; + discount: string; + lower_limit: string; + upper_limit: string; + }[]; + }[] + > + > { + return this.get('/unified/currency_discount_tiers'); + } + + /** + * Portfolio margin calculator + * + * Portfolio Margin Calculator When inputting a simulated position portfolio, each position includes the position name and quantity held, supporting markets within the range of BTC and ETH perpetual contracts, options, and spot markets. When inputting simulated orders, each order includes the market identifier, order price, and order quantity, supporting markets within the range of BTC and ETH perpetual contracts, options, and spot markets. Market orders are not included. + * + * @param params Parameters for portfolio margin calculator + * @returns Promise> + */ + portfolioMarginCalculator(params: { + 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; + }): Promise< + APIResponse<{ + 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; + }[]; + }[]; + }> + > { + return this.post('/unified/portfolio_calculator', params); + } + + /**========================================================================================================================== + * SPOT + * ========================================================================================================================== + */ + + /** + * List all currencies' details + * + * Currency has two forms: + * - Only currency name, e.g., BTC, USDT + * - _, e.g., HT_ETH + * + * The latter one occurs when one currency has multiple chains. Currency detail contains a chain field whatever the form is. To retrieve all chains of one currency, you can use all the details which have the name of the currency or name starting with _. + * + * @returns Promise> + */ + listAllCurrenciesDetails(): Promise< + APIResponse< + { + currency: string; + delisted: boolean; + withdraw_disabled: boolean; + withdraw_delayed: boolean; + deposit_disabled: boolean; + trade_disabled: boolean; + fixed_rate: string; + chain: string; + }[] + > + > { + return this.get('/spot/currencies'); + } + + /** + * Get details of a specific currency + * + * @param params Parameters for retrieving details of a specific currency + * @returns Promise> + */ + getCurrencyDetails(params: { currency: string }): Promise< + APIResponse<{ + currency: string; + delisted: boolean; + withdraw_disabled: boolean; + withdraw_delayed: boolean; + deposit_disabled: boolean; + trade_disabled: boolean; + fixed_rate: string; + chain: string; + }> + > { + return this.get(`/spot/currencies/${params.currency}`); + } + + /** + * List all currency pairs supported + * + * @returns Promise> + */ + listAllCurrencyPairs(): Promise> { + return this.get('/spot/currency_pairs'); + } + + /** + * Get details of a specific currency pair + * + * @param params Parameters for retrieving details of a specific currency pair + * @returns Promise> + */ + getCurrencyPairDetails(params: { + currency_pair: string; + }): Promise> { + return this.get(`/spot/currency_pairs/${params.currency_pair}`); + } + + /** + * Retrieve ticker information + * + * Return only related data if currency_pair is specified; otherwise return all of them. + * + * @param params Parameters for retrieving ticker information + * @returns Promise> + */ + retrieveTickerInformation(params?: { + currency_pair?: string; + timezone?: 'utc0' | 'utc8' | 'all'; + }): Promise< + APIResponse< + { + currency_pair: string; + last: string; + lowest_ask: string; + highest_bid: 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; + }[] + > + > { + return this.get('/spot/tickers', params); + } + + /** + * Retrieve order book + * + * Order book will be sorted by price from high to low on bids; low to high on asks. + * + * @param params Parameters for retrieving order book + * @returns Promise> + */ + retrieveOrderBook(params: { + currency_pair: string; + interval?: string; + limit?: number; + with_id?: boolean; + }): Promise< + APIResponse<{ + id?: number; + current: number; + update: number; + asks: [string, string][]; + bids: [string, string][]; + }> + > { + return this.get('/spot/order_book', params); + } + + /** + * Retrieve market trades + * + * You can use from and to to query by time range, or use last_id by scrolling page. The default behavior is by time range. + * Scrolling query using last_id is not recommended any more. If last_id is specified, time range query parameters will be ignored. + * + * @param params Parameters for retrieving market trades + * @returns Promise> + */ + retrieveMarketTrades(params: { + currency_pair: string; + limit?: number; + last_id?: string; + reverse?: boolean; + from?: number; + to?: number; + page?: number; + }): Promise< + APIResponse< + { + 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; + }[] + > + > { + return this.get('/spot/trades', params); + } + + /** + * Market candlesticks + * + * Maximum of 1000 points can be returned in a query. Be sure not to exceed the limit when specifying from, to and interval. + * + * @param params Parameters for retrieving market candlesticks + * @returns Promise> + */ + marketCandlesticks(params: { + currency_pair: string; + limit?: number; + from?: number; + to?: number; + interval?: + | '10s' + | '1m' + | '5m' + | '15m' + | '30m' + | '1h' + | '4h' + | '8h' + | '1d' + | '7d' + | '30d'; + }): Promise< + APIResponse< + [ + [ + 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 + ], + ] + > + > { + return this.get('/spot/candlesticks', params); + } + + /** + * Query user trading fee rates + * + * This API is deprecated in favour of new fee retrieving API /wallet/fee. + * + * @param params Parameters for querying user trading fee rates + * @returns Promise> + */ + queryUserTradingFeeRates(params?: { currency_pair?: string }): Promise< + APIResponse<{ + 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; + currency_pair: string; + debit_fee: number; + }> + > { + return this.getPrivate('/spot/fee', params); + } + + /** + * Query a batch of user trading fee rates + * + * @param params Parameters for querying a batch of user trading fee rates + * @returns Promise> + */ + queryBatchUserTradingFeeRates(params: { currency_pairs: string }): Promise< + APIResponse<{ + [key: string]: { + 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; + currency_pair: string; + debit_fee: number; + }; + }> + > { + return this.getPrivate('/spot/batch_fee', params); + } + + /** + * List spot accounts + * + * @param params Parameters for listing spot accounts + * @returns Promise> + */ + listSpotAccounts(params?: { currency?: string }): Promise< + APIResponse< + { + currency: string; + available: string; + locked: string; + update_id: number; + }[] + > + > { + return this.getPrivate('/spot/accounts', params); + } + + /** + * Query account book + * + * Record time range cannot exceed 30 days. + * + * @param params Parameters for querying account book + * @returns Promise> + */ + queryAccountBook(params?: { + currency?: string; + from?: number; + to?: number; + page?: number; + limit?: number; + type?: string; + }): Promise< + APIResponse< + { + id: string; + time: number; + currency: string; + change: string; + balance: string; + type: string; + text: string; + }[] + > + > { + return this.getPrivate('/spot/account_book', params); + } + + /** + * Create a batch of orders + * + * Batch orders requirements: + * - custom order field text is required + * - At most 4 currency pairs, maximum 10 orders each, are allowed in one request + * - No mixture of spot orders and margin orders, i.e. account must be identical for all orders + * + * @param params Parameters for creating a batch of orders + * @returns Promise> + */ + createBatchOrders(params: { + body: { + currency_pair: string; + text: 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; + }[]; + }): Promise< + APIResponse< + { + 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' | '-'; + finish_as: 'open' | 'filled' | 'cancelled' | 'ioc' | 'stp'; + }[] + > + > { + return this.postPrivate('/spot/batch_orders', params); + } + + /** + * List all open orders + * + * List open orders in all currency pairs. + * Note that pagination parameters affect record number in each currency pair's open order list. No pagination is applied to the number of currency pairs returned. All currency pairs with open orders will be returned. + * Spot, portfolio, and margin orders are returned by default. To list cross margin orders, account must be set to cross_margin. + * + * @param params Parameters for listing all open orders + * @returns Promise> + */ + listAllOpenOrders(params?: { + page?: number; + limit?: number; + account?: 'spot' | 'margin' | 'cross_margin' | 'unified'; + }): Promise< + APIResponse< + { + currency_pair: string; + total: number; + orders: { + 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_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' | '-'; + finish_as: 'open' | 'filled' | 'cancelled' | 'ioc' | 'stp'; + }[]; + }[] + > + > { + return this.getPrivate('/spot/open_orders', params); + } + + /** + * Close position when cross-currency is disabled + * + * Currently, only cross-margin accounts are supported to close position when cross currencies are disabled. Maximum buy quantity = (unpaid principal and interest - currency balance - the amount of the currency in the order book) / 0.998 + * + * @param params Parameters for closing position when cross-currency is disabled + * @returns Promise> + */ + closePositionWhenCrossCurrencyDisabled(params: { + text?: string; + currency_pair: string; + amount: string; + price: string; + action_mode?: 'ACK' | 'RESULT' | 'FULL'; + }): Promise> { + return this.postPrivate('/spot/cross_liquidate_orders', params); + } + + /** + * Create an order + * + * You can place orders with spot, portfolio, margin or cross margin account through setting the account field. It defaults to spot, which means spot account is used to place orders. If the user is using unified account, it defaults to the unified account. + * + * @param params Parameters for creating an order + * @returns Promise> + */ + createOrder(params: { + text?: string; + 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; + stp_act?: 'cn' | 'co' | 'cb' | '-'; + action_mode?: 'ACK' | 'RESULT' | 'FULL'; + }): Promise> { + return this.postPrivate('/spot/orders', params); + } + + /** + * List orders + * + * Spot, portfolio and margin orders are returned by default. If cross margin orders are needed, account must be set to cross_margin. + * + * @param params Parameters for listing orders + * @returns Promise> + */ + listOrders(params: { + currency_pair: string; + status: 'open' | 'finished'; + page?: number; + limit?: number; + account?: 'spot' | 'margin' | 'cross_margin' | 'unified'; + from?: number; + to?: number; + side?: 'buy' | 'sell'; + }): Promise> { + return this.getPrivate('/spot/orders', params); + } + + /** + * Cancel all open orders in specified currency pair + * + * If account is not set, all open orders, including spot, portfolio, margin and cross margin ones, will be cancelled. + * You can set account to cancel only orders within the specified account. + * + * @param params Parameters for cancelling all open orders in specified currency pair + * @returns Promise> + */ + cancelPairOpenOrders(params: { + currency_pair: string; + side?: 'buy' | 'sell'; + account?: 'spot' | 'margin' | 'cross_margin' | 'unified'; + action_mode?: 'ACK' | 'RESULT' | 'FULL'; + }): Promise> { + return this.deletePrivate('/spot/orders', params); + } + + /** + * Cancel a batch of orders with an ID list + * + * Multiple currency pairs can be specified, but maximum 20 orders are allowed per request. + * + * @param params Parameters for cancelling a batch of orders + * @returns Promise> + */ + cancelBatchOrders(params: { + body: { + currency_pair: string; + id: string; + }[]; + }): Promise< + APIResponse< + { + currency_pair: string; + id: string; + succeeded: boolean; + label: string; + message: string; + account: string; + }[] + > + > { + return this.postPrivate('/spot/cancel_batch_orders', params); + } + + /** + * Get a single order + * + * Spot, portfolio and margin orders are queried by default. If cross margin orders are needed or portfolio margin account are used, account must be set to cross_margin. + * + * @param params Parameters for getting a single order + * @returns Promise> + */ + getSingleOrder(params: { + order_id: string; + currency_pair: string; + account?: 'spot' | 'margin' | 'cross_margin' | 'unified'; + }): Promise> { + return this.getPrivate(`/spot/orders/${params.order_id}`, params); + } + + /** + * Amend an order + * + * By default, the orders of spot, portfolio and margin account are updated. If you need to modify orders of the cross-margin account, you must specify account as cross_margin. For portfolio margin account, only cross_margin account is supported. + * + * Currently, only supports modification of price or amount fields. + * + * @param params Parameters for amending an order + * @returns Promise> + */ + amendOrder(params: { + order_id: string; + currency_pair: string; + account?: 'spot' | 'margin' | 'cross_margin' | 'unified'; + body: { + amount?: string; + price?: string; + amend_text?: string; + action_mode?: 'ACK' | 'RESULT' | 'FULL'; + }; + }): Promise> { + return this.patchPrivate(`/spot/orders/${params.order_id}`, params); + } + + /** + * Cancel a single order + * + * Spot, portfolio and margin orders are cancelled by default. If trying to cancel cross margin orders or portfolio margin account are used, account must be set to cross_margin. + * + * @param params Parameters for cancelling a single order + * @returns Promise> + */ + cancelSingleOrder(params: { + order_id: string; + currency_pair: string; + account?: 'spot' | 'margin' | 'cross_margin' | 'unified'; + action_mode?: 'ACK' | 'RESULT' | 'FULL'; + }): Promise> { + return this.deletePrivate(`/spot/orders/${params.order_id}`, params); + } + + /** + * List personal trading history + * + * Spot, portfolio and margin trades are queried by default. If cross margin trades are needed, account must be set to cross_margin. + * + * You can also set from and/or to to query by time range. If you don't specify from and/or to parameters, only the last 7 days of data will be returned. The range of from and to is not allowed to exceed 30 days. Time range parameters are handled as order finish time. + * + * @param params Parameters for listing personal trading history + * @returns Promise> + */ + listPersonalTradingHistory(params?: { + currency_pair?: string; + limit?: number; + page?: number; + order_id?: string; + account?: 'spot' | 'margin' | 'cross_margin' | 'unified'; + from?: number; + to?: number; + }): Promise< + APIResponse< + { + 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; + }[] + > + > { + return this.getPrivate('/spot/my_trades', params); + } + + /** + * Get server current time + * + * @returns Promise> + */ + getServerTime(): Promise< + APIResponse<{ + server_time: number; + }> + > { + return this.get('/spot/time'); + } + + /** + * Countdown cancel orders + * + * When the timeout set by the user is reached, if there is no cancel or set a new countdown, the related pending orders will be automatically cancelled. This endpoint can be called repeatedly to set a new countdown or cancel the countdown. + * + * @param params Parameters for setting countdown cancel orders + * @returns Promise> + */ + countdownCancelOrders(params: { + timeout: number; + currency_pair?: string; + }): Promise< + APIResponse<{ + triggerTime: number; + }> + > { + return this.postPrivate('/spot/countdown_cancel_all', params); + } + + /** + * Batch modification of orders + * + * Default modification of orders for spot, portfolio, and margin accounts. To modify orders for a cross margin account, the account parameter must be specified as cross_margin. For portfolio margin accounts, the account parameter can only be specified as cross_margin. Currently, only modifications to price or quantity (choose one) are supported. + * + * @param params Parameters for batch modification of orders + * @returns Promise> + */ + amendBatchOrders(params: { + body: { + order_id: string; + amount?: string; + price?: string; + amend_text?: string; + }[]; + }): Promise< + APIResponse< + { + 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' | '-'; + finish_as: 'open' | 'filled' | 'cancelled' | 'ioc' | 'stp'; + }[] + > + > { + return this.postPrivate('/spot/amend_batch_orders', params); + } + + /** + * Create a price-triggered order + * + * @param params Parameters for creating a price-triggered order + * @returns Promise> + */ + createPriceTriggeredOrder(params: { + 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; + }; + market: string; + }): Promise< + APIResponse<{ + id: number; + }> + > { + return this.postPrivate('/spot/price_orders', params); + } + + /** + * Retrieve running auto order list + * + * @param params Parameters for retrieving running auto order list + * @returns Promise=' | '<='; + * 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; + * }; + * market: string; + * status: 'open' | 'finished'; + * }[]>> + */ + retrieveRunningAutoOrderList(params: { + status: 'open' | 'finished'; + market?: string; + account?: 'normal' | 'margin' | 'cross_margin'; + limit?: number; + offset?: number; + }): Promise> { + return this.getPrivate('/spot/price_orders', params); + } + /** + * Cancel all open orders + * + * @param params Parameters for cancelling all open orders + * @returns Promise=' | '<='; + * 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; + * }; + * market: string; + * status: 'open' | 'finished'; + * }[]>> + */ + cancelAllOpenOrders(params?: { + market?: string; + account?: 'normal' | 'margin' | 'cross_margin'; + }): Promise> { + return this.deletePrivate('/spot/price_orders', params); + } + + /** + * Get a price-triggered order + * + * @param params Parameters for getting a price-triggered order + * @returns Promise=' | '<='; + * 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; + * }; + * market: string; + * status: 'open' | 'finished'; + * }>> + */ + getPriceTriggeredOrder(params: { + order_id: string; + }): Promise> { + return this.getPrivate(`/spot/price_orders/${params.order_id}`, params); + } + + /** + * Cancel a price-triggered order + * + * @param params Parameters for cancelling a price-triggered order + * @returns Promise=' | '<='; + * 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; + * }; + * market: string; + * status: 'open' | 'finished'; + * }>> + */ + cancelPriceTriggeredOrder(params: { + order_id: string; + }): Promise> { + return this.deletePrivate(`/spot/price_orders/${params.order_id}`, params); + } + + /**========================================================================================================================== + * MARGIN + * ========================================================================================================================== + */ + + /** + * Margin account list + * + * @param params Parameters for listing margin accounts + * @returns Promise> + */ + listMarginAccounts(params?: { currency_pair?: string }): Promise< + APIResponse< + { + 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; + }; + }[] + > + > { + return this.getPrivate('/margin/accounts', params); + } + + /** + * List margin account balance change history + * + * Only transferals from and to margin account are provided for now. Time range allows 30 days at most. + * + * @param params Parameters for listing margin account balance change history + * @returns Promise> + */ + listMarginAccountBalanceChangeHistory(params?: { + currency?: string; + currency_pair?: string; + type?: string; + from?: number; + to?: number; + page?: number; + limit?: number; + }): Promise< + APIResponse< + { + id: string; + time: string; + time_ms: number; + currency: string; + currency_pair: string; + change: string; + balance: string; + type: string; + }[] + > + > { + return this.getPrivate('/margin/account_book', params); + } + + /** + * Funding account list + * + * @param params Parameters for listing funding accounts + * @returns Promise> + */ + listFundingAccounts(params?: { currency?: string }): Promise< + APIResponse< + { + currency: string; + available: string; + locked: string; + lent: string; + total_lent: string; + }[] + > + > { + return this.getPrivate('/margin/funding_accounts', params); + } + + /** + * Update user's auto repayment setting + * + * @param params Parameters for updating auto repayment setting + * @returns Promise> + */ + updateAutoRepaymentSetting(params: { + status: 'on' | 'off'; + }): Promise> { + return this.postPrivate('/margin/auto_repay', params); + } + + /** + * Retrieve user auto repayment setting + * + * @returns Promise> + */ + retrieveAutoRepaymentSetting(): Promise< + APIResponse<{ status: 'on' | 'off' }> + > { + return this.getPrivate('/margin/auto_repay'); + } + + /** + * Get the max transferable amount for a specific margin currency + * + * @param params Parameters for retrieving the max transferable amount + * @returns Promise> + */ + getMarginTransferableAmount(params: { + currency: string; + currency_pair?: string; + }): Promise< + APIResponse<{ + currency: string; + currency_pair?: string; + amount: string; + }> + > { + return this.getPrivate('/margin/transferable', params); + } + + /** + * Currencies supported by cross margin + * + * @returns Promise> + */ + listCrossMarginCurrencies(): Promise< + APIResponse< + { + name: string; + rate: string; + prec: string; + discount: string; + min_borrow_amount: string; + user_max_borrow_amount: string; + total_max_borrow_amount: string; + price: string; + loanable: boolean; + status: number; + }[] + > + > { + return this.get('/margin/cross/currencies'); + } + + /** + * Retrieve detail of one single currency supported by cross margin + * + * @param params Parameters containing the currency name + * @returns Promise> + */ + getCrossMarginCurrency(params: { currency: string }): Promise< + APIResponse<{ + name: string; + rate: string; + prec: string; + discount: string; + min_borrow_amount: string; + user_max_borrow_amount: string; + total_max_borrow_amount: string; + price: string; + loanable: boolean; + status: number; + }> + > { + return this.get(`/margin/cross/currencies/${params.currency}`); + } + + /** + * Retrieve cross margin account + * + * @returns Promise> + */ + retrieveCrossMarginAccount(): Promise< + APIResponse<{ + user_id: number; + refresh_time: number; + locked: boolean; + balances: { + [currency: string]: { + available: string; + freeze: string; + borrowed: string; + interest: string; + negative_liab: string; + futures_pos_liab: string; + equity: string; + total_freeze: string; + total_liab: string; + }; + }; + total: string; + borrowed: string; + interest: string; + risk: string; + total_initial_margin: string; + total_margin_balance: string; + total_maintenance_margin: string; + total_initial_margin_rate: string; + total_maintenance_margin_rate: string; + total_available_margin: string; + portfolio_margin_total: string; + portfolio_margin_total_liab: string; + portfolio_margin_total_equity: string; + }> + > { + return this.getPrivate('/margin/cross/accounts'); + } + + /** + * Retrieve cross margin account change history + * + * Record time range cannot exceed 30 days. + * + * @param params Parameters for retrieving cross margin account change history + * @returns Promise> + */ + retrieveCrossMarginAccountChangeHistory(params?: { + currency?: string; + from?: number; + to?: number; + page?: number; + limit?: number; + type?: string; + }): Promise< + APIResponse< + { + id: string; + time: number; + currency: string; + change: string; + balance: string; + type: string; + }[] + > + > { + return this.getPrivate('/margin/cross/account_book', params); + } + + /** + * Create a cross margin borrow loan + * + * Borrow amount cannot be less than currency minimum borrow amount. + * + * @param params Parameters for creating a cross margin borrow loan + * @returns Promise> + */ + createCrossMarginBorrowLoan(params: { + currency: string; + amount: string; + text?: string; + }): Promise< + APIResponse<{ + id: string; + create_time: number; + update_time: number; + currency: string; + amount: string; + text?: string; + status: number; + repaid: string; + repaid_interest: string; + unpaid_interest: string; + }> + > { + return this.postPrivate('/margin/cross/loans', params); + } + + /** + * List cross margin borrow history + * + * Sort by creation time in descending order by default. Set reverse=false to return ascending results. + * + * @param params Parameters for listing cross margin borrow history + * @returns Promise> + */ + listCrossMarginBorrowHistory(params: { + status: number; + currency?: string; + limit?: number; + offset?: number; + reverse?: boolean; + }): Promise< + APIResponse< + { + id: string; + create_time: number; + update_time: number; + currency: string; + amount: string; + text: string; + status: number; + repaid: string; + repaid_interest: string; + unpaid_interest: string; + }[] + > + > { + return this.getPrivate('/margin/cross/loans', params); + } + + /** + * Retrieve single borrow loan detail + * + * @param params Parameters containing the borrow loan ID + * @returns Promise> + */ + getSingleBorrowLoanDetail(params: { loan_id: string }): Promise< + APIResponse<{ + id: string; + create_time: number; + update_time: number; + currency: string; + amount: string; + text: string; + status: number; + repaid: string; + repaid_interest: string; + unpaid_interest: string; + }> + > { + return this.getPrivate(`/margin/cross/loans/${params.loan_id}`); + } + /** + * Cross margin repayments + * + * When the liquidity of the currency is insufficient and the transaction risk is high, the currency will be disabled, and funds cannot be transferred. When the available balance of cross-margin is insufficient, the balance of the spot account can be used for repayment. Please ensure that the balance of the spot account is sufficient, and system uses cross-margin account for repayment first. + * + * @param params Parameters for cross margin repayments + * @returns Promise> + */ + crossMarginRepayments(params: { currency: string; amount: string }): Promise< + APIResponse< + { + id: string; + create_time: number; + update_time: number; + currency: string; + amount: string; + text?: string; + status: number; + repaid: string; + repaid_interest: string; + unpaid_interest: string; + }[] + > + > { + return this.postPrivate('/margin/cross/repayments', params); + } + + /** + * Retrieve cross margin repayments + * + * Sort by creation time in descending order by default. Set reverse=false to return ascending results. + * + * @param params Parameters for retrieving cross margin repayments + * @returns Promise> + */ + retrieveCrossMarginRepayments(params?: { + currency?: string; + loan_id?: string; + limit?: number; + offset?: number; + reverse?: boolean; + }): Promise< + APIResponse< + { + id: string; + create_time: number; + loan_id: string; + currency: string; + principal: string; + interest: string; + repayment_type: string; + }[] + > + > { + return this.getPrivate('/margin/cross/repayments', params); + } + + /** + * Interest records for the cross margin account + * + * @param params Parameters for retrieving interest records + * @returns Promise> + */ + getCrossMarginInterestRecords(params?: { + currency?: string; + page?: number; + limit?: number; + from?: number; + to?: number; + }): Promise< + APIResponse< + { + currency: string; + currency_pair: string; + actual_rate: string; + interest: string; + status: number; + type: string; + create_time: number; + }[] + > + > { + return this.getPrivate('/margin/cross/interest_records', params); + } + + /** + * Get the max transferable amount for a specific cross margin currency + * + * @param params Parameters for retrieving the max transferable amount + * @returns Promise> + */ + getCrossMarginTransferableAmount(params: { currency: string }): Promise< + APIResponse<{ + currency: string; + amount: string; + }> + > { + return this.getPrivate('/margin/cross/transferable', params); + } + + /** + * Estimated interest rates + * + * Please note that the interest rates are subject to change based on the borrowing and lending demand, and therefore, the provided rates may not be entirely accurate. + * + * @param params Parameters for retrieving estimated interest rates + * @returns Promise>> + */ + getEstimatedInterestRates(params: { + currencies: string[]; + }): Promise>> { + return this.getPrivate('/margin/cross/estimate_rate', params); + } + + /** + * Get the max borrowable amount for a specific cross margin currency + * + * @param params Parameters for retrieving the max borrowable amount + * @returns Promise> + */ + getCrossMarginBorrowableAmount(params: { currency: string }): Promise< + APIResponse<{ + currency: string; + amount: string; + }> + > { + return this.getPrivate('/margin/cross/borrowable', params); + } + + /**========================================================================================================================== + * MARGIN UNI + * ========================================================================================================================== + */ + /**========================================================================================================================== + * WALLET + * ========================================================================================================================== + */ + /** * */ /** diff --git a/src/lib/BaseRestClient.ts b/src/lib/BaseRestClient.ts index 726a5c2..4508f22 100644 --- a/src/lib/BaseRestClient.ts +++ b/src/lib/BaseRestClient.ts @@ -172,6 +172,14 @@ export abstract class BaseRestClient { return this._call('DELETE', endpoint, params, false); } + protected putPrivate(endpoint: string, params?: any) { + return this._call('PUT', endpoint, params, false); + } + + protected patchPrivate(endpoint: string, params?: any) { + return this._call('PATCH', endpoint, params, false); + } + /** * @private Make a HTTP request to a specific endpoint. Private endpoint API calls are automatically signed. */ From a896543765e5a3dac627574fd7b70db8beefa088 Mon Sep 17 00:00:00 2001 From: Jerko J <83344666+JJ-Cro@users.noreply.github.com> Date: Sun, 19 May 2024 12:13:23 +0200 Subject: [PATCH 03/36] feat(): added MarginUNI and FlashLoans endpoints --- src/RestClient.ts | 378 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 378 insertions(+) diff --git a/src/RestClient.ts b/src/RestClient.ts index 5dc7217..6845df9 100644 --- a/src/RestClient.ts +++ b/src/RestClient.ts @@ -3793,6 +3793,384 @@ export class RestClient extends BaseRestClient { * MARGIN UNI * ========================================================================================================================== */ + /** + * List lending markets + * + * @returns Promise> + */ + listLendingMarkets(): Promise< + APIResponse< + { + currency_pair: string; + base_min_borrow_amount: string; + quote_min_borrow_amount: string; + leverage: string; + }[] + > + > { + return this.get('/margin/uni/currency_pairs'); + } + + /** + * Get detail of lending market + * + * @param params Parameters containing the currency pair + * @returns Promise> + */ + getLendingMarketDetail(params: { currency_pair: string }): Promise< + APIResponse<{ + currency_pair: string; + base_min_borrow_amount: string; + quote_min_borrow_amount: string; + leverage: string; + }> + > { + return this.get(`/margin/uni/currency_pairs/${params.currency_pair}`); + } + + /** + * Estimate interest rate + * + * Please note that the interest rates are subject to change based on the borrowing and lending demand, and therefore, the provided rates may not be entirely accurate. + * + * @param params Parameters for retrieving estimated interest rates + * @returns Promise>> + */ + estimateInterestRate(params: { + currencies: string[]; + }): Promise>> { + return this.getPrivate('/margin/uni/estimate_rate', params); + } + + /** + * Borrow or repay + * + * @param params Parameters for borrowing or repaying + * @returns Promise + */ + borrowOrRepayMarginUNI(params: { + currency: string; + type: 'borrow' | 'repay'; + amount: string; + repaid_all?: boolean; + currency_pair: string; + }): Promise { + return this.postPrivate('/margin/uni/loans', params); + } + + /** + * List loans + * + * @param params Parameters for listing loans + * @returns Promise> + */ + listLoansMarginUNI(params?: { + currency_pair?: string; + currency?: string; + page?: number; + limit?: number; + }): Promise< + APIResponse< + { + currency: string; + currency_pair: string; + amount: string; + type: string; + create_time: number; + update_time: number; + }[] + > + > { + return this.getPrivate('/margin/uni/loans', params); + } + + /** + * Get loan records + * + * @param params Parameters for retrieving loan records + * @returns Promise> + */ + getLoanRecordsMarginUNI(params?: { + type?: 'borrow' | 'repay'; + currency?: string; + currency_pair?: string; + page?: number; + limit?: number; + }): Promise< + APIResponse< + { + type: string; + currency_pair: string; + currency: string; + amount: string; + create_time: number; + }[] + > + > { + return this.getPrivate('/margin/uni/loan_records', params); + } + + /** + * List interest records + * + * @param params Parameters for listing interest records + * @returns Promise> + */ + listInterestRecordsMarginUNI(params?: { + currency_pair?: string; + currency?: string; + page?: number; + limit?: number; + from?: number; + to?: number; + }): Promise< + APIResponse< + { + currency: string; + currency_pair: string; + actual_rate: string; + interest: string; + status: number; + type: string; + create_time: number; + }[] + > + > { + return this.getPrivate('/margin/uni/interest_records', params); + } + + /** + * Get maximum borrowable + * + * @param params Parameters for retrieving the maximum borrowable amount + * @returns Promise> + */ + getMaxBorrowable(params: { + currency: string; + currency_pair: string; + }): Promise< + APIResponse<{ + currency: string; + currency_pair: string; + borrowable: string; + }> + > { + return this.getPrivate('/margin/uni/borrowable', params); + } + + /**========================================================================================================================== + * FLASH SWAP + * ========================================================================================================================== + */ + + /** + * List All Supported Currency Pairs In Flash Swap + * + * @param params Parameters for retrieving data of the specified currency + * @returns Promise> + */ + listFlashSwapCurrencyPairs(params?: { currency?: string }): Promise< + APIResponse< + { + currency_pair: string; + sell_currency: string; + buy_currency: string; + sell_min_amount: string; + sell_max_amount: string; + buy_min_amount: string; + buy_max_amount: string; + }[] + > + > { + return this.get('/flash_swap/currency_pairs', params); + } + + /** + * Create a flash swap order + * + * Initiate a flash swap preview in advance because order creation requires a preview result. + * + * @param params Parameters for creating a flash swap order + * @returns Promise> + */ + createFlashSwapOrder(params: { + preview_id: string; + sell_currency: string; + sell_amount: string; + buy_currency: string; + buy_amount: string; + }): Promise< + APIResponse<{ + id: number; + create_time: number; + user_id: number; + sell_currency: string; + sell_amount: string; + buy_currency: string; + buy_amount: string; + price: string; + status: number; + }> + > { + return this.postPrivate('/flash_swap/orders', params); + } + + /** + * List all flash swap orders + * + * @param params Parameters for listing flash swap orders + * @returns Promise> + */ + listFlashSwapOrders(params?: { + status?: number; + sell_currency?: string; + buy_currency?: string; + reverse?: boolean; + limit?: number; + page?: number; + }): Promise< + APIResponse< + { + id: number; + create_time: number; + user_id: number; + sell_currency: string; + sell_amount: string; + buy_currency: string; + buy_amount: string; + price: string; + status: number; + }[] + > + > { + return this.getPrivate('/flash_swap/orders', params); + } + + /** + * Get a single flash swap order's detail + * + * @param params Parameters containing the flash swap order ID + * @returns Promise> + */ + getFlashSwapOrderDetail(params: { order_id: number }): Promise< + APIResponse<{ + id: number; + create_time: number; + user_id: number; + sell_currency: string; + sell_amount: string; + buy_currency: string; + buy_amount: string; + price: string; + status: number; + }> + > { + return this.getPrivate(`/flash_swap/orders/${params.order_id}`); + } + + /** + * Initiate a flash swap order preview + * + * @param params Parameters for initiating a flash swap order preview + * @returns Promise> + */ + initiateFlashSwapOrderPreview(params: { + sell_currency: string; + sell_amount?: string; + buy_currency: string; + buy_amount?: string; + }): Promise< + APIResponse<{ + preview_id: string; + sell_currency: string; + sell_amount: string; + buy_currency: string; + buy_amount: string; + price: string; + }> + > { + return this.postPrivate('/flash_swap/orders/preview', params); + } /**========================================================================================================================== * WALLET * ========================================================================================================================== From f7d880212352c0cef94b94c47a64ab8aace97616 Mon Sep 17 00:00:00 2001 From: Jerko J <83344666+JJ-Cro@users.noreply.github.com> Date: Sun, 19 May 2024 17:25:51 +0200 Subject: [PATCH 04/36] feat(): Added futures, delivery and options endpoints --- examples/rest-private.ts | 58 +- src/RestClient.ts | 3470 ++++++++++++++++++++++++++++++++++++-- 2 files changed, 3341 insertions(+), 187 deletions(-) diff --git a/examples/rest-private.ts b/examples/rest-private.ts index 76d5e4c..7eaab9a 100644 --- a/examples/rest-private.ts +++ b/examples/rest-private.ts @@ -13,10 +13,64 @@ async function start() { apiSecret: account.secret, }); - const res1 = await rest.getBalances(); + //const res1 = await rest.getBalances(); + /* const res2 = await rest.getIndexConstituents({ + settle: 'usdt', + index: 'BTC_USDT', + }); */ + /* const res3 = await rest.portfolioMarginCalculator({ + body: { + spot_balances: [ + { + currency: 'BTC', + equity: '-1', + }, + ], + spot_orders: [ + { + currency_pairs: 'BTC_USDT', + order_price: '344', + left: '100', + type: 'sell', + }, + ], + futures_positions: [ + { + contract: 'BTC_USDT', + size: '100', + }, + ], + futures_orders: [ + { + contract: 'BTC_USDT', + size: '10', + left: '8', + }, + ], + options_positions: [ + { + options_name: 'BTC_USDT-20240329-32000-C', + size: '10', + }, + ], + options_orders: [ + { + options_name: 'BTC_USDT-20240329-32000-C', + size: '100', + left: '80', + }, + ], + spot_hedge: false, + }, + }); */ + + const res4 = await rest.getDeliveryContract({ + settle: 'usdt', + contract: 'BTC_USDT', + }); // const res1 = await rest.getSystemMaintenanceStatus(); - console.log('res: ', JSON.stringify(res1, null, 2)); + console.log('res: ', JSON.stringify(res4, null, 2)); } catch (e) { console.error(`Error in execution: `, e); } diff --git a/src/RestClient.ts b/src/RestClient.ts index 6845df9..2e1f854 100644 --- a/src/RestClient.ts +++ b/src/RestClient.ts @@ -416,12 +416,14 @@ export class RestClient extends BaseRestClient { * @returns Promise> */ withdraw(params: { - withdraw_order_id?: string; - amount: string; - currency: string; - address?: string; - memo?: string; - chain: string; + body: { + withdraw_order_id?: string; + amount: string; + currency: string; + address?: string; + memo?: string; + chain: string; + }; }): Promise> { return this.postPrivate('/withdrawals', params); } @@ -557,18 +559,26 @@ export class RestClient extends BaseRestClient { * @returns Promise> */ transferBetweenAccounts(params: { - 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; + body: { + 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; + }; }): Promise< APIResponse<{ tx_id: number; @@ -586,12 +596,14 @@ export class RestClient extends BaseRestClient { * @returns Promise> */ transferBetweenMainAndSubAccounts(params: { - currency: string; - sub_account: string; - direction: 'to' | 'from'; - amount: string; - client_order_id?: string; - sub_account_type?: 'spot' | 'futures' | 'cross_margin' | 'delivery'; + body: { + currency: string; + sub_account: string; + direction: 'to' | 'from'; + amount: string; + client_order_id?: string; + sub_account_type?: 'spot' | 'futures' | 'cross_margin' | 'delivery'; + }; }): Promise> { return this.postPrivate('/wallet/sub_account_transfers', params); } @@ -639,13 +651,15 @@ export class RestClient extends BaseRestClient { * @returns Promise> */ subAccountTransfersToSubAccount(params: { - currency: string; - sub_account_type?: 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; + body: { + currency: string; + sub_account_type?: 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; + }; }): Promise> { return this.postPrivate('/wallet/sub_account_to_sub_account', params); } @@ -1015,7 +1029,9 @@ export class RestClient extends BaseRestClient { * @returns Promise> */ convertSmallBalance(params: { - currency?: string[]; + body: { + currency?: string[]; + }; }): Promise> { return this.postPrivate('/wallet/small_balance', params); } @@ -1071,10 +1087,12 @@ export class RestClient extends BaseRestClient { * }>> */ createSubAccount(params: { - remark?: string; - login_name: string; - password?: string; - email?: string; + body: { + remark?: string; + login_name: string; + password?: string; + email?: string; + }; }): Promise< APIResponse<{ remark?: string; @@ -1174,22 +1192,7 @@ export class RestClient extends BaseRestClient { */ createSubAccountApiKey(params: { user_id: number; - mode?: number; - name?: string; - perms?: { - name?: - | 'wallet' - | 'spot' - | 'futures' - | 'delivery' - | 'earn' - | 'options' - | 'account' - | 'unified' - | 'loan'; - read_only?: boolean; - }[]; - ip_whitelist?: string[]; + body: SubAccountKey; }): Promise< APIResponse<{ user_id: string; @@ -1240,22 +1243,7 @@ export class RestClient extends BaseRestClient { updateSubAccountApiKey(params: { user_id: number; key: string; - mode?: number; - name?: string; - perms?: { - name?: - | 'wallet' - | 'spot' - | 'futures' - | 'delivery' - | 'earn' - | 'options' - | 'account' - | 'unified' - | 'loan'; - read_only?: boolean; - }[]; - ip_whitelist?: string[]; + body: SubAccountKey; }): Promise> { return this.putPrivate( `/sub_accounts/${params.user_id}/keys/${params.key}`, @@ -1442,11 +1430,13 @@ export class RestClient extends BaseRestClient { * @returns Promise> */ borrowOrRepay(params: { - currency: string; - type: 'borrow' | 'repay'; - amount: string; - repaid_all?: boolean; - text?: string; + body: { + currency: string; + type: 'borrow' | 'repay'; + amount: string; + repaid_all?: boolean; + text?: string; + }; }): Promise> { return this.postPrivate('/unified/loans', params); } @@ -1604,10 +1594,12 @@ export class RestClient extends BaseRestClient { * @returns Promise> */ setUnifiedAccountMode(params: { - mode: 'classic' | 'multi_currency' | 'portfolio'; - settings?: { - usdt_futures?: boolean; - spot_hedge?: boolean; + body: { + mode: 'classic' | 'multi_currency' | 'portfolio'; + settings?: { + usdt_futures?: boolean; + spot_hedge?: boolean; + }; }; }): Promise> { return this.putPrivate('/unified/unified_mode', params); @@ -1719,36 +1711,38 @@ export class RestClient extends BaseRestClient { * }>> */ portfolioMarginCalculator(params: { - 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; + body: { + 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; + }; }): Promise< APIResponse<{ maintain_margin_total: string; @@ -2285,20 +2279,7 @@ export class RestClient extends BaseRestClient { * finish_as: 'open' | 'filled' | 'cancelled' | 'ioc' | 'stp'; * }[]>> */ - createBatchOrders(params: { - body: { - currency_pair: string; - text: 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; - }[]; - }): Promise< + createBatchOrders(params: { body: Order[] }): Promise< APIResponse< { order_id: string; @@ -2459,11 +2440,13 @@ export class RestClient extends BaseRestClient { * }>> */ closePositionWhenCrossCurrencyDisabled(params: { - text?: string; - currency_pair: string; - amount: string; - price: string; - action_mode?: 'ACK' | 'RESULT' | 'FULL'; + body: { + text?: string; + currency_pair: string; + amount: string; + price: string; + action_mode?: 'ACK' | 'RESULT' | 'FULL'; + }; }): Promise> { return this.postPrivate('/spot/cross_liquidate_orders', params); } @@ -2491,21 +2474,7 @@ export class RestClient extends BaseRestClient { * action_mode?: 'ACK' | 'RESULT' | 'FULL'; * }>> */ - createOrder(params: { - text?: string; - 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; - stp_act?: 'cn' | 'co' | 'cb' | '-'; - action_mode?: 'ACK' | 'RESULT' | 'FULL'; - }): Promise> { + createOrder(params: { body: Order }): Promise> { return this.postPrivate('/spot/orders', params); } @@ -2633,12 +2602,7 @@ export class RestClient extends BaseRestClient { * account: string; * }[]>> */ - cancelBatchOrders(params: { - body: { - currency_pair: string; - id: string; - }[]; - }): Promise< + cancelBatchOrders(params: { body: CancelBatchOrder[] }): Promise< APIResponse< { currency_pair: string; @@ -2901,8 +2865,10 @@ export class RestClient extends BaseRestClient { * }>> */ countdownCancelOrders(params: { - timeout: number; - currency_pair?: string; + body: { + timeout: number; + currency_pair?: string; + }; }): Promise< APIResponse<{ triggerTime: number; @@ -2958,7 +2924,8 @@ export class RestClient extends BaseRestClient { */ amendBatchOrders(params: { body: { - order_id: string; + order_id?: string; + currency_pair?: string; amount?: string; price?: string; amend_text?: string; @@ -3016,23 +2983,7 @@ export class RestClient extends BaseRestClient { * id: number; * }>> */ - createPriceTriggeredOrder(params: { - 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; - }; - market: string; - }): Promise< + createPriceTriggeredOrder(params: { body: SpotPriceTriggeredOrder }): Promise< APIResponse<{ id: number; }> @@ -3530,9 +3481,11 @@ export class RestClient extends BaseRestClient { * }>> */ createCrossMarginBorrowLoan(params: { - currency: string; - amount: string; - text?: string; + body: { + currency: string; + amount: string; + text?: string; + }; }): Promise< APIResponse<{ id: string; @@ -3646,7 +3599,9 @@ export class RestClient extends BaseRestClient { * unpaid_interest: string; * }[]>> */ - crossMarginRepayments(params: { currency: string; amount: string }): Promise< + crossMarginRepayments(params: { + body: { currency: string; amount: string }; + }): Promise< APIResponse< { id: string; @@ -3859,11 +3814,13 @@ export class RestClient extends BaseRestClient { * @returns Promise */ borrowOrRepayMarginUNI(params: { - currency: string; - type: 'borrow' | 'repay'; - amount: string; - repaid_all?: boolean; - currency_pair: string; + body: { + currency: string; + type: 'borrow' | 'repay'; + amount: string; + repaid_all?: boolean; + currency_pair: string; + }; }): Promise { return this.postPrivate('/margin/uni/loans', params); } @@ -4047,11 +4004,13 @@ export class RestClient extends BaseRestClient { * }>> */ createFlashSwapOrder(params: { - preview_id: string; - sell_currency: string; - sell_amount: string; - buy_currency: string; - buy_amount: string; + body: { + preview_id: string; + sell_currency: string; + sell_amount: string; + buy_currency: string; + buy_amount: string; + }; }): Promise< APIResponse<{ id: number; @@ -4155,10 +4114,12 @@ export class RestClient extends BaseRestClient { * }>> */ initiateFlashSwapOrderPreview(params: { - sell_currency: string; - sell_amount?: string; - buy_currency: string; - buy_amount?: string; + body: { + sell_currency: string; + sell_amount?: string; + buy_currency: string; + buy_amount?: string; + }; }): Promise< APIResponse<{ preview_id: string; @@ -4171,6 +4132,3145 @@ export class RestClient extends BaseRestClient { > { return this.postPrivate('/flash_swap/orders/preview', params); } + /**========================================================================================================================== + * FUTURES + * ========================================================================================================================== + */ + + /** + * List all futures contracts + * + * @param params Parameters for listing futures contracts + * @returns Promise> + */ + listFuturesContracts(params: { + settle: 'btc' | 'usdt' | 'usd'; + limit?: number; + offset?: number; + }): Promise> { + return this.get(`/futures/${params.settle}/contracts`, params); + } + + /** + * Get a single contract + * + * @param params Parameters for retrieving a single contract + * @returns Promise> + */ + getSingleContract(params: { + settle: 'btc' | 'usdt' | 'usd'; + contract: string; + }): Promise> { + return this.get( + `/futures/${params.settle}/contracts/${params.contract}`, + params, + ); + } + + /** + * Futures order book + * + * Bids will be sorted by price from high to low, while asks sorted reversely. + * + * @param params Parameters for retrieving the futures order book + * @returns Promise> + */ + getFuturesOrderBook(params: { + settle: 'btc' | 'usdt' | 'usd'; + contract: string; + interval?: string; + limit?: number; + with_id?: boolean; + }): Promise< + APIResponse<{ + id?: number; + current: number; + update: number; + asks: { p: string; s: number }[]; + bids: { p: string; s: number }[]; + }> + > { + return this.get(`/futures/${params.settle}/order_book`, params); + } + + /** + * Futures trading history + * + * @param params Parameters for retrieving futures trading history + * @returns Promise> + */ + getFuturesTradingHistory(params: { + settle: 'btc' | 'usdt' | 'usd'; + contract: string; + limit?: number; + offset?: number; + last_id?: string; + from?: number; + to?: number; + }): Promise< + APIResponse< + { + id: number; + create_time: number; + create_time_ms: number; + contract: string; + size: number; + price: string; + is_internal?: boolean; + }[] + > + > { + return this.get(`/futures/${params.settle}/trades`, params); + } + + /** + * Get futures candlesticks + * + * Return specified contract candlesticks. If prefix contract with mark_, the contract's mark price candlesticks are returned; if prefix with index_, index price candlesticks will be returned. + * + * Maximum of 2000 points are returned in one query. Be sure not to exceed the limit when specifying from, to and interval. + * + * @param params Parameters for retrieving futures candlesticks + * @returns Promise> + */ + getFuturesCandlesticks(params: { + settle: 'btc' | 'usdt' | 'usd'; + contract: string; + from?: number; + to?: number; + limit?: number; + interval?: string; + }): Promise< + APIResponse< + { + t: number; + v?: number; + c: string; + h: string; + l: string; + o: string; + sum: string; + }[] + > + > { + return this.get(`/futures/${params.settle}/candlesticks`, params); + } + + /** + * Premium Index K-Line + * + * Maximum of 1000 points can be returned in a query. Be sure not to exceed the limit when specifying from, to and interval. + * + * @param params Parameters for retrieving premium index K-Line + * @returns Promise> + */ + getPremiumIndexKLine(params: { + settle: 'btc' | 'usdt' | 'usd'; + contract: string; + from?: number; + to?: number; + limit?: number; + interval?: string; + }): Promise< + APIResponse< + { + t: number; + c: string; + h: string; + l: string; + o: string; + }[] + > + > { + return this.get(`/futures/${params.settle}/premium_index`, params); + } + + /** + * List futures tickers + * + * @param params Parameters for listing futures tickers + * @returns Promise> + */ + listFuturesTickers(params: { + settle: 'btc' | 'usdt' | 'usd'; + contract?: string; + }): Promise< + APIResponse< + { + contract: string; + last: string; + change_percentage: string; + total_size: string; + low_24h: string; + high_24h: string; + volume_24h: string; + volume_24h_btc?: string; + volume_24h_usd?: string; + volume_24h_base: string; + volume_24h_quote: string; + volume_24h_settle: string; + mark_price: string; + funding_rate: string; + funding_rate_indicative: string; + index_price: string; + quanto_base_rate?: string; + basis_rate: string; + basis_value: string; + lowest_ask: string; + highest_bid: string; + }[] + > + > { + return this.get(`/futures/${params.settle}/tickers`, params); + } + + /** + * Funding rate history + * + * @param params Parameters for retrieving funding rate history + * @returns Promise> + */ + getFundingRateHistory(params: { + settle: 'btc' | 'usdt' | 'usd'; + contract: string; + limit?: number; + }): Promise< + APIResponse< + { + t: number; + r: string; + }[] + > + > { + return this.get(`/futures/${params.settle}/funding_rate`, params); + } + + /** + * Futures insurance balance history + * + * @param params Parameters for retrieving futures insurance balance history + * @returns Promise> + */ + getFuturesInsuranceBalanceHistory(params: { + settle: 'btc' | 'usdt' | 'usd'; + limit?: number; + }): Promise< + APIResponse< + { + t: number; + b: string; + }[] + > + > { + return this.get(`/futures/${params.settle}/insurance`, params); + } + + /** + * Futures stats + * + * @param params Parameters for retrieving futures stats + * @returns Promise> + */ + getFuturesStats(params: { + settle: 'btc' | 'usdt' | 'usd'; + contract: string; + from?: number; + interval?: string; + limit?: number; + }): Promise< + APIResponse< + { + time: number; + lsr_taker: number; + lsr_account: number; + long_liq_size: number; + long_liq_amount: number; + long_liq_usd: number; + short_liq_size: number; + short_liq_amount: number; + short_liq_usd: number; + open_interest: number; + open_interest_usd: number; + top_lsr_account: number; + top_lsr_size: number; + }[] + > + > { + return this.get(`/futures/${params.settle}/contract_stats`, params); + } + + /** + * Get index constituents + * + * @param params Parameters for retrieving index constituents + * @returns Promise> + */ + getIndexConstituents(params: { + settle: 'btc' | 'usdt' | 'usd'; + index: string; + }): Promise< + APIResponse<{ + index: string; + constituents: { + exchange: string; + symbols: string[]; + }[]; + }> + > { + return this.get( + `/futures/${params.settle}/index_constituents/${params.index}`, + params, + ); + } + + /** + * Retrieve liquidation history + * + * Interval between from and to cannot exceed 3600. Some private fields will not be returned in public endpoints. Refer to field description for detail. + * + * @param params Parameters for retrieving liquidation history + * @returns Promise> + */ + getLiquidationHistory(params: { + settle: 'btc' | 'usdt' | 'usd'; + contract?: string; + from?: number; + to?: number; + limit?: number; + }): Promise< + APIResponse< + { + time: number; + contract: string; + size: number; + order_price: string; + fill_price: string; + left: number; + }[] + > + > { + return this.get(`/futures/${params.settle}/liq_orders`, params); + } + + /** + * List risk limit tiers + * + * When the 'contract' parameter is not passed, the default is to query the risk limits for the top 100 markets. + * 'Limit' and 'offset' correspond to pagination queries at the market level, not to the length of the returned array. + * This only takes effect when the 'contract' parameter is empty. + * + * @param params Parameters for listing risk limit tiers + * @returns Promise> + */ + listRiskLimitTiers(params: { + settle: 'btc' | 'usdt' | 'usd'; + contract: string; + limit?: number; + offset?: number; + }): Promise< + APIResponse< + { + tier: number; + risk_limit: string; + initial_rate: string; + maintenance_rate: string; + leverage_max: string; + contract: string; + }[] + > + > { + return this.get(`/futures/${params.settle}/risk_limit_tiers`, params); + } + + /** + * Query futures account + * + * @param params Parameters for querying futures account + * @returns Promise> + */ + queryFuturesAccount(params: { settle: 'btc' | 'usdt' | 'usd' }): Promise< + APIResponse<{ + 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; + 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; + }; + }> + > { + return this.getPrivate(`/futures/${params.settle}/accounts`, params); + } + + /** + * Query account book + * + * If the contract field is provided, it can only filter records that include this field after 2023-10-30. + * + * @param params Parameters for querying account book + * @returns Promise> + */ + queryFuturesAccountBook(params: { + settle: 'btc' | 'usdt' | 'usd'; + contract?: string; + limit?: number; + offset?: number; + from?: number; + to?: number; + type?: + | 'dnw' + | 'pnl' + | 'fee' + | 'refr' + | 'fund' + | 'point_dnw' + | 'point_fee' + | 'point_refr' + | 'bonus_offset'; + }): Promise< + APIResponse< + { + time: number; + change: string; + balance: string; + type: string; + text: string; + contract?: string; + trade_id: string; + }[] + > + > { + return this.getPrivate(`/futures/${params.settle}/account_book`, params); + } + + /** + * List all positions of a user + * + * @param params Parameters for listing all positions of a user + * @returns Promise> + */ + listUserPositions(params: { + settle: 'btc' | 'usdt' | 'usd'; + holding?: boolean; + limit?: number; + offset?: number; + }): Promise> { + return this.getPrivate(`/futures/${params.settle}/positions`, params); + } + + /** + * Get single position + * + * @param params Parameters for retrieving a single position + * @returns Promise> + */ + getFuturesSinglePosition(params: { + settle: 'btc' | 'usdt' | 'usd'; + contract: string; + }): Promise> { + return this.getPrivate( + `/futures/${params.settle}/positions/${params.contract}`, + params, + ); + } + + /** + * Update position margin + * + * @param params Parameters for updating position margin + * @returns Promise> + */ + updatePositionMargin(params: { + settle: 'btc' | 'usdt' | 'usd'; + contract: string; + change: string; + }): Promise> { + return this.postPrivate( + `/futures/${params.settle}/positions/${params.contract}/margin`, + params, + ); + } + + /** + * Update position leverage + * + * @param params Parameters for updating position leverage + * @returns Promise> + */ + updatePositionLeverage(params: { + settle: 'btc' | 'usdt' | 'usd'; + contract: string; + leverage: string; + cross_leverage_limit?: string; + }): Promise> { + return this.postPrivate( + `/futures/${params.settle}/positions/${params.contract}/leverage`, + params, + ); + } + + /** + * Update position risk limit + * + * @param params Parameters for updating position risk limit + * @returns Promise> + */ + updatePositionRiskLimit(params: { + settle: 'btc' | 'usdt' | 'usd'; + contract: string; + risk_limit: string; + }): Promise> { + return this.postPrivate( + `/futures/${params.settle}/positions/${params.contract}/risk_limit`, + params, + ); + } + + /** + * Enable or disable dual mode + * + * Before setting dual mode, make sure all positions are closed and no orders are open. + * + * @param params Parameters for enabling or disabling dual mode + * @returns Promise> + */ + toggleDualMode(params: { + settle: 'btc' | 'usdt' | 'usd'; + dual_mode: boolean; + }): Promise< + APIResponse<{ + 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; + 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; + }; + }> + > { + return this.postPrivate(`/futures/${params.settle}/dual_mode`, params); + } + + /** + * Retrieve position detail in dual mode + * + * @param params Parameters for retrieving position detail in dual mode + * @returns Promise> + */ + getDualModePositionDetail(params: { + settle: 'btc' | 'usdt' | 'usd'; + contract: string; + }): Promise> { + return this.getPrivate( + `/futures/${params.settle}/dual_comp/positions/${params.contract}`, + params, + ); + } + + /** + * Update position margin in dual mode + * + * @param params Parameters for updating position margin in dual mode + * @returns Promise> + */ + updateDualModePositionMargin(params: { + settle: 'btc' | 'usdt' | 'usd'; + contract: string; + change: string; + dual_side: 'dual_long' | 'dual_short'; + }): Promise> { + return this.postPrivate( + `/futures/${params.settle}/dual_comp/positions/${params.contract}/margin`, + params, + ); + } + + /** + * Update position leverage in dual mode + * + * @param params Parameters for updating position leverage in dual mode + * @returns Promise> + */ + updateDualModePositionLeverage(params: { + settle: 'btc' | 'usdt' | 'usd'; + contract: string; + leverage: string; + cross_leverage_limit?: string; + }): Promise> { + return this.postPrivate( + `/futures/${params.settle}/dual_comp/positions/${params.contract}/leverage`, + params, + ); + } + + /** + * Update position risk limit in dual mode + * + * @param params Parameters for updating position risk limit in dual mode + * @returns Promise> + */ + updateDualModePositionRiskLimit(params: { + settle: 'btc' | 'usdt' | 'usd'; + contract: string; + risk_limit: string; + }): Promise> { + return this.postPrivate( + `/futures/${params.settle}/dual_comp/positions/${params.contract}/risk_limit`, + params, + ); + } + + /** + * Create a futures order + * + * Creating futures orders requires size, which is the number of contracts instead of currency amount. You can use quanto_multiplier in the contract detail response to know how much currency 1 size contract represents. + * Zero-filled order cannot be retrieved 10 minutes after order cancellation. You will get a 404 not found for such orders. + * Set reduce_only to true to keep the position from changing side when reducing position size. + * In single position mode, to close a position, you need to set size to 0 and close to true. + * In dual position mode, to close one side position, you need to set auto_size side, reduce_only to true, and size to 0. + * Set stp_act to decide the strategy of self-trade prevention. For detailed usage, refer to the stp_act parameter in the request body. + * + * @param params Parameters for creating a futures order + * @returns Promise> + */ + createFuturesOrder(params: { + settle: 'btc' | 'usdt' | 'usd'; + body: FuturesOrder; + }): Promise> { + return this.postPrivate(`/futures/${params.settle}/orders`, params); + } + + /** + * List futures orders + * + * Zero-fill order cannot be retrieved for 10 minutes after cancellation. + * Historical orders, by default, only data within the past 6 months is supported. If you need to query data for a longer period, please use GET /futures/{settle}/orders_timerange. + * + * @param params Parameters for listing futures orders + * @returns Promise> + */ + listFuturesOrders(params: { + settle: 'btc' | 'usdt' | 'usd'; + contract?: string; + status: string; + limit?: number; + offset?: number; + last_id?: string; + }): Promise> { + return this.getPrivate(`/futures/${params.settle}/orders`, params); + } + + /** + * Cancel all open orders matched + * + * Zero-filled order cannot be retrieved 10 minutes after order cancellation. + * + * @param params Parameters for cancelling all open orders matched + * @returns Promise> + */ + cancelAllFuturesOpenOrders(params: { + settle: 'btc' | 'usdt' | 'usd'; + contract: string; + side?: string; + }): Promise> { + return this.deletePrivate(`/futures/${params.settle}/orders`, params); + } + + /** + * List Futures Orders By Time Range + * + * @param params Parameters for listing futures orders by time range + * @returns Promise> + */ + listFuturesOrdersByTimeRange(params: { + settle: 'btc' | 'usdt' | 'usd'; + contract?: string; + from?: number; + to?: number; + limit?: number; + offset?: number; + }): Promise> { + return this.getPrivate( + `/futures/${params.settle}/orders_timerange`, + params, + ); + } + + /** + * Create a batch of futures orders + * + * Up to 10 orders per request. + * If any of the order's parameters are missing or in the wrong format, all of them will not be executed, and a http status 400 error will be returned directly. + * If the parameters are checked and passed, all are executed. Even if there is a business logic error in the middle (such as insufficient funds), it will not affect other execution orders. + * The returned result is in array format, and the order corresponds to the orders in the request body. + * In the returned result, the succeeded field of type bool indicates whether the execution was successful or not. + * If the execution is successful, the normal order content is included; if the execution fails, the label field is included to indicate the cause of the error. + * In the rate limiting, each order is counted individually. + * + * @param params Parameters for creating a batch of futures orders + * @returns Promise> + */ + createBatchFuturesOrders(params: { + settle: 'btc' | 'usdt' | 'usd'; + body: FuturesOrder[]; + }): Promise< + APIResponse< + { + succeeded: boolean; + label?: string; + detail?: string; + id: number; + user: number; + create_time: number; + finish_time?: number; + finish_as?: string; + status: string; + contract: string; + size: number; + iceberg: number; + price: string; + is_close: boolean; + is_reduce_only: boolean; + is_liq: boolean; + tif: string; + left: number; + fill_price: string; + text: string; + tkfr: string; + mkfr: string; + refu: number; + stp_act: string; + stp_id: number; + }[] + > + > { + return this.postPrivate(`/futures/${params.settle}/batch_orders`, params); + } + + /** + * Get a single order + * + * Zero-fill order cannot be retrieved for 10 minutes after cancellation. + * Historical orders, by default, only data within the past 6 months is supported. + * + * @param params Parameters for retrieving a single order + * @returns Promise> + */ + getFuturesSingleOrder(params: { + settle: 'btc' | 'usdt' | 'usd'; + order_id: string; + }): Promise> { + return this.getPrivate( + `/futures/${params.settle}/orders/${params.order_id}`, + params, + ); + } + + /** + * Cancel a single order + * + * @param params Parameters for cancelling a single order + * @returns Promise> + */ + cancelFuturesSingleOrder(params: { + settle: 'btc' | 'usdt' | 'usd'; + order_id: string; + }): Promise> { + return this.deletePrivate( + `/futures/${params.settle}/orders/${params.order_id}`, + params, + ); + } + + /** + * Amend an order + * + * @param params Parameters for amending an order + * @returns Promise> + */ + amendFuturesOrder(params: { + settle: 'btc' | 'usdt' | 'usd'; + order_id: string; + body: { + size?: number; + price?: string; + amend_text?: string; + }; + }): Promise> { + return this.putPrivate( + `/futures/${params.settle}/orders/${params.order_id}`, + params, + ); + } + + /** + * List personal trading history + * + * By default, only data within the past 6 months is supported. If you need to query data for a longer period, please use GET /futures/{settle}/my_trades_timerange. + * + * @param params Parameters for listing personal trading history + * @returns Promise> + */ + listFuturesPersonalTradingHistory(params: { + settle: 'btc' | 'usdt' | 'usd'; + contract?: string; + order?: number; + limit?: number; + offset?: number; + last_id?: string; + }): Promise< + APIResponse< + { + id: number; + create_time: number; + contract: string; + order_id: string; + size: number; + price: string; + role: 'taker' | 'maker'; + text: string; + fee: string; + point_fee: string; + }[] + > + > { + return this.getPrivate(`/futures/${params.settle}/my_trades`, params); + } + + /** + * List position close history + * + * @param params Parameters for listing position close history + * @returns Promise> + */ + listPositionCloseHistory(params: { + settle: 'btc' | 'usdt' | 'usd'; + contract?: string; + limit?: number; + offset?: number; + from?: number; + to?: number; + side?: 'long' | 'short'; + pnl?: string; + }): Promise< + APIResponse< + { + time: number; + contract: string; + side: 'long' | 'short'; + pnl: string; + pnl_pnl: string; + pnl_fund: string; + pnl_fee: string; + text: string; + max_size: string; + first_open_time: number; + long_price: string; + short_price: string; + }[] + > + > { + return this.getPrivate(`/futures/${params.settle}/position_close`, params); + } + + /** + * List liquidation history + * + * @param params Parameters for listing liquidation history + * @returns Promise> + */ + listLiquidationHistory(params: { + settle: 'btc' | 'usdt' | 'usd'; + contract?: string; + limit?: number; + at?: number; + }): Promise< + APIResponse< + { + time: number; + contract: string; + leverage: string; + size: number; + margin: string; + entry_price: string; + liq_price: string; + mark_price: string; + order_id: number; + order_price: string; + fill_price: string; + left: number; + }[] + > + > { + return this.getPrivate(`/futures/${params.settle}/liquidates`, params); + } + + /** + * List Auto-Deleveraging History + * + * @param params Parameters for listing auto-deleveraging history + * @returns Promise> + */ + listAutoDeleveragingHistory(params: { + settle: 'btc' | 'usdt' | 'usd'; + contract?: string; + limit?: number; + at?: number; + }): Promise< + APIResponse< + { + time: number; + user: number; + order_id: number; + contract: string; + leverage: string; + cross_leverage_limit: string; + entry_price: string; + fill_price: string; + trade_size: number; + position_size: number; + }[] + > + > { + return this.getPrivate( + `/futures/${params.settle}/auto_deleverages`, + params, + ); + } + + /** + * Countdown cancel orders + * + * When the timeout set by the user is reached, if there is no cancel or set a new countdown, the related pending orders will be automatically cancelled. This endpoint can be called repeatedly to set a new countdown or cancel the countdown. + * For example, call this endpoint at 30s intervals, each countdown timeout is set to 30s. If this endpoint is not called again within 30 seconds, all pending orders on the specified market will be automatically cancelled, if no market is specified, all market pending orders will be cancelled. + * If the timeout is set to 0 within 30 seconds, the countdown timer will expire and the cancel function will be cancelled. + * + * @param params Parameters for setting countdown cancel orders + * @returns Promise> + */ + countdownFuturesCancelOrders(params: { + settle: 'btc' | 'usdt' | 'usd'; + body: { + timeout: number; + contract?: string; + }; + }): Promise> { + return this.postPrivate( + `/futures/${params.settle}/countdown_cancel_all`, + params, + ); + } + + /** + * Query user trading fee rates + * + * @param params Parameters for querying user trading fee rates + * @returns Promise>> + */ + queryFuturesUserTradingFeeRates(params: { + settle: 'btc' | 'usdt' | 'usd'; + contract?: string; + }): Promise< + APIResponse> + > { + return this.getPrivate(`/futures/${params.settle}/fee`, params); + } + + /** + * Cancel a batch of orders with an ID list + * + * Multiple distinct order ID list can be specified. Each request can cancel a maximum of 20 records. + * + * @param params Parameters for cancelling a batch of orders with an ID list + * @returns Promise> + */ + cancelFuturesBatchOrders(params: { + settle: 'btc' | 'usdt' | 'usd'; + body: string[]; + }): Promise< + APIResponse< + { + user_id: number; + id: string; + succeeded: boolean; + message: string; + }[] + > + > { + return this.postPrivate( + `/futures/${params.settle}/batch_cancel_orders`, + params, + ); + } + + /** + * Create a price-triggered order + * + * @param params Parameters for creating a price-triggered order + * @returns Promise> + */ + createFuturesPriceTriggeredOrder(params: { + settle: 'btc' | 'usdt' | 'usd'; + body: FuturesPriceTriggeredOrder; + }): Promise> { + return this.postPrivate(`/futures/${params.settle}/price_orders`, params); + } + + /** + * List all auto orders + * + * @param params Parameters for listing all auto orders + * @returns Promise> + */ + listAllAutoOrders(params: { + settle: 'btc' | 'usdt' | 'usd'; + status: 'open' | 'finished'; + contract?: string; + limit?: number; + offset?: number; + }): Promise> { + return this.getPrivate(`/futures/${params.settle}/price_orders`, params); + } + + /** + * Cancel all open orders + * + * @param params Parameters for cancelling all open orders + * @returns Promise> + */ + cancelFuturesAllOpenOrders(params: { + settle: 'btc' | 'usdt' | 'usd'; + contract: string; + }): Promise> { + return this.deletePrivate(`/futures/${params.settle}/price_orders`, params); + } + + /** + * Get a price-triggered order + * + * @param params Parameters for retrieving a price-triggered order + * @returns Promise> + */ + getFuturesPriceTriggeredOrder(params: { + settle: 'btc' | 'usdt' | 'usd'; + order_id: string; + }): Promise> { + return this.getPrivate( + `/futures/${params.settle}/price_orders/${params.order_id}`, + params, + ); + } + + /** + * Cancel a price-triggered order + * + * @param params Parameters for cancelling a price-triggered order + * @returns Promise> + */ + cancelFuturesPriceTriggeredOrder(params: { + settle: 'btc' | 'usdt' | 'usd'; + order_id: string; + }): Promise> { + return this.deletePrivate( + `/futures/${params.settle}/price_orders/${params.order_id}`, + params, + ); + } + /**========================================================================================================================== + * DELIVERY + * ========================================================================================================================== + */ + + /** + * List all futures contracts + * + * @param params Parameters for listing all futures contracts + * @returns Promise> + */ + getAllDeliveryContracts(params: { + settle: 'usdt'; + }): Promise> { + return this.get(`/delivery/${params.settle}/contracts`, params); + } + + /** + * Get a single contract + * + * @param params Parameters for retrieving a single contract + * @returns Promise> + */ + getDeliveryContract(params: { + settle: 'usdt'; + contract: string; + }): Promise> { + return this.get( + `/delivery/${params.settle}/contracts/${params.contract}`, + params, + ); + } + + /** + * Futures order book + * + * Bids will be sorted by price from high to low, while asks sorted reversely + * + * @param params Parameters for retrieving the futures order book + * @returns Promise> + */ + getDeliveryOrderBook(params: { + settle: 'usdt'; + contract: string; + interval?: '0' | '0.1' | '0.01'; + limit?: number; + with_id?: boolean; + }): Promise< + APIResponse<{ + id?: number; + current: number; + update: number; + asks: { p: string; s: number }[]; + bids: { p: string; s: number }[]; + }> + > { + return this.get(`/delivery/${params.settle}/order_book`, params); + } + + /** + * Futures trading history + * + * @param params Parameters for retrieving the futures trading history + * @returns Promise> + */ + getDeliveryTradingHistory(params: { + settle: 'usdt'; + contract: string; + limit?: number; + last_id?: string; + from?: number; + to?: number; + }): Promise< + APIResponse< + { + id: number; + create_time: number; + create_time_ms: number; + contract: string; + size: number; + price: string; + is_internal?: boolean; + }[] + > + > { + return this.get(`/delivery/${params.settle}/trades`, params); + } + + /** + * Get futures candlesticks + * + * Return specified contract candlesticks. If prefix contract with mark_, the contract's mark price candlesticks are returned; if prefix with index_, index price candlesticks will be returned. + * Maximum of 2000 points are returned in one query. Be sure not to exceed the limit when specifying from, to and interval. + * + * @param params Parameters for retrieving futures candlesticks + * @returns Promise> + */ + getDeliveryCandlesticks(params: { + settle: 'usdt'; + contract: string; + from?: number; + to?: number; + limit?: number; + interval?: + | '10s' + | '30s' + | '1m' + | '5m' + | '15m' + | '30m' + | '1h' + | '2h' + | '4h' + | '6h' + | '8h' + | '12h' + | '1d' + | '7d' + | '1w' + | '30d'; + }): Promise< + APIResponse< + { + t: number; + v?: number; + c: string; + h: string; + l: string; + o: string; + }[] + > + > { + return this.get(`/delivery/${params.settle}/candlesticks`, params); + } + + /** + * List futures tickers + * + * @param params Parameters for listing futures tickers + * @returns Promise> + */ + listDeliveryTickers(params: { settle: 'usdt'; contract?: string }): Promise< + APIResponse< + { + contract: string; + last: string; + change_percentage: string; + total_size: string; + low_24h: string; + high_24h: string; + volume_24h: string; + volume_24h_btc?: string; + volume_24h_usd?: string; + volume_24h_base: string; + volume_24h_quote: string; + volume_24h_settle: string; + mark_price: string; + funding_rate: string; + funding_rate_indicative: string; + index_price: string; + quanto_base_rate?: string; + basis_rate: string; + basis_value: string; + lowest_ask: string; + highest_bid: string; + }[] + > + > { + return this.get(`/delivery/${params.settle}/tickers`, params); + } + + /** + * Futures insurance balance history + * + * @param params Parameters for retrieving the futures insurance balance history + * @returns Promise> + */ + getDeliveryInsuranceBalanceHistory(params: { + settle: 'usdt'; + limit?: number; + }): Promise< + APIResponse< + { + t: number; + b: string; + }[] + > + > { + return this.get(`/delivery/${params.settle}/insurance`, params); + } + + /** + * Query futures account + * + * @param params Parameters for querying futures account + * @returns Promise> + */ + queryDeliveryAccount(params: { settle: 'usdt' }): Promise< + APIResponse<{ + 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; + 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; + }; + }> + > { + return this.getPrivate(`/delivery/${params.settle}/accounts`, params); + } + + /** + * Query account book + * + * @param params Parameters for querying account book + * @returns Promise> + */ + queryDeliveryBook(params: { + settle: 'usdt'; + limit?: number; + from?: number; + to?: number; + type?: + | 'dnw' + | 'pnl' + | 'fee' + | 'refr' + | 'fund' + | 'point_dnw' + | 'point_fee' + | 'point_refr' + | 'bonus_offset'; + }): Promise< + APIResponse< + { + time: number; + change: string; + balance: string; + type: + | 'dnw' + | 'pnl' + | 'fee' + | 'refr' + | 'fund' + | 'point_dnw' + | 'point_fee' + | 'point_refr' + | 'bonus_offset'; + text: string; + contract?: string; + trade_id?: string; + }[] + > + > { + return this.getPrivate(`/delivery/${params.settle}/account_book`, params); + } + + /** + * List all positions of a user + * + * @param params Parameters for listing all positions of a user + * @returns Promise> + */ + getDeliveryPositions(params: { + settle: 'usdt'; + }): Promise> { + return this.getPrivate(`/delivery/${params.settle}/positions`, params); + } + + /** + * Get single position + * + * @param params Parameters for retrieving a single position + * @returns Promise> + */ + getDeliveryPosition(params: { + settle: 'usdt'; + contract: string; + }): Promise> { + return this.getPrivate( + `/delivery/${params.settle}/positions/${params.contract}`, + params, + ); + } + + /** + * Update position margin + * + * @param params Parameters for updating position margin + * @returns Promise> + */ + updateDeliveryMargin(params: { + settle: 'usdt'; + contract: string; + change: string; + }): Promise> { + return this.postPrivate( + `/delivery/${params.settle}/positions/${params.contract}/margin`, + params, + ); + } + + /** + * Update position leverage + * + * @param params Parameters for updating position leverage + * @returns Promise> + */ + updateDeliveryLeverage(params: { + settle: 'usdt'; + contract: string; + leverage: string; + }): Promise> { + return this.postPrivate( + `/delivery/${params.settle}/positions/${params.contract}/leverage`, + params, + ); + } + + /** + * Update position risk limit + * + * @param params Parameters for updating position risk limit + * @returns Promise> + */ + updateDeliveryRiskLimit(params: { + settle: 'usdt'; + contract: string; + risk_limit: string; + }): Promise> { + return this.postPrivate( + `/delivery/${params.settle}/positions/${params.contract}/risk_limit`, + params, + ); + } + + /** + * Create a futures order + * + * Zero-filled order cannot be retrieved 10 minutes after order cancellation + * + * @param params Parameters for creating a futures order + * @returns Promise> + */ + createDeliveryOrder(params: { + settle: 'usdt'; + body: FuturesOrder; + }): Promise> { + return this.postPrivate(`/delivery/${params.settle}/orders`, params); + } + + /** + * List futures orders + * + * Zero-fill order cannot be retrieved 10 minutes after order cancellation. + * + * @param params Parameters for listing futures orders + * @returns Promise> + */ + listDeliveryOrders(params: { + settle: 'usdt'; + contract?: string; + status: 'open' | 'finished'; + limit?: number; + offset?: number; + last_id?: string; + count_total?: 0 | 1; + }): Promise> { + return this.getPrivate(`/delivery/${params.settle}/orders`, params); + } + + /** + * Cancel all open orders matched + * + * Zero-filled order cannot be retrieved 10 minutes after order cancellation + * + * @param params Parameters for cancelling all open orders matched + * @returns Promise> + */ + cancelAllDeliveryOrders(params: { + settle: 'usdt'; + contract: string; + side?: 'ask' | 'bid'; + }): Promise> { + return this.deletePrivate(`/delivery/${params.settle}/orders`, params); + } + + /** + * Get a single order + * + * Zero-filled order cannot be retrieved 10 minutes after order cancellation + * + * @param params Parameters for retrieving a single order + * @returns Promise> + */ + getDeliveryOrder(params: { + settle: 'usdt'; + order_id: string; + }): Promise> { + return this.getPrivate( + `/delivery/${params.settle}/orders/${params.order_id}`, + ); + } + + /** + * Cancel a single order + * + * @param params Parameters for cancelling a single order + * @returns Promise> + */ + cancelDeliveryOrder(params: { + settle: 'usdt'; + order_id: string; + }): Promise> { + return this.deletePrivate( + `/delivery/${params.settle}/orders/${params.order_id}`, + ); + } + + /** + * List personal trading history + * + * @param params Parameters for listing personal trading history + * @returns Promise> + */ + getDeliveryPersonalHistory(params: { + settle: 'usdt'; + contract?: string; + order?: number; + limit?: number; + offset?: number; + last_id?: string; + count_total?: 0 | 1; + }): Promise< + APIResponse< + { + id: number; + create_time: number; + contract: string; + order_id: string; + size: number; + price: string; + role: 'taker' | 'maker'; + text: string; + fee: string; + point_fee: string; + }[] + > + > { + return this.getPrivate(`/delivery/${params.settle}/my_trades`, params); + } + + /** + * List position close history + * + * @param params Parameters for listing position close history + * @returns Promise> + */ + getDeliveryClosedPositions(params: { + settle: 'usdt'; + contract?: string; + limit?: number; + }): Promise< + APIResponse< + { + time: number; + contract: string; + side: 'long' | 'short'; + pnl: string; + pnl_pnl: string; + pnl_fund: string; + pnl_fee: string; + text: string; + max_size: string; + first_open_time: number; + long_price: string; + short_price: string; + }[] + > + > { + return this.getPrivate(`/delivery/${params.settle}/position_close`, params); + } + + /** + * List liquidation history + * + * @param params Parameters for listing liquidation history + * @returns Promise> + */ + getDeliveryLiquidationHistory(params: { + settle: 'usdt'; + contract?: string; + limit?: number; + at?: number; + }): Promise< + APIResponse< + { + time: number; + contract: string; + leverage?: string; + size: number; + margin?: string; + entry_price?: string; + liq_price?: string; + mark_price?: string; + order_id?: number; + order_price: string; + fill_price: string; + left: number; + }[] + > + > { + return this.getPrivate(`/delivery/${params.settle}/liquidates`, params); + } + + /** + * List settlement history + * + * @param params Parameters for listing settlement history + * @returns Promise> + */ + getDeliverySettlementHistory(params: { + settle: 'usdt'; + contract?: string; + limit?: number; + at?: number; + }): Promise< + APIResponse< + { + time: number; + contract: string; + leverage: string; + size: number; + margin: string; + entry_price: string; + settle_price: string; + profit: string; + fee: string; + }[] + > + > { + return this.getPrivate(`/delivery/${params.settle}/settlements`, params); + } + + /** + * Create a price-triggered order + * + * @param params Parameters for creating a price-triggered order + * @returns Promise> + */ + submitDeliveryTriggeredOrder(params: { + settle: 'usdt'; + body: FuturesPriceTriggeredOrder; + }): Promise> { + return this.postPrivate(`/delivery/${params.settle}/price_orders`, params); + } + + /** + * List all auto orders + * + * @param params Parameters for listing all auto orders + * @returns Promise> + */ + getDeliveryAutoOrders(params: { + settle: 'usdt'; + status: 'open' | 'finished'; + contract?: string; + limit?: number; + offset?: number; + }): Promise> { + return this.getPrivate(`/delivery/${params.settle}/price_orders`, params); + } + + /** + * Cancel all open orders + * + * @param params Parameters for cancelling all open orders + * @returns Promise> + */ + cancelAllDeliveryOpenOrders(params: { + settle: 'usdt'; + contract: string; + }): Promise> { + return this.deletePrivate( + `/delivery/${params.settle}/price_orders`, + params, + ); + } + + /** + * Get a price-triggered order + * + * @param params Parameters for retrieving a price-triggered order + * @returns Promise> + */ + getDeliveryTriggeredOrder(params: { + settle: 'usdt'; + order_id: string; + }): Promise> { + return this.getPrivate( + `/delivery/${params.settle}/price_orders/${params.order_id}`, + params, + ); + } + + /** + * Cancel a price-triggered order + * + * @param params Parameters for cancelling a price-triggered order + * @returns Promise> + */ + deleteDeliveryTriggeredOrder(params: { + settle: 'usdt'; + order_id: string; + }): Promise> { + return this.deletePrivate( + `/delivery/${params.settle}/price_orders/${params.order_id}`, + ); + } + + /**========================================================================================================================== + * OPIONS + * ========================================================================================================================== + */ + + /** + * List all underlyings + * + * @returns Promise> + */ + getOptionsUnderlyings(): Promise< + APIResponse<{ name: string; index_price: string }[]> + > { + return this.get(`/options/underlyings`); + } + + /** + * List all expiration times + * + * @param params Parameters for listing expiration times + * @returns Promise> + */ + getOptionsExpirationTimes(params: { + underlying: string; + }): Promise> { + return this.get(`/options/expirations`, params); + } + + /** + * List all the contracts with specified underlying and expiration time + * + * @param params Parameters for listing contracts + * @returns Promise> + */ + getOptionsContracts(params: { + underlying: string; + expiration?: number; + }): Promise< + APIResponse< + { + name: string; + tag: string; + create_time: number; + expiration_time: number; + is_call: boolean; + strike_price: string; + last_price: string; + mark_price: string; + orderbook_id: number; + trade_id: number; + trade_size: number; + position_size: number; + underlying: string; + underlying_price: string; + multiplier: string; + order_price_round: string; + mark_price_round: string; + maker_fee_rate: string; + taker_fee_rate: string; + price_limit_fee_rate: string; + ref_discount_rate: string; + ref_rebate_rate: string; + order_price_deviate: string; + order_size_min: number; + order_size_max: number; + orders_limit: number; + }[] + > + > { + return this.get(`/options/contracts`, params); + } + + /** + * Query specified contract detail + * + * @param params Parameters for querying specified contract detail + * @returns Promise> + */ + getOptionsContract(params: { contract: string }): Promise< + APIResponse<{ + name: string; + tag: string; + create_time: number; + expiration_time: number; + is_call: boolean; + strike_price: string; + last_price: string; + mark_price: string; + orderbook_id: number; + trade_id: number; + trade_size: number; + position_size: number; + underlying: string; + underlying_price: string; + multiplier: string; + order_price_round: string; + mark_price_round: string; + maker_fee_rate: string; + taker_fee_rate: string; + price_limit_fee_rate: string; + ref_discount_rate: string; + ref_rebate_rate: string; + order_price_deviate: string; + order_size_min: number; + order_size_max: number; + orders_limit: number; + }> + > { + return this.get(`/options/contracts/${params.contract}`, params); + } + + /** + * List settlement history + * + * @param params Parameters for listing settlement history + * @returns Promise> + */ + getOptionsSettlementHistory(params: { + underlying: string; + limit?: number; + offset?: number; + from?: number; + to?: number; + }): Promise< + APIResponse< + { + time: number; + contract: string; + profit: string; + fee: string; + strike_price: string; + settle_price: string; + }[] + > + > { + return this.get(`/options/settlements`, params); + } + + /** + * Get specified contract's settlement + * + * @param params Parameters for retrieving specified contract's settlement + * @returns Promise> + */ + getOptionsContractSettlement(params: { + contract: string; + underlying: string; + at: number; + }): Promise< + APIResponse<{ + time: number; + contract: string; + profit: string; + fee: string; + strike_price: string; + settle_price: string; + }> + > { + return this.get(`/options/settlements/${params.contract}`, params); + } + + /** + * List my options settlements + * + * @param params Parameters for listing my options settlements + * @returns Promise> + */ + getOptionsMySettlements(params: { + underlying: string; + contract?: string; + limit?: number; + offset?: number; + from?: number; + to?: number; + }): Promise< + APIResponse< + { + time: number; + underlying: string; + contract: string; + strike_price: string; + settle_price: string; + size: number; + settle_profit: string; + fee: string; + realised_pnl: string; + }[] + > + > { + return this.getPrivate(`/options/my_settlements`, params); + } + + /** + * Options order book + * + * Bids will be sorted by price from high to low, while asks sorted reversely + * + * @param params Parameters for retrieving options order book + * @returns Promise> + */ + getOptionsOrderBook(params: { + contract: string; + interval?: '0' | '0.1' | '0.01'; + limit?: number; + with_id?: boolean; + }): Promise< + APIResponse<{ + id?: number; + current: number; + update: number; + asks: { p: string; s: number }[]; + bids: { p: string; s: number }[]; + }> + > { + return this.get(`/options/order_book`, params); + } + + /** + * List tickers of options contracts + * + * @param params Parameters for listing tickers of options contracts + * @returns Promise> + */ + getOptionsTickers(params: { underlying: string }): Promise< + APIResponse< + { + name: string; + last_price: string; + mark_price: string; + index_price: string; + ask1_size: number; + ask1_price: string; + bid1_size: number; + bid1_price: string; + position_size: number; + mark_iv: string; + bid_iv: string; + ask_iv: string; + leverage: string; + delta: string; + gamma: string; + vega: string; + theta: string; + rho: string; + }[] + > + > { + return this.get(`/options/tickers`, params); + } + + /** + * Get underlying ticker + * + * @param params Parameters for retrieving underlying ticker + * @returns Promise> + */ + getOptionsUnderlyingTicker(params: { underlying: string }): Promise< + APIResponse<{ + trade_put: number; + trade_call: number; + index_price: string; + }> + > { + return this.get(`/options/underlying/tickers/${params.underlying}`); + } + + /** + * Get options candlesticks + * + * @param params Parameters for retrieving options candlesticks + * @returns Promise> + */ + getOptionsCandlesticks(params: { + contract: string; + limit?: number; + from?: number; + to?: number; + interval?: '1m' | '5m' | '15m' | '30m' | '1h'; + }): Promise< + APIResponse< + { + t: number; + v?: number; + c: string; + h: string; + l: string; + o: string; + }[] + > + > { + return this.get(`/options/candlesticks`, params); + } + + /** + * Mark price candlesticks of an underlying + * + * @param params Parameters for retrieving mark price candlesticks of an underlying + * @returns Promise> + */ + getOptionsUnderlyingCandlesticks(params: { + underlying: string; + limit?: number; + from?: number; + to?: number; + interval?: '1m' | '5m' | '15m' | '30m' | '1h'; + }): Promise< + APIResponse< + { + t: number; + v?: number; + c: string; + h: string; + l: string; + o: string; + sum: string; + }[] + > + > { + return this.get(`/options/underlying/candlesticks`, params); + } + + /** + * Options trade history + * + * @param params Parameters for retrieving options trade history + * @returns Promise> + */ + getOptionsTrades(params: { + contract?: string; + type?: 'C' | 'P'; + limit?: number; + offset?: number; + from?: number; + to?: number; + }): Promise< + APIResponse< + { + id: number; + create_time: number; + create_time_ms: number; + contract: string; + size: number; + price: string; + is_internal?: boolean; + }[] + > + > { + return this.get(`/options/trades`, params); + } + + /** + * List options account + * + * @returns Promise> + */ + getOptionsAccount(): Promise< + APIResponse<{ + user: number; + total: string; + short_enabled: boolean; + unrealised_pnl: string; + init_margin: string; + maint_margin: string; + order_margin: string; + available: string; + point: string; + currency: string; + }> + > { + return this.getPrivate(`/options/accounts`); + } + + /** + * List account changing history + * + * @param params Parameters for listing account changing history + * @returns Promise> + */ + getOptionsAccountChange(params: { + limit?: number; + offset?: number; + from?: number; + to?: number; + type?: 'dnw' | 'prem' | 'fee' | 'refr' | 'set'; + }): Promise< + APIResponse< + { + time: number; + change: string; + balance: string; + type: 'dnw' | 'prem' | 'fee' | 'refr' | 'set'; + text: string; + }[] + > + > { + return this.getPrivate(`/options/account_book`, params); + } + + /** + * List user's positions of specified underlying + * + * @param params Parameters for listing user's positions of specified underlying + * @returns Promise> + */ + + getOptionsPositionsUnderlying(params: { underlying?: string }): Promise< + APIResponse< + { + user: number; + underlying: string; + underlying_price: string; + contract: string; + size: number; + entry_price: string; + mark_price: string; + mark_iv: string; + realised_pnl: string; + unrealised_pnl: string; + pending_orders: number; + close_order: { + id: number; + price: string; + is_liq: boolean; + } | null; + delta: string; + gamma: string; + vega: string; + theta: string; + }[] + > + > { + return this.getPrivate(`/options/positions`, params); + } + /** + * Get specified contract position + * + * @param params Parameters for retrieving specified contract position + * @returns Promise> + */ + getOptionsPositionContract(params: { contract: string }): Promise< + APIResponse<{ + user: number; + underlying: string; + underlying_price: string; + contract: string; + size: number; + entry_price: string; + mark_price: string; + mark_iv: string; + realised_pnl: string; + unrealised_pnl: string; + pending_orders: number; + close_order: { + id: number; + price: string; + is_liq: boolean; + } | null; + delta: string; + gamma: string; + vega: string; + theta: string; + }> + > { + return this.getPrivate(`/options/positions/${params.contract}`, params); + } + + /** + * List user's liquidation history of specified underlying + * + * @param params Parameters for listing user's liquidation history of specified underlying + * @returns Promise> + */ + getOptionsLiquidation(params: { + underlying: string; + contract?: string; + }): Promise< + APIResponse< + { + time: number; + contract: string; + side: 'long' | 'short'; + pnl: string; + text: string; + settle_size: string; + }[] + > + > { + return this.getPrivate(`/options/position_close`, params); + } + + /** + * Create an options order + * + * @param body Body parameters for creating an options order + * @returns Promise> + */ + submitOptionsOrder(body: { + contract: string; + size: number; + iceberg?: number; + price?: string; + close?: boolean; + reduce_only?: boolean; + tif?: 'gtc' | 'ioc' | 'poc'; + text?: string; + }): Promise< + APIResponse<{ + id: number; + user: number; + create_time: number; + finish_time: number; + finish_as: + | 'filled' + | 'cancelled' + | 'liquidated' + | 'ioc' + | 'auto_deleveraged' + | 'reduce_only' + | 'position_closed'; + status: 'open' | 'finished'; + contract: string; + size: number; + iceberg: number; + price: string; + is_close: boolean; + is_reduce_only: boolean; + is_liq: boolean; + tif: 'gtc' | 'ioc' | 'poc'; + left: number; + fill_price: string; + text: string; + tkfr: string; + mkfr: string; + refu: number; + refr: string; + }> + > { + return this.post(`/options/orders`, body); + } + + /** + * List options orders + * + * @param params Parameters for listing options orders + * @returns Promise> + */ + getOptionsOrders(params: { + contract?: string; + underlying?: string; + status: 'open' | 'finished'; + limit?: number; + offset?: number; + from?: number; + to?: number; + }): Promise< + APIResponse< + { + id: number; + user: number; + create_time: number; + finish_time: number; + finish_as: + | 'filled' + | 'cancelled' + | 'liquidated' + | 'ioc' + | 'auto_deleveraged' + | 'reduce_only' + | 'position_closed'; + status: 'open' | 'finished'; + contract: string; + size: number; + iceberg: number; + price: string; + is_close: boolean; + is_reduce_only: boolean; + is_liq: boolean; + tif: 'gtc' | 'ioc' | 'poc'; + left: number; + fill_price: string; + text: string; + tkfr: string; + mkfr: string; + refu: number; + refr: string; + }[] + > + > { + return this.getPrivate(`/options/orders`, params); + } + + /** + * Cancel all open orders matched + * + * @param params Parameters for canceling all open orders matched + * @returns Promise> + */ + deleteOptionsOrders(params: { + contract?: string; + underlying?: string; + side?: 'ask' | 'bid'; + }): Promise< + APIResponse< + { + id: number; + user: number; + create_time: number; + finish_time: number; + finish_as: + | 'filled' + | 'cancelled' + | 'liquidated' + | 'ioc' + | 'auto_deleveraged' + | 'reduce_only' + | 'position_closed'; + status: 'open' | 'finished'; + contract: string; + size: number; + iceberg: number; + price: string; + is_close: boolean; + is_reduce_only: boolean; + is_liq: boolean; + tif: 'gtc' | 'ioc' | 'poc'; + left: number; + fill_price: string; + text: string; + tkfr: string; + mkfr: string; + refu: number; + refr: string; + }[] + > + > { + return this.deletePrivate(`/options/orders`, params); + } + + /** + * Get a single order + * + * @param params Parameters for retrieving a single order + * @returns Promise> + */ + getOptionsOrder(params: { order_id: number }): Promise< + APIResponse<{ + id: number; + user: number; + create_time: number; + finish_time: number; + finish_as: + | 'filled' + | 'cancelled' + | 'liquidated' + | 'ioc' + | 'auto_deleveraged' + | 'reduce_only' + | 'position_closed'; + status: 'open' | 'finished'; + contract: string; + size: number; + iceberg: number; + price: string; + is_close: boolean; + is_reduce_only: boolean; + is_liq: boolean; + tif: 'gtc' | 'ioc' | 'poc'; + left: number; + fill_price: string; + text: string; + tkfr: string; + mkfr: string; + refu: number; + refr: string; + }> + > { + return this.getPrivate(`/options/orders/${params.order_id}`); + } + + /** + * Cancel a single order + * + * @param params Parameters for canceling a single order + * @returns Promise> + */ + deleteOptionsOrder(params: { order_id: number }): Promise< + APIResponse<{ + id: number; + user: number; + create_time: number; + finish_time: number; + finish_as: + | 'filled' + | 'cancelled' + | 'liquidated' + | 'ioc' + | 'auto_deleveraged' + | 'reduce_only' + | 'position_closed'; + status: 'open' | 'finished'; + contract: string; + size: number; + iceberg: number; + price: string; + is_close: boolean; + is_reduce_only: boolean; + is_liq: boolean; + tif: 'gtc' | 'ioc' | 'poc'; + left: number; + fill_price: string; + text: string; + tkfr: string; + mkfr: string; + refu: number; + refr: string; + }> + > { + return this.deletePrivate(`/options/orders/${params.order_id}`); + } + + /** + * List personal trading history + * + * @param params Parameters for listing personal trading history + * @returns Promise> + */ + getOptionsPersonalHistory(params: { + underlying: string; + contract?: string; + limit?: number; + offset?: number; + from?: number; + to?: number; + }): Promise< + APIResponse< + { + id: number; + create_time: number; + contract: string; + order_id: number; + size: number; + price: string; + underlying_price: string; + role: 'taker' | 'maker'; + }[] + > + > { + return this.getPrivate(`/options/my_trades`, params); + } + /**========================================================================================================================== * WALLET * ========================================================================================================================== From 9d70616eaddf21e067080e26785df3974864d643 Mon Sep 17 00:00:00 2001 From: Jerko J <83344666+JJ-Cro@users.noreply.github.com> Date: Sun, 19 May 2024 19:27:47 +0200 Subject: [PATCH 05/36] feat(): Added all endpoints --- src/RestClient.ts | 1805 ++++++++++++++++++++++++++++++++++++++++----- 1 file changed, 1621 insertions(+), 184 deletions(-) diff --git a/src/RestClient.ts b/src/RestClient.ts index 2e1f854..60cf116 100644 --- a/src/RestClient.ts +++ b/src/RestClient.ts @@ -35,10 +35,6 @@ interface SubAccountKey { last_access?: number; } -interface EstimateRate { - [key: string]: string; -} - interface CurrencyPair { id?: string; base?: string; @@ -101,44 +97,6 @@ interface CancelBatchOrder { action_mode?: 'ACK' | 'RESULT' | 'FULL'; } -interface Loan { - id?: string; - create_time?: string; - expire_time?: string; - status?: 'open' | 'loaned' | 'finished' | 'auto_repaid'; - side: 'lend' | 'borrow'; - currency: string; - rate?: string; - amount: string; - days?: number; - auto_renew?: boolean; - currency_pair?: string; - left?: string; - repaid?: string; - paid_interest?: string; - unpaid_interest?: string; - fee_rate?: string; - orig_id?: string; - text?: string; -} - -interface LoanRecord { - id?: string; - loan_id?: string; - create_time?: string; - expire_time?: string; - status?: 'loaned' | 'finished'; - borrow_user_id?: string; - currency?: string; - rate?: string; - amount?: string; - days?: number; - auto_renew?: boolean; - repaid?: string; - paid_interest?: string; - unpaid_interest?: string; -} - interface SpotPriceTriggeredOrder { trigger: { price: string; @@ -415,7 +373,7 @@ export class RestClient extends BaseRestClient { * @param params Withdrawal parameters * @returns Promise> */ - withdraw(params: { + submitWithdraw(params: { body: { withdraw_order_id?: string; amount: string; @@ -460,7 +418,7 @@ export class RestClient extends BaseRestClient { decimal: string; }[]>> */ - listCurrencyChains(params: { currency: string }): Promise< + getCurrencyChains(params: { currency: string }): Promise< APIResponse< { chain: string; @@ -493,7 +451,7 @@ export class RestClient extends BaseRestClient { }[]; }>> */ - generateDepositAddress(params: { currency: string }): Promise< + createDepositAddress(params: { currency: string }): Promise< APIResponse<{ currency: string; address: string; @@ -517,7 +475,7 @@ export class RestClient extends BaseRestClient { * @param params Parameters for filtering withdrawal records * @returns Promise> */ - retrieveWithdrawalRecords(params?: { + getWithdrawalRecords(params?: { currency?: string; from?: number; to?: number; @@ -535,7 +493,7 @@ export class RestClient extends BaseRestClient { * @param params Parameters for filtering deposit records * @returns Promise> */ - retrieveDepositRecords(params?: { + getDepositRecords(params?: { currency?: string; from?: number; to?: number; @@ -558,7 +516,7 @@ export class RestClient extends BaseRestClient { * @param params Transfer parameters * @returns Promise> */ - transferBetweenAccounts(params: { + submitTransfer(params: { body: { currency: string; from: @@ -595,7 +553,7 @@ export class RestClient extends BaseRestClient { * @param params Transfer parameters * @returns Promise> */ - transferBetweenMainAndSubAccounts(params: { + submitMainSubTransfer(params: { body: { currency: string; sub_account: string; @@ -618,7 +576,7 @@ export class RestClient extends BaseRestClient { * @param params Parameters for filtering transfer records * @returns Promise> */ - retrieveSubAccountTransferRecords(params?: { + getMainSubTransfers(params?: { sub_uid?: string; from?: number; to?: number; @@ -650,7 +608,7 @@ export class RestClient extends BaseRestClient { * @param params Transfer parameters * @returns Promise> */ - subAccountTransfersToSubAccount(params: { + getSubToSubTransfer(params: { body: { currency: string; sub_account_type?: string; @@ -683,7 +641,7 @@ export class RestClient extends BaseRestClient { withdraw_percent_on_chains: { [key: string]: string }; }[]>> */ - retrieveWithdrawalStatus(params?: { currency?: string }): Promise< + getWithdrawalStatus(params?: { currency?: string }): Promise< APIResponse< { currency: string; @@ -713,7 +671,7 @@ export class RestClient extends BaseRestClient { available: { [key: string]: string }; }[]>> */ - retrieveSubAccountBalances(params?: { sub_uid?: string }): Promise< + getSubBalance(params?: { sub_uid?: string }): Promise< APIResponse< { uid: string; @@ -730,7 +688,7 @@ export class RestClient extends BaseRestClient { * @param params Parameters for querying sub accounts' margin balances * @returns Promise> */ - querySubAccountMarginBalances(params?: { sub_uid?: string }): Promise< + getSubMarginBalances(params?: { sub_uid?: string }): Promise< APIResponse< { uid: string; @@ -765,7 +723,7 @@ export class RestClient extends BaseRestClient { * @param params Parameters for querying sub accounts' futures account balances * @returns Promise> */ - querySubAccountFuturesBalances(params?: { + getSubFuturesBalances(params?: { sub_uid?: string; settle?: string; }): Promise< @@ -840,7 +798,7 @@ export class RestClient extends BaseRestClient { * }; * }[]>> */ - querySubAccountCrossMarginBalances(params?: { sub_uid?: string }): Promise< + getSubCrossMarginBalances(params?: { sub_uid?: string }): Promise< APIResponse< { uid: string; @@ -888,7 +846,7 @@ export class RestClient extends BaseRestClient { * verified: string; * }[]>> */ - querySavedAddress(params: { + getSavedAddress(params: { currency: string; chain?: string; limit?: string; @@ -928,7 +886,7 @@ export class RestClient extends BaseRestClient { * debit_fee: number; * }>> */ - retrievePersonalTradingFee(params?: { + getTradingFees(params?: { currency_pair?: string; settle?: 'BTC' | 'USDT' | 'USD'; }): Promise< @@ -1011,7 +969,7 @@ export class RestClient extends BaseRestClient { * convertible_to_gt: string; * }>> */ - listSmallBalance(): Promise< + getSmallBalances(): Promise< APIResponse<{ currency: string; available_balance: string; @@ -1048,7 +1006,7 @@ export class RestClient extends BaseRestClient { * create_time: number; * }[]>> */ - listSmallBalanceHistory(params?: { + getSmallBalanceHistory(params?: { currency?: string; page?: number; limit?: number; @@ -1123,7 +1081,7 @@ export class RestClient extends BaseRestClient { * create_time: number; * }[]>> */ - listSubAccounts(params?: { type?: string }): Promise< + getSubAccounts(params?: { type?: string }): Promise< APIResponse< { remark?: string; @@ -1228,7 +1186,7 @@ export class RestClient extends BaseRestClient { * @param params Parameters containing the sub-account user ID * @returns Promise> */ - listSubAccountApiKeys(params: { + getSubAccountApiKeys(params: { user_id: number; }): Promise> { return this.getPrivate(`/sub_accounts/${params.user_id}/keys`); @@ -1390,7 +1348,7 @@ export class RestClient extends BaseRestClient { * amount: string; * }>> */ - queryUnifiedAccountMaxBorrowing(params: { currency: string }): Promise< + getUnifiedMaxBorrow(params: { currency: string }): Promise< APIResponse<{ currency: string; amount: string; @@ -1408,7 +1366,7 @@ export class RestClient extends BaseRestClient { * amount: string; * }>> */ - queryUnifiedAccountMaxTransferable(params: { currency: string }): Promise< + getUnifiedMaxTransferable(params: { currency: string }): Promise< APIResponse<{ currency: string; amount: string; @@ -1429,7 +1387,7 @@ export class RestClient extends BaseRestClient { * @param params Parameters for borrowing or repaying * @returns Promise> */ - borrowOrRepay(params: { + submitUnifiedBorrowOrRepay(params: { body: { currency: string; type: 'borrow' | 'repay'; @@ -1454,7 +1412,7 @@ export class RestClient extends BaseRestClient { * update_time: number; * }[]>> */ - listLoans(params?: { + getUnifiedLoans(params?: { currency?: string; page?: number; limit?: number; @@ -1488,7 +1446,7 @@ export class RestClient extends BaseRestClient { * create_time: number; * }[]>> */ - getLoanRecords(params?: { + getUnifiedLoanRecords(params?: { type?: 'borrow' | 'repay'; currency?: string; page?: number; @@ -1527,7 +1485,7 @@ export class RestClient extends BaseRestClient { * create_time: number; * }[]>> */ - listInterestRecords(params?: { + getUnifiedInterestRecords(params?: { currency?: string; page?: number; limit?: number; @@ -1566,7 +1524,7 @@ export class RestClient extends BaseRestClient { * }[]; * }>> */ - retrieveUserRiskUnitDetails(): Promise< + getUnifiedRiskUnitDetails(): Promise< APIResponse<{ user_id: number; spot_hedge: boolean; @@ -1616,7 +1574,7 @@ export class RestClient extends BaseRestClient { * }; * }>> */ - queryUnifiedAccountMode(): Promise< + getUnifiedAccountMode(): Promise< APIResponse<{ mode: 'classic' | 'multi_currency' | 'portfolio'; settings: { @@ -1655,7 +1613,7 @@ export class RestClient extends BaseRestClient { * }[]; * }[]>> */ - listCurrencyDiscountTiers(): Promise< + getUnifiedCurrencyDiscountTiers(): Promise< APIResponse< { currency: string; @@ -1808,7 +1766,7 @@ export class RestClient extends BaseRestClient { * chain: string; * }[]>> */ - listAllCurrenciesDetails(): Promise< + getSpotCurrencies(): Promise< APIResponse< { currency: string; @@ -1840,7 +1798,7 @@ export class RestClient extends BaseRestClient { * chain: string; * }>> */ - getCurrencyDetails(params: { currency: string }): Promise< + getSpotCurrency(params: { currency: string }): Promise< APIResponse<{ currency: string; delisted: boolean; @@ -1872,7 +1830,7 @@ export class RestClient extends BaseRestClient { * buy_start: number; * }[]>> */ - listAllCurrencyPairs(): Promise> { + getSpotCurrencyPairs(): Promise> { return this.get('/spot/currency_pairs'); } @@ -1894,7 +1852,7 @@ export class RestClient extends BaseRestClient { * buy_start: number; * }>> */ - getCurrencyPairDetails(params: { + getSpotCurrencyPair(params: { currency_pair: string; }): Promise> { return this.get(`/spot/currency_pairs/${params.currency_pair}`); @@ -1924,7 +1882,7 @@ export class RestClient extends BaseRestClient { * etf_leverage: string | null; * }[]>> */ - retrieveTickerInformation(params?: { + getSpotTicker(params?: { currency_pair?: string; timezone?: 'utc0' | 'utc8' | 'all'; }): Promise< @@ -1965,7 +1923,7 @@ export class RestClient extends BaseRestClient { * bids: [string, string][]; * }>> */ - retrieveOrderBook(params: { + getSpotOrderBook(params: { currency_pair: string; interval?: string; limit?: number; @@ -2008,7 +1966,7 @@ export class RestClient extends BaseRestClient { * text: string; * }[]>> */ - retrieveMarketTrades(params: { + getSpotTrades(params: { currency_pair: string; limit?: number; last_id?: string; @@ -2058,7 +2016,7 @@ export class RestClient extends BaseRestClient { * boolean // Whether the window is closed * ]]>> */ - marketCandlesticks(params: { + getSpotCandlesticks(params: { currency_pair: string; limit?: number; from?: number; @@ -2113,7 +2071,7 @@ export class RestClient extends BaseRestClient { * debit_fee: number; * }>> */ - queryUserTradingFeeRates(params?: { currency_pair?: string }): Promise< + getSpotFeeRates(params?: { currency_pair?: string }): Promise< APIResponse<{ user_id: number; taker_fee: string; @@ -2149,7 +2107,7 @@ export class RestClient extends BaseRestClient { * }; * }>> */ - queryBatchUserTradingFeeRates(params: { currency_pairs: string }): Promise< + getSpotBatchFeeRates(params: { currency_pairs: string }): Promise< APIResponse<{ [key: string]: { user_id: number; @@ -2179,7 +2137,7 @@ export class RestClient extends BaseRestClient { * update_id: number; * }[]>> */ - listSpotAccounts(params?: { currency?: string }): Promise< + getSpotAccounts(params?: { currency?: string }): Promise< APIResponse< { currency: string; @@ -2208,7 +2166,7 @@ export class RestClient extends BaseRestClient { * text: string; * }[]>> */ - queryAccountBook(params?: { + getSpotAccountBook(params?: { currency?: string; from?: number; to?: number; @@ -2279,7 +2237,7 @@ export class RestClient extends BaseRestClient { * finish_as: 'open' | 'filled' | 'cancelled' | 'ioc' | 'stp'; * }[]>> */ - createBatchOrders(params: { body: Order[] }): Promise< + submitSpotBatchOrders(params: { body: Order[] }): Promise< APIResponse< { order_id: string; @@ -2373,7 +2331,7 @@ export class RestClient extends BaseRestClient { * }[]; * }[]>> */ - listAllOpenOrders(params?: { + getSpotOpenOrders(params?: { page?: number; limit?: number; account?: 'spot' | 'margin' | 'cross_margin' | 'unified'; @@ -2439,7 +2397,7 @@ export class RestClient extends BaseRestClient { * action_mode?: 'ACK' | 'RESULT' | 'FULL'; * }>> */ - closePositionWhenCrossCurrencyDisabled(params: { + submitSpotClosePosCrossDisabled(params: { body: { text?: string; currency_pair: string; @@ -2474,7 +2432,7 @@ export class RestClient extends BaseRestClient { * action_mode?: 'ACK' | 'RESULT' | 'FULL'; * }>> */ - createOrder(params: { body: Order }): Promise> { + submitSpotOrder(params: { body: Order }): Promise> { return this.postPrivate('/spot/orders', params); } @@ -2521,7 +2479,7 @@ export class RestClient extends BaseRestClient { * finish_as: 'open' | 'filled' | 'cancelled' | 'ioc' | 'stp'; * }[]>> */ - listOrders(params: { + getSpotOrders(params: { currency_pair: string; status: 'open' | 'finished'; page?: number; @@ -2578,7 +2536,7 @@ export class RestClient extends BaseRestClient { * finish_as: 'open' | 'filled' | 'cancelled' | 'ioc' | 'stp'; * }[]>> */ - cancelPairOpenOrders(params: { + deleteSpotPairOpenOrders(params: { currency_pair: string; side?: 'buy' | 'sell'; account?: 'spot' | 'margin' | 'cross_margin' | 'unified'; @@ -2602,7 +2560,7 @@ export class RestClient extends BaseRestClient { * account: string; * }[]>> */ - cancelBatchOrders(params: { body: CancelBatchOrder[] }): Promise< + deleteSpotBatchOrders(params: { body: CancelBatchOrder[] }): Promise< APIResponse< { currency_pair: string; @@ -2660,7 +2618,7 @@ export class RestClient extends BaseRestClient { * finish_as: 'open' | 'filled' | 'cancelled' | 'ioc' | 'stp'; * }>> */ - getSingleOrder(params: { + getSpotOrder(params: { order_id: string; currency_pair: string; account?: 'spot' | 'margin' | 'cross_margin' | 'unified'; @@ -2713,7 +2671,7 @@ export class RestClient extends BaseRestClient { * finish_as: 'open' | 'filled' | 'cancelled' | 'ioc' | 'stp'; * }>> */ - amendOrder(params: { + updateSpotOrder(params: { order_id: string; currency_pair: string; account?: 'spot' | 'margin' | 'cross_margin' | 'unified'; @@ -2770,7 +2728,7 @@ export class RestClient extends BaseRestClient { * finish_as: 'open' | 'filled' | 'cancelled' | 'ioc' | 'stp'; * }>> */ - cancelSingleOrder(params: { + deleteSpotOrder(params: { order_id: string; currency_pair: string; account?: 'spot' | 'margin' | 'cross_margin' | 'unified'; @@ -2806,7 +2764,7 @@ export class RestClient extends BaseRestClient { * text: string; * }[]>> */ - listPersonalTradingHistory(params?: { + getSpotTradingHistory(params?: { currency_pair?: string; limit?: number; page?: number; @@ -2864,7 +2822,7 @@ export class RestClient extends BaseRestClient { * triggerTime: number; * }>> */ - countdownCancelOrders(params: { + submitSpotCountdownOrders(params: { body: { timeout: number; currency_pair?: string; @@ -2922,7 +2880,7 @@ export class RestClient extends BaseRestClient { * finish_as: 'open' | 'filled' | 'cancelled' | 'ioc' | 'stp'; * }[]>> */ - amendBatchOrders(params: { + updateSpotBatchOrders(params: { body: { order_id?: string; currency_pair?: string; @@ -2983,7 +2941,9 @@ export class RestClient extends BaseRestClient { * id: number; * }>> */ - createPriceTriggeredOrder(params: { body: SpotPriceTriggeredOrder }): Promise< + submitSpotPriceTriggerOrder(params: { + body: SpotPriceTriggeredOrder; + }): Promise< APIResponse<{ id: number; }> @@ -3015,7 +2975,7 @@ export class RestClient extends BaseRestClient { * status: 'open' | 'finished'; * }[]>> */ - retrieveRunningAutoOrderList(params: { + getSpotAutoOrders(params: { status: 'open' | 'finished'; market?: string; account?: 'normal' | 'margin' | 'cross_margin'; @@ -3048,7 +3008,7 @@ export class RestClient extends BaseRestClient { * status: 'open' | 'finished'; * }[]>> */ - cancelAllOpenOrders(params?: { + deleteSpotAllOpenOrders(params?: { market?: string; account?: 'normal' | 'margin' | 'cross_margin'; }): Promise> { @@ -3109,7 +3069,7 @@ export class RestClient extends BaseRestClient { * status: 'open' | 'finished'; * }>> */ - cancelPriceTriggeredOrder(params: { + deleteSpotPriceTriggeredOrder(params: { order_id: string; }): Promise> { return this.deletePrivate(`/spot/price_orders/${params.order_id}`, params); @@ -3144,7 +3104,7 @@ export class RestClient extends BaseRestClient { * }; * }[]>> */ - listMarginAccounts(params?: { currency_pair?: string }): Promise< + getMarginAccounts(params?: { currency_pair?: string }): Promise< APIResponse< { currency_pair: string; @@ -3187,7 +3147,7 @@ export class RestClient extends BaseRestClient { * type: string; * }[]>> */ - listMarginAccountBalanceChangeHistory(params?: { + getMarginBalanceHistory(params?: { currency?: string; currency_pair?: string; type?: string; @@ -3224,7 +3184,7 @@ export class RestClient extends BaseRestClient { * total_lent: string; * }[]>> */ - listFundingAccounts(params?: { currency?: string }): Promise< + getFundingAccounts(params?: { currency?: string }): Promise< APIResponse< { currency: string; @@ -3255,9 +3215,7 @@ export class RestClient extends BaseRestClient { * * @returns Promise> */ - retrieveAutoRepaymentSetting(): Promise< - APIResponse<{ status: 'on' | 'off' }> - > { + getAutoRepaymentSetting(): Promise> { return this.getPrivate('/margin/auto_repay'); } @@ -3300,7 +3258,7 @@ export class RestClient extends BaseRestClient { * status: number; * }[]>> */ - listCrossMarginCurrencies(): Promise< + getCrossMarginCurrencies(): Promise< APIResponse< { name: string; @@ -3388,7 +3346,7 @@ export class RestClient extends BaseRestClient { * portfolio_margin_total_equity: string; * }>> */ - retrieveCrossMarginAccount(): Promise< + getCrossMarginAccount(): Promise< APIResponse<{ user_id: number; refresh_time: number; @@ -3439,7 +3397,7 @@ export class RestClient extends BaseRestClient { * type: string; * }[]>> */ - retrieveCrossMarginAccountChangeHistory(params?: { + getCrossMarginAccountHistory(params?: { currency?: string; from?: number; to?: number; @@ -3480,7 +3438,7 @@ export class RestClient extends BaseRestClient { * unpaid_interest: string; * }>> */ - createCrossMarginBorrowLoan(params: { + submitCrossMarginBorrowLoan(params: { body: { currency: string; amount: string; @@ -3522,7 +3480,7 @@ export class RestClient extends BaseRestClient { * unpaid_interest: string; * }[]>> */ - listCrossMarginBorrowHistory(params: { + getCrossMarginBorrowHistory(params: { status: number; currency?: string; limit?: number; @@ -3564,7 +3522,7 @@ export class RestClient extends BaseRestClient { * unpaid_interest: string; * }>> */ - getSingleBorrowLoanDetail(params: { loan_id: string }): Promise< + getCrossMarginBorrowLoan(params: { loan_id: string }): Promise< APIResponse<{ id: string; create_time: number; @@ -3599,7 +3557,7 @@ export class RestClient extends BaseRestClient { * unpaid_interest: string; * }[]>> */ - crossMarginRepayments(params: { + submitCrossMarginRepayment(params: { body: { currency: string; amount: string }; }): Promise< APIResponse< @@ -3636,7 +3594,7 @@ export class RestClient extends BaseRestClient { * repayment_type: string; * }[]>> */ - retrieveCrossMarginRepayments(params?: { + getCrossMarginRepayments(params?: { currency?: string; loan_id?: string; limit?: number; @@ -3758,7 +3716,7 @@ export class RestClient extends BaseRestClient { * leverage: string; * }[]>> */ - listLendingMarkets(): Promise< + getLendingMarkets(): Promise< APIResponse< { currency_pair: string; @@ -3782,7 +3740,7 @@ export class RestClient extends BaseRestClient { * leverage: string; * }>> */ - getLendingMarketDetail(params: { currency_pair: string }): Promise< + getLendingMarket(params: { currency_pair: string }): Promise< APIResponse<{ currency_pair: string; base_min_borrow_amount: string; @@ -3813,7 +3771,7 @@ export class RestClient extends BaseRestClient { * @param params Parameters for borrowing or repaying * @returns Promise */ - borrowOrRepayMarginUNI(params: { + submitMarginUNIBorrowOrRepay(params: { body: { currency: string; type: 'borrow' | 'repay'; @@ -3838,7 +3796,7 @@ export class RestClient extends BaseRestClient { * update_time: number; * }[]>> */ - listLoansMarginUNI(params?: { + getMarginUNILoans(params?: { currency_pair?: string; currency?: string; page?: number; @@ -3870,7 +3828,7 @@ export class RestClient extends BaseRestClient { * create_time: number; * }[]>> */ - getLoanRecordsMarginUNI(params?: { + getMarginUNILoanRecords(params?: { type?: 'borrow' | 'repay'; currency?: string; currency_pair?: string; @@ -3904,7 +3862,7 @@ export class RestClient extends BaseRestClient { * create_time: number; * }[]>> */ - listInterestRecordsMarginUNI(params?: { + getMarginUNIInterestRecords(params?: { currency_pair?: string; currency?: string; page?: number; @@ -3937,7 +3895,7 @@ export class RestClient extends BaseRestClient { * borrowable: string; * }>> */ - getMaxBorrowable(params: { + getMarginUNIMaxBorrow(params: { currency: string; currency_pair: string; }): Promise< @@ -3969,7 +3927,7 @@ export class RestClient extends BaseRestClient { * buy_max_amount: string; * }[]>> */ - listFlashSwapCurrencyPairs(params?: { currency?: string }): Promise< + getFlashSwapCurrencyPairs(params?: { currency?: string }): Promise< APIResponse< { currency_pair: string; @@ -4003,7 +3961,7 @@ export class RestClient extends BaseRestClient { * status: number; * }>> */ - createFlashSwapOrder(params: { + submitFlashSwapOrder(params: { body: { preview_id: string; sell_currency: string; @@ -4043,7 +4001,7 @@ export class RestClient extends BaseRestClient { * status: number; * }[]>> */ - listFlashSwapOrders(params?: { + getFlashSwapOrders(params?: { status?: number; sell_currency?: string; buy_currency?: string; @@ -4084,7 +4042,7 @@ export class RestClient extends BaseRestClient { * status: number; * }>> */ - getFlashSwapOrderDetail(params: { order_id: number }): Promise< + getFlashSwapOrder(params: { order_id: number }): Promise< APIResponse<{ id: number; create_time: number; @@ -4113,7 +4071,7 @@ export class RestClient extends BaseRestClient { * price: string; * }>> */ - initiateFlashSwapOrderPreview(params: { + submitFlashSwapOrderPreview(params: { body: { sell_currency: string; sell_amount?: string; @@ -4143,7 +4101,7 @@ export class RestClient extends BaseRestClient { * @param params Parameters for listing futures contracts * @returns Promise> */ - listFuturesContracts(params: { + getFuturesContracts(params: { settle: 'btc' | 'usdt' | 'usd'; limit?: number; offset?: number; @@ -4157,7 +4115,7 @@ export class RestClient extends BaseRestClient { * @param params Parameters for retrieving a single contract * @returns Promise> */ - getSingleContract(params: { + getFuturesContract(params: { settle: 'btc' | 'usdt' | 'usd'; contract: string; }): Promise> { @@ -4213,7 +4171,7 @@ export class RestClient extends BaseRestClient { * is_internal?: boolean; * }[]>> */ - getFuturesTradingHistory(params: { + getFuturesTrades(params: { settle: 'btc' | 'usdt' | 'usd'; contract: string; limit?: number; @@ -4341,7 +4299,7 @@ export class RestClient extends BaseRestClient { * highest_bid: string; * }[]>> */ - listFuturesTickers(params: { + getFuturesTickers(params: { settle: 'btc' | 'usdt' | 'usd'; contract?: string; }): Promise< @@ -4383,7 +4341,7 @@ export class RestClient extends BaseRestClient { * r: string; * }[]>> */ - getFundingRateHistory(params: { + getFundingRates(params: { settle: 'btc' | 'usdt' | 'usd'; contract: string; limit?: number; @@ -4407,7 +4365,7 @@ export class RestClient extends BaseRestClient { * b: string; * }[]>> */ - getFuturesInsuranceBalanceHistory(params: { + getFuturesInsuranceBalance(params: { settle: 'btc' | 'usdt' | 'usd'; limit?: number; }): Promise< @@ -4552,7 +4510,7 @@ export class RestClient extends BaseRestClient { * contract: string; * }[]>> */ - listRiskLimitTiers(params: { + getRiskLimitTiers(params: { settle: 'btc' | 'usdt' | 'usd'; contract: string; limit?: number; @@ -4604,7 +4562,7 @@ export class RestClient extends BaseRestClient { * }; * }>> */ - queryFuturesAccount(params: { settle: 'btc' | 'usdt' | 'usd' }): Promise< + getFuturesAccount(params: { settle: 'btc' | 'usdt' | 'usd' }): Promise< APIResponse<{ total: string; unrealised_pnl: string; @@ -4652,7 +4610,7 @@ export class RestClient extends BaseRestClient { * trade_id: string; * }[]>> */ - queryFuturesAccountBook(params: { + getFuturesAccountBook(params: { settle: 'btc' | 'usdt' | 'usd'; contract?: string; limit?: number; @@ -4691,7 +4649,7 @@ export class RestClient extends BaseRestClient { * @param params Parameters for listing all positions of a user * @returns Promise> */ - listUserPositions(params: { + getFuturesPositions(params: { settle: 'btc' | 'usdt' | 'usd'; holding?: boolean; limit?: number; @@ -4706,7 +4664,7 @@ export class RestClient extends BaseRestClient { * @param params Parameters for retrieving a single position * @returns Promise> */ - getFuturesSinglePosition(params: { + getFuturesPosition(params: { settle: 'btc' | 'usdt' | 'usd'; contract: string; }): Promise> { @@ -4722,7 +4680,7 @@ export class RestClient extends BaseRestClient { * @param params Parameters for updating position margin * @returns Promise> */ - updatePositionMargin(params: { + updateFuturesMargin(params: { settle: 'btc' | 'usdt' | 'usd'; contract: string; change: string; @@ -4739,7 +4697,7 @@ export class RestClient extends BaseRestClient { * @param params Parameters for updating position leverage * @returns Promise> */ - updatePositionLeverage(params: { + updateFuturesLeverage(params: { settle: 'btc' | 'usdt' | 'usd'; contract: string; leverage: string; @@ -4802,7 +4760,7 @@ export class RestClient extends BaseRestClient { * }; * }>> */ - toggleDualMode(params: { + toggleFuturesDualMode(params: { settle: 'btc' | 'usdt' | 'usd'; dual_mode: boolean; }): Promise< @@ -4843,7 +4801,7 @@ export class RestClient extends BaseRestClient { * @param params Parameters for retrieving position detail in dual mode * @returns Promise> */ - getDualModePositionDetail(params: { + getDualModePosition(params: { settle: 'btc' | 'usdt' | 'usd'; contract: string; }): Promise> { @@ -4919,7 +4877,7 @@ export class RestClient extends BaseRestClient { * @param params Parameters for creating a futures order * @returns Promise> */ - createFuturesOrder(params: { + submitFuturesOrder(params: { settle: 'btc' | 'usdt' | 'usd'; body: FuturesOrder; }): Promise> { @@ -4935,7 +4893,7 @@ export class RestClient extends BaseRestClient { * @param params Parameters for listing futures orders * @returns Promise> */ - listFuturesOrders(params: { + getFuturesOrders(params: { settle: 'btc' | 'usdt' | 'usd'; contract?: string; status: string; @@ -4954,7 +4912,7 @@ export class RestClient extends BaseRestClient { * @param params Parameters for cancelling all open orders matched * @returns Promise> */ - cancelAllFuturesOpenOrders(params: { + deleteAllFuturesOrders(params: { settle: 'btc' | 'usdt' | 'usd'; contract: string; side?: string; @@ -4968,7 +4926,7 @@ export class RestClient extends BaseRestClient { * @param params Parameters for listing futures orders by time range * @returns Promise> */ - listFuturesOrdersByTimeRange(params: { + getFuturesOrdersByTimeRange(params: { settle: 'btc' | 'usdt' | 'usd'; contract?: string; from?: number; @@ -5022,7 +4980,7 @@ export class RestClient extends BaseRestClient { * stp_id: number; * }[]>> */ - createBatchFuturesOrders(params: { + submitFuturesBatchOrders(params: { settle: 'btc' | 'usdt' | 'usd'; body: FuturesOrder[]; }): Promise< @@ -5068,7 +5026,7 @@ export class RestClient extends BaseRestClient { * @param params Parameters for retrieving a single order * @returns Promise> */ - getFuturesSingleOrder(params: { + getFuturesOrder(params: { settle: 'btc' | 'usdt' | 'usd'; order_id: string; }): Promise> { @@ -5084,13 +5042,12 @@ export class RestClient extends BaseRestClient { * @param params Parameters for cancelling a single order * @returns Promise> */ - cancelFuturesSingleOrder(params: { + deleteFuturesOrder(params: { settle: 'btc' | 'usdt' | 'usd'; order_id: string; }): Promise> { return this.deletePrivate( `/futures/${params.settle}/orders/${params.order_id}`, - params, ); } @@ -5100,7 +5057,7 @@ export class RestClient extends BaseRestClient { * @param params Parameters for amending an order * @returns Promise> */ - amendFuturesOrder(params: { + updateFuturesOrder(params: { settle: 'btc' | 'usdt' | 'usd'; order_id: string; body: { @@ -5134,7 +5091,7 @@ export class RestClient extends BaseRestClient { * point_fee: string; * }[]>> */ - listFuturesPersonalTradingHistory(params: { + getFuturesTradingHistory(params: { settle: 'btc' | 'usdt' | 'usd'; contract?: string; order?: number; @@ -5179,7 +5136,7 @@ export class RestClient extends BaseRestClient { * short_price: string; * }[]>> */ - listPositionCloseHistory(params: { + getFuturesPositionHistory(params: { settle: 'btc' | 'usdt' | 'usd'; contract?: string; limit?: number; @@ -5228,7 +5185,7 @@ export class RestClient extends BaseRestClient { * left: number; * }[]>> */ - listLiquidationHistory(params: { + getFuturesLiquidationHistory(params: { settle: 'btc' | 'usdt' | 'usd'; contract?: string; limit?: number; @@ -5271,7 +5228,7 @@ export class RestClient extends BaseRestClient { * position_size: number; * }[]>> */ - listAutoDeleveragingHistory(params: { + getFuturesAutoDeleveragingHistory(params: { settle: 'btc' | 'usdt' | 'usd'; contract?: string; limit?: number; @@ -5308,7 +5265,7 @@ export class RestClient extends BaseRestClient { * @param params Parameters for setting countdown cancel orders * @returns Promise> */ - countdownFuturesCancelOrders(params: { + deleteFuturesOrdersCountdown(params: { settle: 'btc' | 'usdt' | 'usd'; body: { timeout: number; @@ -5327,7 +5284,7 @@ export class RestClient extends BaseRestClient { * @param params Parameters for querying user trading fee rates * @returns Promise>> */ - queryFuturesUserTradingFeeRates(params: { + getFuturesUserTradingFees(params: { settle: 'btc' | 'usdt' | 'usd'; contract?: string; }): Promise< @@ -5349,7 +5306,7 @@ export class RestClient extends BaseRestClient { * message: string; * }[]>> */ - cancelFuturesBatchOrders(params: { + deleteFuturesBatchOrders(params: { settle: 'btc' | 'usdt' | 'usd'; body: string[]; }): Promise< @@ -5374,7 +5331,7 @@ export class RestClient extends BaseRestClient { * @param params Parameters for creating a price-triggered order * @returns Promise> */ - createFuturesPriceTriggeredOrder(params: { + submitFuturesPriceTriggeredOrder(params: { settle: 'btc' | 'usdt' | 'usd'; body: FuturesPriceTriggeredOrder; }): Promise> { @@ -5387,7 +5344,7 @@ export class RestClient extends BaseRestClient { * @param params Parameters for listing all auto orders * @returns Promise> */ - listAllAutoOrders(params: { + getFuturesAutoOrders(params: { settle: 'btc' | 'usdt' | 'usd'; status: 'open' | 'finished'; contract?: string; @@ -5403,7 +5360,7 @@ export class RestClient extends BaseRestClient { * @param params Parameters for cancelling all open orders * @returns Promise> */ - cancelFuturesAllOpenOrders(params: { + deleteFuturesAllOpenOrders(params: { settle: 'btc' | 'usdt' | 'usd'; contract: string; }): Promise> { @@ -5432,7 +5389,7 @@ export class RestClient extends BaseRestClient { * @param params Parameters for cancelling a price-triggered order * @returns Promise> */ - cancelFuturesPriceTriggeredOrder(params: { + deleteFuturesPriceTriggeredOrder(params: { settle: 'btc' | 'usdt' | 'usd'; order_id: string; }): Promise> { @@ -5520,7 +5477,7 @@ export class RestClient extends BaseRestClient { * is_internal?: boolean; * }[]>> */ - getDeliveryTradingHistory(params: { + getDeliveryTrades(params: { settle: 'usdt'; contract: string; limit?: number; @@ -5625,7 +5582,7 @@ export class RestClient extends BaseRestClient { * highest_bid: string; * }[]>> */ - listDeliveryTickers(params: { settle: 'usdt'; contract?: string }): Promise< + getDeliveryTickers(params: { settle: 'usdt'; contract?: string }): Promise< APIResponse< { contract: string; @@ -5710,7 +5667,7 @@ export class RestClient extends BaseRestClient { * }; * }>> */ - queryDeliveryAccount(params: { settle: 'usdt' }): Promise< + getDeliveryAccount(params: { settle: 'usdt' }): Promise< APIResponse<{ total: string; unrealised_pnl: string; @@ -5756,7 +5713,7 @@ export class RestClient extends BaseRestClient { * trade_id?: string; * }[]>> */ - queryDeliveryBook(params: { + getDeliveryBook(params: { settle: 'usdt'; limit?: number; from?: number; @@ -5883,7 +5840,7 @@ export class RestClient extends BaseRestClient { * @param params Parameters for creating a futures order * @returns Promise> */ - createDeliveryOrder(params: { + submitDeliveryOrder(params: { settle: 'usdt'; body: FuturesOrder; }): Promise> { @@ -5898,7 +5855,7 @@ export class RestClient extends BaseRestClient { * @param params Parameters for listing futures orders * @returns Promise> */ - listDeliveryOrders(params: { + getDeliveryOrders(params: { settle: 'usdt'; contract?: string; status: 'open' | 'finished'; @@ -5918,7 +5875,7 @@ export class RestClient extends BaseRestClient { * @param params Parameters for cancelling all open orders matched * @returns Promise> */ - cancelAllDeliveryOrders(params: { + deleteAllDeliveryOrders(params: { settle: 'usdt'; contract: string; side?: 'ask' | 'bid'; @@ -5949,7 +5906,7 @@ export class RestClient extends BaseRestClient { * @param params Parameters for cancelling a single order * @returns Promise> */ - cancelDeliveryOrder(params: { + deleteDeliveryOrder(params: { settle: 'usdt'; order_id: string; }): Promise> { @@ -5975,7 +5932,7 @@ export class RestClient extends BaseRestClient { * point_fee: string; * }[]>> */ - getDeliveryPersonalHistory(params: { + getDeliveryTradingHistory(params: { settle: 'usdt'; contract?: string; order?: number; @@ -6165,7 +6122,7 @@ export class RestClient extends BaseRestClient { * @param params Parameters for cancelling all open orders * @returns Promise> */ - cancelAllDeliveryOpenOrders(params: { + deleteDeliveryOrders(params: { settle: 'usdt'; contract: string; }): Promise> { @@ -6207,7 +6164,7 @@ export class RestClient extends BaseRestClient { } /**========================================================================================================================== - * OPIONS + * OPTIONS * ========================================================================================================================== */ @@ -6895,7 +6852,7 @@ export class RestClient extends BaseRestClient { /** * Create an options order * - * @param body Body parameters for creating an options order + * @param params Parameters for creating an options order * @returns Promise> */ - submitOptionsOrder(body: { - contract: string; - size: number; - iceberg?: number; - price?: string; - close?: boolean; - reduce_only?: boolean; - tif?: 'gtc' | 'ioc' | 'poc'; - text?: string; + submitOptionsOrder(params: { + body: { + contract: string; + size: number; + iceberg?: number; + price?: string; + close?: boolean; + reduce_only?: boolean; + tif?: 'gtc' | 'ioc' | 'poc'; + text?: string; + }; }): Promise< APIResponse<{ id: number; @@ -6961,7 +6920,7 @@ export class RestClient extends BaseRestClient { refr: string; }> > { - return this.post(`/options/orders`, body); + return this.postPrivate(`/options/orders`, params); } /** @@ -7272,10 +7231,1488 @@ export class RestClient extends BaseRestClient { } /**========================================================================================================================== - * WALLET + * EARN UNI + * ========================================================================================================================== + */ + + /** + * List currencies for lending + * + * @returns Promise> + */ + getLendingCurrencies(): Promise< + APIResponse< + { + currency: string; + min_lend_amount: string; + max_lend_amount: string; + max_rate: string; + min_rate: string; + }[] + > + > { + return this.get(`/earn/uni/currencies`); + } + + /** + * Get currency detail for lending + * + * @param params Parameters for retrieving currency detail for lending + * @returns Promise> + */ + getLendingCurrency(params: { currency: string }): Promise< + APIResponse<{ + currency: string; + min_lend_amount: string; + max_lend_amount: string; + max_rate: string; + min_rate: string; + }> + > { + return this.get(`/earn/uni/currencies/${params.currency}`, params); + } + + /** + * Lend or redeem + * + * @param params Parameters for lending or redeeming + * @returns Promise> + */ + submitLendOrRedeem(params: { + body: { + currency: string; + amount: string; + type: 'lend' | 'redeem'; + min_rate?: string; + }; + }): Promise> { + return this.postPrivate(`/earn/uni/lends`, params); + } + + /** + * List user's lending orders + * + * @param params Parameters for listing user's lending orders + * @returns Promise> + */ + getLendingOrders(params?: { + currency?: string; + page?: number; + limit?: number; + }): Promise< + APIResponse< + { + currency: string; + current_amount: string; + amount: string; + lent_amount: string; + frozen_amount: string; + min_rate: string; + interest_status: string; + reinvest_left_amount: string; + create_time: number; + update_time: number; + }[] + > + > { + return this.getPrivate(`/earn/uni/lends`, params); + } + + /** + * Amend lending order + * + * Currently only supports amending the minimum interest rate (hour) + * + * @param params Parameters for amending lending order + * @returns Promise> + */ + updateLendingOrder(params: { + body: { + currency?: string; + min_rate?: string; + }; + }): Promise> { + return this.patchPrivate(`/earn/uni/lends`, params); + } + + /** + * List records of lending + * + * @param params Parameters for listing records of lending + * @returns Promise> + */ + getLendingRecords(params?: { + currency?: string; + page?: number; + limit?: number; + from?: number; + to?: number; + type?: 'lend' | 'redeem'; + }): Promise< + APIResponse< + { + currency: string; + amount: string; + last_wallet_amount: string; + last_lent_amount: string; + last_frozen_amount: string; + type: 'lend' | 'redeem'; + create_time: number; + }[] + > + > { + return this.getPrivate(`/earn/uni/lend_records`, params); + } + + /** + * Get the user's total interest income of specified currency + * + * @param params Parameters for retrieving the user's total interest income of specified currency + * @returns Promise> + */ + getLendingTotalInterest(params: { currency: string }): Promise< + APIResponse<{ + currency: string; + interest: string; + }> + > { + return this.getPrivate(`/earn/uni/interests/${params.currency}`); + } + + /** + * List interest records + * + * @param params Parameters for listing interest records + * @returns Promise> + */ + getLendingInterestRecords(params?: { + currency?: string; + page?: number; + limit?: number; + from?: number; + to?: number; + }): Promise< + APIResponse< + { + status: number; + currency: string; + actual_rate: string; + interest: string; + interest_status: string; + create_time: number; + }[] + > + > { + return this.getPrivate(`/earn/uni/interest_records`, params); + } + + /** + * Set interest reinvestment toggle + * + * @param params Parameters for setting interest reinvestment toggle + * @returns Promise> + */ + updateInterestReinvestment(params: { + body: { + currency: string; + status: boolean; + }; + }): Promise> { + return this.putPrivate(`/earn/uni/interest_reinvest`, params); + } + + /** + * Query currency interest compounding status + * + * @param params Parameters for querying currency interest compounding status + * @returns Promise> + */ + getLendingInterestStatus(params: { currency: string }): Promise< + APIResponse<{ + currency: string; + interest_status: string; + }> + > { + return this.getPrivate(`/earn/uni/interest_status/${params.currency}`); + } + + /**========================================================================================================================== + * COLLATERAL LOAN * ========================================================================================================================== */ + /** + * Place order + * + * @param params Parameters for placing an order + * @returns Promise> + */ + submitLoanOrder(params: { + body: { + collateral_amount: string; + collateral_currency: string; + borrow_amount: string; + borrow_currency: string; + }; + }): Promise> { + return this.postPrivate(`/loan/collateral/orders`, params); + } + + /** + * List Orders + * + * @param params Parameters for listing orders + * @returns Promise> + */ + getLoanOrders(params?: { + page?: number; + limit?: number; + collateral_currency?: string; + borrow_currency?: string; + }): Promise< + APIResponse< + { + order_id: number; + collateral_currency: string; + collateral_amount: string; + borrow_currency: string; + borrow_amount: string; + repaid_amount: string; + repaid_principal: string; + repaid_interest: string; + init_ltv: string; + current_ltv: string; + liquidate_ltv: string; + status: string; + borrow_time: number; + left_repay_total: string; + left_repay_principal: string; + left_repay_interest: string; + }[] + > + > { + return this.getPrivate(`/loan/collateral/orders`, params); + } + + /** + * Get a single order + * + * @param params Parameters for retrieving a single order + * @returns Promise> + */ + getLoanOrder(params: { order_id: number }): Promise< + APIResponse<{ + order_id: number; + collateral_currency: string; + collateral_amount: string; + borrow_currency: string; + borrow_amount: string; + repaid_amount: string; + repaid_principal: string; + repaid_interest: string; + init_ltv: string; + current_ltv: string; + liquidate_ltv: string; + status: string; + borrow_time: number; + left_repay_total: string; + left_repay_principal: string; + left_repay_interest: string; + }> + > { + return this.getPrivate(`/loan/collateral/orders/${params.order_id}`); + } + + /** + * Repayment + * + * @param params Parameters for repayment + * @returns Promise> + */ + submitLoanRepay(params: { + body: { + order_id: number; + repay_amount: string; + repaid_all: boolean; + }; + }): Promise< + APIResponse<{ + repaid_principal: string; + repaid_interest: string; + }> + > { + return this.postPrivate(`/loan/collateral/repay`, params); + } + + /** + * Repayment history + * + * @param params Parameters for retrieving repayment history + * @returns Promise> + */ + getLoanRepaymentHistory(params: { + source: 'repay' | 'liquidate'; + borrow_currency?: string; + collateral_currency?: string; + page?: number; + limit?: number; + from?: number; + to?: number; + }): Promise< + APIResponse< + { + order_id: number; + record_id: number; + repaid_amount: string; + borrow_currency: string; + collateral_currency: string; + init_ltv: string; + borrow_time: number; + repay_time: number; + total_interest: string; + before_left_principal: string; + after_left_principal: string; + before_left_collateral: string; + after_left_collateral: string; + }[] + > + > { + return this.getPrivate(`/loan/collateral/repay_records`, params); + } + + /** + * Increase or redeem collateral + * + * @param params Parameters for increasing or redeeming collateral + * @returns Promise> + */ + updateLoanCollateral(params: { + body: { + order_id: number; + collateral_currency: string; + collateral_amount: string; + type: 'append' | 'redeem'; + }; + }): Promise> { + return this.postPrivate(`/loan/collateral/collaterals`, params); + } + + /** + * Query collateral adjustment records + * + * @param params Parameters for querying collateral adjustment records + * @returns Promise> + */ + getLoanCollateralRecords(params?: { + page?: number; + limit?: number; + from?: number; + to?: number; + borrow_currency?: string; + collateral_currency?: string; + }): Promise< + APIResponse< + { + order_id: number; + record_id: number; + borrow_currency: string; + borrow_amount: string; + collateral_currency: string; + before_collateral: string; + after_collateral: string; + before_ltv: string; + after_ltv: string; + operate_time: number; + }[] + > + > { + return this.getPrivate(`/loan/collateral/collaterals`, params); + } + + /** + * Query the total borrowing and collateral amount for the user + * + * @returns Promise> + */ + getLoanTotalAmount(): Promise< + APIResponse<{ + borrow_amount: string; + collateral_amount: string; + }> + > { + return this.getPrivate(`/loan/collateral/total_amount`); + } + + /** + * Query user's collateralization ratio + * + * @param params Parameters for querying user's collateralization ratio + * @returns Promise> + */ + getLoanCollateralizationRatio(params: { + collateral_currency: string; + borrow_currency: string; + }): Promise< + APIResponse<{ + collateral_currency: string; + borrow_currency: string; + init_ltv: string; + alert_ltv: string; + liquidate_ltv: string; + min_borrow_amount: string; + left_borrowable_amount: string; + }> + > { + return this.getPrivate(`/loan/collateral/ltv`, params); + } + + /** + * Query supported borrowing and collateral currencies + * + * @param params Parameters for querying supported borrowing and collateral currencies + * @returns Promise> + */ + getLoanSupportedCurrencies(params?: { loan_currency?: string }): Promise< + APIResponse< + { + loan_currency: string; + collateral_currency: string[]; + }[] + > + > { + return this.get(`/loan/collateral/currencies`, params); + } + + /**========================================================================================================================== + * MULTI COLLATERAL LOAN + * ========================================================================================================================== + */ + + /** + * Create Multi-Collateral Order + * + * @param params Parameters for creating a multi-collateral order + * @returns Promise> + */ + submitMultiLoanOrder(params: { + body: { + order_id?: string; + order_type?: string; + fixed_type?: string; + fixed_rate?: string; + auto_renew?: boolean; + auto_repay?: boolean; + borrow_currency: string; + borrow_amount: string; + collateral_currencies?: { + currency?: string; + amount?: string; + }[]; + }; + }): Promise> { + return this.postPrivate(`/loan/multi_collateral/orders`, params); + } + + /** + * List Multi-Collateral Orders + * + * @param params Parameters for listing multi-collateral orders + * @returns Promise> + */ + getMultiLoanOrders(params?: { + page?: number; + limit?: number; + sort?: string; + order_type?: string; + }): Promise< + APIResponse< + { + order_id: string; + order_type: string; + fixed_type: string; + fixed_rate: string; + expire_time: number; + auto_renew: boolean; + auto_repay: boolean; + current_ltv: string; + status: string; + borrow_time: number; + total_left_repay_usdt: string; + total_left_collateral_usdt: string; + borrow_currencies: { + currency: string; + index_price: string; + left_repay_principal: string; + left_repay_interest: string; + left_repay_usdt: string; + }[]; + collateral_currencies: { + currency: string; + index_price: string; + left_collateral: string; + left_collateral_usdt: string; + }[]; + }[] + > + > { + return this.getPrivate(`/loan/multi_collateral/orders`, params); + } + + /** + * Get Multi-Collateral Order Detail + * + * @param params Parameters for retrieving a multi-collateral order detail + * @returns Promise> + */ + getMultiLoanOrder(params: { order_id: string }): Promise< + APIResponse<{ + order_id: string; + order_type: string; + fixed_type: string; + fixed_rate: string; + expire_time: number; + auto_renew: boolean; + auto_repay: boolean; + current_ltv: string; + status: string; + borrow_time: number; + total_left_repay_usdt: string; + total_left_collateral_usdt: string; + borrow_currencies: { + currency: string; + index_price: string; + left_repay_principal: string; + left_repay_interest: string; + left_repay_usdt: string; + }[]; + collateral_currencies: { + currency: string; + index_price: string; + left_collateral: string; + left_collateral_usdt: string; + }[]; + }> + > { + return this.getPrivate( + `/loan/multi_collateral/orders/${params.order_id}`, + params, + ); + } + + /** + * Repay Multi-Collateral Loan + * + * @param params Parameters for repaying a multi-collateral loan + * @returns Promise> + */ + repayMultiLoan(params: { + body: { + order_id: number; + repay_items: { + currency?: string; + amount?: string; + repaid_all?: boolean; + }[]; + }; + }): Promise< + APIResponse<{ + order_id: number; + repaid_currencies: { + succeeded: boolean; + label?: string; + message?: string; + currency: string; + repaid_principal: string; + repaid_interest: string; + }[]; + }> + > { + return this.postPrivate(`/loan/multi_collateral/repay`, params); + } + + /** + * List Multi-Collateral Repay Records + * + * @param params Parameters for listing multi-collateral repay records + * @returns Promise> + */ + getMultiLoanRepayRecords(params: { + type: 'repay' | 'liquidate'; + borrow_currency?: string; + page?: number; + limit?: number; + from?: number; + to?: number; + }): Promise< + APIResponse< + { + order_id: number; + record_id: number; + init_ltv: string; + before_ltv: string; + after_ltv: string; + borrow_time: number; + repay_time: number; + borrow_currencies: { + currency: string; + index_price: string; + before_amount: string; + before_amount_usdt: string; + after_amount: string; + after_amount_usdt: string; + }[]; + collateral_currencies: { + currency: string; + index_price: string; + before_amount: string; + before_amount_usdt: string; + after_amount: string; + after_amount_usdt: string; + }[]; + repaid_currencies: { + currency: string; + index_price: string; + repaid_amount: string; + repaid_principal: string; + repaid_interest: string; + repaid_amount_usdt: string; + }[]; + total_interest_list: { + currency: string; + index_price: string; + amount: string; + amount_usdt: string; + }[]; + left_repay_interest_list: { + currency: string; + index_price: string; + before_amount: string; + before_amount_usdt: string; + after_amount: string; + after_amount_usdt: string; + }[]; + }[] + > + > { + return this.getPrivate(`/loan/multi_collateral/repay`, params); + } + + /** + * Operate Multi-Collateral + * + * @param params Parameters for operating multi-collateral + * @returns Promise> + */ + operateMultiLoan(params: { + body: { + order_id: number; + type: 'append' | 'redeem'; + collaterals?: { + currency?: string; + amount?: string; + }[]; + }; + }): Promise< + APIResponse<{ + order_id: number; + collateral_currencies: { + succeeded: boolean; + label?: string; + message?: string; + currency: string; + amount: string; + }[]; + }> + > { + return this.postPrivate(`/loan/multi_collateral/mortgage`, params); + } + + /** + * Query collateral adjustment records + * + * @param params Parameters for querying collateral adjustment records + * @returns Promise> + */ + getMultiLoanAdjustmentRecords(params?: { + page?: number; + limit?: number; + from?: number; + to?: number; + collateral_currency?: string; + }): Promise< + APIResponse< + { + order_id: number; + record_id: number; + before_ltv: string; + after_ltv: string; + operate_time: number; + borrow_currencies: { + currency: string; + index_price: string; + before_amount: string; + before_amount_usdt: string; + after_amount: string; + after_amount_usdt: string; + }[]; + collateral_currencies: { + currency: string; + index_price: string; + before_amount: string; + before_amount_usdt: string; + after_amount: string; + after_amount_usdt: string; + }[]; + }[] + > + > { + return this.getPrivate(`/loan/multi_collateral/mortgage`, params); + } + + /** + * List User Currency Quota + * + * @param params Parameters for listing user currency quota + * @returns Promise> + */ + getMultiLoanCurrencyQuota(params: { + type: 'collateral' | 'borrow'; + currency: string; + }): Promise< + APIResponse< + { + currency: string; + index_price: string; + min_quota: string; + left_quota: string; + left_quote_usdt: string; + }[] + > + > { + return this.getPrivate(`/loan/multi_collateral/currency_quota`, params); + } + + /** + * Query supported borrowing and collateral currencies in Multi-Collateral + * + * @returns Promise> + */ + getMultiLoanSupportedCurrencies(): Promise< + APIResponse<{ + loan_currencies: { + currency: string; + price: string; + }[]; + collateral_currencies: { + currency: string; + index_price: string; + discount: string; + }[]; + }> + > { + return this.get(`/loan/multi_collateral/currencies`); + } + + /** + * Get Multi-Collateral ratio + * + * @returns Promise> + */ + getMultiLoanRatio(): Promise< + APIResponse<{ + init_ltv: string; + alert_ltv: string; + liquidate_ltv: string; + }> + > { + return this.get(`/loan/multi_collateral/ltv`); + } + + /** + * Query fixed interest rates for the currency for 7 days and 30 days + * + * @returns Promise> + */ + getMultiLoanFixedRates(): Promise< + APIResponse< + { + currency: string; + rate_7d: string; + rate_30d: string; + update_time: number; + }[] + > + > { + return this.get(`/loan/multi_collateral/fixed_rate`); + } + + /**========================================================================================================================== + * EARN + * ========================================================================================================================== + */ + + /** + * ETH2 swap + * + * @param params Parameters for ETH2 swap + * @returns Promise> + */ + submitEth2Swap(params: { + body: { + side: '1' | '2'; + amount: string; + }; + }): Promise> { + return this.postPrivate(`/earn/staking/eth2/swap`, params); + } + + /** + * Dual Investment product list + * + * @returns Promise> + */ + getDualInvestmentProducts(): Promise< + APIResponse< + { + id: number; + instrument_name: string; + invest_currency: string; + exercise_currency: string; + exercise_price: number; + delivery_time: number; + min_copies: number; + max_copies: number; + per_value: string; + apy_display: string; + start_time: number; + end_time: number; + status: 'NOTSTARTED' | 'ONGOING' | 'ENDED'; + }[] + > + > { + return this.get(`/earn/dual/investment_plan`); + } + + /** + * Dual Investment order list + * + * @returns Promise> + */ + getDualInvestmentOrders(): Promise< + APIResponse< + { + 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; + }[] + > + > { + return this.getPrivate(`/earn/dual/orders`); + } + + /** + * Place Dual Investment order + * + * @param params Parameters for placing a dual investment order + * @returns Promise> + */ + submitDualInvestmentOrder(params: { + body: { + plan_id: string; + copies: string; + }; + }): Promise> { + return this.postPrivate(`/earn/dual/orders`, params); + } + + /** + * Structured Product List + * + * @param params Parameters for listing structured products + * @returns Promise> + */ + getStructuredProductList(params: { + status: string; + type?: string; + page?: number; + limit?: number; + }): Promise< + APIResponse< + { + id: number; + type: string; + name_en: string; + investment_coin: string; + investment_period: string; + min_annual_rate: string; + mid_annual_rate: string; + max_annual_rate: string; + watch_market: string; + start_time: number; + end_time: number; + status: 'in_process' | 'will_begin' | 'wait_settlement' | 'done'; + }[] + > + > { + return this.get(`/earn/structured/products`, params); + } + + /** + * Structured Product Order List + * + * @param params Parameters for listing structured product orders + * @returns Promise> + */ + getStructuredProductOrders(params?: { + from?: number; + to?: number; + page?: number; + limit?: number; + }): Promise< + APIResponse< + { + id: number; + pid: string; + lock_coin: string; + amount: string; + status: 'SUCCESS' | 'FAILED' | 'DONE'; + income: string; + create_time: number; + }[] + > + > { + return this.getPrivate(`/earn/structured/orders`, params); + } + + /** + * Place Structured Product Order + * + * @param params Parameters for placing a structured product order + * @returns Promise> + */ + submitStructuredProductOrder(params: { + body: { + pid?: string; + amount?: string; + }; + }): Promise> { + return this.postPrivate(`/earn/structured/orders`, params); + } + + /**========================================================================================================================== + * ACCOUNT + * ========================================================================================================================== + */ + + /** + * Get account detail + * + * @returns Promise> + */ + getAccountDetail(): Promise< + APIResponse<{ + user_id: number; + ip_whitelist: string[]; + currency_pairs: string[]; + key: { + mode: number; + }; + tier: number; + }> + > { + return this.getPrivate(`/account/detail`); + } + + /** + * Create STP Group + * + * @param params Parameters for creating an STP group + * @returns Promise> + */ + createStpGroup(params: { + body: { + id?: number; + name: string; + creator_id?: number; + create_time?: number; + }; + }): Promise< + APIResponse<{ + id: number; + name: string; + creator_id: number; + create_time: number; + }> + > { + return this.postPrivate(`/account/stp_groups`, params); + } + + /** + * List STP Groups + * + * @param params Parameters for listing STP groups + * @returns Promise> + */ + getStpGroups(params?: { name?: string }): Promise< + APIResponse< + { + id: number; + name: string; + creator_id: number; + create_time: number; + }[] + > + > { + return this.getPrivate(`/account/stp_groups`, params); + } + + /** + * List users of the STP group + * + * @param params Parameters for listing users of the STP group + * @returns Promise> + */ + getStpGroupUsers(params: { stp_id: number }): Promise< + APIResponse< + { + user_id: number; + stp_id: number; + create_time: number; + }[] + > + > { + return this.getPrivate( + `/account/stp_groups/${params.stp_id}/users`, + params, + ); + } + + /** + * Add users to the STP group + * + * @param params Parameters for adding users to the STP group + * @returns Promise> + */ + addUsersToStpGroup(params: { stp_id: number; body: number[] }): Promise< + APIResponse< + { + user_id: number; + stp_id: number; + create_time: number; + }[] + > + > { + return this.postPrivate( + `/account/stp_groups/${params.stp_id}/users`, + params, + ); + } + + /** + * Delete the user in the STP group + * + * @param params Parameters for deleting users from the STP group + * @returns Promise> + */ + deleteUserFromStpGroup(params: { stp_id: number; user_id: number }): Promise< + APIResponse< + { + user_id: number; + stp_id: number; + create_time: number; + }[] + > + > { + return this.deletePrivate( + `/account/stp_groups/${params.stp_id}/users`, + params, + ); + } + /** * */ /** From 71e33cd7ad0ea4df18b9a1e185f21efa8b9d9aaa Mon Sep 17 00:00:00 2001 From: Jerko J <83344666+JJ-Cro@users.noreply.github.com> Date: Sun, 19 May 2024 20:53:17 +0200 Subject: [PATCH 06/36] chore(): refactoring types --- examples/rest-private.ts | 10 +- src/RestClient.ts | 467 +++++------------------------ src/types/requests/shared.types.ts | 45 +++ src/types/response/shared.types.ts | 192 ++++++++++++ 4 files changed, 315 insertions(+), 399 deletions(-) create mode 100644 src/types/requests/shared.types.ts diff --git a/examples/rest-private.ts b/examples/rest-private.ts index 7eaab9a..b4179eb 100644 --- a/examples/rest-private.ts +++ b/examples/rest-private.ts @@ -19,7 +19,7 @@ async function start() { index: 'BTC_USDT', }); */ - /* const res3 = await rest.portfolioMarginCalculator({ + const res3 = await rest.portfolioMarginCalculator({ body: { spot_balances: [ { @@ -63,14 +63,14 @@ async function start() { ], spot_hedge: false, }, - }); */ + }); - const res4 = await rest.getDeliveryContract({ + /* const res4 = await rest.getDeliveryContract({ settle: 'usdt', contract: 'BTC_USDT', - }); + }); */ // const res1 = await rest.getSystemMaintenanceStatus(); - console.log('res: ', JSON.stringify(res4, null, 2)); + console.log('res: ', JSON.stringify(res3, null, 2)); } catch (e) { console.error(`Error in execution: `, e); } diff --git a/src/RestClient.ts b/src/RestClient.ts index 60cf116..6e81dc4 100644 --- a/src/RestClient.ts +++ b/src/RestClient.ts @@ -1,4 +1,11 @@ import { AxiosRequestConfig } from 'axios'; +import { + GetMainSubTransfersReq, + GetSavedAddressReq, + GetSmallBalanceHistoryReq, + GetWithdrawalDepositRecordsReq, + SubmitTransferReq, +} from 'types/requests/shared.types.js'; import { BaseRestClient, @@ -6,7 +13,21 @@ import { RestClientType, } from './lib/BaseRestClient.js'; import { RestClientOptions } from './lib/requestUtils.js'; -import { APIResponse } from './types/response/shared.types.js'; +import { + APIResponse, + CreateDepositAddressResp, + GetBalancesResp, + GetCurrencyChainsResp, + GetSavedAddressResp, + GetSmallBalanceHistoryResp, + GetSmallBalancesResp, + GetTradingFeesResp, + GetWithdrawalStatusResp, + SubAccountCrossMarginBalancesResp, + SubAccountFuturesBalancesResp, + SubAccountMarginBalancesResp, + SubAccountTransferRecordResp, +} from './types/response/shared.types.js'; // interfaces @@ -407,31 +428,11 @@ export class RestClient extends BaseRestClient { * List chains supported for specified currency * * @param params Parameters containing the currency name - * @returns Promise> + * @returns Promise> */ - getCurrencyChains(params: { currency: string }): Promise< - APIResponse< - { - chain: string; - name_cn: string; - name_en: string; - contract_address: string; - is_disabled: number; - is_deposit_disabled: number; - is_withdraw_disabled: number; - decimal: string; - }[] - > - > { + getCurrencyChains(params: { + currency: string; + }): Promise> { return this.get('/wallet/currency_chains', params); } @@ -439,31 +440,11 @@ export class RestClient extends BaseRestClient { * Generate currency deposit address * * @param params Parameters containing the currency name - * @returns Promise> + * @returns Promise> */ - createDepositAddress(params: { currency: string }): Promise< - APIResponse<{ - currency: string; - address: string; - multichain_addresses: { - chain: string; - address: string; - payment_id: string; - payment_name: string; - obtain_failed: number; - }[]; - }> - > { + createDepositAddress(params: { + currency: string; + }): Promise> { return this.getPrivate('/wallet/deposit_address', params); } @@ -475,13 +456,9 @@ export class RestClient extends BaseRestClient { * @param params Parameters for filtering withdrawal records * @returns Promise> */ - getWithdrawalRecords(params?: { - currency?: string; - from?: number; - to?: number; - limit?: number; - offset?: number; - }): Promise> { + getWithdrawalRecords( + params?: GetWithdrawalDepositRecordsReq, + ): Promise> { return this.getPrivate('/wallet/withdrawals', params); } @@ -493,13 +470,9 @@ export class RestClient extends BaseRestClient { * @param params Parameters for filtering deposit records * @returns Promise> */ - getDepositRecords(params?: { - currency?: string; - from?: number; - to?: number; - limit?: number; - offset?: number; - }): Promise> { + getDepositRecords( + params?: GetWithdrawalDepositRecordsReq, + ): Promise> { return this.getPrivate('/wallet/deposits', params); } @@ -516,32 +489,9 @@ export class RestClient extends BaseRestClient { * @param params Transfer parameters * @returns Promise> */ - submitTransfer(params: { - body: { - 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; - }; - }): Promise< - APIResponse<{ - tx_id: number; - }> - > { + submitTransfer( + params: SubmitTransferReq, + ): Promise> { return this.postPrivate('/wallet/transfers', params); } @@ -574,29 +524,11 @@ export class RestClient extends BaseRestClient { * Note: only records after 2020-04-10 can be retrieved * * @param params Parameters for filtering transfer records - * @returns Promise> + * @returns Promise> */ - getMainSubTransfers(params?: { - sub_uid?: string; - from?: number; - to?: number; - limit?: number; - offset?: number; - }): Promise< - APIResponse< - { - 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'; - }[] - > - > { + getMainSubTransfers( + params?: GetMainSubTransfersReq, + ): Promise> { return this.getPrivate('/wallet/sub_account_transfers', params); } @@ -626,39 +558,11 @@ export class RestClient extends BaseRestClient { * Retrieve withdrawal status * * @param params Parameters for retrieving withdrawal status - * @returns Promise> + * @returns Promise> */ - getWithdrawalStatus(params?: { currency?: string }): Promise< - APIResponse< - { - 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 }; - }[] - > - > { + getWithdrawalStatus(params?: { + currency?: string; + }): Promise> { return this.getPrivate('/wallet/withdraw_status', params); } @@ -686,34 +590,11 @@ export class RestClient extends BaseRestClient { * Query sub accounts' margin balances * * @param params Parameters for querying sub accounts' margin balances - * @returns Promise> + * @returns Promise> */ - getSubMarginBalances(params?: { sub_uid?: string }): Promise< - APIResponse< - { - uid: string; - available: { - 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; - }; - }[]; - }[] - > - > { + getSubMarginBalances(params?: { + sub_uid?: string; + }): Promise> { return this.getPrivate('/wallet/sub_account_margin_balances', params); } @@ -721,47 +602,12 @@ export class RestClient extends BaseRestClient { * Query sub accounts' futures account balances * * @param params Parameters for querying sub accounts' futures account balances - * @returns Promise> + * @returns Promise> */ getSubFuturesBalances(params?: { sub_uid?: string; settle?: string; - }): Promise< - APIResponse< - { - 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; - 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; - }; - }; - }; - }[] - > - > { + }): Promise> { return this.getPrivate('/wallet/sub_account_futures_balances', params); } @@ -769,67 +615,11 @@ export class RestClient extends BaseRestClient { * Query subaccount's cross_margin account info * * @param params Parameters for querying subaccount's cross_margin account info - * @returns Promise> + * @returns Promise> */ - getSubCrossMarginBalances(params?: { sub_uid?: string }): Promise< - APIResponse< - { - 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; - }; - }[] - > - > { + getSubCrossMarginBalances(params?: { + sub_uid?: string; + }): Promise> { return this.getPrivate('/wallet/sub_account_cross_margin_balances', params); } @@ -837,32 +627,11 @@ export class RestClient extends BaseRestClient { * Query saved address * * @param params Parameters for querying saved address - * @returns Promise> + * @returns Promise> */ - getSavedAddress(params: { - currency: string; - chain?: string; - limit?: string; - page?: number; - }): Promise< - APIResponse< - { - currency: string; - chain: string; - address: string; - name: string; - tag: string; - verified: string; - }[] - > - > { + getSavedAddress( + params: GetSavedAddressReq, + ): Promise> { return this.getPrivate('/wallet/saved_address', params); } @@ -870,42 +639,12 @@ export class RestClient extends BaseRestClient { * Retrieve personal trading fee * * @param params Parameters for retrieving personal trading fee - * @returns Promise> + * @returns Promise> */ getTradingFees(params?: { currency_pair?: string; settle?: 'BTC' | 'USDT' | 'USD'; - }): Promise< - APIResponse<{ - 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; - }> - > { + }): Promise> { return this.getPrivate('/wallet/fee', params); } @@ -921,62 +660,20 @@ export class RestClient extends BaseRestClient { * - GET /futures/{settle}/accounts to query futures account balance * * @param params Parameters for retrieving total balances - * @returns Promise> + * @returns Promise> */ - getBalances(params?: { currency?: string }): Promise< - APIResponse<{ - total: { - amount: string; - currency: string; - unrealised_pnl?: string; - borrowed?: string; - }; - details: { - [key: string]: { - amount: string; - currency: string; - unrealised_pnl?: string; - borrowed?: string; - }; - }; - }> - > { + getBalances(params?: { + currency?: string; + }): Promise> { return this.getPrivate('/wallet/total_balance', params); } /** * List small balance * - * @returns Promise> + * @returns Promise> */ - getSmallBalances(): Promise< - APIResponse<{ - currency: string; - available_balance: string; - estimated_as_btc: string; - convertible_to_gt: string; - }> - > { + getSmallBalances(): Promise> { return this.getPrivate('/wallet/small_balance'); } @@ -998,29 +695,11 @@ export class RestClient extends BaseRestClient { * List small balance history * * @param params Parameters for listing small balance history - * @returns Promise> + * @returns Promise> */ - getSmallBalanceHistory(params?: { - currency?: string; - page?: number; - limit?: number; - }): Promise< - APIResponse< - { - id: string; - currency: string; - amount: string; - gt_amount: string; - create_time: number; - }[] - > - > { + getSmallBalanceHistory( + params?: GetSmallBalanceHistoryReq, + ): Promise> { return this.getPrivate('/wallet/small_balance_history', params); } diff --git a/src/types/requests/shared.types.ts b/src/types/requests/shared.types.ts new file mode 100644 index 0000000..15a7a74 --- /dev/null +++ b/src/types/requests/shared.types.ts @@ -0,0 +1,45 @@ +export interface GetWithdrawalDepositRecordsReq { + currency?: string; + from?: number; + to?: number; + limit?: number; + offset?: number; +} + +export interface SubmitTransferReq { + body: { + 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; + }; +} + +export interface GetMainSubTransfersReq { + sub_uid?: string; + from?: number; + to?: number; + limit?: number; + offset?: number; +} + +export interface GetSavedAddressReq { + currency: string; + chain?: string; + limit?: string; + page?: number; +} + +export interface GetSmallBalanceHistoryReq { + currency?: string; + page?: number; + limit?: number; +} diff --git a/src/types/response/shared.types.ts b/src/types/response/shared.types.ts index a1e0287..0cdf34f 100644 --- a/src/types/response/shared.types.ts +++ b/src/types/response/shared.types.ts @@ -3,3 +3,195 @@ export interface APIResponse { data: TData; timestamp: number; } + +export interface GetCurrencyChainsResp { + 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 CreateDepositAddressResp { + currency: string; + address: string; + multichain_addresses: { + chain: string; + address: string; + payment_id: string; + payment_name: string; + obtain_failed: number; + }[]; +} + +export interface SubAccountTransferRecordResp { + 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 GetWithdrawalStatusResp { + 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 SubAccountMarginBalancesResp { + uid: string; + available: { + 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; + 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 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 GetSavedAddressResp { + currency: string; + chain: string; + address: string; + name: string; + tag: string; + verified: string; +} + +export interface GetTradingFeesResp { + 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; + }; + }; +} + +export interface GetSmallBalancesResp { + currency: string; + available_balance: string; + estimated_as_btc: string; + convertible_to_gt: string; +} + +export interface GetSmallBalanceHistoryResp { + id: string; + currency: string; + amount: string; + gt_amount: string; + create_time: number; +} From 972eabdba52155fb26a3004e6626a329b1d6d446 Mon Sep 17 00:00:00 2001 From: Jerko J <83344666+JJ-Cro@users.noreply.github.com> Date: Sun, 19 May 2024 21:00:42 +0200 Subject: [PATCH 07/36] chore(): refactoring types --- src/RestClient.ts | 26 ++++++++++++++++++++++---- src/types/requests/shared.types.ts | 17 ----------------- 2 files changed, 22 insertions(+), 21 deletions(-) diff --git a/src/RestClient.ts b/src/RestClient.ts index 6e81dc4..fb885c4 100644 --- a/src/RestClient.ts +++ b/src/RestClient.ts @@ -4,7 +4,6 @@ import { GetSavedAddressReq, GetSmallBalanceHistoryReq, GetWithdrawalDepositRecordsReq, - SubmitTransferReq, } from 'types/requests/shared.types.js'; import { @@ -489,9 +488,28 @@ export class RestClient extends BaseRestClient { * @param params Transfer parameters * @returns Promise> */ - submitTransfer( - params: SubmitTransferReq, - ): Promise> { + submitTransfer(params: { + body: { + 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; + }; + }): Promise> { return this.postPrivate('/wallet/transfers', params); } diff --git a/src/types/requests/shared.types.ts b/src/types/requests/shared.types.ts index 15a7a74..1080a60 100644 --- a/src/types/requests/shared.types.ts +++ b/src/types/requests/shared.types.ts @@ -6,23 +6,6 @@ export interface GetWithdrawalDepositRecordsReq { offset?: number; } -export interface SubmitTransferReq { - body: { - 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; - }; -} - export interface GetMainSubTransfersReq { sub_uid?: string; from?: number; From 7cdabf71afec6ab3d983b63dd72b091df09692dd Mon Sep 17 00:00:00 2001 From: Tiago Siebler Date: Mon, 20 May 2024 13:35:47 +0100 Subject: [PATCH 08/36] feat(): auth for GET with params --- src/lib/BaseRestClient.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/lib/BaseRestClient.ts b/src/lib/BaseRestClient.ts index 4508f22..fb0ea1d 100644 --- a/src/lib/BaseRestClient.ts +++ b/src/lib/BaseRestClient.ts @@ -304,7 +304,7 @@ export abstract class BaseRestClient { res.originalParams, strictParamValidation, encodeQueryStringValues, - '?', + '', ) : JSON.stringify(res.originalParams) || ''; @@ -443,7 +443,7 @@ export abstract class BaseRestClient { ...authHeaders, ...options.headers, }, - url: options.url + signResult.queryParamsWithSign, + url: options.url + '?' + signResult.queryParamsWithSign, }; } From 8633eb7227f94a514d6eccd9ffa927bb3671f98e Mon Sep 17 00:00:00 2001 From: Tiago Siebler Date: Mon, 20 May 2024 13:38:36 +0100 Subject: [PATCH 09/36] feat(): post auth with params --- src/lib/BaseRestClient.ts | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/src/lib/BaseRestClient.ts b/src/lib/BaseRestClient.ts index fb0ea1d..ef30042 100644 --- a/src/lib/BaseRestClient.ts +++ b/src/lib/BaseRestClient.ts @@ -306,14 +306,19 @@ export abstract class BaseRestClient { encodeQueryStringValues, '', ) - : JSON.stringify(res.originalParams) || ''; + : ''; - const params = method === 'GET' ? '' : JSON.stringify(res.originalParams); + const hashedMsgParams = + method === 'GET' ? '' : JSON.stringify(res.originalParams); const signAlgoritm: SignAlgorithm = 'SHA-512'; const signEncoding: SignEncodeMethod = 'hex'; - const hashedData = await hashMessage(params, signEncoding, signAlgoritm); + const hashedData = await hashMessage( + hashedMsgParams, + signEncoding, + signAlgoritm, + ); const toSign = [ method, From ab711b7ef850cd7648ae6d15c38676c05942680f Mon Sep 17 00:00:00 2001 From: Jerko J <83344666+JJ-Cro@users.noreply.github.com> Date: Mon, 20 May 2024 14:40:34 +0200 Subject: [PATCH 10/36] chore(): Refactoring types --- examples/rest-private.ts | 84 ++- src/RestClient.ts | 978 +++++++++++------------------ src/types/requests/shared.types.ts | 28 + src/types/response/shared.types.ts | 97 +++ 4 files changed, 522 insertions(+), 665 deletions(-) diff --git a/examples/rest-private.ts b/examples/rest-private.ts index b4179eb..34ef8af 100644 --- a/examples/rest-private.ts +++ b/examples/rest-private.ts @@ -20,49 +20,47 @@ async function start() { }); */ const res3 = await rest.portfolioMarginCalculator({ - body: { - spot_balances: [ - { - currency: 'BTC', - equity: '-1', - }, - ], - spot_orders: [ - { - currency_pairs: 'BTC_USDT', - order_price: '344', - left: '100', - type: 'sell', - }, - ], - futures_positions: [ - { - contract: 'BTC_USDT', - size: '100', - }, - ], - futures_orders: [ - { - contract: 'BTC_USDT', - size: '10', - left: '8', - }, - ], - options_positions: [ - { - options_name: 'BTC_USDT-20240329-32000-C', - size: '10', - }, - ], - options_orders: [ - { - options_name: 'BTC_USDT-20240329-32000-C', - size: '100', - left: '80', - }, - ], - spot_hedge: false, - }, + spot_balances: [ + { + currency: 'BTC', + equity: '-1', + }, + ], + spot_orders: [ + { + currency_pairs: 'BTC_USDT', + order_price: '344', + left: '100', + type: 'sell', + }, + ], + futures_positions: [ + { + contract: 'BTC_USDT', + size: '100', + }, + ], + futures_orders: [ + { + contract: 'BTC_USDT', + size: '10', + left: '8', + }, + ], + options_positions: [ + { + options_name: 'BTC_USDT-20240329-32000-C', + size: '10', + }, + ], + options_orders: [ + { + options_name: 'BTC_USDT-20240329-32000-C', + size: '100', + left: '80', + }, + ], + spot_hedge: false, }); /* const res4 = await rest.getDeliveryContract({ diff --git a/src/RestClient.ts b/src/RestClient.ts index fb885c4..e6cd8c3 100644 --- a/src/RestClient.ts +++ b/src/RestClient.ts @@ -3,7 +3,11 @@ import { GetMainSubTransfersReq, GetSavedAddressReq, GetSmallBalanceHistoryReq, + GetUnifiedInterestRecordsReq, + GetUnifiedLoanRecordsReq, + GetUnifiedLoansReq, GetWithdrawalDepositRecordsReq, + SubmitUnifiedBorrowOrRepayReq, } from 'types/requests/shared.types.js'; import { @@ -15,16 +19,22 @@ import { RestClientOptions } from './lib/requestUtils.js'; import { APIResponse, CreateDepositAddressResp, + CreateSubAccountApiKeyResp, GetBalancesResp, GetCurrencyChainsResp, GetSavedAddressResp, GetSmallBalanceHistoryResp, GetSmallBalancesResp, GetTradingFeesResp, + GetUnifiedAccountInfoResp, + GetUnifiedInterestRecordsResp, + GetUnifiedLoanRecordsResp, + GetUnifiedLoansResp, GetWithdrawalStatusResp, SubAccountCrossMarginBalancesResp, SubAccountFuturesBalancesResp, SubAccountMarginBalancesResp, + SubAccountResp, SubAccountTransferRecordResp, } from './types/response/shared.types.js'; @@ -393,17 +403,15 @@ export class RestClient extends BaseRestClient { * @param params Withdrawal parameters * @returns Promise> */ - submitWithdraw(params: { - body: { - withdraw_order_id?: string; - amount: string; - currency: string; - address?: string; - memo?: string; - chain: string; - }; + submitWithdraw(body: { + withdraw_order_id?: string; + amount: string; + currency: string; + address?: string; + memo?: string; + chain: string; }): Promise> { - return this.postPrivate('/withdrawals', params); + return this.postPrivate('/withdrawals', body); } /** @@ -488,29 +496,21 @@ export class RestClient extends BaseRestClient { * @param params Transfer parameters * @returns Promise> */ - submitTransfer(params: { - body: { - 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; - }; + submitTransfer(body: { + 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; }): Promise> { - return this.postPrivate('/wallet/transfers', params); + return this.postPrivate('/wallet/transfers', body); } /** @@ -521,17 +521,15 @@ export class RestClient extends BaseRestClient { * @param params Transfer parameters * @returns Promise> */ - submitMainSubTransfer(params: { - body: { - currency: string; - sub_account: string; - direction: 'to' | 'from'; - amount: string; - client_order_id?: string; - sub_account_type?: 'spot' | 'futures' | 'cross_margin' | 'delivery'; - }; + submitMainSubTransfer(body: { + currency: string; + sub_account: string; + direction: 'to' | 'from'; + amount: string; + client_order_id?: string; + sub_account_type?: 'spot' | 'futures' | 'cross_margin' | 'delivery'; }): Promise> { - return this.postPrivate('/wallet/sub_account_transfers', params); + return this.postPrivate('/wallet/sub_account_transfers', body); } /** @@ -558,18 +556,16 @@ export class RestClient extends BaseRestClient { * @param params Transfer parameters * @returns Promise> */ - getSubToSubTransfer(params: { - body: { - currency: string; - sub_account_type?: 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; - }; + getSubToSubTransfer(body: { + currency: string; + sub_account_type?: 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; }): Promise> { - return this.postPrivate('/wallet/sub_account_to_sub_account', params); + return this.postPrivate('/wallet/sub_account_to_sub_account', body); } /** @@ -701,12 +697,10 @@ export class RestClient extends BaseRestClient { * @param params Parameters for converting small balance * @returns Promise> */ - convertSmallBalance(params: { - body: { - currency?: string[]; - }; + convertSmallBalance(body: { + currency?: string[]; }): Promise> { - return this.postPrivate('/wallet/small_balance', params); + return this.postPrivate('/wallet/small_balance', body); } /** @@ -730,68 +724,27 @@ export class RestClient extends BaseRestClient { * Create a new sub-account * * @param params Parameters for creating a new sub-account - * @returns Promise> + * @returns Promise> */ - createSubAccount(params: { - body: { - remark?: string; - login_name: string; - password?: string; - email?: string; - }; - }): Promise< - APIResponse<{ - remark?: string; - login_name: string; - password?: string; - email?: string; - state: number; - type: number; - user_id: number; - create_time: number; - }> - > { - return this.postPrivate('/sub_accounts', params); + createSubAccount(body: { + remark?: string; + login_name: string; + password?: string; + email?: string; + }): Promise> { + return this.postPrivate('/sub_accounts', body); } /** * List sub-accounts * * @param params Parameters for listing sub-accounts - * @returns Promise> + * @returns Promise> */ - getSubAccounts(params?: { type?: string }): Promise< - APIResponse< - { - remark?: string; - login_name: string; - password?: string; - email?: string; - state: number; - type: number; - user_id: number; - create_time: number; - }[] - > - > { + + getSubAccounts(params?: { + type?: string; + }): Promise> { return this.getPrivate('/sub_accounts', params); } @@ -799,29 +752,11 @@ export class RestClient extends BaseRestClient { * Get the sub-account * * @param params Parameters containing the sub-account user ID - * @returns Promise> + * @returns Promise> */ - getSubAccount(params: { user_id: number }): Promise< - APIResponse<{ - remark?: string; - login_name: string; - password?: string; - email?: string; - state: number; - type: number; - user_id: number; - create_time: number; - }> - > { + getSubAccount(params: { + user_id: number; + }): Promise> { return this.getPrivate(`/sub_accounts/${params.user_id}`); } @@ -829,54 +764,17 @@ export class RestClient extends BaseRestClient { * Create API Key of the sub-account * * @param params Parameters for creating API Key of the sub-account - * @returns Promise> + * @returns Promise> */ - createSubAccountApiKey(params: { - user_id: number; - body: SubAccountKey; - }): Promise< - APIResponse<{ - user_id: string; - mode?: number; - name?: string; - perms?: { - name?: - | 'wallet' - | 'spot' - | 'futures' - | 'delivery' - | 'earn' - | 'options' - | 'account' - | 'unified' - | 'loan'; - read_only?: boolean; - }[]; - ip_whitelist?: string[]; - key: string; - state: number; - created_at: number; - updated_at: number; - last_access: number; - }> - > { - return this.postPrivate(`/sub_accounts/${params.user_id}/keys`, params); - } + createSubAccountApiKey( + params: { + user_id: number; + }, + body: SubAccountKey, + ): Promise> { + return this.postPrivate(`/sub_accounts/${params.user_id}/keys`, body); + } /** * List all API Key of the sub-account * @@ -895,14 +793,16 @@ export class RestClient extends BaseRestClient { * @param params Parameters for updating API key of the sub-account * @returns Promise> */ - updateSubAccountApiKey(params: { - user_id: number; - key: string; - body: SubAccountKey; - }): Promise> { + updateSubAccountApiKey( + params: { + user_id: number; + key: string; + }, + body: SubAccountKey, + ): Promise> { return this.putPrivate( `/sub_accounts/${params.user_id}/keys/${params.key}`, - params, + body, ); } @@ -966,73 +866,11 @@ export class RestClient extends BaseRestClient { * The assets of each currency in the account will be adjusted according to their liquidity, defined by corresponding adjustment coefficients, and then uniformly converted to USD to calculate the total asset value and position value of the account. * * @param params Parameters for retrieving unified account information - * @returns Promise> + * @returns Promise> */ - getUnifiedAccountInfo(params?: { currency?: string }): Promise< - APIResponse<{ - user_id: number; - refresh_time: number; - locked: boolean; - balances: { - [key: string]: { - available: string; - freeze: string; - borrowed: string; - negative_liab: string; - futures_pos_liab: string; - equity: string; - total_freeze: string; - total_liab: string; - spot_in_use: string; - }; - }; - total: string; - borrowed: 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; - unified_account_total: string; - unified_account_total_liab: string; - unified_account_total_equity: string; - leverage: string; - spot_order_loss: string; - spot_hedge: boolean; - }> - > { + getUnifiedAccountInfo(params?: { + currency?: string; + }): Promise> { return this.getPrivate('/unified/accounts', params); } @@ -1084,48 +922,21 @@ export class RestClient extends BaseRestClient { * @param params Parameters for borrowing or repaying * @returns Promise> */ - submitUnifiedBorrowOrRepay(params: { - body: { - currency: string; - type: 'borrow' | 'repay'; - amount: string; - repaid_all?: boolean; - text?: string; - }; - }): Promise> { - return this.postPrivate('/unified/loans', params); + submitUnifiedBorrowOrRepay( + body: SubmitUnifiedBorrowOrRepayReq, + ): Promise> { + return this.postPrivate('/unified/loans', body); } /** * List loans * * @param params Parameters for listing loans - * @returns Promise> + * @returns Promise> */ - getUnifiedLoans(params?: { - currency?: string; - page?: number; - limit?: number; - type?: 'platform' | 'margin'; - }): Promise< - APIResponse< - { - currency: string; - currency_pair: string; - amount: string; - type: 'platform' | 'margin'; - create_time: number; - update_time: number; - }[] - > - > { + getUnifiedLoans( + params?: GetUnifiedLoansReq, + ): Promise> { return this.getPrivate('/unified/loans', params); } @@ -1133,38 +944,11 @@ export class RestClient extends BaseRestClient { * Get loan records * * @param params Parameters for getting loan records - * @returns Promise> + * @returns Promise> */ - getUnifiedLoanRecords(params?: { - type?: 'borrow' | 'repay'; - currency?: string; - page?: number; - limit?: number; - }): Promise< - APIResponse< - { - 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; - }[] - > - > { + getUnifiedLoanRecords( + params?: GetUnifiedLoanRecordsReq, + ): Promise> { return this.getPrivate('/unified/loan_records', params); } @@ -1172,34 +956,11 @@ export class RestClient extends BaseRestClient { * List interest records * * @param params Parameters for listing interest records - * @returns Promise> + * @returns Promise> */ - getUnifiedInterestRecords(params?: { - currency?: string; - page?: number; - limit?: number; - type?: 'platform' | 'margin'; - }): Promise< - APIResponse< - { - currency: string; - currency_pair: string; - actual_rate: string; - interest: string; - status: number; - type: 'platform' | 'margin'; - create_time: number; - }[] - > - > { + getUnifiedInterestRecords( + params?: GetUnifiedInterestRecordsReq, + ): Promise> { return this.getPrivate('/unified/interest_records', params); } @@ -1248,16 +1009,14 @@ export class RestClient extends BaseRestClient { * @param params Parameters for setting the mode of the unified account * @returns Promise> */ - setUnifiedAccountMode(params: { - body: { - mode: 'classic' | 'multi_currency' | 'portfolio'; - settings?: { - usdt_futures?: boolean; - spot_hedge?: boolean; - }; + setUnifiedAccountMode(body: { + mode: 'classic' | 'multi_currency' | 'portfolio'; + settings?: { + usdt_futures?: boolean; + spot_hedge?: boolean; }; }): Promise> { - return this.putPrivate('/unified/unified_mode', params); + return this.putPrivate('/unified/unified_mode', body); } /** @@ -1365,39 +1124,37 @@ export class RestClient extends BaseRestClient { * }[]; * }>> */ - portfolioMarginCalculator(params: { - body: { - 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; - }; + portfolioMarginCalculator(body: { + 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; }): Promise< APIResponse<{ maintain_margin_total: string; @@ -1435,7 +1192,7 @@ export class RestClient extends BaseRestClient { }[]; }> > { - return this.post('/unified/portfolio_calculator', params); + return this.post('/unified/portfolio_calculator', body); } /**========================================================================================================================== @@ -1934,7 +1691,7 @@ export class RestClient extends BaseRestClient { * finish_as: 'open' | 'filled' | 'cancelled' | 'ioc' | 'stp'; * }[]>> */ - submitSpotBatchOrders(params: { body: Order[] }): Promise< + submitSpotBatchOrders(body: Order[]): Promise< APIResponse< { order_id: string; @@ -1976,7 +1733,7 @@ export class RestClient extends BaseRestClient { }[] > > { - return this.postPrivate('/spot/batch_orders', params); + return this.postPrivate('/spot/batch_orders', body); } /** @@ -2094,16 +1851,14 @@ export class RestClient extends BaseRestClient { * action_mode?: 'ACK' | 'RESULT' | 'FULL'; * }>> */ - submitSpotClosePosCrossDisabled(params: { - body: { - text?: string; - currency_pair: string; - amount: string; - price: string; - action_mode?: 'ACK' | 'RESULT' | 'FULL'; - }; + submitSpotClosePosCrossDisabled(body: { + text?: string; + currency_pair: string; + amount: string; + price: string; + action_mode?: 'ACK' | 'RESULT' | 'FULL'; }): Promise> { - return this.postPrivate('/spot/cross_liquidate_orders', params); + return this.postPrivate('/spot/cross_liquidate_orders', body); } /** @@ -2129,8 +1884,8 @@ export class RestClient extends BaseRestClient { * action_mode?: 'ACK' | 'RESULT' | 'FULL'; * }>> */ - submitSpotOrder(params: { body: Order }): Promise> { - return this.postPrivate('/spot/orders', params); + submitSpotOrder(body: Order): Promise> { + return this.postPrivate('/spot/orders', body); } /** @@ -2257,7 +2012,7 @@ export class RestClient extends BaseRestClient { * account: string; * }[]>> */ - deleteSpotBatchOrders(params: { body: CancelBatchOrder[] }): Promise< + deleteSpotBatchOrders(body: CancelBatchOrder[]): Promise< APIResponse< { currency_pair: string; @@ -2269,7 +2024,7 @@ export class RestClient extends BaseRestClient { }[] > > { - return this.postPrivate('/spot/cancel_batch_orders', params); + return this.postPrivate('/spot/cancel_batch_orders', body); } /** @@ -2368,18 +2123,20 @@ export class RestClient extends BaseRestClient { * finish_as: 'open' | 'filled' | 'cancelled' | 'ioc' | 'stp'; * }>> */ - updateSpotOrder(params: { - order_id: string; - currency_pair: string; - account?: 'spot' | 'margin' | 'cross_margin' | 'unified'; + updateSpotOrder( + params: { + order_id: string; + currency_pair: string; + account?: 'spot' | 'margin' | 'cross_margin' | 'unified'; + }, body: { amount?: string; price?: string; amend_text?: string; action_mode?: 'ACK' | 'RESULT' | 'FULL'; - }; - }): Promise> { - return this.patchPrivate(`/spot/orders/${params.order_id}`, params); + }, + ): Promise> { + return this.patchPrivate(`/spot/orders/${params.order_id}`, body); } /** @@ -2519,17 +2276,15 @@ export class RestClient extends BaseRestClient { * triggerTime: number; * }>> */ - submitSpotCountdownOrders(params: { - body: { - timeout: number; - currency_pair?: string; - }; + submitSpotCountdownOrders(body: { + timeout: number; + currency_pair?: string; }): Promise< APIResponse<{ triggerTime: number; }> > { - return this.postPrivate('/spot/countdown_cancel_all', params); + return this.postPrivate('/spot/countdown_cancel_all', body); } /** @@ -2577,15 +2332,15 @@ export class RestClient extends BaseRestClient { * finish_as: 'open' | 'filled' | 'cancelled' | 'ioc' | 'stp'; * }[]>> */ - updateSpotBatchOrders(params: { + updateSpotBatchOrders( body: { order_id?: string; currency_pair?: string; amount?: string; price?: string; amend_text?: string; - }[]; - }): Promise< + }[], + ): Promise< APIResponse< { order_id: string; @@ -2627,7 +2382,7 @@ export class RestClient extends BaseRestClient { }[] > > { - return this.postPrivate('/spot/amend_batch_orders', params); + return this.postPrivate('/spot/amend_batch_orders', body); } /** @@ -2638,14 +2393,12 @@ export class RestClient extends BaseRestClient { * id: number; * }>> */ - submitSpotPriceTriggerOrder(params: { - body: SpotPriceTriggeredOrder; - }): Promise< + submitSpotPriceTriggerOrder(body: SpotPriceTriggeredOrder): Promise< APIResponse<{ id: number; }> > { - return this.postPrivate('/spot/price_orders', params); + return this.postPrivate('/spot/price_orders', body); } /** @@ -3135,12 +2888,10 @@ export class RestClient extends BaseRestClient { * unpaid_interest: string; * }>> */ - submitCrossMarginBorrowLoan(params: { - body: { - currency: string; - amount: string; - text?: string; - }; + submitCrossMarginBorrowLoan(body: { + currency: string; + amount: string; + text?: string; }): Promise< APIResponse<{ id: string; @@ -3155,7 +2906,7 @@ export class RestClient extends BaseRestClient { unpaid_interest: string; }> > { - return this.postPrivate('/margin/cross/loans', params); + return this.postPrivate('/margin/cross/loans', body); } /** @@ -3254,8 +3005,9 @@ export class RestClient extends BaseRestClient { * unpaid_interest: string; * }[]>> */ - submitCrossMarginRepayment(params: { - body: { currency: string; amount: string }; + submitCrossMarginRepayment(body: { + currency: string; + amount: string; }): Promise< APIResponse< { @@ -3272,7 +3024,7 @@ export class RestClient extends BaseRestClient { }[] > > { - return this.postPrivate('/margin/cross/repayments', params); + return this.postPrivate('/margin/cross/repayments', body); } /** @@ -3468,16 +3220,14 @@ export class RestClient extends BaseRestClient { * @param params Parameters for borrowing or repaying * @returns Promise */ - submitMarginUNIBorrowOrRepay(params: { - body: { - currency: string; - type: 'borrow' | 'repay'; - amount: string; - repaid_all?: boolean; - currency_pair: string; - }; + submitMarginUNIBorrowOrRepay(body: { + currency: string; + type: 'borrow' | 'repay'; + amount: string; + repaid_all?: boolean; + currency_pair: string; }): Promise { - return this.postPrivate('/margin/uni/loans', params); + return this.postPrivate('/margin/uni/loans', body); } /** @@ -3658,14 +3408,12 @@ export class RestClient extends BaseRestClient { * status: number; * }>> */ - submitFlashSwapOrder(params: { - body: { - preview_id: string; - sell_currency: string; - sell_amount: string; - buy_currency: string; - buy_amount: string; - }; + submitFlashSwapOrder(body: { + preview_id: string; + sell_currency: string; + sell_amount: string; + buy_currency: string; + buy_amount: string; }): Promise< APIResponse<{ id: number; @@ -3679,7 +3427,7 @@ export class RestClient extends BaseRestClient { status: number; }> > { - return this.postPrivate('/flash_swap/orders', params); + return this.postPrivate('/flash_swap/orders', body); } /** @@ -3768,13 +3516,11 @@ export class RestClient extends BaseRestClient { * price: string; * }>> */ - submitFlashSwapOrderPreview(params: { - body: { - sell_currency: string; - sell_amount?: string; - buy_currency: string; - buy_amount?: string; - }; + submitFlashSwapOrderPreview(body: { + sell_currency: string; + sell_amount?: string; + buy_currency: string; + buy_amount?: string; }): Promise< APIResponse<{ preview_id: string; @@ -3785,7 +3531,7 @@ export class RestClient extends BaseRestClient { price: string; }> > { - return this.postPrivate('/flash_swap/orders/preview', params); + return this.postPrivate('/flash_swap/orders/preview', body); } /**========================================================================================================================== * FUTURES @@ -4574,11 +4320,13 @@ export class RestClient extends BaseRestClient { * @param params Parameters for creating a futures order * @returns Promise> */ - submitFuturesOrder(params: { - settle: 'btc' | 'usdt' | 'usd'; - body: FuturesOrder; - }): Promise> { - return this.postPrivate(`/futures/${params.settle}/orders`, params); + submitFuturesOrder( + params: { + settle: 'btc' | 'usdt' | 'usd'; + }, + body: FuturesOrder, + ): Promise> { + return this.postPrivate(`/futures/${params.settle}/orders`, body); } /** @@ -4677,10 +4425,12 @@ export class RestClient extends BaseRestClient { * stp_id: number; * }[]>> */ - submitFuturesBatchOrders(params: { - settle: 'btc' | 'usdt' | 'usd'; - body: FuturesOrder[]; - }): Promise< + submitFuturesBatchOrders( + params: { + settle: 'btc' | 'usdt' | 'usd'; + }, + body: FuturesOrder[], + ): Promise< APIResponse< { succeeded: boolean; @@ -4711,7 +4461,7 @@ export class RestClient extends BaseRestClient { }[] > > { - return this.postPrivate(`/futures/${params.settle}/batch_orders`, params); + return this.postPrivate(`/futures/${params.settle}/batch_orders`, body); } /** @@ -4754,18 +4504,20 @@ export class RestClient extends BaseRestClient { * @param params Parameters for amending an order * @returns Promise> */ - updateFuturesOrder(params: { - settle: 'btc' | 'usdt' | 'usd'; - order_id: string; + updateFuturesOrder( + params: { + settle: 'btc' | 'usdt' | 'usd'; + order_id: string; + }, body: { size?: number; price?: string; amend_text?: string; - }; - }): Promise> { + }, + ): Promise> { return this.putPrivate( `/futures/${params.settle}/orders/${params.order_id}`, - params, + body, ); } @@ -4962,16 +4714,18 @@ export class RestClient extends BaseRestClient { * @param params Parameters for setting countdown cancel orders * @returns Promise> */ - deleteFuturesOrdersCountdown(params: { - settle: 'btc' | 'usdt' | 'usd'; + deleteFuturesOrdersCountdown( + params: { + settle: 'btc' | 'usdt' | 'usd'; + }, body: { timeout: number; contract?: string; - }; - }): Promise> { + }, + ): Promise> { return this.postPrivate( `/futures/${params.settle}/countdown_cancel_all`, - params, + body, ); } @@ -5003,10 +4757,12 @@ export class RestClient extends BaseRestClient { * message: string; * }[]>> */ - deleteFuturesBatchOrders(params: { - settle: 'btc' | 'usdt' | 'usd'; - body: string[]; - }): Promise< + deleteFuturesBatchOrders( + params: { + settle: 'btc' | 'usdt' | 'usd'; + }, + body: string[], + ): Promise< APIResponse< { user_id: number; @@ -5018,7 +4774,7 @@ export class RestClient extends BaseRestClient { > { return this.postPrivate( `/futures/${params.settle}/batch_cancel_orders`, - params, + body, ); } @@ -5028,11 +4784,13 @@ export class RestClient extends BaseRestClient { * @param params Parameters for creating a price-triggered order * @returns Promise> */ - submitFuturesPriceTriggeredOrder(params: { - settle: 'btc' | 'usdt' | 'usd'; - body: FuturesPriceTriggeredOrder; - }): Promise> { - return this.postPrivate(`/futures/${params.settle}/price_orders`, params); + submitFuturesPriceTriggeredOrder( + params: { + settle: 'btc' | 'usdt' | 'usd'; + }, + body: FuturesPriceTriggeredOrder, + ): Promise> { + return this.postPrivate(`/futures/${params.settle}/price_orders`, body); } /** @@ -5537,11 +5295,13 @@ export class RestClient extends BaseRestClient { * @param params Parameters for creating a futures order * @returns Promise> */ - submitDeliveryOrder(params: { - settle: 'usdt'; - body: FuturesOrder; - }): Promise> { - return this.postPrivate(`/delivery/${params.settle}/orders`, params); + submitDeliveryOrder( + params: { + settle: 'usdt'; + }, + body: FuturesOrder, + ): Promise> { + return this.postPrivate(`/delivery/${params.settle}/orders`, body); } /** @@ -5790,11 +5550,13 @@ export class RestClient extends BaseRestClient { * @param params Parameters for creating a price-triggered order * @returns Promise> */ - submitDeliveryTriggeredOrder(params: { - settle: 'usdt'; - body: FuturesPriceTriggeredOrder; - }): Promise> { - return this.postPrivate(`/delivery/${params.settle}/price_orders`, params); + submitDeliveryTriggeredOrder( + params: { + settle: 'usdt'; + }, + body: FuturesPriceTriggeredOrder, + ): Promise> { + return this.postPrivate(`/delivery/${params.settle}/price_orders`, body); } /** @@ -6574,17 +6336,15 @@ export class RestClient extends BaseRestClient { * refr: string; * }>> */ - submitOptionsOrder(params: { - body: { - contract: string; - size: number; - iceberg?: number; - price?: string; - close?: boolean; - reduce_only?: boolean; - tif?: 'gtc' | 'ioc' | 'poc'; - text?: string; - }; + submitOptionsOrder(body: { + contract: string; + size: number; + iceberg?: number; + price?: string; + close?: boolean; + reduce_only?: boolean; + tif?: 'gtc' | 'ioc' | 'poc'; + text?: string; }): Promise< APIResponse<{ id: number; @@ -6617,7 +6377,7 @@ export class RestClient extends BaseRestClient { refr: string; }> > { - return this.postPrivate(`/options/orders`, params); + return this.postPrivate(`/options/orders`, body); } /** @@ -6987,15 +6747,13 @@ export class RestClient extends BaseRestClient { * @param params Parameters for lending or redeeming * @returns Promise> */ - submitLendOrRedeem(params: { - body: { - currency: string; - amount: string; - type: 'lend' | 'redeem'; - min_rate?: string; - }; + submitLendOrRedeem(body: { + currency: string; + amount: string; + type: 'lend' | 'redeem'; + min_rate?: string; }): Promise> { - return this.postPrivate(`/earn/uni/lends`, params); + return this.postPrivate(`/earn/uni/lends`, body); } /** @@ -7046,13 +6804,11 @@ export class RestClient extends BaseRestClient { * @param params Parameters for amending lending order * @returns Promise> */ - updateLendingOrder(params: { - body: { - currency?: string; - min_rate?: string; - }; + updateLendingOrder(body: { + currency?: string; + min_rate?: string; }): Promise> { - return this.patchPrivate(`/earn/uni/lends`, params); + return this.patchPrivate(`/earn/uni/lends`, body); } /** @@ -7150,13 +6906,11 @@ export class RestClient extends BaseRestClient { * @param params Parameters for setting interest reinvestment toggle * @returns Promise> */ - updateInterestReinvestment(params: { - body: { - currency: string; - status: boolean; - }; + updateInterestReinvestment(body: { + currency: string; + status: boolean; }): Promise> { - return this.putPrivate(`/earn/uni/interest_reinvest`, params); + return this.putPrivate(`/earn/uni/interest_reinvest`, body); } /** @@ -7188,15 +6942,13 @@ export class RestClient extends BaseRestClient { * @param params Parameters for placing an order * @returns Promise> */ - submitLoanOrder(params: { - body: { - collateral_amount: string; - collateral_currency: string; - borrow_amount: string; - borrow_currency: string; - }; + submitLoanOrder(body: { + collateral_amount: string; + collateral_currency: string; + borrow_amount: string; + borrow_currency: string; }): Promise> { - return this.postPrivate(`/loan/collateral/orders`, params); + return this.postPrivate(`/loan/collateral/orders`, body); } /** @@ -7307,19 +7059,17 @@ export class RestClient extends BaseRestClient { * repaid_interest: string; * }>> */ - submitLoanRepay(params: { - body: { - order_id: number; - repay_amount: string; - repaid_all: boolean; - }; + submitLoanRepay(body: { + order_id: number; + repay_amount: string; + repaid_all: boolean; }): Promise< APIResponse<{ repaid_principal: string; repaid_interest: string; }> > { - return this.postPrivate(`/loan/collateral/repay`, params); + return this.postPrivate(`/loan/collateral/repay`, body); } /** @@ -7378,15 +7128,13 @@ export class RestClient extends BaseRestClient { * @param params Parameters for increasing or redeeming collateral * @returns Promise> */ - updateLoanCollateral(params: { - body: { - order_id: number; - collateral_currency: string; - collateral_amount: string; - type: 'append' | 'redeem'; - }; + updateLoanCollateral(body: { + order_id: number; + collateral_currency: string; + collateral_amount: string; + type: 'append' | 'redeem'; }): Promise> { - return this.postPrivate(`/loan/collateral/collaterals`, params); + return this.postPrivate(`/loan/collateral/collaterals`, body); } /** @@ -7511,23 +7259,21 @@ export class RestClient extends BaseRestClient { * @param params Parameters for creating a multi-collateral order * @returns Promise> */ - submitMultiLoanOrder(params: { - body: { - order_id?: string; - order_type?: string; - fixed_type?: string; - fixed_rate?: string; - auto_renew?: boolean; - auto_repay?: boolean; - borrow_currency: string; - borrow_amount: string; - collateral_currencies?: { - currency?: string; - amount?: string; - }[]; - }; + submitMultiLoanOrder(body: { + order_id?: string; + order_type?: string; + fixed_type?: string; + fixed_rate?: string; + auto_renew?: boolean; + auto_repay?: boolean; + borrow_currency: string; + borrow_amount: string; + collateral_currencies?: { + currency?: string; + amount?: string; + }[]; }): Promise> { - return this.postPrivate(`/loan/multi_collateral/orders`, params); + return this.postPrivate(`/loan/multi_collateral/orders`, body); } /** @@ -7684,15 +7430,13 @@ export class RestClient extends BaseRestClient { * }[]; * }>> */ - repayMultiLoan(params: { - body: { - order_id: number; - repay_items: { - currency?: string; - amount?: string; - repaid_all?: boolean; - }[]; - }; + repayMultiLoan(body: { + order_id: number; + repay_items: { + currency?: string; + amount?: string; + repaid_all?: boolean; + }[]; }): Promise< APIResponse<{ order_id: number; @@ -7706,7 +7450,7 @@ export class RestClient extends BaseRestClient { }[]; }> > { - return this.postPrivate(`/loan/multi_collateral/repay`, params); + return this.postPrivate(`/loan/multi_collateral/repay`, body); } /** @@ -7837,15 +7581,13 @@ export class RestClient extends BaseRestClient { * }[]; * }>> */ - operateMultiLoan(params: { - body: { - order_id: number; - type: 'append' | 'redeem'; - collaterals?: { - currency?: string; - amount?: string; - }[]; - }; + operateMultiLoan(body: { + order_id: number; + type: 'append' | 'redeem'; + collaterals?: { + currency?: string; + amount?: string; + }[]; }): Promise< APIResponse<{ order_id: number; @@ -7858,7 +7600,7 @@ export class RestClient extends BaseRestClient { }[]; }> > { - return this.postPrivate(`/loan/multi_collateral/mortgage`, params); + return this.postPrivate(`/loan/multi_collateral/mortgage`, body); } /** @@ -8038,13 +7780,11 @@ export class RestClient extends BaseRestClient { * @param params Parameters for ETH2 swap * @returns Promise> */ - submitEth2Swap(params: { - body: { - side: '1' | '2'; - amount: string; - }; + submitEth2Swap(body: { + side: '1' | '2'; + amount: string; }): Promise> { - return this.postPrivate(`/earn/staking/eth2/swap`, params); + return this.postPrivate(`/earn/staking/eth2/swap`, body); } /** @@ -8146,13 +7886,11 @@ export class RestClient extends BaseRestClient { * @param params Parameters for placing a dual investment order * @returns Promise> */ - submitDualInvestmentOrder(params: { - body: { - plan_id: string; - copies: string; - }; + submitDualInvestmentOrder(body: { + plan_id: string; + copies: string; }): Promise> { - return this.postPrivate(`/earn/dual/orders`, params); + return this.postPrivate(`/earn/dual/orders`, body); } /** @@ -8241,13 +7979,11 @@ export class RestClient extends BaseRestClient { * @param params Parameters for placing a structured product order * @returns Promise> */ - submitStructuredProductOrder(params: { - body: { - pid?: string; - amount?: string; - }; + submitStructuredProductOrder(body: { + pid?: string; + amount?: string; }): Promise> { - return this.postPrivate(`/earn/structured/orders`, params); + return this.postPrivate(`/earn/structured/orders`, body); } /**========================================================================================================================== @@ -8293,13 +8029,11 @@ export class RestClient extends BaseRestClient { * create_time: number; * }>> */ - createStpGroup(params: { - body: { - id?: number; - name: string; - creator_id?: number; - create_time?: number; - }; + createStpGroup(body: { + id?: number; + name: string; + creator_id?: number; + create_time?: number; }): Promise< APIResponse<{ id: number; @@ -8308,7 +8042,7 @@ export class RestClient extends BaseRestClient { create_time: number; }> > { - return this.postPrivate(`/account/stp_groups`, params); + return this.postPrivate(`/account/stp_groups`, body); } /** @@ -8370,7 +8104,10 @@ export class RestClient extends BaseRestClient { * create_time: number; * }[]>> */ - addUsersToStpGroup(params: { stp_id: number; body: number[] }): Promise< + addUsersToStpGroup( + params: { stp_id: number }, + body: number[], + ): Promise< APIResponse< { user_id: number; @@ -8379,10 +8116,7 @@ export class RestClient extends BaseRestClient { }[] > > { - return this.postPrivate( - `/account/stp_groups/${params.stp_id}/users`, - params, - ); + return this.postPrivate(`/account/stp_groups/${params.stp_id}/users`, body); } /** diff --git a/src/types/requests/shared.types.ts b/src/types/requests/shared.types.ts index 1080a60..324820d 100644 --- a/src/types/requests/shared.types.ts +++ b/src/types/requests/shared.types.ts @@ -26,3 +26,31 @@ export interface GetSmallBalanceHistoryReq { page?: number; limit?: number; } + +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; + type?: 'platform' | 'margin'; +} diff --git a/src/types/response/shared.types.ts b/src/types/response/shared.types.ts index 0cdf34f..d6cb0e5 100644 --- a/src/types/response/shared.types.ts +++ b/src/types/response/shared.types.ts @@ -195,3 +195,100 @@ export interface GetSmallBalanceHistoryResp { gt_amount: string; create_time: number; } + +export interface SubAccountResp { + remark?: string; + login_name: string; + password?: string; + email?: string; + state: number; + type: number; + user_id: number; + create_time: number; +} + +export interface CreateSubAccountApiKeyResp { + user_id: string; + mode?: number; + name?: string; + perms?: { + name?: + | 'wallet' + | 'spot' + | 'futures' + | 'delivery' + | 'earn' + | 'options' + | 'account' + | 'unified' + | 'loan'; + read_only?: boolean; + }[]; + ip_whitelist?: string[]; + key: string; + state: number; + created_at: number; + updated_at: number; + last_access: number; +} + +export interface GetUnifiedAccountInfoResp { + user_id: number; + refresh_time: number; + locked: boolean; + balances: { + [key: string]: { + available: string; + freeze: string; + borrowed: string; + negative_liab: string; + futures_pos_liab: string; + equity: string; + total_freeze: string; + total_liab: string; + spot_in_use: string; + }; + }; + total: string; + borrowed: 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; + unified_account_total: string; + unified_account_total_liab: string; + unified_account_total_equity: string; + leverage: string; + spot_order_loss: string; + spot_hedge: boolean; +} + +export interface GetUnifiedLoansResp { + currency: string; + currency_pair: string; + amount: string; + type: 'platform' | 'margin'; + create_time: number; + update_time: number; +} + +export interface GetUnifiedLoanRecordsResp { + 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; +} +export interface GetUnifiedInterestRecordsResp { + currency: string; + currency_pair: string; + actual_rate: string; + interest: string; + status: number; + type: 'platform' | 'margin'; + create_time: number; +} From 1db9de820ed409f2875ea9b63384f6de5f5ff653 Mon Sep 17 00:00:00 2001 From: Tiago Siebler Date: Mon, 20 May 2024 14:50:10 +0100 Subject: [PATCH 11/36] feat(): allow post requests to use query instead of body --- src/RestClient.ts | 8 +++- src/lib/BaseRestClient.ts | 82 ++++++++++++++++++++++++++------------- 2 files changed, 61 insertions(+), 29 deletions(-) diff --git a/src/RestClient.ts b/src/RestClient.ts index e6cd8c3..e3233df 100644 --- a/src/RestClient.ts +++ b/src/RestClient.ts @@ -4146,9 +4146,13 @@ export class RestClient extends BaseRestClient { leverage: string; cross_leverage_limit?: string; }): Promise> { + const paramsAsQuery = true; + + const { settle, contract, ...remainingParams } = params; return this.postPrivate( - `/futures/${params.settle}/positions/${params.contract}/leverage`, - params, + `/futures/${settle}/positions/${contract}/leverage`, + remainingParams, + paramsAsQuery, ); } diff --git a/src/lib/BaseRestClient.ts b/src/lib/BaseRestClient.ts index ef30042..15fabf9 100644 --- a/src/lib/BaseRestClient.ts +++ b/src/lib/BaseRestClient.ts @@ -153,31 +153,42 @@ export abstract class BaseRestClient { } protected get(endpoint: string, params?: any) { - return this._call('GET', endpoint, params, true); + const isPublicAPI = true; + return this._call('GET', endpoint, params, isPublicAPI); } protected post(endpoint: string, params?: any) { - return this._call('POST', endpoint, params, true); + const isPublicAPI = true; + return this._call('POST', endpoint, params, isPublicAPI); } protected getPrivate(endpoint: string, params?: any) { - return this._call('GET', endpoint, params, false); + const isPublicAPI = false; + return this._call('GET', endpoint, params, isPublicAPI); } - protected postPrivate(endpoint: string, params?: any) { - return this._call('POST', endpoint, params, false); + protected postPrivate( + endpoint: string, + params?: any, + paramsAsQuery?: boolean, + ) { + const isPublicAPI = false; + return this._call('POST', endpoint, params, isPublicAPI, paramsAsQuery); } protected deletePrivate(endpoint: string, params?: any) { - return this._call('DELETE', endpoint, params, false); + const isPublicAPI = false; + return this._call('DELETE', endpoint, params, isPublicAPI); } protected putPrivate(endpoint: string, params?: any) { - return this._call('PUT', endpoint, params, false); + const isPublicAPI = false; + return this._call('PUT', endpoint, params, isPublicAPI); } protected patchPrivate(endpoint: string, params?: any) { - return this._call('PATCH', endpoint, params, false); + const isPublicAPI = false; + return this._call('PATCH', endpoint, params, isPublicAPI); } /** @@ -188,6 +199,7 @@ export abstract class BaseRestClient { endpoint: string, params?: any, isPublicApi?: boolean, + passParamsAsQueryString?: boolean, ): Promise { // Sanity check to make sure it's only ever prefixed by one forward slash const requestUrl = [this.baseUrl, endpoint].join( @@ -201,6 +213,7 @@ export abstract class BaseRestClient { requestUrl, params, isPublicApi, + passParamsAsQueryString, ); if (ENABLE_HTTP_TRACE) { @@ -274,6 +287,7 @@ export abstract class BaseRestClient { endpoint: string, method: Method, signMethod: SignMethod, + passParamsAsQueryString?: boolean, ): Promise> { const timestamp = +(this.getSignTimestampMs() / 1000).toFixed(0); // in seconds @@ -298,24 +312,27 @@ export abstract class BaseRestClient { const encodeQueryStringValues = true; if (signMethod === 'gateV4') { - const requestParamsToSign = - method === 'GET' || method === 'DELETE' - ? serializeParams( - res.originalParams, - strictParamValidation, - encodeQueryStringValues, - '', - ) - : ''; - - const hashedMsgParams = - method === 'GET' ? '' : JSON.stringify(res.originalParams); + const useQueryStringParamAuth = + method === 'GET' || method === 'DELETE' || passParamsAsQueryString; const signAlgoritm: SignAlgorithm = 'SHA-512'; const signEncoding: SignEncodeMethod = 'hex'; - const hashedData = await hashMessage( - hashedMsgParams, + const queryStringToSign = useQueryStringParamAuth + ? serializeParams( + res.originalParams, + strictParamValidation, + encodeQueryStringValues, + '', + ) + : ''; + + const requestBodyToHash = useQueryStringParamAuth + ? '' + : JSON.stringify(res.originalParams); + + const hashedRequestBody = await hashMessage( + requestBodyToHash, signEncoding, signAlgoritm, ); @@ -323,8 +340,8 @@ export abstract class BaseRestClient { const toSign = [ method, this.baseUrlPath + endpoint, - requestParamsToSign, - hashedData, + queryStringToSign, + hashedRequestBody, timestamp, ].join('\n'); @@ -340,7 +357,7 @@ export abstract class BaseRestClient { signEncoding, signAlgoritm, ); - res.queryParamsWithSign = requestParamsToSign; + res.queryParamsWithSign = queryStringToSign; return res; } @@ -370,6 +387,7 @@ export abstract class BaseRestClient { signMethod: SignMethod, params?: TParams, isPublicApi?: true, + passParamsAsQueryString?: boolean, ): Promise>; private async prepareSignParams( method: Method, @@ -377,6 +395,7 @@ export abstract class BaseRestClient { signMethod: SignMethod, params?: TParams, isPublicApi?: false | undefined, + passParamsAsQueryString?: boolean, ): Promise>; private async prepareSignParams( method: Method, @@ -384,6 +403,7 @@ export abstract class BaseRestClient { signMethod: SignMethod, params?: TParams, isPublicApi?: boolean, + passParamsAsQueryString?: boolean, ) { if (isPublicApi) { return { @@ -396,7 +416,13 @@ export abstract class BaseRestClient { throw new Error(MISSING_API_KEYS_ERROR); } - return this.signRequest(params, endpoint, method, signMethod); + return this.signRequest( + params, + endpoint, + method, + signMethod, + passParamsAsQueryString, + ); } /** Returns an axios request object. Handles signing process automatically if this is a private API call */ @@ -406,6 +432,7 @@ export abstract class BaseRestClient { url: string, params?: any, isPublicApi?: boolean, + passParamsAsQueryString?: boolean, ): Promise { const options: AxiosRequestConfig = { ...this.globalRequestOptions, @@ -432,6 +459,7 @@ export abstract class BaseRestClient { 'gateV4', params, isPublicApi, + passParamsAsQueryString, ); const authHeaders = { @@ -441,7 +469,7 @@ export abstract class BaseRestClient { // 'X-Client-Request-Id': 'todo' }; - if (method === 'GET') { + if (method === 'GET' || passParamsAsQueryString) { return { ...options, headers: { From ecb4a3f9801c157b5a6346b4936832463524fc13 Mon Sep 17 00:00:00 2001 From: Tiago Siebler Date: Mon, 20 May 2024 14:56:41 +0100 Subject: [PATCH 12/36] feat(): fix post req --- src/RestClient.ts | 3 ++- src/lib/BaseRestClient.ts | 2 ++ 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/src/RestClient.ts b/src/RestClient.ts index e3233df..5dcc0cd 100644 --- a/src/RestClient.ts +++ b/src/RestClient.ts @@ -2657,7 +2657,8 @@ export class RestClient extends BaseRestClient { updateAutoRepaymentSetting(params: { status: 'on' | 'off'; }): Promise> { - return this.postPrivate('/margin/auto_repay', params); + const paramsAsQuery = true; + return this.postPrivate('/margin/auto_repay', params, paramsAsQuery); } /** diff --git a/src/lib/BaseRestClient.ts b/src/lib/BaseRestClient.ts index 15fabf9..a370d75 100644 --- a/src/lib/BaseRestClient.ts +++ b/src/lib/BaseRestClient.ts @@ -274,6 +274,8 @@ export abstract class BaseRestClient { apiKey: 'omittedFromError', apiMemo: 'omittedFromError', apiSecret: 'omittedFromError', + reqUrl: request.url, + reqBody: request.data, }, ...debugData, }; From 9361b3e7295447763d03ee3736168a331ce7261b Mon Sep 17 00:00:00 2001 From: Tiago Siebler Date: Mon, 20 May 2024 15:07:18 +0100 Subject: [PATCH 13/36] feat(): attempt to fix tsconfig --- .gitignore | 1 + src/WebsocketClient.ts | 1 + test/tsconfig.test.json | 10 ++++++++++ tsconfig.json | 5 ++--- 4 files changed, 14 insertions(+), 3 deletions(-) create mode 100644 test/tsconfig.test.json diff --git a/.gitignore b/.gitignore index 40dec87..37e2f54 100644 --- a/.gitignore +++ b/.gitignore @@ -21,3 +21,4 @@ node_modules/ .cache bundleReport.html .history/ +dist diff --git a/src/WebsocketClient.ts b/src/WebsocketClient.ts index 3019be9..14fb187 100644 --- a/src/WebsocketClient.ts +++ b/src/WebsocketClient.ts @@ -451,6 +451,7 @@ export class WebsocketClient extends BaseWebsocketClient< signMessageInput, this.options.apiSecret, 'hex', + 'SHA-512', ); } diff --git a/test/tsconfig.test.json b/test/tsconfig.test.json new file mode 100644 index 0000000..c4bad3b --- /dev/null +++ b/test/tsconfig.test.json @@ -0,0 +1,10 @@ +{ + "extends": "../tsconfig.json", + "compilerOptions": { + "module": "commonjs", + "outDir": "dist/cjs", + "target": "esnext", + "rootDir": "../" + }, + "include": ["../src/**/*.*", "../test/**/*.*"] +} diff --git a/tsconfig.json b/tsconfig.json index 312cba1..9521a4b 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -17,7 +17,6 @@ "pretty": true, "removeComments": false, "resolveJsonModule": true, - "rootDir": "src", "skipLibCheck": false, "sourceMap": true, "strict": true, @@ -28,6 +27,6 @@ "target": "esnext" }, "compileOnSave": true, - "exclude": ["node_modules", "dist", "test"], - "include": ["src/**/*.*", ".eslintrc.cjs"] + "exclude": ["node_modules", "dist"], + "include": ["src/**/*.*", "test/**/*.*", ".eslintrc.cjs"] } From 543ac1803cd020fee153321d211655770ead7f36 Mon Sep 17 00:00:00 2001 From: Tiago Siebler Date: Mon, 20 May 2024 15:48:47 +0100 Subject: [PATCH 14/36] feat(): add test config --- .gitignore | 1 + jest.config.ts | 218 ++++++++++++++++++++++++++++++++++++++ test/REST/private.test.ts | 28 +++++ test/tsconfig.test.json | 5 +- tsconfig.linting.json | 8 +- 5 files changed, 257 insertions(+), 3 deletions(-) create mode 100644 jest.config.ts create mode 100644 test/REST/private.test.ts diff --git a/.gitignore b/.gitignore index 37e2f54..512e5d9 100644 --- a/.gitignore +++ b/.gitignore @@ -22,3 +22,4 @@ node_modules/ bundleReport.html .history/ dist +coverage diff --git a/jest.config.ts b/jest.config.ts new file mode 100644 index 0000000..c003b0e --- /dev/null +++ b/jest.config.ts @@ -0,0 +1,218 @@ +/** + * For a detailed explanation regarding each configuration property, visit: + * https://jestjs.io/docs/configuration + */ + +import type { Config } from 'jest'; + +const config: Config = { + // All imported modules in your tests should be mocked automatically + // automock: false, + + // Stop running tests after `n` failures + // bail: 0, + bail: false, // enable to stop test when an error occur, + + // The directory where Jest should store its cached dependency information + // cacheDirectory: "/private/var/folders/kf/2k3sz4px6c9cbyzj1h_b192h0000gn/T/jest_dx", + + // Automatically clear mock calls, instances, contexts and results before every test + clearMocks: true, + + // Indicates whether the coverage information should be collected while executing the test + collectCoverage: true, + + // An array of glob patterns indicating a set of files for which coverage information should be collected + collectCoverageFrom: ['src/**/*.ts'], + + // The directory where Jest should output its coverage files + coverageDirectory: 'coverage', + + // An array of regexp pattern strings used to skip coverage collection + // coveragePathIgnorePatterns: [ + // "/node_modules/" + // ], + + // Indicates which provider should be used to instrument code for coverage + coverageProvider: 'v8', + + // A list of reporter names that Jest uses when writing coverage reports + // coverageReporters: [ + // "json", + // "text", + // "lcov", + // "clover" + // ], + + // An object that configures minimum threshold enforcement for coverage results + // coverageThreshold: undefined, + + // A path to a custom dependency extractor + // dependencyExtractor: undefined, + + // Make calling deprecated APIs throw helpful error messages + // errorOnDeprecated: false, + + // The default configuration for fake timers + // fakeTimers: { + // "enableGlobally": false + // }, + + // Force coverage collection from ignored files using an array of glob patterns + // forceCoverageMatch: [], + + // A path to a module which exports an async function that is triggered once before all test suites + // globalSetup: undefined, + + // A path to a module which exports an async function that is triggered once after all test suites + // globalTeardown: undefined, + + // A set of global variables that need to be available in all test environments + // globals: {}, + + // The maximum amount of workers used to run your tests. Can be specified as % or a number. E.g. maxWorkers: 10% will use 10% of your CPU amount + 1 as the maximum worker number. maxWorkers: 2 will use a maximum of 2 workers. + // maxWorkers: "50%", + + // An array of directory names to be searched recursively up from the requiring module's location + // moduleDirectories: [ + // "node_modules" + // ], + moduleDirectories: ['node_modules', 'src', 'test'], + + // An array of file extensions your modules use + moduleFileExtensions: [ + 'js', + 'mjs', + 'cjs', + 'jsx', + 'ts', + 'tsx', + 'json', + 'node', + ], + + // modulePaths: ['src'], + + // A map from regular expressions to module names or to arrays of module names that allow to stub out resources with a single module + // moduleNameMapper: {}, + + // An array of regexp pattern strings, matched against all module paths before considered 'visible' to the module loader + // modulePathIgnorePatterns: [], + + // Activates notifications for test results + // notify: false, + + // An enum that specifies notification mode. Requires { notify: true } + // notifyMode: "failure-change", + + // A preset that is used as a base for Jest's configuration + // preset: undefined, + + // Run tests from one or more projects + // projects: undefined, + + // Use this configuration option to add custom reporters to Jest + // reporters: undefined, + + // Automatically reset mock state before every test + // resetMocks: false, + + // Reset the module registry before running each individual test + // resetModules: false, + + // A path to a custom resolver + // resolver: undefined, + + // Automatically restore mock state and implementation before every test + // restoreMocks: false, + + // The root directory that Jest should scan for tests and modules within + // rootDir: undefined, + + // A list of paths to directories that Jest should use to search for files in + // roots: [ + // "" + // ], + + // Allows you to use a custom runner instead of Jest's default test runner + // runner: "jest-runner", + + // The paths to modules that run some code to configure or set up the testing environment before each test + // setupFiles: [], + + // A list of paths to modules that run some code to configure or set up the testing framework before each test + // setupFilesAfterEnv: [], + + // The number of seconds after which a test is considered as slow and reported as such in the results. + // slowTestThreshold: 5, + + // A list of paths to snapshot serializer modules Jest should use for snapshot testing + // snapshotSerializers: [], + + // The test environment that will be used for testing + // testEnvironment: "jest-environment-node", + + // Options that will be passed to the testEnvironment + // testEnvironmentOptions: {}, + + // Adds a location field to test results + // testLocationInResults: false, + + // The glob patterns Jest uses to detect test files + testMatch: [ + // "**/__tests__/**/*.[jt]s?(x)", + '**/?(*.)+(spec|test).[tj]s?(x)', + ], + + testTimeout: 15000, + + // An array of regexp pattern strings that are matched against all test paths, matched tests are skipped + // testPathIgnorePatterns: [ + // "/node_modules/" + // ], + + // The regexp pattern or array of patterns that Jest uses to detect test files + // testRegex: [], + + // This option allows the use of a custom results processor + // testResultsProcessor: undefined, + + // This option allows use of a custom test runner + // testRunner: "jest-circus/runner", + + // A map from regular expressions to paths to transformers + // transform: undefined, + + transform: { + '^.+\\.(t|j)s$': [ + 'ts-jest', + { + tsconfig: 'test/tsconfig.test.json', + }, + ], + }, + + // An array of regexp pattern strings that are matched against all source file paths, matched files will skip transformation + // transformIgnorePatterns: [ + // "/node_modules/", + // "\\.pnp\\.[^\\/]+$" + // ], + + // Prevents import esm module error from v1 axios release, issue #5026 + transformIgnorePatterns: ['node_modules/(?!axios)'], + + // An array of regexp pattern strings that are matched against all modules before the module loader will automatically return a mock for them + // unmockedModulePathPatterns: undefined, + + // Indicates whether each individual test should be reported during the run + // verbose: undefined, + verbose: true, // report individual test + + // An array of regexp patterns that are matched against all source file paths before re-running tests in watch mode + // watchPathIgnorePatterns: [], + + // Whether to use watchman for file crawling + // watchman: true, +}; + +export default config; diff --git a/test/REST/private.test.ts b/test/REST/private.test.ts new file mode 100644 index 0000000..8658430 --- /dev/null +++ b/test/REST/private.test.ts @@ -0,0 +1,28 @@ +import { RestClient } from '../../src/RestClient'; + +describe('REST PRIVATE', () => { + const account = { + key: process.env.API_KEY, + secret: process.env.API_SECRET, + }; + + const rest = new RestClient({ + apiKey: account.key, + apiSecret: account.secret, + }); + + it('should have credentials to test with', () => { + expect(account.key).toBeDefined(); + expect(account.secret).toBeDefined(); + }); + + describe('GET without auth', async () => { + // + + const res = await rest.getSpotTicker(); + console.log('res'); + expect(res).toMatchObject({ + true: true, + }); + }); +}); diff --git a/test/tsconfig.test.json b/test/tsconfig.test.json index c4bad3b..625f1d9 100644 --- a/test/tsconfig.test.json +++ b/test/tsconfig.test.json @@ -1,8 +1,9 @@ { "extends": "../tsconfig.json", "compilerOptions": { - "module": "commonjs", - "outDir": "dist/cjs", + "module": "CommonJS", + "baseUrl": "", + "outDir": "dist", "target": "esnext", "rootDir": "../" }, diff --git a/tsconfig.linting.json b/tsconfig.linting.json index 72ab1b2..c55e821 100644 --- a/tsconfig.linting.json +++ b/tsconfig.linting.json @@ -6,5 +6,11 @@ "target": "esnext", "rootDir": "../" }, - "include": ["src/**/*.*", "test/**/*.*", "examples/**/*.*", ".eslintrc.cjs"] + "include": [ + "src/**/*.*", + "test/**/*.*", + "examples/**/*.*", + ".eslintrc.cjs", + "jest.config.ts" + ] } From 440422d80442a7a35f03f954d79020d2000534fc Mon Sep 17 00:00:00 2001 From: Jerko J <83344666+JJ-Cro@users.noreply.github.com> Date: Mon, 20 May 2024 16:52:41 +0200 Subject: [PATCH 15/36] chore(): Refactoring types --- src/RestClient.ts | 308 ++++------------------------- src/types/requests/shared.types.ts | 46 +++++ src/types/response/shared.types.ts | 95 +++++++++ 3 files changed, 177 insertions(+), 272 deletions(-) diff --git a/src/RestClient.ts b/src/RestClient.ts index e6cd8c3..20576dc 100644 --- a/src/RestClient.ts +++ b/src/RestClient.ts @@ -1,4 +1,11 @@ import { AxiosRequestConfig } from 'axios'; + +import { + BaseRestClient, + REST_CLIENT_TYPE_ENUM, + RestClientType, +} from './lib/BaseRestClient.js'; +import { RestClientOptions } from './lib/requestUtils.js'; import { GetMainSubTransfersReq, GetSavedAddressReq, @@ -7,15 +14,10 @@ import { GetUnifiedLoanRecordsReq, GetUnifiedLoansReq, GetWithdrawalDepositRecordsReq, + PortfolioMarginCalculatorReq, + SetUnifiedAccountModeReq, SubmitUnifiedBorrowOrRepayReq, -} from 'types/requests/shared.types.js'; - -import { - BaseRestClient, - REST_CLIENT_TYPE_ENUM, - RestClientType, -} from './lib/BaseRestClient.js'; -import { RestClientOptions } from './lib/requestUtils.js'; +} from './types/requests/shared.types.js'; import { APIResponse, CreateDepositAddressResp, @@ -25,12 +27,17 @@ import { GetSavedAddressResp, GetSmallBalanceHistoryResp, GetSmallBalancesResp, + GetSpotCurrenciesResp, + GetSpotTickerResp, GetTradingFeesResp, GetUnifiedAccountInfoResp, + GetUnifiedCurrencyDiscountTiersResp, GetUnifiedInterestRecordsResp, GetUnifiedLoanRecordsResp, GetUnifiedLoansResp, + GetUnifiedRiskUnitDetailsResp, GetWithdrawalStatusResp, + PortfolioMarginCalculatorResp, SubAccountCrossMarginBalancesResp, SubAccountFuturesBalancesResp, SubAccountMarginBalancesResp, @@ -967,36 +974,10 @@ export class RestClient extends BaseRestClient { /** * Retrieve user risk unit details, only valid in portfolio margin mode * - * @returns Promise> + * @returns Promise> */ getUnifiedRiskUnitDetails(): Promise< - APIResponse<{ - 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; - }[]; - }> + APIResponse > { return this.getPrivate('/unified/risk_units'); } @@ -1009,13 +990,9 @@ export class RestClient extends BaseRestClient { * @param params Parameters for setting the mode of the unified account * @returns Promise> */ - setUnifiedAccountMode(body: { - mode: 'classic' | 'multi_currency' | 'portfolio'; - settings?: { - usdt_futures?: boolean; - spot_hedge?: boolean; - }; - }): Promise> { + setUnifiedAccountMode( + body: SetUnifiedAccountModeReq, + ): Promise> { return this.putPrivate('/unified/unified_mode', body); } @@ -1030,15 +1007,7 @@ export class RestClient extends BaseRestClient { * }; * }>> */ - getUnifiedAccountMode(): Promise< - APIResponse<{ - mode: 'classic' | 'multi_currency' | 'portfolio'; - settings: { - usdt_futures?: boolean; - spot_hedge?: boolean; - }; - }> - > { + getUnifiedAccountMode(): Promise> { return this.getPrivate('/unified/unified_mode'); } @@ -1059,28 +1028,10 @@ export class RestClient extends BaseRestClient { /** * List currency discount tiers * - * @returns Promise> + * @returns Promise> */ getUnifiedCurrencyDiscountTiers(): Promise< - APIResponse< - { - currency: string; - discount_tiers: { - tier: string; - discount: string; - lower_limit: string; - upper_limit: string; - }[]; - }[] - > + APIResponse > { return this.get('/unified/currency_discount_tiers'); } @@ -1091,107 +1042,11 @@ export class RestClient extends BaseRestClient { * Portfolio Margin Calculator When inputting a simulated position portfolio, each position includes the position name and quantity held, supporting markets within the range of BTC and ETH perpetual contracts, options, and spot markets. When inputting simulated orders, each order includes the market identifier, order price, and order quantity, supporting markets within the range of BTC and ETH perpetual contracts, options, and spot markets. Market orders are not included. * * @param params Parameters for portfolio margin calculator - * @returns Promise> + * @returns Promise> */ - portfolioMarginCalculator(body: { - 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; - }): Promise< - APIResponse<{ - 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; - }[]; - }[]; - }> - > { + portfolioMarginCalculator( + body: PortfolioMarginCalculatorReq, + ): Promise> { return this.post('/unified/portfolio_calculator', body); } @@ -1209,31 +1064,9 @@ export class RestClient extends BaseRestClient { * * The latter one occurs when one currency has multiple chains. Currency detail contains a chain field whatever the form is. To retrieve all chains of one currency, you can use all the details which have the name of the currency or name starting with _. * - * @returns Promise> + * @returns Promise> */ - getSpotCurrencies(): Promise< - APIResponse< - { - currency: string; - delisted: boolean; - withdraw_disabled: boolean; - withdraw_delayed: boolean; - deposit_disabled: boolean; - trade_disabled: boolean; - fixed_rate: string; - chain: string; - }[] - > - > { + getSpotCurrencies(): Promise> { return this.get('/spot/currencies'); } @@ -1252,37 +1085,16 @@ export class RestClient extends BaseRestClient { * chain: string; * }>> */ - getSpotCurrency(params: { currency: string }): Promise< - APIResponse<{ - currency: string; - delisted: boolean; - withdraw_disabled: boolean; - withdraw_delayed: boolean; - deposit_disabled: boolean; - trade_disabled: boolean; - fixed_rate: string; - chain: string; - }> - > { + getSpotCurrency(params: { + currency: string; + }): Promise> { return this.get(`/spot/currencies/${params.currency}`); } /** * List all currency pairs supported * - * @returns Promise> + * @returns Promise> */ getSpotCurrencyPairs(): Promise> { return this.get('/spot/currency_pairs'); @@ -1292,19 +1104,7 @@ export class RestClient extends BaseRestClient { * Get details of a specific currency pair * * @param params Parameters for retrieving details of a specific currency pair - * @returns Promise> + * @returns Promise> */ getSpotCurrencyPair(params: { currency_pair: string; @@ -1318,48 +1118,12 @@ export class RestClient extends BaseRestClient { * Return only related data if currency_pair is specified; otherwise return all of them. * * @param params Parameters for retrieving ticker information - * @returns Promise> + * @returns Promise> */ getSpotTicker(params?: { currency_pair?: string; timezone?: 'utc0' | 'utc8' | 'all'; - }): Promise< - APIResponse< - { - currency_pair: string; - last: string; - lowest_ask: string; - highest_bid: 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; - }[] - > - > { + }): Promise> { return this.get('/spot/tickers', params); } diff --git a/src/types/requests/shared.types.ts b/src/types/requests/shared.types.ts index 324820d..e10a0b4 100644 --- a/src/types/requests/shared.types.ts +++ b/src/types/requests/shared.types.ts @@ -54,3 +54,49 @@ export interface GetUnifiedInterestRecordsReq { limit?: number; type?: 'platform' | 'margin'; } + +export interface SetUnifiedAccountModeReq { + mode: 'classic' | 'multi_currency' | 'portfolio'; + settings?: { + usdt_futures?: boolean; + spot_hedge?: 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; +} + +/**========================================================================================================================== + * SPOT + * ========================================================================================================================== + */ diff --git a/src/types/response/shared.types.ts b/src/types/response/shared.types.ts index d6cb0e5..6d01d68 100644 --- a/src/types/response/shared.types.ts +++ b/src/types/response/shared.types.ts @@ -292,3 +292,98 @@ export interface GetUnifiedInterestRecordsResp { type: 'platform' | 'margin'; create_time: number; } + +export interface GetUnifiedRiskUnitDetailsResp { + 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 GetUnifiedCurrencyDiscountTiersResp { + currency: string; + discount_tiers: { + tier: string; + discount: string; + lower_limit: string; + upper_limit: string; + }[]; +} + +export interface PortfolioMarginCalculatorResp { + 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; + }[]; + }[]; +} + +/**========================================================================================================================== + * SPOT + * ========================================================================================================================== + */ + +export interface GetSpotCurrenciesResp { + currency: string; + delisted: boolean; + withdraw_disabled: boolean; + withdraw_delayed: boolean; + deposit_disabled: boolean; + trade_disabled: boolean; + fixed_rate: string; + chain: string; +} + +export interface GetSpotTickerResp { + currency_pair: string; + last: string; + lowest_ask: string; + highest_bid: 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; +} From 702a8c43125a18250a673bb38d07de8b47727813 Mon Sep 17 00:00:00 2001 From: Tiago Siebler Date: Mon, 20 May 2024 16:27:26 +0100 Subject: [PATCH 16/36] feat(): add auth tests --- jest.config.ts | 8 +++- test/REST/private.test.ts | 94 ++++++++++++++++++++++++++++++++++++--- 2 files changed, 94 insertions(+), 8 deletions(-) diff --git a/jest.config.ts b/jest.config.ts index c003b0e..eb2e820 100644 --- a/jest.config.ts +++ b/jest.config.ts @@ -53,6 +53,8 @@ const config: Config = { // Make calling deprecated APIs throw helpful error messages // errorOnDeprecated: false, + extensionsToTreatAsEsm: ['.ts'], + // The default configuration for fake timers // fakeTimers: { // "enableGlobally": false @@ -95,6 +97,9 @@ const config: Config = { // A map from regular expressions to module names or to arrays of module names that allow to stub out resources with a single module // moduleNameMapper: {}, + moduleNameMapper: { + '^(\\.{1,2}/.*)\\.js$': '$1', + }, // An array of regexp pattern strings, matched against all module paths before considered 'visible' to the module loader // modulePathIgnorePatterns: [], @@ -184,10 +189,11 @@ const config: Config = { // transform: undefined, transform: { - '^.+\\.(t|j)s$': [ + '^.+\\.m?[tj]sx?$': [ 'ts-jest', { tsconfig: 'test/tsconfig.test.json', + useESM: true, }, ], }, diff --git a/test/REST/private.test.ts b/test/REST/private.test.ts index 8658430..74e239d 100644 --- a/test/REST/private.test.ts +++ b/test/REST/private.test.ts @@ -1,4 +1,4 @@ -import { RestClient } from '../../src/RestClient'; +import { RestClient } from '../../src'; describe('REST PRIVATE', () => { const account = { @@ -16,13 +16,93 @@ describe('REST PRIVATE', () => { expect(account.secret).toBeDefined(); }); - describe('GET without auth', async () => { - // + describe('public endpoints', () => { + it('should succeed making a GET request', async () => { + const res = await rest.getSpotTicker(); + // console.log('res', res); + expect(res).toMatchObject(expect.any(Array)); + }); + }); + + describe('private endpoints', () => { + describe('GET requests', () => { + test('without params', async () => { + const res = await rest.getBalances(); + // console.log('res without', res); + expect(res).toMatchObject({ + details: expect.any(Object), + total: expect.any(Object), + }); + }); + + test('with params', async () => { + const res = await rest.getBalances({ currency: 'USDT' }); + // console.log('res with', res); + expect(res).toMatchObject({ + details: expect.any(Object), + total: expect.any(Object), + }); + }); + }); + + describe('POST requests', () => { + test('with params as query strings', async () => { + const res = await rest.updateAutoRepaymentSetting({ status: 'on' }); + // console.log('res "${expect.getState().currentTestName}"', res); + expect(res).toMatchObject({ + status: 'on', + }); + }); + + test('with params as request body', async () => { + try { + const res = await rest.getSubToSubTransfer({ + currency: 'BTC', + sub_account_from: 'notReal1', + sub_account_from_type: 'spot', + sub_account_to: 'notReal2', + sub_account_to_type: 'spot', + amount: '10000', + }); + console.log('res "${expect.getState().currentTestName}"', res); + expect(res).toMatchObject({ + whatever: true, + }); + } catch (e: any) { + const authSuccessMatchError = 'Invalid sub_account_from'; + if (e.body.message !== authSuccessMatchError) { + console.error( + `Request failed for test: "${expect.getState().currentTestName}"`, + e, + ); + } + expect(e.body.message).toStrictEqual(authSuccessMatchError); + } + }); - const res = await rest.getSpotTicker(); - console.log('res'); - expect(res).toMatchObject({ - true: true, + test('with params as query string AND request body', async () => { + try { + const res = await rest.updateFuturesLeverage({ + settle: 'usdt', + contract: 'BTC_USDT', + leverage: '1', + }); + console.log('res "${expect.getState().currentTestName}"', res); + expect(res).toMatchObject({ + whatever: true, + }); + } catch (e: any) { + const authSuccessMatchError = + 'please transfer funds first to create futures account'; + if (e.body.message !== authSuccessMatchError) { + console.error( + `Request failed for test: "${expect.getState().currentTestName}"`, + e, + ); + } + expect(e.body.message).toStrictEqual(authSuccessMatchError); + } + }); }); }); }); From a6dd846989787df5689681f4842071a2c94ff7f6 Mon Sep 17 00:00:00 2001 From: Tiago Siebler Date: Mon, 20 May 2024 16:36:12 +0100 Subject: [PATCH 17/36] feat(): add github ci + tests --- .github/FUNDING.yml | 12 ++++++++++ .github/workflow-settings.json | 16 +++++++++++++ .github/workflows/e2etest.yml | 42 ++++++++++++++++++++++++++++++++++ 3 files changed, 70 insertions(+) create mode 100644 .github/FUNDING.yml create mode 100644 .github/workflow-settings.json create mode 100644 .github/workflows/e2etest.yml diff --git a/.github/FUNDING.yml b/.github/FUNDING.yml new file mode 100644 index 0000000..43c383d --- /dev/null +++ b/.github/FUNDING.yml @@ -0,0 +1,12 @@ +# These are supported funding model platforms + +github: [tiagosiebler, JJ-Cro] # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2] +patreon: # Replace with a single Patreon username +open_collective: # Replace with a single Open Collective username +ko_fi: # Replace with a single Ko-fi username +tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel +community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry +liberapay: # Replace with a single Liberapay username +issuehunt: # Replace with a single IssueHunt username +otechie: # Replace with a single Otechie username +custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] diff --git a/.github/workflow-settings.json b/.github/workflow-settings.json new file mode 100644 index 0000000..24b1cdd --- /dev/null +++ b/.github/workflow-settings.json @@ -0,0 +1,16 @@ +{ + "EXCLUDE_MESSAGES": [ + "update package version", + "update packages", + "update wp version", + "trigger workflow", + "update TOC" + ], + "PROJECT": "Backlog", + "ISSUE_COLUMN": "To do", + "PR_COLUMN": "In progress", + "PR_BODY_TITLE": "## Changes", + "TOC_FOLDING": "1", + "TOC_MAX_HEADER_LEVEL": "3", + "TOC_TITLE": "Summary" +} \ No newline at end of file diff --git a/.github/workflows/e2etest.yml b/.github/workflows/e2etest.yml new file mode 100644 index 0000000..f1ce991 --- /dev/null +++ b/.github/workflows/e2etest.yml @@ -0,0 +1,42 @@ +name: 'Build & Test' + +on: [push] + +# on: +# # pull_request: +# # branches: +# # - "master" +# push: +# branches: + +jobs: + build: + name: 'Build & Test' + runs-on: ubuntu-latest + + steps: + - name: 'Checkout source code' + uses: actions/checkout@v4 + + - uses: actions/setup-node@v4 + with: + node-version-file: '.nvmrc' + registry-url: 'https://registry.npmjs.org/' + cache: 'npm' + + - name: Install + run: npm ci --ignore-scripts + + - name: Build + run: npm run build + + - name: Test + run: npm run test + env: + API_KEY: ${{ secrets.API_KEY }} + API_SECRET: ${{ secrets.API_SECRET }} + PROXY_ENABLED: ${{ secrets.PROXY_ENABLED }} + PROXY_HOST: ${{ secrets.PROXY_HOST }} + PROXY_PASS: ${{ secrets.PROXY_PASS }} + PROXY_PORT: ${{ secrets.PROXY_PORT }} + PROXY_USER: ${{ secrets.PROXY_USER }} From a88f59476377c4b2f55153d2a5df739088ddf19c Mon Sep 17 00:00:00 2001 From: Jerko J <83344666+JJ-Cro@users.noreply.github.com> Date: Mon, 20 May 2024 18:24:09 +0200 Subject: [PATCH 18/36] chore(): Refactoring types --- examples/rest-private.ts | 26 +- src/RestClient.ts | 1369 +++------------------------- src/types/requests/shared.types.ts | 127 +++ src/types/response/shared.types.ts | 196 ++++ src/types/shared.ts | 333 +++++++ 5 files changed, 794 insertions(+), 1257 deletions(-) diff --git a/examples/rest-private.ts b/examples/rest-private.ts index 34ef8af..7ef20a6 100644 --- a/examples/rest-private.ts +++ b/examples/rest-private.ts @@ -3,8 +3,10 @@ import { RestClient } from '../src'; async function start() { try { const account = { - key: process.env.API_KEY || 'apiKeyHere', - secret: process.env.API_SECRET || 'apiSecretHere', + key: process.env.API_KEY || '8b8eff02d6b6105d195e81684017a43d', + secret: + process.env.API_SECRET || + '545055d0b75c9c2f9234369990bac79e3df4d2c9cda852a8531be65d901f5719', }; console.log('using creds: ', account); @@ -13,13 +15,25 @@ async function start() { apiSecret: account.secret, }); - //const res1 = await rest.getBalances(); + /* const res1 = await rest.submitSpotOrder({ + currency_pair: 'BTC_USDT', + side: 'buy', + type: 'limit', + amount: '10', + time_in_force: 'gtc', + price: '1', + }); */ + + const res1 = await rest.updateAutoRepaymentSetting({ + status: 'on', + }); + /* const res2 = await rest.getIndexConstituents({ settle: 'usdt', index: 'BTC_USDT', }); */ - const res3 = await rest.portfolioMarginCalculator({ + /* const res3 = await rest.portfolioMarginCalculator({ spot_balances: [ { currency: 'BTC', @@ -61,14 +75,14 @@ async function start() { }, ], spot_hedge: false, - }); + }); */ /* const res4 = await rest.getDeliveryContract({ settle: 'usdt', contract: 'BTC_USDT', }); */ // const res1 = await rest.getSystemMaintenanceStatus(); - console.log('res: ', JSON.stringify(res3, null, 2)); + console.log('res: ', JSON.stringify(res1, null, 2)); } catch (e) { console.error(`Error in execution: `, e); } diff --git a/src/RestClient.ts b/src/RestClient.ts index 42100a2..4df9429 100644 --- a/src/RestClient.ts +++ b/src/RestClient.ts @@ -1,3 +1,7 @@ +// double check if schemas are requests +// double check if names are set to what the call represents(get, delete, update etc...) +// check where query params and body is as it should be + import { AxiosRequestConfig } from 'axios'; import { @@ -7,28 +11,52 @@ import { } from './lib/BaseRestClient.js'; import { RestClientOptions } from './lib/requestUtils.js'; import { + DeleteSpotOrderReq, GetMainSubTransfersReq, + GetMarginBalanceHistoryReq, GetSavedAddressReq, GetSmallBalanceHistoryReq, + GetSpotAccountBookReq, + GetSpotAutoOrdersReq, + GetSpotCandlesticksReq, + GetSpotOrderBookReq, + GetSpotOrdersReq, + GetSpotTradesReq, + GetSpotTradingHistoryReq, GetUnifiedInterestRecordsReq, GetUnifiedLoanRecordsReq, GetUnifiedLoansReq, GetWithdrawalDepositRecordsReq, PortfolioMarginCalculatorReq, SetUnifiedAccountModeReq, + SubmitSpotClosePosCrossDisabledReq, + SubmitSpotOrderReq, SubmitUnifiedBorrowOrRepayReq, + UpdateSpotBatchOrdersReq, } from './types/requests/shared.types.js'; import { APIResponse, CreateDepositAddressResp, CreateSubAccountApiKeyResp, + DeleteSpotBatchOrdersResp, GetBalancesResp, GetCurrencyChainsResp, + GetMarginAccountsResp, + GetMarginBalanceHistoryResp, GetSavedAddressResp, GetSmallBalanceHistoryResp, GetSmallBalancesResp, + GetSpotAccountBookResp, + GetSpotAccountsResp, + GetSpotBatchFeeRatesResp, + GetSpotCandlesticksResp, GetSpotCurrenciesResp, + GetSpotFeeRatesResp, + GetSpotOpenOrdersResp, + GetSpotOrderBookResp, GetSpotTickerResp, + GetSpotTradesResp, + GetSpotTradingHistoryResp, GetTradingFeesResp, GetUnifiedAccountInfoResp, GetUnifiedCurrencyDiscountTiersResp, @@ -43,340 +71,22 @@ import { SubAccountMarginBalancesResp, SubAccountResp, SubAccountTransferRecordResp, + SubmitSpotBatchOrdersResp, } from './types/response/shared.types.js'; +import { + CancelBatchOrder, + Contract, + CurrencyPair, + DeliveryContract, + FuturesOrder, + FuturesPriceTriggeredOrder, + Order, + Position, + SpotPriceTriggeredOrder, + SubAccountKey, + Withdraw, +} from './types/shared.js'; -// interfaces - -interface SubAccountKey { - user_id?: string; - mode?: number; - name?: string; - perms?: { - name?: - | 'wallet' - | 'spot' - | 'futures' - | 'delivery' - | 'earn' - | 'options' - | 'account' - | 'unified' - | 'loan'; - read_only?: boolean; - }[]; - ip_whitelist?: string[]; - key?: string; - state?: number; - created_at?: number; - updated_at?: number; - last_access?: number; -} - -interface CurrencyPair { - id?: string; - base?: string; - quote?: string; - 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; -} - -interface Order { - 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' | '-'; - finish_as?: 'open' | 'filled' | 'cancelled' | 'ioc' | 'stp'; - action_mode?: 'ACK' | 'RESULT' | 'FULL'; -} - -interface CancelBatchOrder { - currency_pair: string; - id: string; - account?: 'cross_margin'; - action_mode?: 'ACK' | 'RESULT' | 'FULL'; -} - -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; -} - -interface Contract { - name?: string; - type?: 'inverse' | 'direct'; - quanto_multiplier?: string; - leverage_min?: string; - leverage_max?: string; - maintenance_rate?: string; - mark_type?: 'internal' | 'index'; - mark_price?: string; - index_price?: string; - last_price?: string; - maker_fee_rate?: string; - taker_fee_rate?: string; - order_price_round?: string; - mark_price_round?: string; - funding_rate?: string; - funding_interval?: number; - funding_next_apply?: number; - risk_limit_base?: string; - risk_limit_step?: string; - risk_limit_max?: string; - order_size_min?: number; - order_size_max?: number; - order_price_deviate?: string; - ref_discount_rate?: string; - ref_rebate_rate?: string; - orderbook_id?: number; - trade_id?: number; - trade_size?: number; - position_size?: number; - config_change_time?: number; - in_delisting?: boolean; - orders_limit?: number; - enable_bonus?: boolean; - enable_credit?: boolean; - create_time?: number; - funding_cap_ratio?: string; -} - -interface Position { - user?: number; - contract?: string; - size?: number; - leverage?: string; - risk_limit?: string; - leverage_max?: string; - maintenance_rate?: string; - value?: string; - margin?: string; - entry_price?: string; - liq_price?: string; - mark_price?: string; - initial_margin?: string; - maintenance_margin?: string; - unrealised_pnl?: string; - realised_pnl?: string; - pnl_pnl?: string; - pnl_fund?: string; - pnl_fee?: string; - history_pnl?: string; - last_close_pnl?: string; - realised_point?: string; - history_point?: string; - adl_ranking?: number; - pending_orders?: number; - close_order?: { - id?: number; - price?: string; - is_liq?: boolean; - } | null; - mode?: 'single' | 'dual_long' | 'dual_short'; - cross_leverage_limit?: string; - update_time?: number; - open_time?: number; -} - -interface FuturesOrder { - id?: number; - user?: number; - create_time?: number; - finish_time?: number; - finish_as?: - | 'filled' - | 'cancelled' - | 'liquidated' - | 'ioc' - | 'auto_deleveraged' - | 'reduce_only' - | 'position_closed' - | 'stp'; - status?: 'open' | 'finished'; - contract: string; - size: number; - iceberg?: number; - price?: string; - close?: boolean; - is_close?: boolean; - reduce_only?: boolean; - is_reduce_only?: boolean; - is_liq?: boolean; - tif?: 'gtc' | 'ioc' | 'poc' | 'fok'; - left?: number; - fill_price?: string; - text?: string; - tkfr?: string; - mkfr?: string; - refu?: number; - auto_size?: 'close_long' | 'close_short'; - stp_id?: number; - stp_act?: 'cn' | 'co' | 'cb' | '-'; - amend_text?: string; - biz_info?: string; -} - -interface FuturesPriceTriggeredOrder { - initial: { - contract: string; - size?: number; - price?: string; - close?: boolean; - tif?: 'gtc' | 'ioc'; - text?: string; - reduce_only?: boolean; - auto_size?: string; - is_reduce_only?: boolean; - is_close?: boolean; - }; - trigger: { - strategy_type?: 0 | 1; - price_type?: 0 | 1 | 2; - price?: string; - rule?: 1 | 2; - expiration?: number; - }; - id?: number; - user?: number; - create_time?: number; - finish_time?: number; - trade_id?: number; - status?: 'open' | 'finished' | 'inactive' | 'invalid'; - finish_as?: 'cancelled' | 'succeeded' | 'failed' | 'expired'; - reason?: string; - order_type?: - | 'close-long-order' - | 'close-short-order' - | 'close-long-position' - | 'close-short-position' - | 'plan-close-long-position' - | 'plan-close-short-position'; - me_order_id?: number; -} - -interface DeliveryContract { - name?: string; - underlying?: string; - cycle?: 'WEEKLY' | 'BI-WEEKLY' | 'QUARTERLY' | 'BI-QUARTERLY'; - type?: 'inverse' | 'direct'; - quanto_multiplier?: string; - leverage_min?: string; - leverage_max?: string; - maintenance_rate?: string; - mark_type?: 'internal' | 'index'; - mark_price?: string; - index_price?: string; - last_price?: string; - maker_fee_rate?: string; - taker_fee_rate?: string; - order_price_round?: string; - mark_price_round?: string; - basis_rate?: string; - basis_value?: string; - basis_impact_value?: string; - settle_price?: string; - settle_price_interval?: number; - settle_price_duration?: number; - expire_time?: number; - risk_limit_base?: string; - risk_limit_step?: string; - risk_limit_max?: string; - order_size_min?: number; - order_size_max?: number; - order_price_deviate?: string; - ref_discount_rate?: string; - ref_rebate_rate?: string; - orderbook_id?: number; - trade_id?: number; - trade_size?: number; - position_size?: number; - config_change_time?: number; - in_delisting?: boolean; - orders_limit?: number; -} - -interface Withdraw { - id: string; - txid: string; - withdraw_order_id: string; - timestamp: string; - amount: string; - currency: string; - address: string; - memo?: string; - status: - | 'DONE' - | 'CANCEL' - | 'REQUEST' - | 'MANUAL' - | 'BCODE' - | 'EXTPEND' - | 'FAIL' - | 'INVALID' - | 'VERIFY' - | 'PROCES' - | 'PEND' - | 'DMOVE' - | 'SPLITPEND'; - chain: string; -} /** * Unified REST API client for all of Gate's REST APIs */ @@ -563,7 +273,7 @@ export class RestClient extends BaseRestClient { * @param params Transfer parameters * @returns Promise> */ - getSubToSubTransfer(body: { + submitSubToSubTransfer(body: { currency: string; sub_account_type?: string; sub_account_from: string; @@ -1133,28 +843,11 @@ export class RestClient extends BaseRestClient { * Order book will be sorted by price from high to low on bids; low to high on asks. * * @param params Parameters for retrieving order book - * @returns Promise> + * @returns Promise> */ - getSpotOrderBook(params: { - currency_pair: string; - interval?: string; - limit?: number; - with_id?: boolean; - }): Promise< - APIResponse<{ - id?: number; - current: number; - update: number; - asks: [string, string][]; - bids: [string, string][]; - }> - > { + getSpotOrderBook( + params: GetSpotOrderBookReq, + ): Promise> { return this.get('/spot/order_book', params); } @@ -1165,55 +858,11 @@ export class RestClient extends BaseRestClient { * Scrolling query using last_id is not recommended any more. If last_id is specified, time range query parameters will be ignored. * * @param params Parameters for retrieving market trades - * @returns Promise> + * @returns Promise> */ - getSpotTrades(params: { - currency_pair: string; - limit?: number; - last_id?: string; - reverse?: boolean; - from?: number; - to?: number; - page?: number; - }): Promise< - APIResponse< - { - 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; - }[] - > - > { + getSpotTrades( + params: GetSpotTradesReq, + ): Promise> { return this.get('/spot/trades', params); } @@ -1223,50 +872,11 @@ export class RestClient extends BaseRestClient { * Maximum of 1000 points can be returned in a query. Be sure not to exceed the limit when specifying from, to and interval. * * @param params Parameters for retrieving market candlesticks - * @returns Promise> - */ - getSpotCandlesticks(params: { - currency_pair: string; - limit?: number; - from?: number; - to?: number; - interval?: - | '10s' - | '1m' - | '5m' - | '15m' - | '30m' - | '1h' - | '4h' - | '8h' - | '1d' - | '7d' - | '30d'; - }): Promise< - APIResponse< - [ - [ - 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 - ], - ] - > - > { + * @returns Promise> + */ + getSpotCandlesticks( + params: GetSpotCandlesticksReq, + ): Promise> { return this.get('/spot/candlesticks', params); } @@ -1276,33 +886,11 @@ export class RestClient extends BaseRestClient { * This API is deprecated in favour of new fee retrieving API /wallet/fee. * * @param params Parameters for querying user trading fee rates - * @returns Promise> + * @returns Promise> */ - getSpotFeeRates(params?: { currency_pair?: string }): Promise< - APIResponse<{ - 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; - currency_pair: string; - debit_fee: number; - }> - > { + getSpotFeeRates(params?: { + currency_pair?: string; + }): Promise> { return this.getPrivate('/spot/fee', params); } @@ -1310,37 +898,11 @@ export class RestClient extends BaseRestClient { * Query a batch of user trading fee rates * * @param params Parameters for querying a batch of user trading fee rates - * @returns Promise> + * @returns Promise> */ - getSpotBatchFeeRates(params: { currency_pairs: string }): Promise< - APIResponse<{ - [key: string]: { - 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; - currency_pair: string; - debit_fee: number; - }; - }> - > { + getSpotBatchFeeRates(params: { + currency_pairs: string; + }): Promise> { return this.getPrivate('/spot/batch_fee', params); } @@ -1348,23 +910,11 @@ export class RestClient extends BaseRestClient { * List spot accounts * * @param params Parameters for listing spot accounts - * @returns Promise> + * @returns Promise> */ - getSpotAccounts(params?: { currency?: string }): Promise< - APIResponse< - { - currency: string; - available: string; - locked: string; - update_id: number; - }[] - > - > { + getSpotAccounts(params?: { + currency?: string; + }): Promise> { return this.getPrivate('/spot/accounts', params); } @@ -1374,36 +924,11 @@ export class RestClient extends BaseRestClient { * Record time range cannot exceed 30 days. * * @param params Parameters for querying account book - * @returns Promise> + * @returns Promise> */ - getSpotAccountBook(params?: { - currency?: string; - from?: number; - to?: number; - page?: number; - limit?: number; - type?: string; - }): Promise< - APIResponse< - { - id: string; - time: number; - currency: string; - change: string; - balance: string; - type: string; - text: string; - }[] - > - > { + getSpotAccountBook( + params?: GetSpotAccountBookReq, + ): Promise> { return this.getPrivate('/spot/account_book', params); } @@ -1416,87 +941,11 @@ export class RestClient extends BaseRestClient { * - No mixture of spot orders and margin orders, i.e. account must be identical for all orders * * @param params Parameters for creating a batch of orders - * @returns Promise> + * @returns Promise> */ - submitSpotBatchOrders(body: Order[]): Promise< - APIResponse< - { - 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' | '-'; - finish_as: 'open' | 'filled' | 'cancelled' | 'ioc' | 'stp'; - }[] - > - > { + submitSpotBatchOrders( + body: Order[], + ): Promise> { return this.postPrivate('/spot/batch_orders', body); } @@ -1508,95 +957,13 @@ export class RestClient extends BaseRestClient { * Spot, portfolio, and margin orders are returned by default. To list cross margin orders, account must be set to cross_margin. * * @param params Parameters for listing all open orders - * @returns Promise> + * @returns Promise> */ getSpotOpenOrders(params?: { page?: number; limit?: number; account?: 'spot' | 'margin' | 'cross_margin' | 'unified'; - }): Promise< - APIResponse< - { - currency_pair: string; - total: number; - orders: { - 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_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' | '-'; - finish_as: 'open' | 'filled' | 'cancelled' | 'ioc' | 'stp'; - }[]; - }[] - > - > { + }): Promise> { return this.getPrivate('/spot/open_orders', params); } @@ -1606,22 +973,11 @@ export class RestClient extends BaseRestClient { * Currently, only cross-margin accounts are supported to close position when cross currencies are disabled. Maximum buy quantity = (unpaid principal and interest - currency balance - the amount of the currency in the order book) / 0.998 * * @param params Parameters for closing position when cross-currency is disabled - * @returns Promise> + * @returns Promise> */ - submitSpotClosePosCrossDisabled(body: { - text?: string; - currency_pair: string; - amount: string; - price: string; - action_mode?: 'ACK' | 'RESULT' | 'FULL'; - }): Promise> { + submitSpotClosePosCrossDisabled( + body: SubmitSpotClosePosCrossDisabledReq, + ): Promise> { return this.postPrivate('/spot/cross_liquidate_orders', body); } @@ -1631,24 +987,9 @@ export class RestClient extends BaseRestClient { * You can place orders with spot, portfolio, margin or cross margin account through setting the account field. It defaults to spot, which means spot account is used to place orders. If the user is using unified account, it defaults to the unified account. * * @param params Parameters for creating an order - * @returns Promise> + * @returns Promise> */ - submitSpotOrder(body: Order): Promise> { + submitSpotOrder(body: SubmitSpotOrderReq): Promise> { return this.postPrivate('/spot/orders', body); } @@ -1658,53 +999,9 @@ export class RestClient extends BaseRestClient { * Spot, portfolio and margin orders are returned by default. If cross margin orders are needed, account must be set to cross_margin. * * @param params Parameters for listing orders - * @returns Promise> + * @returns Promise> */ - getSpotOrders(params: { - currency_pair: string; - status: 'open' | 'finished'; - page?: number; - limit?: number; - account?: 'spot' | 'margin' | 'cross_margin' | 'unified'; - from?: number; - to?: number; - side?: 'buy' | 'sell'; - }): Promise> { + getSpotOrders(params: GetSpotOrdersReq): Promise> { return this.getPrivate('/spot/orders', params); } @@ -1715,42 +1012,7 @@ export class RestClient extends BaseRestClient { * You can set account to cancel only orders within the specified account. * * @param params Parameters for cancelling all open orders in specified currency pair - * @returns Promise> + * @returns Promise> */ deleteSpotPairOpenOrders(params: { currency_pair: string; @@ -1767,27 +1029,11 @@ export class RestClient extends BaseRestClient { * Multiple currency pairs can be specified, but maximum 20 orders are allowed per request. * * @param params Parameters for cancelling a batch of orders - * @returns Promise> + * @returns Promise> */ - deleteSpotBatchOrders(body: CancelBatchOrder[]): Promise< - APIResponse< - { - currency_pair: string; - id: string; - succeeded: boolean; - label: string; - message: string; - account: string; - }[] - > - > { + deleteSpotBatchOrders( + body: CancelBatchOrder[], + ): Promise> { return this.postPrivate('/spot/cancel_batch_orders', body); } @@ -1797,42 +1043,7 @@ export class RestClient extends BaseRestClient { * Spot, portfolio and margin orders are queried by default. If cross margin orders are needed or portfolio margin account are used, account must be set to cross_margin. * * @param params Parameters for getting a single order - * @returns Promise> + * @returns Promise> */ getSpotOrder(params: { order_id: string; @@ -1850,42 +1061,7 @@ export class RestClient extends BaseRestClient { * Currently, only supports modification of price or amount fields. * * @param params Parameters for amending an order - * @returns Promise> + * @returns Promise> */ updateSpotOrder( params: { @@ -1909,49 +1085,9 @@ export class RestClient extends BaseRestClient { * Spot, portfolio and margin orders are cancelled by default. If trying to cancel cross margin orders or portfolio margin account are used, account must be set to cross_margin. * * @param params Parameters for cancelling a single order - * @returns Promise> + * @returns Promise> */ - deleteSpotOrder(params: { - order_id: string; - currency_pair: string; - account?: 'spot' | 'margin' | 'cross_margin' | 'unified'; - action_mode?: 'ACK' | 'RESULT' | 'FULL'; - }): Promise> { + deleteSpotOrder(params: DeleteSpotOrderReq): Promise> { return this.deletePrivate(`/spot/orders/${params.order_id}`, params); } @@ -1963,55 +1099,11 @@ export class RestClient extends BaseRestClient { * You can also set from and/or to to query by time range. If you don't specify from and/or to parameters, only the last 7 days of data will be returned. The range of from and to is not allowed to exceed 30 days. Time range parameters are handled as order finish time. * * @param params Parameters for listing personal trading history - * @returns Promise> + * @returns Promise> */ - getSpotTradingHistory(params?: { - currency_pair?: string; - limit?: number; - page?: number; - order_id?: string; - account?: 'spot' | 'margin' | 'cross_margin' | 'unified'; - from?: number; - to?: number; - }): Promise< - APIResponse< - { - 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; - }[] - > - > { + getSpotTradingHistory( + params?: GetSpotTradingHistoryReq, + ): Promise> { return this.getPrivate('/spot/my_trades', params); } @@ -2057,95 +1149,11 @@ export class RestClient extends BaseRestClient { * Default modification of orders for spot, portfolio, and margin accounts. To modify orders for a cross margin account, the account parameter must be specified as cross_margin. For portfolio margin accounts, the account parameter can only be specified as cross_margin. Currently, only modifications to price or quantity (choose one) are supported. * * @param params Parameters for batch modification of orders - * @returns Promise> + * @returns Promise> */ updateSpotBatchOrders( - body: { - order_id?: string; - currency_pair?: string; - amount?: string; - price?: string; - amend_text?: string; - }[], - ): Promise< - APIResponse< - { - 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' | '-'; - finish_as: 'open' | 'filled' | 'cancelled' | 'ioc' | 'stp'; - }[] - > - > { + body: UpdateSpotBatchOrdersReq[], + ): Promise> { return this.postPrivate('/spot/amend_batch_orders', body); } @@ -2169,58 +1177,19 @@ export class RestClient extends BaseRestClient { * Retrieve running auto order list * * @param params Parameters for retrieving running auto order list - * @returns Promise=' | '<='; - * 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; - * }; - * market: string; - * status: 'open' | 'finished'; - * }[]>> + * @returns Promise> */ - getSpotAutoOrders(params: { - status: 'open' | 'finished'; - market?: string; - account?: 'normal' | 'margin' | 'cross_margin'; - limit?: number; - offset?: number; - }): Promise> { + getSpotAutoOrders( + params: GetSpotAutoOrdersReq, + ): Promise> { return this.getPrivate('/spot/price_orders', params); } + /** * Cancel all open orders * * @param params Parameters for cancelling all open orders - * @returns Promise=' | '<='; - * 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; - * }; - * market: string; - * status: 'open' | 'finished'; - * }[]>> + * @returns Promise> */ deleteSpotAllOpenOrders(params?: { market?: string; @@ -2233,25 +1202,7 @@ export class RestClient extends BaseRestClient { * Get a price-triggered order * * @param params Parameters for getting a price-triggered order - * @returns Promise=' | '<='; - * 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; - * }; - * market: string; - * status: 'open' | 'finished'; - * }>> + * @returns Promise> */ getPriceTriggeredOrder(params: { order_id: string; @@ -2263,25 +1214,7 @@ export class RestClient extends BaseRestClient { * Cancel a price-triggered order * * @param params Parameters for cancelling a price-triggered order - * @returns Promise=' | '<='; - * 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; - * }; - * market: string; - * status: 'open' | 'finished'; - * }>> + * @returns Promise> */ deleteSpotPriceTriggeredOrder(params: { order_id: string; @@ -2298,49 +1231,11 @@ export class RestClient extends BaseRestClient { * Margin account list * * @param params Parameters for listing margin accounts - * @returns Promise> + * @returns Promise> */ - getMarginAccounts(params?: { currency_pair?: string }): Promise< - APIResponse< - { - 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; - }; - }[] - > - > { + getMarginAccounts(params?: { + currency_pair?: string; + }): Promise> { return this.getPrivate('/margin/accounts', params); } @@ -2350,39 +1245,11 @@ export class RestClient extends BaseRestClient { * Only transferals from and to margin account are provided for now. Time range allows 30 days at most. * * @param params Parameters for listing margin account balance change history - * @returns Promise> + * @returns Promise> */ - getMarginBalanceHistory(params?: { - currency?: string; - currency_pair?: string; - type?: string; - from?: number; - to?: number; - page?: number; - limit?: number; - }): Promise< - APIResponse< - { - id: string; - time: string; - time_ms: number; - currency: string; - currency_pair: string; - change: string; - balance: string; - type: string; - }[] - > - > { + getMarginBalanceHistory( + params?: GetMarginBalanceHistoryReq, + ): Promise> { return this.getPrivate('/margin/account_book', params); } diff --git a/src/types/requests/shared.types.ts b/src/types/requests/shared.types.ts index e10a0b4..44a8137 100644 --- a/src/types/requests/shared.types.ts +++ b/src/types/requests/shared.types.ts @@ -100,3 +100,130 @@ export interface PortfolioMarginCalculatorReq { * SPOT * ========================================================================================================================== */ + +export interface GetSpotOrderBookReq { + currency_pair: string; + interval?: string; + limit?: number; + with_id?: boolean; +} + +export interface GetSpotTradesReq { + currency_pair: string; + limit?: number; + last_id?: string; + reverse?: boolean; + from?: number; + to?: number; + page?: number; +} + +export interface GetSpotCandlesticksReq { + currency_pair: string; + limit?: number; + from?: number; + to?: number; + interval?: + | '10s' + | '1m' + | '5m' + | '15m' + | '30m' + | '1h' + | '4h' + | '8h' + | '1d' + | '7d' + | '30d'; +} + +export interface GetSpotAccountBookReq { + currency?: string; + from?: number; + to?: number; + page?: number; + limit?: number; + type?: string; +} + +export interface SubmitSpotClosePosCrossDisabledReq { + text?: string; + currency_pair: string; + amount: string; + price: string; + action_mode?: 'ACK' | 'RESULT' | 'FULL'; +} + +export interface GetSpotOrdersReq { + currency_pair: string; + status: 'open' | 'finished'; + page?: number; + limit?: number; + account?: 'spot' | 'margin' | 'cross_margin' | 'unified'; + from?: number; + to?: number; + side?: 'buy' | 'sell'; +} + +export interface DeleteSpotOrderReq { + order_id: string; + currency_pair: string; + account?: 'spot' | 'margin' | 'cross_margin' | 'unified'; + action_mode?: 'ACK' | 'RESULT' | 'FULL'; +} + +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 UpdateSpotBatchOrdersReq { + order_id?: string; + currency_pair?: string; + amount?: string; + price?: string; + amend_text?: string; +} + +export interface GetSpotAutoOrdersReq { + status: 'open' | 'finished'; + market?: string; + account?: 'normal' | 'margin' | 'cross_margin'; + limit?: number; + offset?: number; +} + +export interface SubmitSpotOrderReq { + 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; +} +/**========================================================================================================================== + * MARGIN + * ========================================================================================================================== + */ + +export interface GetMarginBalanceHistoryReq { + currency?: string; + currency_pair?: string; + type?: string; + from?: number; + to?: number; + page?: number; + limit?: number; +} diff --git a/src/types/response/shared.types.ts b/src/types/response/shared.types.ts index 6d01d68..a45d372 100644 --- a/src/types/response/shared.types.ts +++ b/src/types/response/shared.types.ts @@ -1,3 +1,5 @@ +import { Order } from '../shared'; + export interface APIResponse { success: boolean; data: TData; @@ -387,3 +389,197 @@ export interface GetSpotTickerResp { etf_pre_timestamp: number | null; etf_leverage: string | null; } + +export interface GetSpotOrderBookResp { + id?: number; + current: number; + update: number; + asks: [string, string][]; + bids: [string, string][]; +} + +export interface GetSpotTradesResp { + 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; +} + +export type GetSpotCandlesticksResp = [ + [ + 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 GetSpotFeeRatesResp { + 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; + currency_pair: string; + debit_fee: number; +} + +export interface GetSpotBatchFeeRatesResp { + [key: string]: { + 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; + currency_pair: string; + debit_fee: number; + }; +} + +export interface GetSpotAccountsResp { + currency: string; + available: string; + locked: string; + update_id: number; +} + +export interface GetSpotAccountBookResp { + id: string; + time: number; + currency: string; + change: string; + balance: string; + type: string; + text: 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' | '-'; + finish_as: 'open' | 'filled' | 'cancelled' | 'ioc' | 'stp'; +} + +export interface GetSpotOpenOrdersResp { + currency_pair: string; + total: number; + orders: Order[]; +} + +export interface DeleteSpotBatchOrdersResp { + currency_pair: string; + id: string; + succeeded: boolean; + label: string; + message: string; + account: string; +} + +export interface GetSpotTradingHistoryResp { + 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; +} + +/**========================================================================================================================== + * MARGIN + * ========================================================================================================================== + */ + +export interface GetMarginAccountsResp { + 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 GetMarginBalanceHistoryResp { + id: string; + time: string; + time_ms: number; + currency: string; + currency_pair: string; + change: string; + balance: string; + type: string; +} diff --git a/src/types/shared.ts b/src/types/shared.ts index 13bbbd0..870e392 100644 --- a/src/types/shared.ts +++ b/src/types/shared.ts @@ -2,3 +2,336 @@ export type GateBaseUrlKey = | 'live' | 'futuresLiveAlternative' | 'futuresTestnet'; + +// interfaces + +export interface SubAccountKey { + user_id?: string; + mode?: number; + name?: string; + perms?: { + name?: + | 'wallet' + | 'spot' + | 'futures' + | 'delivery' + | 'earn' + | 'options' + | 'account' + | 'unified' + | 'loan'; + read_only?: boolean; + }[]; + ip_whitelist?: string[]; + key?: string; + state?: number; + created_at?: number; + updated_at?: number; + last_access?: number; +} + +export interface CurrencyPair { + id?: string; + base?: string; + quote?: string; + 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; +} + +export interface Order { + 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' | '-'; + finish_as?: 'open' | 'filled' | 'cancelled' | 'ioc' | 'stp'; + action_mode?: 'ACK' | 'RESULT' | 'FULL'; +} + +export interface CancelBatchOrder { + currency_pair: string; + id: string; + account?: 'cross_margin'; + action_mode?: 'ACK' | 'RESULT' | 'FULL'; +} + +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 Contract { + name?: string; + type?: 'inverse' | 'direct'; + quanto_multiplier?: string; + leverage_min?: string; + leverage_max?: string; + maintenance_rate?: string; + mark_type?: 'internal' | 'index'; + mark_price?: string; + index_price?: string; + last_price?: string; + maker_fee_rate?: string; + taker_fee_rate?: string; + order_price_round?: string; + mark_price_round?: string; + funding_rate?: string; + funding_interval?: number; + funding_next_apply?: number; + risk_limit_base?: string; + risk_limit_step?: string; + risk_limit_max?: string; + order_size_min?: number; + order_size_max?: number; + order_price_deviate?: string; + ref_discount_rate?: string; + ref_rebate_rate?: string; + orderbook_id?: number; + trade_id?: number; + trade_size?: number; + position_size?: number; + config_change_time?: number; + in_delisting?: boolean; + orders_limit?: number; + enable_bonus?: boolean; + enable_credit?: boolean; + create_time?: number; + funding_cap_ratio?: string; +} + +export interface Position { + user?: number; + contract?: string; + size?: number; + leverage?: string; + risk_limit?: string; + leverage_max?: string; + maintenance_rate?: string; + value?: string; + margin?: string; + entry_price?: string; + liq_price?: string; + mark_price?: string; + initial_margin?: string; + maintenance_margin?: string; + unrealised_pnl?: string; + realised_pnl?: string; + pnl_pnl?: string; + pnl_fund?: string; + pnl_fee?: string; + history_pnl?: string; + last_close_pnl?: string; + realised_point?: string; + history_point?: string; + adl_ranking?: number; + pending_orders?: number; + close_order?: { + id?: number; + price?: string; + is_liq?: boolean; + } | null; + mode?: 'single' | 'dual_long' | 'dual_short'; + cross_leverage_limit?: string; + update_time?: number; + open_time?: number; +} + +export interface FuturesOrder { + id?: number; + user?: number; + create_time?: number; + finish_time?: number; + finish_as?: + | 'filled' + | 'cancelled' + | 'liquidated' + | 'ioc' + | 'auto_deleveraged' + | 'reduce_only' + | 'position_closed' + | 'stp'; + status?: 'open' | 'finished'; + contract: string; + size: number; + iceberg?: number; + price?: string; + close?: boolean; + is_close?: boolean; + reduce_only?: boolean; + is_reduce_only?: boolean; + is_liq?: boolean; + tif?: 'gtc' | 'ioc' | 'poc' | 'fok'; + left?: number; + fill_price?: string; + text?: string; + tkfr?: string; + mkfr?: string; + refu?: number; + auto_size?: 'close_long' | 'close_short'; + stp_id?: number; + stp_act?: 'cn' | 'co' | 'cb' | '-'; + amend_text?: string; + biz_info?: string; +} + +export interface FuturesPriceTriggeredOrder { + initial: { + contract: string; + size?: number; + price?: string; + close?: boolean; + tif?: 'gtc' | 'ioc'; + text?: string; + reduce_only?: boolean; + auto_size?: string; + is_reduce_only?: boolean; + is_close?: boolean; + }; + trigger: { + strategy_type?: 0 | 1; + price_type?: 0 | 1 | 2; + price?: string; + rule?: 1 | 2; + expiration?: number; + }; + id?: number; + user?: number; + create_time?: number; + finish_time?: number; + trade_id?: number; + status?: 'open' | 'finished' | 'inactive' | 'invalid'; + finish_as?: 'cancelled' | 'succeeded' | 'failed' | 'expired'; + reason?: string; + order_type?: + | 'close-long-order' + | 'close-short-order' + | 'close-long-position' + | 'close-short-position' + | 'plan-close-long-position' + | 'plan-close-short-position'; + me_order_id?: number; +} + +export interface DeliveryContract { + name?: string; + underlying?: string; + cycle?: 'WEEKLY' | 'BI-WEEKLY' | 'QUARTERLY' | 'BI-QUARTERLY'; + type?: 'inverse' | 'direct'; + quanto_multiplier?: string; + leverage_min?: string; + leverage_max?: string; + maintenance_rate?: string; + mark_type?: 'internal' | 'index'; + mark_price?: string; + index_price?: string; + last_price?: string; + maker_fee_rate?: string; + taker_fee_rate?: string; + order_price_round?: string; + mark_price_round?: string; + basis_rate?: string; + basis_value?: string; + basis_impact_value?: string; + settle_price?: string; + settle_price_interval?: number; + settle_price_duration?: number; + expire_time?: number; + risk_limit_base?: string; + risk_limit_step?: string; + risk_limit_max?: string; + order_size_min?: number; + order_size_max?: number; + order_price_deviate?: string; + ref_discount_rate?: string; + ref_rebate_rate?: string; + orderbook_id?: number; + trade_id?: number; + trade_size?: number; + position_size?: number; + config_change_time?: number; + in_delisting?: boolean; + orders_limit?: number; +} + +export interface Withdraw { + id: string; + txid: string; + withdraw_order_id: string; + timestamp: string; + amount: string; + currency: string; + address: string; + memo?: string; + status: + | 'DONE' + | 'CANCEL' + | 'REQUEST' + | 'MANUAL' + | 'BCODE' + | 'EXTPEND' + | 'FAIL' + | 'INVALID' + | 'VERIFY' + | 'PROCES' + | 'PEND' + | 'DMOVE' + | 'SPLITPEND'; + chain: string; +} From 93c43326206621ea5b45b6a1556326c41a01520e Mon Sep 17 00:00:00 2001 From: Jerko J <83344666+JJ-Cro@users.noreply.github.com> Date: Mon, 20 May 2024 18:28:22 +0200 Subject: [PATCH 19/36] chore(): Refactoring types --- src/RestClient.ts | 29 +++-------------------------- src/types/response/shared.types.ts | 13 +++++++++++++ 2 files changed, 16 insertions(+), 26 deletions(-) diff --git a/src/RestClient.ts b/src/RestClient.ts index 4df9429..e4c29bc 100644 --- a/src/RestClient.ts +++ b/src/RestClient.ts @@ -40,6 +40,7 @@ import { CreateSubAccountApiKeyResp, DeleteSpotBatchOrdersResp, GetBalancesResp, + GetCrossMarginCurrenciesResp, GetCurrencyChainsResp, GetMarginAccountsResp, GetMarginBalanceHistoryResp, @@ -1327,34 +1328,10 @@ export class RestClient extends BaseRestClient { /** * Currencies supported by cross margin * - * @returns Promise> + * @returns Promise> */ getCrossMarginCurrencies(): Promise< - APIResponse< - { - name: string; - rate: string; - prec: string; - discount: string; - min_borrow_amount: string; - user_max_borrow_amount: string; - total_max_borrow_amount: string; - price: string; - loanable: boolean; - status: number; - }[] - > + APIResponse > { return this.get('/margin/cross/currencies'); } diff --git a/src/types/response/shared.types.ts b/src/types/response/shared.types.ts index a45d372..3b476c4 100644 --- a/src/types/response/shared.types.ts +++ b/src/types/response/shared.types.ts @@ -583,3 +583,16 @@ export interface GetMarginBalanceHistoryResp { balance: string; type: string; } + +export interface GetCrossMarginCurrenciesResp { + name: string; + rate: string; + prec: string; + discount: string; + min_borrow_amount: string; + user_max_borrow_amount: string; + total_max_borrow_amount: string; + price: string; + loanable: boolean; + status: number; +} From 91c0c40abf9c12217146fe451bf8fa186feb9d97 Mon Sep 17 00:00:00 2001 From: Jerko J <83344666+JJ-Cro@users.noreply.github.com> Date: Mon, 20 May 2024 18:45:09 +0200 Subject: [PATCH 20/36] chore(): refactoring types --- src/RestClient.ts | 335 ++++------------------------- src/types/requests/shared.types.ts | 44 ++++ src/types/response/shared.types.ts | 59 +++++ 3 files changed, 145 insertions(+), 293 deletions(-) diff --git a/src/RestClient.ts b/src/RestClient.ts index e4c29bc..9b3d4dd 100644 --- a/src/RestClient.ts +++ b/src/RestClient.ts @@ -12,6 +12,10 @@ import { import { RestClientOptions } from './lib/requestUtils.js'; import { DeleteSpotOrderReq, + GetCrossMarginAccountHistoryReq, + GetCrossMarginBorrowHistoryReq, + GetCrossMarginInterestRecordsReq, + GetCrossMarginRepaymentsReq, GetMainSubTransfersReq, GetMarginBalanceHistoryReq, GetSavedAddressReq, @@ -29,6 +33,7 @@ import { GetWithdrawalDepositRecordsReq, PortfolioMarginCalculatorReq, SetUnifiedAccountModeReq, + SubmitCrossMarginBorrowLoanReq, SubmitSpotClosePosCrossDisabledReq, SubmitSpotOrderReq, SubmitUnifiedBorrowOrRepayReq, @@ -40,6 +45,8 @@ import { CreateSubAccountApiKeyResp, DeleteSpotBatchOrdersResp, GetBalancesResp, + GetCrossMarginAccountHistoryResp, + GetCrossMarginAccountResp, GetCrossMarginCurrenciesResp, GetCurrencyChainsResp, GetMarginAccountsResp, @@ -72,6 +79,7 @@ import { SubAccountMarginBalancesResp, SubAccountResp, SubAccountTransferRecordResp, + SubmitCrossMarginBorrowLoanResp, SubmitSpotBatchOrdersResp, } from './types/response/shared.types.js'; import { @@ -1340,104 +1348,20 @@ export class RestClient extends BaseRestClient { * Retrieve detail of one single currency supported by cross margin * * @param params Parameters containing the currency name - * @returns Promise> + * @returns Promise> */ - getCrossMarginCurrency(params: { currency: string }): Promise< - APIResponse<{ - name: string; - rate: string; - prec: string; - discount: string; - min_borrow_amount: string; - user_max_borrow_amount: string; - total_max_borrow_amount: string; - price: string; - loanable: boolean; - status: number; - }> - > { + getCrossMarginCurrency(params: { + currency: string; + }): Promise> { return this.get(`/margin/cross/currencies/${params.currency}`); } /** * Retrieve cross margin account * - * @returns Promise> + * @returns Promise> */ - getCrossMarginAccount(): Promise< - APIResponse<{ - user_id: number; - refresh_time: number; - locked: boolean; - balances: { - [currency: string]: { - available: string; - freeze: string; - borrowed: string; - interest: string; - negative_liab: string; - futures_pos_liab: string; - equity: string; - total_freeze: string; - total_liab: string; - }; - }; - total: string; - borrowed: string; - interest: string; - risk: string; - total_initial_margin: string; - total_margin_balance: string; - total_maintenance_margin: string; - total_initial_margin_rate: string; - total_maintenance_margin_rate: string; - total_available_margin: string; - portfolio_margin_total: string; - portfolio_margin_total_liab: string; - portfolio_margin_total_equity: string; - }> - > { + getCrossMarginAccount(): Promise> { return this.getPrivate('/margin/cross/accounts'); } @@ -1447,34 +1371,11 @@ export class RestClient extends BaseRestClient { * Record time range cannot exceed 30 days. * * @param params Parameters for retrieving cross margin account change history - * @returns Promise> + * @returns Promise> */ - getCrossMarginAccountHistory(params?: { - currency?: string; - from?: number; - to?: number; - page?: number; - limit?: number; - type?: string; - }): Promise< - APIResponse< - { - id: string; - time: number; - currency: string; - change: string; - balance: string; - type: string; - }[] - > - > { + getCrossMarginAccountHistory( + params?: GetCrossMarginAccountHistoryReq, + ): Promise> { return this.getPrivate('/margin/cross/account_book', params); } @@ -1484,37 +1385,11 @@ export class RestClient extends BaseRestClient { * Borrow amount cannot be less than currency minimum borrow amount. * * @param params Parameters for creating a cross margin borrow loan - * @returns Promise> + * @returns Promise> */ - submitCrossMarginBorrowLoan(body: { - currency: string; - amount: string; - text?: string; - }): Promise< - APIResponse<{ - id: string; - create_time: number; - update_time: number; - currency: string; - amount: string; - text?: string; - status: number; - repaid: string; - repaid_interest: string; - unpaid_interest: string; - }> - > { + submitCrossMarginBorrowLoan( + body: SubmitCrossMarginBorrowLoanReq, + ): Promise> { return this.postPrivate('/margin/cross/loans', body); } @@ -1524,41 +1399,11 @@ export class RestClient extends BaseRestClient { * Sort by creation time in descending order by default. Set reverse=false to return ascending results. * * @param params Parameters for listing cross margin borrow history - * @returns Promise> + * @returns Promise> */ - getCrossMarginBorrowHistory(params: { - status: number; - currency?: string; - limit?: number; - offset?: number; - reverse?: boolean; - }): Promise< - APIResponse< - { - id: string; - create_time: number; - update_time: number; - currency: string; - amount: string; - text: string; - status: number; - repaid: string; - repaid_interest: string; - unpaid_interest: string; - }[] - > - > { + getCrossMarginBorrowHistory( + params: GetCrossMarginBorrowHistoryReq, + ): Promise> { return this.getPrivate('/margin/cross/loans', params); } @@ -1566,33 +1411,11 @@ export class RestClient extends BaseRestClient { * Retrieve single borrow loan detail * * @param params Parameters containing the borrow loan ID - * @returns Promise> + * @returns Promise> */ - getCrossMarginBorrowLoan(params: { loan_id: string }): Promise< - APIResponse<{ - id: string; - create_time: number; - update_time: number; - currency: string; - amount: string; - text: string; - status: number; - repaid: string; - repaid_interest: string; - unpaid_interest: string; - }> - > { + getCrossMarginBorrowLoan(params: { + loan_id: string; + }): Promise> { return this.getPrivate(`/margin/cross/loans/${params.loan_id}`); } /** @@ -1601,38 +1424,12 @@ export class RestClient extends BaseRestClient { * When the liquidity of the currency is insufficient and the transaction risk is high, the currency will be disabled, and funds cannot be transferred. When the available balance of cross-margin is insufficient, the balance of the spot account can be used for repayment. Please ensure that the balance of the spot account is sufficient, and system uses cross-margin account for repayment first. * * @param params Parameters for cross margin repayments - * @returns Promise> + * @returns Promise> */ submitCrossMarginRepayment(body: { currency: string; amount: string; - }): Promise< - APIResponse< - { - id: string; - create_time: number; - update_time: number; - currency: string; - amount: string; - text?: string; - status: number; - repaid: string; - repaid_interest: string; - unpaid_interest: string; - }[] - > - > { + }): Promise> { return this.postPrivate('/margin/cross/repayments', body); } @@ -1642,35 +1439,11 @@ export class RestClient extends BaseRestClient { * Sort by creation time in descending order by default. Set reverse=false to return ascending results. * * @param params Parameters for retrieving cross margin repayments - * @returns Promise> + * @returns Promise> */ - getCrossMarginRepayments(params?: { - currency?: string; - loan_id?: string; - limit?: number; - offset?: number; - reverse?: boolean; - }): Promise< - APIResponse< - { - id: string; - create_time: number; - loan_id: string; - currency: string; - principal: string; - interest: string; - repayment_type: string; - }[] - > - > { + getCrossMarginRepayments( + params?: GetCrossMarginRepaymentsReq, + ): Promise> { return this.getPrivate('/margin/cross/repayments', params); } @@ -1678,35 +1451,11 @@ export class RestClient extends BaseRestClient { * Interest records for the cross margin account * * @param params Parameters for retrieving interest records - * @returns Promise> + * @returns Promise> */ - getCrossMarginInterestRecords(params?: { - currency?: string; - page?: number; - limit?: number; - from?: number; - to?: number; - }): Promise< - APIResponse< - { - currency: string; - currency_pair: string; - actual_rate: string; - interest: string; - status: number; - type: string; - create_time: number; - }[] - > - > { + getCrossMarginInterestRecords( + params?: GetCrossMarginInterestRecordsReq, + ): Promise> { return this.getPrivate('/margin/cross/interest_records', params); } @@ -1734,11 +1483,11 @@ export class RestClient extends BaseRestClient { * Please note that the interest rates are subject to change based on the borrowing and lending demand, and therefore, the provided rates may not be entirely accurate. * * @param params Parameters for retrieving estimated interest rates - * @returns Promise>> + * @returns Promise> */ getEstimatedInterestRates(params: { currencies: string[]; - }): Promise>> { + }): Promise> { return this.getPrivate('/margin/cross/estimate_rate', params); } diff --git a/src/types/requests/shared.types.ts b/src/types/requests/shared.types.ts index 44a8137..49733f8 100644 --- a/src/types/requests/shared.types.ts +++ b/src/types/requests/shared.types.ts @@ -227,3 +227,47 @@ export interface GetMarginBalanceHistoryReq { page?: number; limit?: number; } + +export interface GetCrossMarginAccountHistoryReq { + currency?: string; + from?: number; + to?: number; + page?: number; + limit?: number; + type?: string; +} + +export interface SubmitCrossMarginBorrowLoanReq { + currency: string; + amount: string; + text?: string; +} + +export interface GetCrossMarginBorrowHistoryReq { + status: number; + currency?: string; + limit?: number; + offset?: number; + reverse?: boolean; +} + +export interface GetCrossMarginRepaymentsReq { + currency?: string; + loan_id?: string; + limit?: number; + offset?: number; + reverse?: boolean; +} + +export interface GetCrossMarginInterestRecordsReq { + currency?: string; + page?: number; + limit?: number; + from?: number; + to?: number; +} + +/**========================================================================================================================== + * MARGIN UNI + * ========================================================================================================================== + */ diff --git a/src/types/response/shared.types.ts b/src/types/response/shared.types.ts index 3b476c4..af10b5f 100644 --- a/src/types/response/shared.types.ts +++ b/src/types/response/shared.types.ts @@ -596,3 +596,62 @@ export interface GetCrossMarginCurrenciesResp { loanable: boolean; status: number; } + +export interface GetCrossMarginAccountResp { + user_id: number; + refresh_time: number; + locked: boolean; + balances: { + [currency: string]: { + available: string; + freeze: string; + borrowed: string; + interest: string; + negative_liab: string; + futures_pos_liab: string; + equity: string; + total_freeze: string; + total_liab: string; + }; + }; + total: string; + borrowed: string; + interest: string; + risk: string; + total_initial_margin: string; + total_margin_balance: string; + total_maintenance_margin: string; + total_initial_margin_rate: string; + total_maintenance_margin_rate: string; + total_available_margin: string; + portfolio_margin_total: string; + portfolio_margin_total_liab: string; + portfolio_margin_total_equity: string; +} + +export interface GetCrossMarginAccountHistoryResp { + id: string; + time: number; + currency: string; + change: string; + balance: string; + type: string; +} + +export interface SubmitCrossMarginBorrowLoanResp { + id: string; + create_time: number; + update_time: number; + currency: string; + amount: string; + text?: string; + status: number; + repaid: string; + repaid_interest: string; + unpaid_interest: string; +} + +/**========================================================================================================================== + * MARGIN UNI + * ========================================================================================================================== + */ From 3ce47e40601a12325c7891919d06b4e6507f20ef Mon Sep 17 00:00:00 2001 From: Tiago Siebler Date: Mon, 20 May 2024 18:01:05 +0100 Subject: [PATCH 21/36] feat(): allow request to use query and/or string --- src/RestClient.ts | 209 ++++++++++++++++++++------------------ src/lib/BaseRestClient.ts | 120 ++++++++++++---------- 2 files changed, 180 insertions(+), 149 deletions(-) diff --git a/src/RestClient.ts b/src/RestClient.ts index 42100a2..a6ff013 100644 --- a/src/RestClient.ts +++ b/src/RestClient.ts @@ -418,7 +418,7 @@ export class RestClient extends BaseRestClient { memo?: string; chain: string; }): Promise> { - return this.postPrivate('/withdrawals', body); + return this.postPrivate('/withdrawals', { body }); } /** @@ -517,7 +517,7 @@ export class RestClient extends BaseRestClient { currency_pair?: string; settle?: string; }): Promise> { - return this.postPrivate('/wallet/transfers', body); + return this.postPrivate('/wallet/transfers', { body }); } /** @@ -536,7 +536,7 @@ export class RestClient extends BaseRestClient { client_order_id?: string; sub_account_type?: 'spot' | 'futures' | 'cross_margin' | 'delivery'; }): Promise> { - return this.postPrivate('/wallet/sub_account_transfers', body); + return this.postPrivate('/wallet/sub_account_transfers', { body }); } /** @@ -572,7 +572,7 @@ export class RestClient extends BaseRestClient { sub_account_to_type: 'spot' | 'futures' | 'delivery' | 'cross_margin'; amount: string; }): Promise> { - return this.postPrivate('/wallet/sub_account_to_sub_account', body); + return this.postPrivate('/wallet/sub_account_to_sub_account', { body }); } /** @@ -707,7 +707,7 @@ export class RestClient extends BaseRestClient { convertSmallBalance(body: { currency?: string[]; }): Promise> { - return this.postPrivate('/wallet/small_balance', body); + return this.postPrivate('/wallet/small_balance', { body }); } /** @@ -739,7 +739,7 @@ export class RestClient extends BaseRestClient { password?: string; email?: string; }): Promise> { - return this.postPrivate('/sub_accounts', body); + return this.postPrivate('/sub_accounts', { body }); } /** @@ -780,7 +780,7 @@ export class RestClient extends BaseRestClient { }, body: SubAccountKey, ): Promise> { - return this.postPrivate(`/sub_accounts/${params.user_id}/keys`, body); + return this.postPrivate(`/sub_accounts/${params.user_id}/keys`, { body }); } /** * List all API Key of the sub-account @@ -809,7 +809,7 @@ export class RestClient extends BaseRestClient { ): Promise> { return this.putPrivate( `/sub_accounts/${params.user_id}/keys/${params.key}`, - body, + { body }, ); } @@ -932,7 +932,7 @@ export class RestClient extends BaseRestClient { submitUnifiedBorrowOrRepay( body: SubmitUnifiedBorrowOrRepayReq, ): Promise> { - return this.postPrivate('/unified/loans', body); + return this.postPrivate('/unified/loans', { body }); } /** @@ -993,7 +993,7 @@ export class RestClient extends BaseRestClient { setUnifiedAccountMode( body: SetUnifiedAccountModeReq, ): Promise> { - return this.putPrivate('/unified/unified_mode', body); + return this.putPrivate('/unified/unified_mode', { body }); } /** @@ -1047,7 +1047,7 @@ export class RestClient extends BaseRestClient { portfolioMarginCalculator( body: PortfolioMarginCalculatorReq, ): Promise> { - return this.post('/unified/portfolio_calculator', body); + return this.post('/unified/portfolio_calculator', { body }); } /**========================================================================================================================== @@ -1497,7 +1497,7 @@ export class RestClient extends BaseRestClient { }[] > > { - return this.postPrivate('/spot/batch_orders', body); + return this.postPrivate('/spot/batch_orders', { body }); } /** @@ -1622,7 +1622,7 @@ export class RestClient extends BaseRestClient { price: string; action_mode?: 'ACK' | 'RESULT' | 'FULL'; }): Promise> { - return this.postPrivate('/spot/cross_liquidate_orders', body); + return this.postPrivate('/spot/cross_liquidate_orders', { body }); } /** @@ -1649,7 +1649,7 @@ export class RestClient extends BaseRestClient { * }>> */ submitSpotOrder(body: Order): Promise> { - return this.postPrivate('/spot/orders', body); + return this.postPrivate('/spot/orders', { body }); } /** @@ -1758,7 +1758,7 @@ export class RestClient extends BaseRestClient { account?: 'spot' | 'margin' | 'cross_margin' | 'unified'; action_mode?: 'ACK' | 'RESULT' | 'FULL'; }): Promise> { - return this.deletePrivate('/spot/orders', params); + return this.deletePrivate('/spot/orders', { body: params }); } /** @@ -1788,7 +1788,7 @@ export class RestClient extends BaseRestClient { }[] > > { - return this.postPrivate('/spot/cancel_batch_orders', body); + return this.postPrivate('/spot/cancel_batch_orders', { body }); } /** @@ -1887,20 +1887,26 @@ export class RestClient extends BaseRestClient { * finish_as: 'open' | 'filled' | 'cancelled' | 'ioc' | 'stp'; * }>> */ - updateSpotOrder( - params: { - order_id: string; - currency_pair: string; - account?: 'spot' | 'margin' | 'cross_margin' | 'unified'; - }, - body: { - amount?: string; - price?: string; - amend_text?: string; - action_mode?: 'ACK' | 'RESULT' | 'FULL'; - }, - ): Promise> { - return this.patchPrivate(`/spot/orders/${params.order_id}`, body); + updateSpotOrder(params: { + order_id: string; + currency_pair: string; + account?: 'spot' | 'margin' | 'cross_margin' | 'unified'; + amount?: string; + price?: string; + amend_text?: string; + action_mode?: 'ACK' | 'RESULT' | 'FULL'; + }): Promise> { + const { order_id, currency_pair, account, ...body } = params; + + const query = { + currency_pair: currency_pair, + account: account, + }; + + return this.patchPrivate(`/spot/orders/${order_id}`, { + query, + body, + }); } /** @@ -1952,7 +1958,9 @@ export class RestClient extends BaseRestClient { account?: 'spot' | 'margin' | 'cross_margin' | 'unified'; action_mode?: 'ACK' | 'RESULT' | 'FULL'; }): Promise> { - return this.deletePrivate(`/spot/orders/${params.order_id}`, params); + return this.deletePrivate(`/spot/orders/${params.order_id}`, { + body: params, + }); } /** @@ -2048,7 +2056,7 @@ export class RestClient extends BaseRestClient { triggerTime: number; }> > { - return this.postPrivate('/spot/countdown_cancel_all', body); + return this.postPrivate('/spot/countdown_cancel_all', { body }); } /** @@ -2146,7 +2154,7 @@ export class RestClient extends BaseRestClient { }[] > > { - return this.postPrivate('/spot/amend_batch_orders', body); + return this.postPrivate('/spot/amend_batch_orders', { body }); } /** @@ -2162,7 +2170,7 @@ export class RestClient extends BaseRestClient { id: number; }> > { - return this.postPrivate('/spot/price_orders', body); + return this.postPrivate('/spot/price_orders', { body }); } /** @@ -2226,7 +2234,7 @@ export class RestClient extends BaseRestClient { market?: string; account?: 'normal' | 'margin' | 'cross_margin'; }): Promise> { - return this.deletePrivate('/spot/price_orders', params); + return this.deletePrivate('/spot/price_orders', { body: params }); } /** @@ -2286,7 +2294,9 @@ export class RestClient extends BaseRestClient { deleteSpotPriceTriggeredOrder(params: { order_id: string; }): Promise> { - return this.deletePrivate(`/spot/price_orders/${params.order_id}`, params); + return this.deletePrivate(`/spot/price_orders/${params.order_id}`, { + body: params, + }); } /**========================================================================================================================== @@ -2421,8 +2431,7 @@ export class RestClient extends BaseRestClient { updateAutoRepaymentSetting(params: { status: 'on' | 'off'; }): Promise> { - const paramsAsQuery = true; - return this.postPrivate('/margin/auto_repay', params, paramsAsQuery); + return this.postPrivate('/margin/auto_repay', { query: params }); } /** @@ -2671,7 +2680,7 @@ export class RestClient extends BaseRestClient { unpaid_interest: string; }> > { - return this.postPrivate('/margin/cross/loans', body); + return this.postPrivate('/margin/cross/loans', { body }); } /** @@ -2789,7 +2798,7 @@ export class RestClient extends BaseRestClient { }[] > > { - return this.postPrivate('/margin/cross/repayments', body); + return this.postPrivate('/margin/cross/repayments', { body }); } /** @@ -2992,7 +3001,7 @@ export class RestClient extends BaseRestClient { repaid_all?: boolean; currency_pair: string; }): Promise { - return this.postPrivate('/margin/uni/loans', body); + return this.postPrivate('/margin/uni/loans', { body }); } /** @@ -3192,7 +3201,7 @@ export class RestClient extends BaseRestClient { status: number; }> > { - return this.postPrivate('/flash_swap/orders', body); + return this.postPrivate('/flash_swap/orders', { body }); } /** @@ -3296,7 +3305,7 @@ export class RestClient extends BaseRestClient { price: string; }> > { - return this.postPrivate('/flash_swap/orders/preview', body); + return this.postPrivate('/flash_swap/orders/preview', { body }); } /**========================================================================================================================== * FUTURES @@ -3895,7 +3904,7 @@ export class RestClient extends BaseRestClient { }): Promise> { return this.postPrivate( `/futures/${params.settle}/positions/${params.contract}/margin`, - params, + { body: params }, ); } @@ -3911,13 +3920,10 @@ export class RestClient extends BaseRestClient { leverage: string; cross_leverage_limit?: string; }): Promise> { - const paramsAsQuery = true; - const { settle, contract, ...remainingParams } = params; return this.postPrivate( `/futures/${settle}/positions/${contract}/leverage`, - remainingParams, - paramsAsQuery, + { query: remainingParams }, ); } @@ -3934,7 +3940,7 @@ export class RestClient extends BaseRestClient { }): Promise> { return this.postPrivate( `/futures/${params.settle}/positions/${params.contract}/risk_limit`, - params, + { body: params }, ); } @@ -4004,7 +4010,9 @@ export class RestClient extends BaseRestClient { }; }> > { - return this.postPrivate(`/futures/${params.settle}/dual_mode`, params); + return this.postPrivate(`/futures/${params.settle}/dual_mode`, { + body: params, + }); } /** @@ -4037,7 +4045,7 @@ export class RestClient extends BaseRestClient { }): Promise> { return this.postPrivate( `/futures/${params.settle}/dual_comp/positions/${params.contract}/margin`, - params, + { body: params }, ); } @@ -4055,7 +4063,7 @@ export class RestClient extends BaseRestClient { }): Promise> { return this.postPrivate( `/futures/${params.settle}/dual_comp/positions/${params.contract}/leverage`, - params, + { body: params }, ); } @@ -4072,7 +4080,7 @@ export class RestClient extends BaseRestClient { }): Promise> { return this.postPrivate( `/futures/${params.settle}/dual_comp/positions/${params.contract}/risk_limit`, - params, + { body: params }, ); } @@ -4095,7 +4103,7 @@ export class RestClient extends BaseRestClient { }, body: FuturesOrder, ): Promise> { - return this.postPrivate(`/futures/${params.settle}/orders`, body); + return this.postPrivate(`/futures/${params.settle}/orders`, { body }); } /** @@ -4131,7 +4139,9 @@ export class RestClient extends BaseRestClient { contract: string; side?: string; }): Promise> { - return this.deletePrivate(`/futures/${params.settle}/orders`, params); + return this.deletePrivate(`/futures/${params.settle}/orders`, { + body: params, + }); } /** @@ -4230,7 +4240,7 @@ export class RestClient extends BaseRestClient { }[] > > { - return this.postPrivate(`/futures/${params.settle}/batch_orders`, body); + return this.postPrivate(`/futures/${params.settle}/batch_orders`, { body }); } /** @@ -4286,7 +4296,7 @@ export class RestClient extends BaseRestClient { ): Promise> { return this.putPrivate( `/futures/${params.settle}/orders/${params.order_id}`, - body, + { body }, ); } @@ -4492,10 +4502,9 @@ export class RestClient extends BaseRestClient { contract?: string; }, ): Promise> { - return this.postPrivate( - `/futures/${params.settle}/countdown_cancel_all`, + return this.postPrivate(`/futures/${params.settle}/countdown_cancel_all`, { body, - ); + }); } /** @@ -4541,10 +4550,9 @@ export class RestClient extends BaseRestClient { }[] > > { - return this.postPrivate( - `/futures/${params.settle}/batch_cancel_orders`, + return this.postPrivate(`/futures/${params.settle}/batch_cancel_orders`, { body, - ); + }); } /** @@ -4559,7 +4567,7 @@ export class RestClient extends BaseRestClient { }, body: FuturesPriceTriggeredOrder, ): Promise> { - return this.postPrivate(`/futures/${params.settle}/price_orders`, body); + return this.postPrivate(`/futures/${params.settle}/price_orders`, { body }); } /** @@ -4588,7 +4596,9 @@ export class RestClient extends BaseRestClient { settle: 'btc' | 'usdt' | 'usd'; contract: string; }): Promise> { - return this.deletePrivate(`/futures/${params.settle}/price_orders`, params); + return this.deletePrivate(`/futures/${params.settle}/price_orders`, { + body: params, + }); } /** @@ -4619,7 +4629,7 @@ export class RestClient extends BaseRestClient { }): Promise> { return this.deletePrivate( `/futures/${params.settle}/price_orders/${params.order_id}`, - params, + { body: params }, ); } /**========================================================================================================================== @@ -5018,7 +5028,7 @@ export class RestClient extends BaseRestClient { }): Promise> { return this.postPrivate( `/delivery/${params.settle}/positions/${params.contract}/margin`, - params, + { body: params }, ); } @@ -5035,7 +5045,7 @@ export class RestClient extends BaseRestClient { }): Promise> { return this.postPrivate( `/delivery/${params.settle}/positions/${params.contract}/leverage`, - params, + { body: params }, ); } @@ -5052,7 +5062,7 @@ export class RestClient extends BaseRestClient { }): Promise> { return this.postPrivate( `/delivery/${params.settle}/positions/${params.contract}/risk_limit`, - params, + { body: params }, ); } @@ -5070,7 +5080,7 @@ export class RestClient extends BaseRestClient { }, body: FuturesOrder, ): Promise> { - return this.postPrivate(`/delivery/${params.settle}/orders`, body); + return this.postPrivate(`/delivery/${params.settle}/orders`, { body }); } /** @@ -5106,7 +5116,9 @@ export class RestClient extends BaseRestClient { contract: string; side?: 'ask' | 'bid'; }): Promise> { - return this.deletePrivate(`/delivery/${params.settle}/orders`, params); + return this.deletePrivate(`/delivery/${params.settle}/orders`, { + body: params, + }); } /** @@ -5325,7 +5337,10 @@ export class RestClient extends BaseRestClient { }, body: FuturesPriceTriggeredOrder, ): Promise> { - return this.postPrivate(`/delivery/${params.settle}/price_orders`, body); + return this.postPrivate(`/delivery/${params.settle}/price_orders`, { + query: params, + body, + }); } /** @@ -5354,10 +5369,9 @@ export class RestClient extends BaseRestClient { settle: 'usdt'; contract: string; }): Promise> { - return this.deletePrivate( - `/delivery/${params.settle}/price_orders`, - params, - ); + return this.deletePrivate(`/delivery/${params.settle}/price_orders`, { + body: params, + }); } /** @@ -6146,7 +6160,7 @@ export class RestClient extends BaseRestClient { refr: string; }> > { - return this.postPrivate(`/options/orders`, body); + return this.postPrivate(`/options/orders`, { body }); } /** @@ -6288,7 +6302,7 @@ export class RestClient extends BaseRestClient { }[] > > { - return this.deletePrivate(`/options/orders`, params); + return this.deletePrivate(`/options/orders`, { body: params }); } /** @@ -6522,7 +6536,7 @@ export class RestClient extends BaseRestClient { type: 'lend' | 'redeem'; min_rate?: string; }): Promise> { - return this.postPrivate(`/earn/uni/lends`, body); + return this.postPrivate(`/earn/uni/lends`, { body }); } /** @@ -6573,11 +6587,11 @@ export class RestClient extends BaseRestClient { * @param params Parameters for amending lending order * @returns Promise> */ - updateLendingOrder(body: { + updateLendingOrder(params: { currency?: string; min_rate?: string; }): Promise> { - return this.patchPrivate(`/earn/uni/lends`, body); + return this.patchPrivate(`/earn/uni/lends`, { body: params }); } /** @@ -6679,7 +6693,7 @@ export class RestClient extends BaseRestClient { currency: string; status: boolean; }): Promise> { - return this.putPrivate(`/earn/uni/interest_reinvest`, body); + return this.putPrivate(`/earn/uni/interest_reinvest`, { body }); } /** @@ -6717,7 +6731,7 @@ export class RestClient extends BaseRestClient { borrow_amount: string; borrow_currency: string; }): Promise> { - return this.postPrivate(`/loan/collateral/orders`, body); + return this.postPrivate(`/loan/collateral/orders`, { body }); } /** @@ -6838,7 +6852,7 @@ export class RestClient extends BaseRestClient { repaid_interest: string; }> > { - return this.postPrivate(`/loan/collateral/repay`, body); + return this.postPrivate(`/loan/collateral/repay`, { body }); } /** @@ -6903,7 +6917,7 @@ export class RestClient extends BaseRestClient { collateral_amount: string; type: 'append' | 'redeem'; }): Promise> { - return this.postPrivate(`/loan/collateral/collaterals`, body); + return this.postPrivate(`/loan/collateral/collaterals`, { body }); } /** @@ -7042,7 +7056,7 @@ export class RestClient extends BaseRestClient { amount?: string; }[]; }): Promise> { - return this.postPrivate(`/loan/multi_collateral/orders`, body); + return this.postPrivate(`/loan/multi_collateral/orders`, { body }); } /** @@ -7219,7 +7233,7 @@ export class RestClient extends BaseRestClient { }[]; }> > { - return this.postPrivate(`/loan/multi_collateral/repay`, body); + return this.postPrivate(`/loan/multi_collateral/repay`, { body }); } /** @@ -7369,7 +7383,7 @@ export class RestClient extends BaseRestClient { }[]; }> > { - return this.postPrivate(`/loan/multi_collateral/mortgage`, body); + return this.postPrivate(`/loan/multi_collateral/mortgage`, { body }); } /** @@ -7553,7 +7567,7 @@ export class RestClient extends BaseRestClient { side: '1' | '2'; amount: string; }): Promise> { - return this.postPrivate(`/earn/staking/eth2/swap`, body); + return this.postPrivate(`/earn/staking/eth2/swap`, { body }); } /** @@ -7659,7 +7673,7 @@ export class RestClient extends BaseRestClient { plan_id: string; copies: string; }): Promise> { - return this.postPrivate(`/earn/dual/orders`, body); + return this.postPrivate(`/earn/dual/orders`, { body }); } /** @@ -7752,7 +7766,7 @@ export class RestClient extends BaseRestClient { pid?: string; amount?: string; }): Promise> { - return this.postPrivate(`/earn/structured/orders`, body); + return this.postPrivate(`/earn/structured/orders`, { body }); } /**========================================================================================================================== @@ -7811,7 +7825,7 @@ export class RestClient extends BaseRestClient { create_time: number; }> > { - return this.postPrivate(`/account/stp_groups`, body); + return this.postPrivate(`/account/stp_groups`, { body }); } /** @@ -7885,7 +7899,9 @@ export class RestClient extends BaseRestClient { }[] > > { - return this.postPrivate(`/account/stp_groups/${params.stp_id}/users`, body); + return this.postPrivate(`/account/stp_groups/${params.stp_id}/users`, { + body, + }); } /** @@ -7907,10 +7923,9 @@ export class RestClient extends BaseRestClient { }[] > > { - return this.deletePrivate( - `/account/stp_groups/${params.stp_id}/users`, - params, - ); + return this.deletePrivate(`/account/stp_groups/${params.stp_id}/users`, { + body: params, + }); } /** diff --git a/src/lib/BaseRestClient.ts b/src/lib/BaseRestClient.ts index a370d75..1ea83ca 100644 --- a/src/lib/BaseRestClient.ts +++ b/src/lib/BaseRestClient.ts @@ -43,6 +43,14 @@ interface UnsignedRequest { type SignMethod = 'gateV4'; +/** + * Some requests require some params to be in the query string and some in the body. + * This type anticipates both are possible in any combination. + * + * The request builder will automatically handle where parameters should go. + */ +type ParamsInQueryAndOrBody = { query?: object; body?: object }; + /** * Enables: * - Detailed request/response logging @@ -90,6 +98,22 @@ if (ENABLE_HTTP_TRACE) { }); } +/** + * Impure, mutates params to remove any values that have a key but are undefined. + */ +function deleteUndefinedValues(params?: any): void { + if (!params) { + return; + } + + for (const key in params) { + const value = params[key]; + if (typeof value === 'undefined') { + delete params[key]; + } + } +} + export abstract class BaseRestClient { private options: RestClientOptions; private baseUrl: string; @@ -152,41 +176,40 @@ export abstract class BaseRestClient { return Date.now(); } - protected get(endpoint: string, params?: any) { + protected get(endpoint: string, params?: object) { const isPublicAPI = true; - return this._call('GET', endpoint, params, isPublicAPI); + // GET only supports params in the query string + return this._call('GET', endpoint, { query: params }, isPublicAPI); } - protected post(endpoint: string, params?: any) { + protected post(endpoint: string, params?: ParamsInQueryAndOrBody) { const isPublicAPI = true; return this._call('POST', endpoint, params, isPublicAPI); } - protected getPrivate(endpoint: string, params?: any) { + protected getPrivate(endpoint: string, params?: object) { const isPublicAPI = false; - return this._call('GET', endpoint, params, isPublicAPI); + // GET only supports params in the query string + return this._call('GET', endpoint, { query: params }, isPublicAPI); } - protected postPrivate( - endpoint: string, - params?: any, - paramsAsQuery?: boolean, - ) { + protected postPrivate(endpoint: string, params?: ParamsInQueryAndOrBody) { const isPublicAPI = false; - return this._call('POST', endpoint, params, isPublicAPI, paramsAsQuery); + return this._call('POST', endpoint, params, isPublicAPI); } - protected deletePrivate(endpoint: string, params?: any) { + protected deletePrivate(endpoint: string, params?: ParamsInQueryAndOrBody) { const isPublicAPI = false; return this._call('DELETE', endpoint, params, isPublicAPI); } - protected putPrivate(endpoint: string, params?: any) { + protected putPrivate(endpoint: string, params?: ParamsInQueryAndOrBody) { const isPublicAPI = false; return this._call('PUT', endpoint, params, isPublicAPI); } - protected patchPrivate(endpoint: string, params?: any) { + // protected patchPrivate(endpoint: string, params?: any) { + protected patchPrivate(endpoint: string, params?: ParamsInQueryAndOrBody) { const isPublicAPI = false; return this._call('PATCH', endpoint, params, isPublicAPI); } @@ -197,9 +220,8 @@ export abstract class BaseRestClient { private async _call( method: Method, endpoint: string, - params?: any, + params?: ParamsInQueryAndOrBody, isPublicApi?: boolean, - passParamsAsQueryString?: boolean, ): Promise { // Sanity check to make sure it's only ever prefixed by one forward slash const requestUrl = [this.baseUrl, endpoint].join( @@ -213,7 +235,6 @@ export abstract class BaseRestClient { requestUrl, params, isPublicApi, - passParamsAsQueryString, ); if (ENABLE_HTTP_TRACE) { @@ -284,12 +305,11 @@ export abstract class BaseRestClient { /** * @private sign request and set recv window */ - private async signRequest( + private async signRequest( data: T, endpoint: string, method: Method, signMethod: SignMethod, - passParamsAsQueryString?: boolean, ): Promise> { const timestamp = +(this.getSignTimestampMs() / 1000).toFixed(0); // in seconds @@ -298,6 +318,7 @@ export abstract class BaseRestClient { // recvWindow: this.options.recvWindow, ...data, }, + sign: '', timestamp, recvWindow: 0, @@ -314,24 +335,21 @@ export abstract class BaseRestClient { const encodeQueryStringValues = true; if (signMethod === 'gateV4') { - const useQueryStringParamAuth = - method === 'GET' || method === 'DELETE' || passParamsAsQueryString; - const signAlgoritm: SignAlgorithm = 'SHA-512'; const signEncoding: SignEncodeMethod = 'hex'; - const queryStringToSign = useQueryStringParamAuth + const queryStringToSign = data?.query ? serializeParams( - res.originalParams, + res.originalParams?.query, strictParamValidation, encodeQueryStringValues, '', ) : ''; - const requestBodyToHash = useQueryStringParamAuth - ? '' - : JSON.stringify(res.originalParams); + const requestBodyToHash = res.originalParams?.body + ? JSON.stringify(res.originalParams?.body) + : ''; const hashedRequestBody = await hashMessage( requestBodyToHash, @@ -348,6 +366,7 @@ export abstract class BaseRestClient { ].join('\n'); // console.log('sign params: ', { + // requestBodyToHash, // paramsStr: toSign, // url: this.baseUrl, // urlPath: this.baseUrlPath, @@ -383,29 +402,32 @@ export abstract class BaseRestClient { return await signMessage(paramsStr, secret, method, algorithm); } - private async prepareSignParams( + private async prepareSignParams< + TParams extends ParamsInQueryAndOrBody | undefined, + >( method: Method, endpoint: string, signMethod: SignMethod, params?: TParams, isPublicApi?: true, - passParamsAsQueryString?: boolean, ): Promise>; - private async prepareSignParams( + private async prepareSignParams< + TParams extends ParamsInQueryAndOrBody | undefined, + >( method: Method, endpoint: string, signMethod: SignMethod, params?: TParams, isPublicApi?: false | undefined, - passParamsAsQueryString?: boolean, ): Promise>; - private async prepareSignParams( + private async prepareSignParams< + TParams extends ParamsInQueryAndOrBody | undefined, + >( method: Method, endpoint: string, signMethod: SignMethod, params?: TParams, isPublicApi?: boolean, - passParamsAsQueryString?: boolean, ) { if (isPublicApi) { return { @@ -418,13 +440,7 @@ export abstract class BaseRestClient { throw new Error(MISSING_API_KEYS_ERROR); } - return this.signRequest( - params, - endpoint, - method, - signMethod, - passParamsAsQueryString, - ); + return this.signRequest(params, endpoint, method, signMethod); } /** Returns an axios request object. Handles signing process automatically if this is a private API call */ @@ -432,9 +448,8 @@ export abstract class BaseRestClient { method: Method, endpoint: string, url: string, - params?: any, + params?: ParamsInQueryAndOrBody, isPublicApi?: boolean, - passParamsAsQueryString?: boolean, ): Promise { const options: AxiosRequestConfig = { ...this.globalRequestOptions, @@ -442,16 +457,14 @@ export abstract class BaseRestClient { method: method, }; - for (const key in params) { - if (typeof params[key] === 'undefined') { - delete params[key]; - } - } + deleteUndefinedValues(params); + deleteUndefinedValues(params?.body); + deleteUndefinedValues(params?.query); if (isPublicApi || !this.apiKey || !this.apiSecret) { return { ...options, - params: params, + params: params?.query || params?.body || params, }; } @@ -461,7 +474,6 @@ export abstract class BaseRestClient { 'gateV4', params, isPublicApi, - passParamsAsQueryString, ); const authHeaders = { @@ -471,14 +483,17 @@ export abstract class BaseRestClient { // 'X-Client-Request-Id': 'todo' }; - if (method === 'GET' || passParamsAsQueryString) { + const urlWithQueryParams = + options.url + '?' + signResult.queryParamsWithSign; + + if (method === 'GET' || !params?.body) { return { ...options, headers: { ...authHeaders, ...options.headers, }, - url: options.url + '?' + signResult.queryParamsWithSign, + url: urlWithQueryParams, }; } @@ -488,7 +503,8 @@ export abstract class BaseRestClient { ...authHeaders, ...options.headers, }, - data: signResult.originalParams, + url: params?.query ? urlWithQueryParams : options.url, + data: signResult.originalParams.body, }; } } From eece3c229de504d088267958046ba231aa3ab2ad Mon Sep 17 00:00:00 2001 From: Tiago Siebler Date: Mon, 20 May 2024 18:05:49 +0100 Subject: [PATCH 22/36] fix(): test fn name --- test/REST/private.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/REST/private.test.ts b/test/REST/private.test.ts index 74e239d..1ba0706 100644 --- a/test/REST/private.test.ts +++ b/test/REST/private.test.ts @@ -56,7 +56,7 @@ describe('REST PRIVATE', () => { test('with params as request body', async () => { try { - const res = await rest.getSubToSubTransfer({ + const res = await rest.submitSubToSubTransfer({ currency: 'BTC', sub_account_from: 'notReal1', sub_account_from_type: 'spot', From d894caf76e6590584cf6453a827b4d77de2f48c5 Mon Sep 17 00:00:00 2001 From: Tiago Siebler Date: Mon, 20 May 2024 18:15:24 +0100 Subject: [PATCH 23/36] chore(): refactor body to query mapping --- src/RestClient.ts | 46 +++++++++++++++++++++++----------------------- 1 file changed, 23 insertions(+), 23 deletions(-) diff --git a/src/RestClient.ts b/src/RestClient.ts index 81627a9..29c55a2 100644 --- a/src/RestClient.ts +++ b/src/RestClient.ts @@ -129,7 +129,7 @@ export class RestClient extends BaseRestClient { * @param params Withdrawal parameters * @returns Promise> */ - submitWithdraw(body: { + submitWithdraw(params: { withdraw_order_id?: string; amount: string; currency: string; @@ -137,7 +137,7 @@ export class RestClient extends BaseRestClient { memo?: string; chain: string; }): Promise> { - return this.postPrivate('/withdrawals', { body }); + return this.postPrivate('/withdrawals', { query: params }); } /** @@ -1029,7 +1029,7 @@ export class RestClient extends BaseRestClient { account?: 'spot' | 'margin' | 'cross_margin' | 'unified'; action_mode?: 'ACK' | 'RESULT' | 'FULL'; }): Promise> { - return this.deletePrivate('/spot/orders', { body: params }); + return this.deletePrivate('/spot/orders', { query: params }); } /** @@ -1104,7 +1104,7 @@ export class RestClient extends BaseRestClient { */ deleteSpotOrder(params: DeleteSpotOrderReq): Promise> { return this.deletePrivate(`/spot/orders/${params.order_id}`, { - body: params, + query: params, }); } @@ -1212,7 +1212,7 @@ export class RestClient extends BaseRestClient { market?: string; account?: 'normal' | 'margin' | 'cross_margin'; }): Promise> { - return this.deletePrivate('/spot/price_orders', { body: params }); + return this.deletePrivate('/spot/price_orders', { query: params }); } /** @@ -1237,7 +1237,7 @@ export class RestClient extends BaseRestClient { order_id: string; }): Promise> { return this.deletePrivate(`/spot/price_orders/${params.order_id}`, { - body: params, + query: params, }); } @@ -2497,7 +2497,7 @@ export class RestClient extends BaseRestClient { }): Promise> { return this.postPrivate( `/futures/${params.settle}/positions/${params.contract}/margin`, - { body: params }, + { query: params }, ); } @@ -2533,7 +2533,7 @@ export class RestClient extends BaseRestClient { }): Promise> { return this.postPrivate( `/futures/${params.settle}/positions/${params.contract}/risk_limit`, - { body: params }, + { query: params }, ); } @@ -2604,7 +2604,7 @@ export class RestClient extends BaseRestClient { }> > { return this.postPrivate(`/futures/${params.settle}/dual_mode`, { - body: params, + query: params, }); } @@ -2638,7 +2638,7 @@ export class RestClient extends BaseRestClient { }): Promise> { return this.postPrivate( `/futures/${params.settle}/dual_comp/positions/${params.contract}/margin`, - { body: params }, + { query: params }, ); } @@ -2656,7 +2656,7 @@ export class RestClient extends BaseRestClient { }): Promise> { return this.postPrivate( `/futures/${params.settle}/dual_comp/positions/${params.contract}/leverage`, - { body: params }, + { query: params }, ); } @@ -2673,7 +2673,7 @@ export class RestClient extends BaseRestClient { }): Promise> { return this.postPrivate( `/futures/${params.settle}/dual_comp/positions/${params.contract}/risk_limit`, - { body: params }, + { query: params }, ); } @@ -2733,7 +2733,7 @@ export class RestClient extends BaseRestClient { side?: string; }): Promise> { return this.deletePrivate(`/futures/${params.settle}/orders`, { - body: params, + query: params, }); } @@ -3190,7 +3190,7 @@ export class RestClient extends BaseRestClient { contract: string; }): Promise> { return this.deletePrivate(`/futures/${params.settle}/price_orders`, { - body: params, + query: params, }); } @@ -3222,7 +3222,7 @@ export class RestClient extends BaseRestClient { }): Promise> { return this.deletePrivate( `/futures/${params.settle}/price_orders/${params.order_id}`, - { body: params }, + { query: params }, ); } /**========================================================================================================================== @@ -3621,7 +3621,7 @@ export class RestClient extends BaseRestClient { }): Promise> { return this.postPrivate( `/delivery/${params.settle}/positions/${params.contract}/margin`, - { body: params }, + { query: params }, ); } @@ -3638,7 +3638,7 @@ export class RestClient extends BaseRestClient { }): Promise> { return this.postPrivate( `/delivery/${params.settle}/positions/${params.contract}/leverage`, - { body: params }, + { query: params }, ); } @@ -3655,7 +3655,7 @@ export class RestClient extends BaseRestClient { }): Promise> { return this.postPrivate( `/delivery/${params.settle}/positions/${params.contract}/risk_limit`, - { body: params }, + { query: params }, ); } @@ -3710,7 +3710,7 @@ export class RestClient extends BaseRestClient { side?: 'ask' | 'bid'; }): Promise> { return this.deletePrivate(`/delivery/${params.settle}/orders`, { - body: params, + query: params, }); } @@ -3963,7 +3963,7 @@ export class RestClient extends BaseRestClient { contract: string; }): Promise> { return this.deletePrivate(`/delivery/${params.settle}/price_orders`, { - body: params, + query: params, }); } @@ -4895,7 +4895,7 @@ export class RestClient extends BaseRestClient { }[] > > { - return this.deletePrivate(`/options/orders`, { body: params }); + return this.deletePrivate(`/options/orders`, { query: params }); } /** @@ -5184,7 +5184,7 @@ export class RestClient extends BaseRestClient { currency?: string; min_rate?: string; }): Promise> { - return this.patchPrivate(`/earn/uni/lends`, { body: params }); + return this.patchPrivate(`/earn/uni/lends`, { query: params }); } /** @@ -6517,7 +6517,7 @@ export class RestClient extends BaseRestClient { > > { return this.deletePrivate(`/account/stp_groups/${params.stp_id}/users`, { - body: params, + query: params, }); } From 660ab71443f73344583234b9a55a9b2ed4cf3c33 Mon Sep 17 00:00:00 2001 From: Jerko J <83344666+JJ-Cro@users.noreply.github.com> Date: Mon, 20 May 2024 23:12:26 +0200 Subject: [PATCH 24/36] chore(): refactoring types and requests --- src/RestClient.ts | 88 +++++++++++++----------------- src/types/requests/shared.types.ts | 34 ++++++++++++ 2 files changed, 72 insertions(+), 50 deletions(-) diff --git a/src/RestClient.ts b/src/RestClient.ts index 29c55a2..eb34b1a 100644 --- a/src/RestClient.ts +++ b/src/RestClient.ts @@ -1,6 +1,7 @@ // double check if schemas are requests // double check if names are set to what the call represents(get, delete, update etc...) // check where query params and body is as it should be +// check all inputs where we have a link import { AxiosRequestConfig } from 'axios'; @@ -11,6 +12,7 @@ import { } from './lib/BaseRestClient.js'; import { RestClientOptions } from './lib/requestUtils.js'; import { + CreateSubAccountApiKeyReq, DeleteSpotOrderReq, GetCrossMarginAccountHistoryReq, GetCrossMarginBorrowHistoryReq, @@ -38,6 +40,8 @@ import { SubmitSpotOrderReq, SubmitUnifiedBorrowOrRepayReq, UpdateSpotBatchOrdersReq, + UpdateSpotOrderReq, + UpdateSubAccountApiKeyReq, } from './types/requests/shared.types.js'; import { APIResponse, @@ -236,7 +240,7 @@ export class RestClient extends BaseRestClient { currency_pair?: string; settle?: string; }): Promise> { - return this.postPrivate('/wallet/transfers', { body }); + return this.postPrivate('/wallet/transfers', { body: body }); } /** @@ -255,7 +259,7 @@ export class RestClient extends BaseRestClient { client_order_id?: string; sub_account_type?: 'spot' | 'futures' | 'cross_margin' | 'delivery'; }): Promise> { - return this.postPrivate('/wallet/sub_account_transfers', { body }); + return this.postPrivate('/wallet/sub_account_transfers', { body: body }); } /** @@ -291,7 +295,9 @@ export class RestClient extends BaseRestClient { sub_account_to_type: 'spot' | 'futures' | 'delivery' | 'cross_margin'; amount: string; }): Promise> { - return this.postPrivate('/wallet/sub_account_to_sub_account', { body }); + return this.postPrivate('/wallet/sub_account_to_sub_account', { + body: body, + }); } /** @@ -423,10 +429,10 @@ export class RestClient extends BaseRestClient { * @param params Parameters for converting small balance * @returns Promise> */ - convertSmallBalance(body: { + convertSmallBalance(body?: { currency?: string[]; }): Promise> { - return this.postPrivate('/wallet/small_balance', { body }); + return this.postPrivate('/wallet/small_balance', { body: body }); } /** @@ -458,7 +464,7 @@ export class RestClient extends BaseRestClient { password?: string; email?: string; }): Promise> { - return this.postPrivate('/sub_accounts', { body }); + return this.postPrivate('/sub_accounts', { body: body }); } /** @@ -492,14 +498,11 @@ export class RestClient extends BaseRestClient { * @param params Parameters for creating API Key of the sub-account * @returns Promise> */ - createSubAccountApiKey( - params: { - user_id: number; - }, - body: SubAccountKey, + params: CreateSubAccountApiKeyReq, ): Promise> { - return this.postPrivate(`/sub_accounts/${params.user_id}/keys`, { body }); + const { user_id, ...body } = params; + return this.postPrivate(`/sub_accounts/${user_id}/keys`, { body: body }); } /** * List all API Key of the sub-account @@ -520,16 +523,10 @@ export class RestClient extends BaseRestClient { * @returns Promise> */ updateSubAccountApiKey( - params: { - user_id: number; - key: string; - }, - body: SubAccountKey, + params: UpdateSubAccountApiKeyReq, ): Promise> { - return this.putPrivate( - `/sub_accounts/${params.user_id}/keys/${params.key}`, - { body }, - ); + const { user_id, key, ...body } = params; + return this.putPrivate(`/sub_accounts/${user_id}/keys/${key}`, { body }); } /** @@ -651,7 +648,7 @@ export class RestClient extends BaseRestClient { submitUnifiedBorrowOrRepay( body: SubmitUnifiedBorrowOrRepayReq, ): Promise> { - return this.postPrivate('/unified/loans', { body }); + return this.postPrivate('/unified/loans', { body: body }); } /** @@ -712,7 +709,7 @@ export class RestClient extends BaseRestClient { setUnifiedAccountMode( body: SetUnifiedAccountModeReq, ): Promise> { - return this.putPrivate('/unified/unified_mode', { body }); + return this.putPrivate('/unified/unified_mode', { body: body }); } /** @@ -766,7 +763,7 @@ export class RestClient extends BaseRestClient { portfolioMarginCalculator( body: PortfolioMarginCalculatorReq, ): Promise> { - return this.post('/unified/portfolio_calculator', { body }); + return this.post('/unified/portfolio_calculator', { body: body }); } /**========================================================================================================================== @@ -955,7 +952,7 @@ export class RestClient extends BaseRestClient { submitSpotBatchOrders( body: Order[], ): Promise> { - return this.postPrivate('/spot/batch_orders', { body }); + return this.postPrivate('/spot/batch_orders', { body: body }); } /** @@ -987,7 +984,7 @@ export class RestClient extends BaseRestClient { submitSpotClosePosCrossDisabled( body: SubmitSpotClosePosCrossDisabledReq, ): Promise> { - return this.postPrivate('/spot/cross_liquidate_orders', { body }); + return this.postPrivate('/spot/cross_liquidate_orders', { body: body }); } /** @@ -999,7 +996,7 @@ export class RestClient extends BaseRestClient { * @returns Promise> */ submitSpotOrder(body: SubmitSpotOrderReq): Promise> { - return this.postPrivate('/spot/orders', { body }); + return this.postPrivate('/spot/orders', { body: body }); } /** @@ -1043,7 +1040,7 @@ export class RestClient extends BaseRestClient { deleteSpotBatchOrders( body: CancelBatchOrder[], ): Promise> { - return this.postPrivate('/spot/cancel_batch_orders', { body }); + return this.postPrivate('/spot/cancel_batch_orders', { body: body }); } /** @@ -1072,15 +1069,7 @@ export class RestClient extends BaseRestClient { * @param params Parameters for amending an order * @returns Promise> */ - updateSpotOrder(params: { - order_id: string; - currency_pair: string; - account?: 'spot' | 'margin' | 'cross_margin' | 'unified'; - amount?: string; - price?: string; - amend_text?: string; - action_mode?: 'ACK' | 'RESULT' | 'FULL'; - }): Promise> { + updateSpotOrder(params: UpdateSpotOrderReq): Promise> { const { order_id, currency_pair, account, ...body } = params; const query = { @@ -1089,8 +1078,8 @@ export class RestClient extends BaseRestClient { }; return this.patchPrivate(`/spot/orders/${order_id}`, { - query, - body, + query: query, + body: body, }); } @@ -1103,8 +1092,9 @@ export class RestClient extends BaseRestClient { * @returns Promise> */ deleteSpotOrder(params: DeleteSpotOrderReq): Promise> { - return this.deletePrivate(`/spot/orders/${params.order_id}`, { - query: params, + const { order_id, ...query } = params; + return this.deletePrivate(`/spot/orders/${order_id}`, { + query: query, }); } @@ -1157,7 +1147,7 @@ export class RestClient extends BaseRestClient { triggerTime: number; }> > { - return this.postPrivate('/spot/countdown_cancel_all', { body }); + return this.postPrivate('/spot/countdown_cancel_all', { body: body }); } /** @@ -1171,7 +1161,7 @@ export class RestClient extends BaseRestClient { updateSpotBatchOrders( body: UpdateSpotBatchOrdersReq[], ): Promise> { - return this.postPrivate('/spot/amend_batch_orders', { body }); + return this.postPrivate('/spot/amend_batch_orders', { body: body }); } /** @@ -1187,7 +1177,7 @@ export class RestClient extends BaseRestClient { id: number; }> > { - return this.postPrivate('/spot/price_orders', { body }); + return this.postPrivate('/spot/price_orders', { body: body }); } /** @@ -1224,7 +1214,7 @@ export class RestClient extends BaseRestClient { getPriceTriggeredOrder(params: { order_id: string; }): Promise> { - return this.getPrivate(`/spot/price_orders/${params.order_id}`, params); + return this.getPrivate(`/spot/price_orders/${params.order_id}`); } /** @@ -1236,9 +1226,7 @@ export class RestClient extends BaseRestClient { deleteSpotPriceTriggeredOrder(params: { order_id: string; }): Promise> { - return this.deletePrivate(`/spot/price_orders/${params.order_id}`, { - query: params, - }); + return this.deletePrivate(`/spot/price_orders/${params.order_id}`); } /**========================================================================================================================== @@ -1399,7 +1387,7 @@ export class RestClient extends BaseRestClient { submitCrossMarginBorrowLoan( body: SubmitCrossMarginBorrowLoanReq, ): Promise> { - return this.postPrivate('/margin/cross/loans', { body }); + return this.postPrivate('/margin/cross/loans', { body: body }); } /** @@ -1439,7 +1427,7 @@ export class RestClient extends BaseRestClient { currency: string; amount: string; }): Promise> { - return this.postPrivate('/margin/cross/repayments', { body }); + return this.postPrivate('/margin/cross/repayments', { body: body }); } /** diff --git a/src/types/requests/shared.types.ts b/src/types/requests/shared.types.ts index 49733f8..bb94487 100644 --- a/src/types/requests/shared.types.ts +++ b/src/types/requests/shared.types.ts @@ -14,6 +14,30 @@ export interface GetMainSubTransfersReq { offset?: number; } +export interface CreateSubAccountApiKeyReq { + user_id: number; + mode?: number; // Mode: 1 - classic, 2 - portfolio account + name?: string; // API key name + perms?: { + name?: + | 'wallet' + | 'spot' + | 'futures' + | 'delivery' + | 'earn' + | 'options' + | 'account' + | 'unified' + | 'loan'; // Permission name + read_only?: boolean; // Read only + }[]; + ip_whitelist?: string[]; // IP white list +} + +export interface UpdateSubAccountApiKeyReq extends CreateSubAccountApiKeyReq { + key: string; +} + export interface GetSavedAddressReq { currency: string; chain?: string; @@ -213,6 +237,16 @@ export interface SubmitSpotOrderReq { stp_act?: string; action_mode?: string; } + +export interface UpdateSpotOrderReq { + order_id: string; + currency_pair: string; + account?: 'spot' | 'margin' | 'cross_margin' | 'unified'; + amount?: string; + price?: string; + amend_text?: string; + action_mode?: 'ACK' | 'RESULT' | 'FULL'; +} /**========================================================================================================================== * MARGIN * ========================================================================================================================== From f1a77ac2369c6bea6bb5cc29055ac81f79eadd26 Mon Sep 17 00:00:00 2001 From: Jerko J <83344666+JJ-Cro@users.noreply.github.com> Date: Tue, 21 May 2024 10:21:36 +0200 Subject: [PATCH 25/36] chore(): Refactoring types --- src/RestClient.ts | 441 ++++++++++------------------------------------ 1 file changed, 93 insertions(+), 348 deletions(-) diff --git a/src/RestClient.ts b/src/RestClient.ts index eb34b1a..516d806 100644 --- a/src/RestClient.ts +++ b/src/RestClient.ts @@ -1,7 +1,7 @@ // double check if schemas are requests // double check if names are set to what the call represents(get, delete, update etc...) -// check where query params and body is as it should be -// check all inputs where we have a link +// check in all non-get calls that query params and body params are as it should be +// check all inputs where we have a path to make sure all is right. import { AxiosRequestConfig } from 'axios'; @@ -18,8 +18,16 @@ import { GetCrossMarginBorrowHistoryReq, GetCrossMarginInterestRecordsReq, GetCrossMarginRepaymentsReq, + GetFlashSwapOrdersReq, + GetFuturesCandlesticksReq, + GetFuturesOrderBookReq, + GetFuturesTradesReq, GetMainSubTransfersReq, GetMarginBalanceHistoryReq, + GetMarginUNIInterestRecordsReq, + GetMarginUNILoanRecordsReq, + GetMarginUNILoansReq, + GetMarginUNIMaxBorrowReq, GetSavedAddressReq, GetSmallBalanceHistoryReq, GetSpotAccountBookReq, @@ -36,6 +44,8 @@ import { PortfolioMarginCalculatorReq, SetUnifiedAccountModeReq, SubmitCrossMarginBorrowLoanReq, + SubmitFlashSwapOrderPreviewReq, + SubmitFlashSwapOrderReq, SubmitSpotClosePosCrossDisabledReq, SubmitSpotOrderReq, SubmitUnifiedBorrowOrRepayReq, @@ -48,13 +58,23 @@ import { CreateDepositAddressResp, CreateSubAccountApiKeyResp, DeleteSpotBatchOrdersResp, + FlashSwapOrderResp, GetBalancesResp, GetCrossMarginAccountHistoryResp, GetCrossMarginAccountResp, GetCrossMarginCurrenciesResp, GetCurrencyChainsResp, + GetFlashSwapCurrencyPairsResp, + GetFuturesCandlesticksResp, + GetFuturesOrderBookResp, + GetFuturesTradesResp, + GetLendingMarketsResp, GetMarginAccountsResp, GetMarginBalanceHistoryResp, + GetMarginUNIInterestRecordsResp, + GetMarginUNILoanRecordsResp, + GetMarginUNILoansResp, + GetMarginUNIMaxBorrowResp, GetSavedAddressResp, GetSmallBalanceHistoryResp, GetSmallBalancesResp, @@ -84,6 +104,7 @@ import { SubAccountResp, SubAccountTransferRecordResp, SubmitCrossMarginBorrowLoanResp, + SubmitFlashSwapOrderPreviewResp, SubmitSpotBatchOrdersResp, } from './types/response/shared.types.js'; import { @@ -1513,23 +1534,9 @@ export class RestClient extends BaseRestClient { /** * List lending markets * - * @returns Promise> + * @returns Promise> */ - getLendingMarkets(): Promise< - APIResponse< - { - currency_pair: string; - base_min_borrow_amount: string; - quote_min_borrow_amount: string; - leverage: string; - }[] - > - > { + getLendingMarkets(): Promise> { return this.get('/margin/uni/currency_pairs'); } @@ -1544,14 +1551,9 @@ export class RestClient extends BaseRestClient { * leverage: string; * }>> */ - getLendingMarket(params: { currency_pair: string }): Promise< - APIResponse<{ - currency_pair: string; - base_min_borrow_amount: string; - quote_min_borrow_amount: string; - leverage: string; - }> - > { + getLendingMarket(params: { + currency_pair: string; + }): Promise> { return this.get(`/margin/uni/currency_pairs/${params.currency_pair}`); } @@ -1561,11 +1563,11 @@ export class RestClient extends BaseRestClient { * Please note that the interest rates are subject to change based on the borrowing and lending demand, and therefore, the provided rates may not be entirely accurate. * * @param params Parameters for retrieving estimated interest rates - * @returns Promise>> + * @returns Promise> */ estimateInterestRate(params: { currencies: string[]; - }): Promise>> { + }): Promise> { return this.getPrivate('/margin/uni/estimate_rate', params); } @@ -1573,48 +1575,27 @@ export class RestClient extends BaseRestClient { * Borrow or repay * * @param params Parameters for borrowing or repaying - * @returns Promise + * @returns Promise */ submitMarginUNIBorrowOrRepay(body: { currency: string; type: 'borrow' | 'repay'; amount: string; - repaid_all?: boolean; currency_pair: string; - }): Promise { - return this.postPrivate('/margin/uni/loans', { body }); + repaid_all?: boolean; + }): Promise { + return this.postPrivate('/margin/uni/loans', { body: body }); } /** * List loans * * @param params Parameters for listing loans - * @returns Promise> + * @returns Promise> */ - getMarginUNILoans(params?: { - currency_pair?: string; - currency?: string; - page?: number; - limit?: number; - }): Promise< - APIResponse< - { - currency: string; - currency_pair: string; - amount: string; - type: string; - create_time: number; - update_time: number; - }[] - > - > { + getMarginUNILoans( + params?: GetMarginUNILoansReq, + ): Promise> { return this.getPrivate('/margin/uni/loans', params); } @@ -1622,31 +1603,11 @@ export class RestClient extends BaseRestClient { * Get loan records * * @param params Parameters for retrieving loan records - * @returns Promise> + * @returns Promise> */ - getMarginUNILoanRecords(params?: { - type?: 'borrow' | 'repay'; - currency?: string; - currency_pair?: string; - page?: number; - limit?: number; - }): Promise< - APIResponse< - { - type: string; - currency_pair: string; - currency: string; - amount: string; - create_time: number; - }[] - > - > { + getMarginUNILoanRecords( + params?: GetMarginUNILoanRecordsReq, + ): Promise> { return this.getPrivate('/margin/uni/loan_records', params); } @@ -1654,36 +1615,11 @@ export class RestClient extends BaseRestClient { * List interest records * * @param params Parameters for listing interest records - * @returns Promise> + * @returns Promise> */ - getMarginUNIInterestRecords(params?: { - currency_pair?: string; - currency?: string; - page?: number; - limit?: number; - from?: number; - to?: number; - }): Promise< - APIResponse< - { - currency: string; - currency_pair: string; - actual_rate: string; - interest: string; - status: number; - type: string; - create_time: number; - }[] - > - > { + getMarginUNIInterestRecords( + params?: GetMarginUNIInterestRecordsReq, + ): Promise> { return this.getPrivate('/margin/uni/interest_records', params); } @@ -1691,25 +1627,13 @@ export class RestClient extends BaseRestClient { * Get maximum borrowable * * @param params Parameters for retrieving the maximum borrowable amount - * @returns Promise> + * @returns Promise> */ - getMarginUNIMaxBorrow(params: { - currency: string; - currency_pair: string; - }): Promise< - APIResponse<{ - currency: string; - currency_pair: string; - borrowable: string; - }> - > { + getMarginUNIMaxBorrow( + params: GetMarginUNIMaxBorrowReq, + ): Promise> { return this.getPrivate('/margin/uni/borrowable', params); } - /**========================================================================================================================== * FLASH SWAP * ========================================================================================================================== @@ -1719,29 +1643,11 @@ export class RestClient extends BaseRestClient { * List All Supported Currency Pairs In Flash Swap * * @param params Parameters for retrieving data of the specified currency - * @returns Promise> + * @returns Promise> */ - getFlashSwapCurrencyPairs(params?: { currency?: string }): Promise< - APIResponse< - { - currency_pair: string; - sell_currency: string; - buy_currency: string; - sell_min_amount: string; - sell_max_amount: string; - buy_min_amount: string; - buy_max_amount: string; - }[] - > - > { + getFlashSwapCurrencyPairs(params?: { + currency?: string; + }): Promise> { return this.get('/flash_swap/currency_pairs', params); } @@ -1751,78 +1657,23 @@ export class RestClient extends BaseRestClient { * Initiate a flash swap preview in advance because order creation requires a preview result. * * @param params Parameters for creating a flash swap order - * @returns Promise> + * @returns Promise> */ - submitFlashSwapOrder(body: { - preview_id: string; - sell_currency: string; - sell_amount: string; - buy_currency: string; - buy_amount: string; - }): Promise< - APIResponse<{ - id: number; - create_time: number; - user_id: number; - sell_currency: string; - sell_amount: string; - buy_currency: string; - buy_amount: string; - price: string; - status: number; - }> - > { - return this.postPrivate('/flash_swap/orders', { body }); + submitFlashSwapOrder( + body: SubmitFlashSwapOrderReq, + ): Promise> { + return this.postPrivate('/flash_swap/orders', { body: body }); } /** * List all flash swap orders * * @param params Parameters for listing flash swap orders - * @returns Promise> + * @returns Promise> */ - getFlashSwapOrders(params?: { - status?: number; - sell_currency?: string; - buy_currency?: string; - reverse?: boolean; - limit?: number; - page?: number; - }): Promise< - APIResponse< - { - id: number; - create_time: number; - user_id: number; - sell_currency: string; - sell_amount: string; - buy_currency: string; - buy_amount: string; - price: string; - status: number; - }[] - > - > { + getFlashSwapOrders( + params?: GetFlashSwapOrdersReq, + ): Promise> { return this.getPrivate('/flash_swap/orders', params); } @@ -1830,31 +1681,11 @@ export class RestClient extends BaseRestClient { * Get a single flash swap order's detail * * @param params Parameters containing the flash swap order ID - * @returns Promise> + * @returns Promise> */ - getFlashSwapOrder(params: { order_id: number }): Promise< - APIResponse<{ - id: number; - create_time: number; - user_id: number; - sell_currency: string; - sell_amount: string; - buy_currency: string; - buy_amount: string; - price: string; - status: number; - }> - > { + getFlashSwapOrder(params: { + order_id: number; + }): Promise> { return this.getPrivate(`/flash_swap/orders/${params.order_id}`); } @@ -1862,32 +1693,14 @@ export class RestClient extends BaseRestClient { * Initiate a flash swap order preview * * @param params Parameters for initiating a flash swap order preview - * @returns Promise> + * @returns Promise> */ - submitFlashSwapOrderPreview(body: { - sell_currency: string; - sell_amount?: string; - buy_currency: string; - buy_amount?: string; - }): Promise< - APIResponse<{ - preview_id: string; - sell_currency: string; - sell_amount: string; - buy_currency: string; - buy_amount: string; - price: string; - }> - > { + submitFlashSwapOrderPreview( + body: SubmitFlashSwapOrderPreviewReq, + ): Promise> { return this.postPrivate('/flash_swap/orders/preview', { body }); } + /**========================================================================================================================== * FUTURES * ========================================================================================================================== @@ -1904,7 +1717,8 @@ export class RestClient extends BaseRestClient { limit?: number; offset?: number; }): Promise> { - return this.get(`/futures/${params.settle}/contracts`, params); + const { settle, ...query } = params; + return this.get(`/futures/${settle}/contracts`, query); } /** @@ -1917,10 +1731,7 @@ export class RestClient extends BaseRestClient { settle: 'btc' | 'usdt' | 'usd'; contract: string; }): Promise> { - return this.get( - `/futures/${params.settle}/contracts/${params.contract}`, - params, - ); + return this.get(`/futures/${params.settle}/contracts/${params.contract}`); } /** @@ -1929,68 +1740,26 @@ export class RestClient extends BaseRestClient { * Bids will be sorted by price from high to low, while asks sorted reversely. * * @param params Parameters for retrieving the futures order book - * @returns Promise> + * @returns Promise> */ - getFuturesOrderBook(params: { - settle: 'btc' | 'usdt' | 'usd'; - contract: string; - interval?: string; - limit?: number; - with_id?: boolean; - }): Promise< - APIResponse<{ - id?: number; - current: number; - update: number; - asks: { p: string; s: number }[]; - bids: { p: string; s: number }[]; - }> - > { - return this.get(`/futures/${params.settle}/order_book`, params); + getFuturesOrderBook( + params: GetFuturesOrderBookReq, + ): Promise> { + const { settle, ...query } = params; + return this.get(`/futures/${settle}/order_book`, query); } /** * Futures trading history * * @param params Parameters for retrieving futures trading history - * @returns Promise> + * @returns Promise> */ - getFuturesTrades(params: { - settle: 'btc' | 'usdt' | 'usd'; - contract: string; - limit?: number; - offset?: number; - last_id?: string; - from?: number; - to?: number; - }): Promise< - APIResponse< - { - id: number; - create_time: number; - create_time_ms: number; - contract: string; - size: number; - price: string; - is_internal?: boolean; - }[] - > - > { - return this.get(`/futures/${params.settle}/trades`, params); + getFuturesTrades( + params: GetFuturesTradesReq, + ): Promise> { + const { settle, ...query } = params; + return this.get(`/futures/${settle}/trades`, query); } /** @@ -2001,37 +1770,13 @@ export class RestClient extends BaseRestClient { * Maximum of 2000 points are returned in one query. Be sure not to exceed the limit when specifying from, to and interval. * * @param params Parameters for retrieving futures candlesticks - * @returns Promise> + * @returns Promise> */ - getFuturesCandlesticks(params: { - settle: 'btc' | 'usdt' | 'usd'; - contract: string; - from?: number; - to?: number; - limit?: number; - interval?: string; - }): Promise< - APIResponse< - { - t: number; - v?: number; - c: string; - h: string; - l: string; - o: string; - sum: string; - }[] - > - > { - return this.get(`/futures/${params.settle}/candlesticks`, params); + getFuturesCandlesticks( + params: GetFuturesCandlesticksReq, + ): Promise> { + const { settle, ...query } = params; + return this.get(`/futures/${settle}/candlesticks`, query); } /** From 4b2b78a6b7cce78134f4e9a7b65afbd2f8087a7b Mon Sep 17 00:00:00 2001 From: Jerko J <83344666+JJ-Cro@users.noreply.github.com> Date: Tue, 21 May 2024 10:21:50 +0200 Subject: [PATCH 26/36] chore(): refactoring types --- src/types/requests/shared.types.ts | 94 +++++++++++++++++++++++++ src/types/response/shared.types.ts | 109 +++++++++++++++++++++++++++++ 2 files changed, 203 insertions(+) diff --git a/src/types/requests/shared.types.ts b/src/types/requests/shared.types.ts index bb94487..dd25eb4 100644 --- a/src/types/requests/shared.types.ts +++ b/src/types/requests/shared.types.ts @@ -305,3 +305,97 @@ export interface GetCrossMarginInterestRecordsReq { * MARGIN UNI * ========================================================================================================================== */ + +export interface GetMarginUNILoansReq { + currency_pair?: string; + currency?: string; + page?: number; + limit?: number; +} + +export interface GetMarginUNILoanRecordsReq { + type?: 'borrow' | 'repay'; + currency?: string; + currency_pair?: string; + page?: number; + limit?: number; +} + +export interface GetMarginUNIInterestRecordsReq { + currency_pair?: string; + currency?: string; + page?: number; + limit?: number; + from?: number; + to?: number; +} + +export interface GetMarginUNIMaxBorrowReq { + currency: string; + currency_pair: string; +} + +/**========================================================================================================================== + * FLASH SWAP + * ========================================================================================================================== + */ + +export interface SubmitFlashSwapOrderReq { + preview_id: string; + sell_currency: string; + sell_amount: string; + buy_currency: string; + buy_amount: string; +} + +export interface GetFlashSwapOrdersReq { + status?: number; + sell_currency?: string; + buy_currency?: string; + reverse?: boolean; + limit?: number; + page?: number; +} + +export interface GetFlashSwapOrderReq { + order_id: number; +} + +export interface SubmitFlashSwapOrderPreviewReq { + sell_currency: string; + sell_amount?: string; + buy_currency: string; + buy_amount?: string; +} + +/**========================================================================================================================== + * FUTURES + * ========================================================================================================================== + */ + +export interface GetFuturesOrderBookReq { + settle: 'btc' | 'usdt' | 'usd'; + contract: string; + interval?: string; + limit?: number; + with_id?: boolean; +} + +export interface GetFuturesTradesReq { + settle: 'btc' | 'usdt' | 'usd'; + contract: string; + limit?: number; + offset?: number; + last_id?: string; + from?: number; + to?: number; +} + +export interface GetFuturesCandlesticksReq { + settle: 'btc' | 'usdt' | 'usd'; + contract: string; + from?: number; + to?: number; + limit?: number; + interval?: string; +} diff --git a/src/types/response/shared.types.ts b/src/types/response/shared.types.ts index af10b5f..0933a83 100644 --- a/src/types/response/shared.types.ts +++ b/src/types/response/shared.types.ts @@ -655,3 +655,112 @@ export interface SubmitCrossMarginBorrowLoanResp { * MARGIN UNI * ========================================================================================================================== */ + +export interface GetLendingMarketsResp { + currency_pair: string; + base_min_borrow_amount: string; + quote_min_borrow_amount: string; + leverage: string; +} + +export interface GetMarginUNILoansResp { + currency: string; + currency_pair: string; + amount: string; + type: string; + create_time: number; + update_time: number; +} + +export interface GetMarginUNILoanRecordsResp { + type: string; + currency_pair: string; + currency: string; + amount: string; + create_time: number; +} + +export interface GetMarginUNIInterestRecordsResp { + currency: string; + currency_pair: string; + actual_rate: string; + interest: string; + status: number; + type: string; + create_time: number; +} + +export interface GetMarginUNIMaxBorrowResp { + currency: string; + currency_pair: string; + borrowable: string; +} + +/**========================================================================================================================== + * FLASH SWAP + * ========================================================================================================================== + */ + +export interface GetFlashSwapCurrencyPairsResp { + currency_pair: string; + sell_currency: string; + buy_currency: string; + sell_min_amount: string; + sell_max_amount: string; + buy_min_amount: string; + buy_max_amount: string; +} + +export interface FlashSwapOrderResp { + id: number; + create_time: number; + user_id: number; + sell_currency: string; + sell_amount: string; + buy_currency: string; + buy_amount: string; + price: string; + status: number; +} + +export interface SubmitFlashSwapOrderPreviewResp { + preview_id: string; + sell_currency: string; + sell_amount: string; + buy_currency: string; + buy_amount: string; + price: string; +} + +/**========================================================================================================================== + * FUTURES + * ========================================================================================================================== + */ + +export interface GetFuturesOrderBookResp { + id?: number; + current: number; + update: number; + asks: { p: string; s: number }[]; + bids: { p: string; s: number }[]; +} + +export interface GetFuturesTradesResp { + id: number; + create_time: number; + create_time_ms: number; + contract: string; + size: number; + price: string; + is_internal?: boolean; +} + +export interface GetFuturesCandlesticksResp { + t: number; + v?: number; + c: string; + h: string; + l: string; + o: string; + sum: string; +} From d3ee76eedef39988c2c006b3fcc11d2c026a2c2b Mon Sep 17 00:00:00 2001 From: Jerko J <83344666+JJ-Cro@users.noreply.github.com> Date: Tue, 21 May 2024 15:43:38 +0200 Subject: [PATCH 27/36] chore(): refactoring types --- examples/rest-private.ts | 4 +- src/RestClient.ts | 904 +++++++---------------------- src/types/requests/shared.types.ts | 152 +++++ src/types/response/shared.types.ts | 207 +++++++ 4 files changed, 562 insertions(+), 705 deletions(-) diff --git a/examples/rest-private.ts b/examples/rest-private.ts index 7ef20a6..13bfd8e 100644 --- a/examples/rest-private.ts +++ b/examples/rest-private.ts @@ -3,10 +3,10 @@ import { RestClient } from '../src'; async function start() { try { const account = { - key: process.env.API_KEY || '8b8eff02d6b6105d195e81684017a43d', + key: process.env.API_KEY || 'a4ed617b3c02b6a9d4900be5446f402d', secret: process.env.API_SECRET || - '545055d0b75c9c2f9234369990bac79e3df4d2c9cda852a8531be65d901f5719', + '68151540a9808cd12bb57ed31e2fa868f5022879bf969eb27cfd7125c0dcea6e', }; console.log('using creds: ', account); diff --git a/src/RestClient.ts b/src/RestClient.ts index 516d806..2dd7b29 100644 --- a/src/RestClient.ts +++ b/src/RestClient.ts @@ -13,21 +13,33 @@ import { import { RestClientOptions } from './lib/requestUtils.js'; import { CreateSubAccountApiKeyReq, + DeleteAllFuturesOrdersReq, DeleteSpotOrderReq, GetCrossMarginAccountHistoryReq, GetCrossMarginBorrowHistoryReq, GetCrossMarginInterestRecordsReq, GetCrossMarginRepaymentsReq, GetFlashSwapOrdersReq, + GetFuturesAccountBookReq, + GetFuturesAutoOrdersReq, GetFuturesCandlesticksReq, + GetFuturesLiquidationHistoryReq, GetFuturesOrderBookReq, + GetFuturesOrdersByTimeRangeReq, + GetFuturesOrdersReq, + GetFuturesPositionHistoryReq, + GetFuturesPositionsReq, + GetFuturesStatsReq, GetFuturesTradesReq, + GetFuturesTradingHistoryReq, + GetLiquidationHistoryReq, GetMainSubTransfersReq, GetMarginBalanceHistoryReq, GetMarginUNIInterestRecordsReq, GetMarginUNILoanRecordsReq, GetMarginUNILoansReq, GetMarginUNIMaxBorrowReq, + GetRiskLimitTiersReq, GetSavedAddressReq, GetSmallBalanceHistoryReq, GetSpotAccountBookReq, @@ -46,9 +58,14 @@ import { SubmitCrossMarginBorrowLoanReq, SubmitFlashSwapOrderPreviewReq, SubmitFlashSwapOrderReq, + submitFuturesBatchOrdersReq, + SubmitFuturesOrderReq, + SubmitFuturesPriceTriggeredOrderReq, SubmitSpotClosePosCrossDisabledReq, SubmitSpotOrderReq, SubmitUnifiedBorrowOrRepayReq, + UpdateDualModePositionLeverageReq, + UpdateDualModePositionMarginReq, UpdateSpotBatchOrdersReq, UpdateSpotOrderReq, UpdateSubAccountApiKeyReq, @@ -57,6 +74,7 @@ import { APIResponse, CreateDepositAddressResp, CreateSubAccountApiKeyResp, + DeleteFuturesBatchOrdersResp, DeleteSpotBatchOrdersResp, FlashSwapOrderResp, GetBalancesResp, @@ -65,16 +83,27 @@ import { GetCrossMarginCurrenciesResp, GetCurrencyChainsResp, GetFlashSwapCurrencyPairsResp, + GetFuturesAccountResp, + GetFuturesAutoDeleveragingHistoryResp, GetFuturesCandlesticksResp, + GetFuturesLiquidationHistoryResp, GetFuturesOrderBookResp, + GetFuturesPositionHistoryResp, + GetFuturesStatsResp, + GetFuturesTickersResp, GetFuturesTradesResp, + GetFuturesTradingHistoryResp, + GetIndexConstituentsResp, GetLendingMarketsResp, + GetLiquidationHistoryResp, GetMarginAccountsResp, GetMarginBalanceHistoryResp, GetMarginUNIInterestRecordsResp, GetMarginUNILoanRecordsResp, GetMarginUNILoansResp, GetMarginUNIMaxBorrowResp, + GetPremiumIndexKLineResp, + GetRiskLimitTiersResp, GetSavedAddressResp, GetSmallBalanceHistoryResp, GetSmallBalancesResp, @@ -106,6 +135,7 @@ import { SubmitCrossMarginBorrowLoanResp, SubmitFlashSwapOrderPreviewResp, SubmitSpotBatchOrdersResp, + ToggleFuturesDualModeResp, } from './types/response/shared.types.js'; import { CancelBatchOrder, @@ -1785,94 +1815,27 @@ export class RestClient extends BaseRestClient { * Maximum of 1000 points can be returned in a query. Be sure not to exceed the limit when specifying from, to and interval. * * @param params Parameters for retrieving premium index K-Line - * @returns Promise> + * @returns Promise> */ - getPremiumIndexKLine(params: { - settle: 'btc' | 'usdt' | 'usd'; - contract: string; - from?: number; - to?: number; - limit?: number; - interval?: string; - }): Promise< - APIResponse< - { - t: number; - c: string; - h: string; - l: string; - o: string; - }[] - > - > { - return this.get(`/futures/${params.settle}/premium_index`, params); + getPremiumIndexKLine( + params: GetFuturesCandlesticksReq, + ): Promise> { + const { settle, ...query } = params; + return this.get(`/futures/${settle}/premium_index`, query); } /** * List futures tickers * * @param params Parameters for listing futures tickers - * @returns Promise> + * @returns Promise> */ getFuturesTickers(params: { settle: 'btc' | 'usdt' | 'usd'; contract?: string; - }): Promise< - APIResponse< - { - contract: string; - last: string; - change_percentage: string; - total_size: string; - low_24h: string; - high_24h: string; - volume_24h: string; - volume_24h_btc?: string; - volume_24h_usd?: string; - volume_24h_base: string; - volume_24h_quote: string; - volume_24h_settle: string; - mark_price: string; - funding_rate: string; - funding_rate_indicative: string; - index_price: string; - quanto_base_rate?: string; - basis_rate: string; - basis_value: string; - lowest_ask: string; - highest_bid: string; - }[] - > - > { - return this.get(`/futures/${params.settle}/tickers`, params); + }): Promise> { + const { settle, ...query } = params; + return this.get(`/futures/${settle}/tickers`, query); } /** @@ -1896,7 +1859,8 @@ export class RestClient extends BaseRestClient { }[] > > { - return this.get(`/futures/${params.settle}/funding_rate`, params); + const { settle, ...query } = params; + return this.get(`/futures/${settle}/funding_rate`, query); } /** @@ -1919,84 +1883,35 @@ export class RestClient extends BaseRestClient { }[] > > { - return this.get(`/futures/${params.settle}/insurance`, params); + const { settle, ...query } = params; + return this.get(`/futures/${settle}/insurance`, query); } /** * Futures stats * * @param params Parameters for retrieving futures stats - * @returns Promise> + * @returns Promise> */ - getFuturesStats(params: { - settle: 'btc' | 'usdt' | 'usd'; - contract: string; - from?: number; - interval?: string; - limit?: number; - }): Promise< - APIResponse< - { - time: number; - lsr_taker: number; - lsr_account: number; - long_liq_size: number; - long_liq_amount: number; - long_liq_usd: number; - short_liq_size: number; - short_liq_amount: number; - short_liq_usd: number; - open_interest: number; - open_interest_usd: number; - top_lsr_account: number; - top_lsr_size: number; - }[] - > - > { - return this.get(`/futures/${params.settle}/contract_stats`, params); + getFuturesStats( + params: GetFuturesStatsReq, + ): Promise> { + const { settle, ...query } = params; + return this.get(`/futures/${settle}/contract_stats`, query); } /** * Get index constituents * * @param params Parameters for retrieving index constituents - * @returns Promise> + * @returns Promise> */ getIndexConstituents(params: { settle: 'btc' | 'usdt' | 'usd'; index: string; - }): Promise< - APIResponse<{ - index: string; - constituents: { - exchange: string; - symbols: string[]; - }[]; - }> - > { + }): Promise> { return this.get( `/futures/${params.settle}/index_constituents/${params.index}`, - params, ); } @@ -2006,34 +1921,13 @@ export class RestClient extends BaseRestClient { * Interval between from and to cannot exceed 3600. Some private fields will not be returned in public endpoints. Refer to field description for detail. * * @param params Parameters for retrieving liquidation history - * @returns Promise> + * @returns Promise> */ - getLiquidationHistory(params: { - settle: 'btc' | 'usdt' | 'usd'; - contract?: string; - from?: number; - to?: number; - limit?: number; - }): Promise< - APIResponse< - { - time: number; - contract: string; - size: number; - order_price: string; - fill_price: string; - left: number; - }[] - > - > { - return this.get(`/futures/${params.settle}/liq_orders`, params); + getLiquidationHistory( + params: GetLiquidationHistoryReq, + ): Promise> { + const { settle, ...query } = params; + return this.get(`/futures/${settle}/liq_orders`, query); } /** @@ -2044,97 +1938,25 @@ export class RestClient extends BaseRestClient { * This only takes effect when the 'contract' parameter is empty. * * @param params Parameters for listing risk limit tiers - * @returns Promise> + * @returns Promise> */ - getRiskLimitTiers(params: { - settle: 'btc' | 'usdt' | 'usd'; - contract: string; - limit?: number; - offset?: number; - }): Promise< - APIResponse< - { - tier: number; - risk_limit: string; - initial_rate: string; - maintenance_rate: string; - leverage_max: string; - contract: string; - }[] - > - > { - return this.get(`/futures/${params.settle}/risk_limit_tiers`, params); + getRiskLimitTiers( + params: GetRiskLimitTiersReq, + ): Promise> { + const { settle, ...query } = params; + return this.get(`/futures/${settle}/risk_limit_tiers`, query); } /** * Query futures account * * @param params Parameters for querying futures account - * @returns Promise> + * @returns Promise> */ - getFuturesAccount(params: { settle: 'btc' | 'usdt' | 'usd' }): Promise< - APIResponse<{ - 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; - 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; - }; - }> - > { - return this.getPrivate(`/futures/${params.settle}/accounts`, params); + getFuturesAccount(params: { + settle: 'btc' | 'usdt' | 'usd'; + }): Promise> { + return this.getPrivate(`/futures/${params.settle}/accounts`); } /** @@ -2143,47 +1965,13 @@ export class RestClient extends BaseRestClient { * If the contract field is provided, it can only filter records that include this field after 2023-10-30. * * @param params Parameters for querying account book - * @returns Promise> + * @returns Promise> */ - getFuturesAccountBook(params: { - settle: 'btc' | 'usdt' | 'usd'; - contract?: string; - limit?: number; - offset?: number; - from?: number; - to?: number; - type?: - | 'dnw' - | 'pnl' - | 'fee' - | 'refr' - | 'fund' - | 'point_dnw' - | 'point_fee' - | 'point_refr' - | 'bonus_offset'; - }): Promise< - APIResponse< - { - time: number; - change: string; - balance: string; - type: string; - text: string; - contract?: string; - trade_id: string; - }[] - > - > { - return this.getPrivate(`/futures/${params.settle}/account_book`, params); + getFuturesAccountBook( + params: GetFuturesAccountBookReq, + ): Promise> { + const { settle, ...query } = params; + return this.getPrivate(`/futures/${settle}/account_book`, query); } /** @@ -2192,15 +1980,12 @@ export class RestClient extends BaseRestClient { * @param params Parameters for listing all positions of a user * @returns Promise> */ - getFuturesPositions(params: { - settle: 'btc' | 'usdt' | 'usd'; - holding?: boolean; - limit?: number; - offset?: number; - }): Promise> { - return this.getPrivate(`/futures/${params.settle}/positions`, params); + getFuturesPositions( + params: GetFuturesPositionsReq, + ): Promise> { + const { settle, ...query } = params; + return this.getPrivate(`/futures/${settle}/positions`, query); } - /** * Get single position * @@ -2213,7 +1998,6 @@ export class RestClient extends BaseRestClient { }): Promise> { return this.getPrivate( `/futures/${params.settle}/positions/${params.contract}`, - params, ); } @@ -2228,10 +2012,10 @@ export class RestClient extends BaseRestClient { contract: string; change: string; }): Promise> { - return this.postPrivate( - `/futures/${params.settle}/positions/${params.contract}/margin`, - { query: params }, - ); + const { settle, contract, ...query } = params; + return this.postPrivate(`/futures/${settle}/positions/${contract}/margin`, { + query: query, + }); } /** @@ -2246,10 +2030,10 @@ export class RestClient extends BaseRestClient { leverage: string; cross_leverage_limit?: string; }): Promise> { - const { settle, contract, ...remainingParams } = params; + const { settle, contract, ...query } = params; return this.postPrivate( `/futures/${settle}/positions/${contract}/leverage`, - { query: remainingParams }, + { query: query }, ); } @@ -2264,9 +2048,10 @@ export class RestClient extends BaseRestClient { contract: string; risk_limit: string; }): Promise> { + const { settle, contract, ...query } = params; return this.postPrivate( - `/futures/${params.settle}/positions/${params.contract}/risk_limit`, - { query: params }, + `/futures/${settle}/positions/${contract}/risk_limit`, + { query: query }, ); } @@ -2276,68 +2061,15 @@ export class RestClient extends BaseRestClient { * Before setting dual mode, make sure all positions are closed and no orders are open. * * @param params Parameters for enabling or disabling dual mode - * @returns Promise> + * @returns Promise> */ toggleFuturesDualMode(params: { settle: 'btc' | 'usdt' | 'usd'; dual_mode: boolean; - }): Promise< - APIResponse<{ - 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; - 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; - }; - }> - > { - return this.postPrivate(`/futures/${params.settle}/dual_mode`, { - query: params, + }): Promise> { + const { settle, ...query } = params; + return this.postPrivate(`/futures/${settle}/dual_mode`, { + query: query, }); } @@ -2353,7 +2085,6 @@ export class RestClient extends BaseRestClient { }): Promise> { return this.getPrivate( `/futures/${params.settle}/dual_comp/positions/${params.contract}`, - params, ); } @@ -2363,15 +2094,13 @@ export class RestClient extends BaseRestClient { * @param params Parameters for updating position margin in dual mode * @returns Promise> */ - updateDualModePositionMargin(params: { - settle: 'btc' | 'usdt' | 'usd'; - contract: string; - change: string; - dual_side: 'dual_long' | 'dual_short'; - }): Promise> { + updateDualModePositionMargin( + params: UpdateDualModePositionMarginReq, + ): Promise> { + const { settle, contract, ...query } = params; return this.postPrivate( - `/futures/${params.settle}/dual_comp/positions/${params.contract}/margin`, - { query: params }, + `/futures/${settle}/dual_comp/positions/${contract}/margin`, + { query: query }, ); } @@ -2381,15 +2110,13 @@ export class RestClient extends BaseRestClient { * @param params Parameters for updating position leverage in dual mode * @returns Promise> */ - updateDualModePositionLeverage(params: { - settle: 'btc' | 'usdt' | 'usd'; - contract: string; - leverage: string; - cross_leverage_limit?: string; - }): Promise> { + updateDualModePositionLeverage( + params: UpdateDualModePositionLeverageReq, + ): Promise> { + const { settle, contract, ...query } = params; return this.postPrivate( - `/futures/${params.settle}/dual_comp/positions/${params.contract}/leverage`, - { query: params }, + `/futures/${settle}/dual_comp/positions/${contract}/leverage`, + { query: query }, ); } @@ -2404,9 +2131,10 @@ export class RestClient extends BaseRestClient { contract: string; risk_limit: string; }): Promise> { + const { settle, contract, ...query } = params; return this.postPrivate( - `/futures/${params.settle}/dual_comp/positions/${params.contract}/risk_limit`, - { query: params }, + `/futures/${settle}/dual_comp/positions/${contract}/risk_limit`, + { query: query }, ); } @@ -2421,15 +2149,13 @@ export class RestClient extends BaseRestClient { * Set stp_act to decide the strategy of self-trade prevention. For detailed usage, refer to the stp_act parameter in the request body. * * @param params Parameters for creating a futures order - * @returns Promise> + * @returns Promise> */ submitFuturesOrder( - params: { - settle: 'btc' | 'usdt' | 'usd'; - }, - body: FuturesOrder, + params: SubmitFuturesOrderReq, ): Promise> { - return this.postPrivate(`/futures/${params.settle}/orders`, { body }); + const { settle, ...body } = params; + return this.postPrivate(`/futures/${settle}/orders`, { body: body }); } /** @@ -2441,15 +2167,11 @@ export class RestClient extends BaseRestClient { * @param params Parameters for listing futures orders * @returns Promise> */ - getFuturesOrders(params: { - settle: 'btc' | 'usdt' | 'usd'; - contract?: string; - status: string; - limit?: number; - offset?: number; - last_id?: string; - }): Promise> { - return this.getPrivate(`/futures/${params.settle}/orders`, params); + getFuturesOrders( + params: GetFuturesOrdersReq, + ): Promise> { + const { settle, ...query } = params; + return this.getPrivate(`/futures/${settle}/orders`, query); } /** @@ -2460,13 +2182,12 @@ export class RestClient extends BaseRestClient { * @param params Parameters for cancelling all open orders matched * @returns Promise> */ - deleteAllFuturesOrders(params: { - settle: 'btc' | 'usdt' | 'usd'; - contract: string; - side?: string; - }): Promise> { - return this.deletePrivate(`/futures/${params.settle}/orders`, { - query: params, + deleteAllFuturesOrders( + params: DeleteAllFuturesOrdersReq, + ): Promise> { + const { settle, ...query } = params; + return this.deletePrivate(`/futures/${settle}/orders`, { + query: query, }); } @@ -2476,18 +2197,11 @@ export class RestClient extends BaseRestClient { * @param params Parameters for listing futures orders by time range * @returns Promise> */ - getFuturesOrdersByTimeRange(params: { - settle: 'btc' | 'usdt' | 'usd'; - contract?: string; - from?: number; - to?: number; - limit?: number; - offset?: number; - }): Promise> { - return this.getPrivate( - `/futures/${params.settle}/orders_timerange`, - params, - ); + getFuturesOrdersByTimeRange( + params: GetFuturesOrdersByTimeRangeReq, + ): Promise> { + const { settle, ...query } = params; + return this.getPrivate(`/futures/${settle}/orders_timerange`, query); } /** @@ -2502,71 +2216,13 @@ export class RestClient extends BaseRestClient { * In the rate limiting, each order is counted individually. * * @param params Parameters for creating a batch of futures orders - * @returns Promise> + * @returns Promise> */ submitFuturesBatchOrders( - params: { - settle: 'btc' | 'usdt' | 'usd'; - }, - body: FuturesOrder[], - ): Promise< - APIResponse< - { - succeeded: boolean; - label?: string; - detail?: string; - id: number; - user: number; - create_time: number; - finish_time?: number; - finish_as?: string; - status: string; - contract: string; - size: number; - iceberg: number; - price: string; - is_close: boolean; - is_reduce_only: boolean; - is_liq: boolean; - tif: string; - left: number; - fill_price: string; - text: string; - tkfr: string; - mkfr: string; - refu: number; - stp_act: string; - stp_id: number; - }[] - > - > { - return this.postPrivate(`/futures/${params.settle}/batch_orders`, { body }); + params: submitFuturesBatchOrdersReq, + ): Promise> { + const { settle, ...body } = params; + return this.postPrivate(`/futures/${settle}/batch_orders`, { body: body }); } /** @@ -2584,7 +2240,6 @@ export class RestClient extends BaseRestClient { }): Promise> { return this.getPrivate( `/futures/${params.settle}/orders/${params.order_id}`, - params, ); } @@ -2609,21 +2264,17 @@ export class RestClient extends BaseRestClient { * @param params Parameters for amending an order * @returns Promise> */ - updateFuturesOrder( - params: { - settle: 'btc' | 'usdt' | 'usd'; - order_id: string; - }, - body: { - size?: number; - price?: string; - amend_text?: string; - }, - ): Promise> { - return this.putPrivate( - `/futures/${params.settle}/orders/${params.order_id}`, - { body }, - ); + updateFuturesOrder(params: { + settle: 'btc' | 'usdt' | 'usd'; + order_id: string; + size?: number; + price?: string; + amend_text?: string; + }): Promise> { + const { settle, order_id, ...body } = params; + return this.putPrivate(`/futures/${settle}/orders/${order_id}`, { + body: body, + }); } /** @@ -2632,181 +2283,52 @@ export class RestClient extends BaseRestClient { * By default, only data within the past 6 months is supported. If you need to query data for a longer period, please use GET /futures/{settle}/my_trades_timerange. * * @param params Parameters for listing personal trading history - * @returns Promise> + * @returns Promise> */ - getFuturesTradingHistory(params: { - settle: 'btc' | 'usdt' | 'usd'; - contract?: string; - order?: number; - limit?: number; - offset?: number; - last_id?: string; - }): Promise< - APIResponse< - { - id: number; - create_time: number; - contract: string; - order_id: string; - size: number; - price: string; - role: 'taker' | 'maker'; - text: string; - fee: string; - point_fee: string; - }[] - > - > { - return this.getPrivate(`/futures/${params.settle}/my_trades`, params); + getFuturesTradingHistory( + params: GetFuturesTradingHistoryReq, + ): Promise> { + const { settle, ...query } = params; + return this.getPrivate(`/futures/${settle}/my_trades`, query); } /** * List position close history * * @param params Parameters for listing position close history - * @returns Promise> + * @returns Promise> */ - getFuturesPositionHistory(params: { - settle: 'btc' | 'usdt' | 'usd'; - contract?: string; - limit?: number; - offset?: number; - from?: number; - to?: number; - side?: 'long' | 'short'; - pnl?: string; - }): Promise< - APIResponse< - { - time: number; - contract: string; - side: 'long' | 'short'; - pnl: string; - pnl_pnl: string; - pnl_fund: string; - pnl_fee: string; - text: string; - max_size: string; - first_open_time: number; - long_price: string; - short_price: string; - }[] - > - > { - return this.getPrivate(`/futures/${params.settle}/position_close`, params); + getFuturesPositionHistory( + params: GetFuturesPositionHistoryReq, + ): Promise> { + const { settle, ...query } = params; + return this.getPrivate(`/futures/${settle}/position_close`, query); } /** * List liquidation history * * @param params Parameters for listing liquidation history - * @returns Promise> + * @returns Promise> */ - getFuturesLiquidationHistory(params: { - settle: 'btc' | 'usdt' | 'usd'; - contract?: string; - limit?: number; - at?: number; - }): Promise< - APIResponse< - { - time: number; - contract: string; - leverage: string; - size: number; - margin: string; - entry_price: string; - liq_price: string; - mark_price: string; - order_id: number; - order_price: string; - fill_price: string; - left: number; - }[] - > - > { - return this.getPrivate(`/futures/${params.settle}/liquidates`, params); + getFuturesLiquidationHistory( + params: GetFuturesLiquidationHistoryReq, + ): Promise> { + const { settle, ...query } = params; + return this.getPrivate(`/futures/${settle}/liquidates`, query); } /** * List Auto-Deleveraging History * * @param params Parameters for listing auto-deleveraging history - * @returns Promise> + * @returns Promise> */ - getFuturesAutoDeleveragingHistory(params: { - settle: 'btc' | 'usdt' | 'usd'; - contract?: string; - limit?: number; - at?: number; - }): Promise< - APIResponse< - { - time: number; - user: number; - order_id: number; - contract: string; - leverage: string; - cross_leverage_limit: string; - entry_price: string; - fill_price: string; - trade_size: number; - position_size: number; - }[] - > - > { - return this.getPrivate( - `/futures/${params.settle}/auto_deleverages`, - params, - ); + getFuturesAutoDeleveragingHistory( + params: GetFuturesLiquidationHistoryReq, + ): Promise> { + const { settle, ...query } = params; + return this.getPrivate(`/futures/${settle}/auto_deleverages`, query); } /** @@ -2819,17 +2341,14 @@ export class RestClient extends BaseRestClient { * @param params Parameters for setting countdown cancel orders * @returns Promise> */ - deleteFuturesOrdersCountdown( - params: { - settle: 'btc' | 'usdt' | 'usd'; - }, - body: { - timeout: number; - contract?: string; - }, - ): Promise> { - return this.postPrivate(`/futures/${params.settle}/countdown_cancel_all`, { - body, + deleteFuturesOrdersCountdown(params: { + settle: 'btc' | 'usdt' | 'usd'; + timeout: number; + contract?: string; + }): Promise> { + const { settle, ...body } = params; + return this.postPrivate(`/futures/${settle}/countdown_cancel_all`, { + body: body, }); } @@ -2837,15 +2356,14 @@ export class RestClient extends BaseRestClient { * Query user trading fee rates * * @param params Parameters for querying user trading fee rates - * @returns Promise>> + * @returns Promise>> */ getFuturesUserTradingFees(params: { settle: 'btc' | 'usdt' | 'usd'; contract?: string; - }): Promise< - APIResponse> - > { - return this.getPrivate(`/futures/${params.settle}/fee`, params); + }): Promise> { + const { settle, ...query } = params; + return this.getPrivate(`/futures/${settle}/fee`, query); } /** @@ -2854,30 +2372,15 @@ export class RestClient extends BaseRestClient { * Multiple distinct order ID list can be specified. Each request can cancel a maximum of 20 records. * * @param params Parameters for cancelling a batch of orders with an ID list - * @returns Promise> + * @returns Promise> */ - deleteFuturesBatchOrders( - params: { - settle: 'btc' | 'usdt' | 'usd'; - }, - body: string[], - ): Promise< - APIResponse< - { - user_id: number; - id: string; - succeeded: boolean; - message: string; - }[] - > - > { - return this.postPrivate(`/futures/${params.settle}/batch_cancel_orders`, { - body, + deleteFuturesBatchOrders(params: { + settle: 'btc' | 'usdt' | 'usd'; + body: string[]; + }): Promise> { + const { settle, ...body } = params; + return this.postPrivate(`/futures/${settle}/batch_cancel_orders`, { + body: body, }); } @@ -2888,12 +2391,10 @@ export class RestClient extends BaseRestClient { * @returns Promise> */ submitFuturesPriceTriggeredOrder( - params: { - settle: 'btc' | 'usdt' | 'usd'; - }, - body: FuturesPriceTriggeredOrder, + params: SubmitFuturesPriceTriggeredOrderReq, ): Promise> { - return this.postPrivate(`/futures/${params.settle}/price_orders`, { body }); + const { settle, ...body } = params; + return this.postPrivate(`/futures/${settle}/price_orders`, { body: body }); } /** @@ -2902,14 +2403,11 @@ export class RestClient extends BaseRestClient { * @param params Parameters for listing all auto orders * @returns Promise> */ - getFuturesAutoOrders(params: { - settle: 'btc' | 'usdt' | 'usd'; - status: 'open' | 'finished'; - contract?: string; - limit?: number; - offset?: number; - }): Promise> { - return this.getPrivate(`/futures/${params.settle}/price_orders`, params); + getFuturesAutoOrders( + params: GetFuturesAutoOrdersReq, + ): Promise> { + const { settle, ...query } = params; + return this.getPrivate(`/futures/${settle}/price_orders`, query); } /** @@ -2922,8 +2420,9 @@ export class RestClient extends BaseRestClient { settle: 'btc' | 'usdt' | 'usd'; contract: string; }): Promise> { - return this.deletePrivate(`/futures/${params.settle}/price_orders`, { - query: params, + const { settle, ...query } = params; + return this.deletePrivate(`/futures/${settle}/price_orders`, { + query: query, }); } @@ -2939,7 +2438,6 @@ export class RestClient extends BaseRestClient { }): Promise> { return this.getPrivate( `/futures/${params.settle}/price_orders/${params.order_id}`, - params, ); } @@ -2955,9 +2453,9 @@ export class RestClient extends BaseRestClient { }): Promise> { return this.deletePrivate( `/futures/${params.settle}/price_orders/${params.order_id}`, - { query: params }, ); } + /**========================================================================================================================== * DELIVERY * ========================================================================================================================== diff --git a/src/types/requests/shared.types.ts b/src/types/requests/shared.types.ts index dd25eb4..154fd01 100644 --- a/src/types/requests/shared.types.ts +++ b/src/types/requests/shared.types.ts @@ -1,3 +1,5 @@ +import { FuturesOrder, FuturesPriceTriggeredOrder } from 'types/shared'; + export interface GetWithdrawalDepositRecordsReq { currency?: string; from?: number; @@ -399,3 +401,153 @@ export interface GetFuturesCandlesticksReq { limit?: number; interval?: string; } + +export interface GetFuturesStatsReq { + settle: 'btc' | 'usdt' | 'usd'; + contract: string; + from?: number; + interval?: string; + limit?: number; +} + +export interface GetLiquidationHistoryReq { + settle: 'btc' | 'usdt' | 'usd'; + contract?: string; + from?: number; + to?: number; + limit?: number; +} + +export interface GetRiskLimitTiersReq { + settle: 'btc' | 'usdt' | 'usd'; + contract: string; + limit?: number; + offset?: number; +} + +export interface GetFuturesAccountBookReq { + settle: 'btc' | 'usdt' | 'usd'; + contract?: string; + limit?: number; + offset?: number; + from?: number; + to?: number; + type?: + | 'dnw' + | 'pnl' + | 'fee' + | 'refr' + | 'fund' + | 'point_dnw' + | 'point_fee' + | 'point_refr' + | 'bonus_offset'; +} + +export interface GetFuturesPositionsReq { + settle: 'btc' | 'usdt' | 'usd'; + holding?: boolean; + limit?: number; + offset?: number; +} + +export interface UpdateDualModePositionMarginReq { + settle: 'btc' | 'usdt' | 'usd'; + contract: string; + change: string; + dual_side: 'dual_long' | 'dual_short'; +} + +export interface UpdateDualModePositionLeverageReq { + settle: 'btc' | 'usdt' | 'usd'; + contract: string; + leverage: string; + cross_leverage_limit?: string; +} + +export interface SubmitFuturesOrderReq { + settle: 'btc' | 'usdt' | 'usd'; + contract: string; + size: number; + iceberg?: number; + price?: string; + close?: boolean; + reduce_only?: boolean; + tif?: string; + text?: string; + auto_size?: string; + stp_act?: string; +} + +export interface GetFuturesOrdersReq { + settle: 'btc' | 'usdt' | 'usd'; + contract?: string; + status: string; + limit?: number; + offset?: number; + last_id?: string; +} + +export interface DeleteAllFuturesOrdersReq { + settle: 'btc' | 'usdt' | 'usd'; + contract: string; + side?: string; +} + +export interface GetFuturesOrdersByTimeRangeReq { + settle: 'btc' | 'usdt' | 'usd'; + contract?: string; + from?: number; + to?: number; + limit?: number; + offset?: number; +} + +export interface submitFuturesBatchOrdersReq extends FuturesOrder { + settle: 'btc' | 'usdt' | 'usd'; +} + +export interface GetFuturesTradingHistoryReq { + settle: 'btc' | 'usdt' | 'usd'; + contract?: string; + order?: number; + limit?: number; + offset?: number; + last_id?: string; +} + +export interface GetFuturesPositionHistoryReq { + settle: 'btc' | 'usdt' | 'usd'; + contract?: string; + limit?: number; + offset?: number; + from?: number; + to?: number; + side?: 'long' | 'short'; + pnl?: string; +} + +export interface GetFuturesLiquidationHistoryReq { + settle: 'btc' | 'usdt' | 'usd'; + contract?: string; + limit?: number; + at?: number; +} + +export interface SubmitFuturesPriceTriggeredOrderReq + extends FuturesPriceTriggeredOrder { + settle: 'btc' | 'usdt' | 'usd'; +} + +export interface GetFuturesAutoOrdersReq { + settle: 'btc' | 'usdt' | 'usd'; + status: 'open' | 'finished'; + contract?: string; + limit?: number; + offset?: number; +} + +/**========================================================================================================================== + * DELIVERY + * ========================================================================================================================== + */ diff --git a/src/types/response/shared.types.ts b/src/types/response/shared.types.ts index 0933a83..380b4df 100644 --- a/src/types/response/shared.types.ts +++ b/src/types/response/shared.types.ts @@ -764,3 +764,210 @@ export interface GetFuturesCandlesticksResp { o: string; sum: string; } + +export interface GetPremiumIndexKLineResp { + t: number; + c: string; + h: string; + l: string; + o: string; +} + +export interface GetFuturesTickersResp { + contract: string; + last: string; + change_percentage: string; + total_size: string; + low_24h: string; + high_24h: string; + volume_24h: string; + volume_24h_btc?: string; + volume_24h_usd?: string; + volume_24h_base: string; + volume_24h_quote: string; + volume_24h_settle: string; + mark_price: string; + funding_rate: string; + funding_rate_indicative: string; + index_price: string; + quanto_base_rate?: string; + basis_rate: string; + basis_value: string; + lowest_ask: string; + highest_bid: string; +} + +export interface GetFuturesStatsResp { + time: number; + lsr_taker: number; + lsr_account: number; + long_liq_size: number; + long_liq_amount: number; + long_liq_usd: number; + short_liq_size: number; + short_liq_amount: number; + short_liq_usd: number; + open_interest: number; + open_interest_usd: number; + top_lsr_account: number; + top_lsr_size: number; +} + +export interface GetIndexConstituentsResp { + index: string; + constituents: { + exchange: string; + symbols: string[]; + }[]; +} + +export interface GetLiquidationHistoryResp { + time: number; + contract: string; + size: number; + order_price: string; + fill_price: string; + left: number; +} + +export interface GetRiskLimitTiersResp { + tier: number; + risk_limit: string; + initial_rate: string; + maintenance_rate: string; + leverage_max: string; + contract: string; +} + +export interface GetFuturesAccountResp { + 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; + 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 GetFuturesAccountBookResp { + time: number; + change: string; + balance: string; + type: string; + text: string; + contract?: string; + trade_id: string; +} + +export interface ToggleFuturesDualModeResp { + 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; + 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 GetFuturesTradingHistoryResp { + id: number; + create_time: number; + contract: string; + order_id: string; + size: number; + price: string; + role: 'taker' | 'maker'; + text: string; + fee: string; + point_fee: string; +} + +export interface GetFuturesPositionHistoryResp { + time: number; + contract: string; + side: 'long' | 'short'; + pnl: string; + pnl_pnl: string; + pnl_fund: string; + pnl_fee: string; + text: string; + max_size: string; + first_open_time: number; + long_price: string; + short_price: string; +} + +export interface GetFuturesLiquidationHistoryResp { + time: number; + contract: string; + leverage: string; + size: number; + margin: string; + entry_price: string; + liq_price: string; + mark_price: string; + order_id: number; + order_price: string; + fill_price: string; + left: number; +} +export interface GetFuturesAutoDeleveragingHistoryResp { + time: number; + user: number; + order_id: number; + contract: string; + leverage: string; + cross_leverage_limit: string; + entry_price: string; + fill_price: string; + trade_size: number; + position_size: number; +} + +export interface DeleteFuturesBatchOrdersResp { + user_id: number; + id: string; + succeeded: boolean; + message: string; +} + +/**========================================================================================================================== + * DELIVERY + * ========================================================================================================================== + */ From 7be2a147672b1a7e1cf4b14e11c87ba678d015af Mon Sep 17 00:00:00 2001 From: Jerko J <83344666+JJ-Cro@users.noreply.github.com> Date: Tue, 21 May 2024 18:17:21 +0200 Subject: [PATCH 28/36] chore() : Refactoring futures types --- examples/rest-private.ts | 5 +- src/RestClient.ts | 566 ++++++----------------------- src/types/requests/shared.types.ts | 131 +++++++ src/types/response/shared.types.ts | 158 ++++++++ 4 files changed, 412 insertions(+), 448 deletions(-) diff --git a/examples/rest-private.ts b/examples/rest-private.ts index 13bfd8e..af99b83 100644 --- a/examples/rest-private.ts +++ b/examples/rest-private.ts @@ -24,8 +24,9 @@ async function start() { price: '1', }); */ - const res1 = await rest.updateAutoRepaymentSetting({ - status: 'on', + const res1 = await rest.getDeliveryTradingHistory({ + contract: 'BTC_USDT', + settle: 'usdt', }); /* const res2 = await rest.getIndexConstituents({ diff --git a/src/RestClient.ts b/src/RestClient.ts index 2dd7b29..20f88d4 100644 --- a/src/RestClient.ts +++ b/src/RestClient.ts @@ -19,6 +19,16 @@ import { GetCrossMarginBorrowHistoryReq, GetCrossMarginInterestRecordsReq, GetCrossMarginRepaymentsReq, + GetDeliveryAutoOrdersReq, + GetDeliveryBookReq, + GetDeliveryCandlesticksReq, + GetDeliveryClosedPositionsReq, + GetDeliveryLiquidationHistoryReq, + GetDeliveryOrderBookReq, + GetDeliveryOrdersReq, + GetDeliverySettlementHistoryReq, + GetDeliveryTradesReq, + GetDeliveryTradingHistoryReq, GetFlashSwapOrdersReq, GetFuturesAccountBookReq, GetFuturesAutoOrdersReq, @@ -56,6 +66,8 @@ import { PortfolioMarginCalculatorReq, SetUnifiedAccountModeReq, SubmitCrossMarginBorrowLoanReq, + SubmitDeliveryFuturesOrderReq, + submitDeliveryTriggeredOrderReq, SubmitFlashSwapOrderPreviewReq, SubmitFlashSwapOrderReq, submitFuturesBatchOrdersReq, @@ -82,6 +94,16 @@ import { GetCrossMarginAccountResp, GetCrossMarginCurrenciesResp, GetCurrencyChainsResp, + GetDeliveryAccountResp, + GetDeliveryBookResp, + GetDeliveryCandlesticksResp, + GetDeliveryClosedPositionsResp, + GetDeliveryLiquidationHistoryResp, + GetDeliveryOrderBookResp, + GetDeliverySettlementHistoryResp, + GetDeliveryTickersResp, + GetDeliveryTradesResp, + GetDeliveryTradingHistoryResp, GetFlashSwapCurrencyPairsResp, GetFuturesAccountResp, GetFuturesAutoDeleveragingHistoryResp, @@ -2470,7 +2492,7 @@ export class RestClient extends BaseRestClient { getAllDeliveryContracts(params: { settle: 'usdt'; }): Promise> { - return this.get(`/delivery/${params.settle}/contracts`, params); + return this.get(`/delivery/${params.settle}/contracts`); } /** @@ -2483,10 +2505,7 @@ export class RestClient extends BaseRestClient { settle: 'usdt'; contract: string; }): Promise> { - return this.get( - `/delivery/${params.settle}/contracts/${params.contract}`, - params, - ); + return this.get(`/delivery/${params.settle}/contracts/${params.contract}`); } /** @@ -2495,67 +2514,26 @@ export class RestClient extends BaseRestClient { * Bids will be sorted by price from high to low, while asks sorted reversely * * @param params Parameters for retrieving the futures order book - * @returns Promise> + * @returns Promise> */ - getDeliveryOrderBook(params: { - settle: 'usdt'; - contract: string; - interval?: '0' | '0.1' | '0.01'; - limit?: number; - with_id?: boolean; - }): Promise< - APIResponse<{ - id?: number; - current: number; - update: number; - asks: { p: string; s: number }[]; - bids: { p: string; s: number }[]; - }> - > { - return this.get(`/delivery/${params.settle}/order_book`, params); + getDeliveryOrderBook( + params: GetDeliveryOrderBookReq, + ): Promise> { + const { settle, ...query } = params; + return this.get(`/delivery/${settle}/order_book`, query); } /** * Futures trading history * * @param params Parameters for retrieving the futures trading history - * @returns Promise> + * @returns Promise> */ - getDeliveryTrades(params: { - settle: 'usdt'; - contract: string; - limit?: number; - last_id?: string; - from?: number; - to?: number; - }): Promise< - APIResponse< - { - id: number; - create_time: number; - create_time_ms: number; - contract: string; - size: number; - price: string; - is_internal?: boolean; - }[] - > - > { - return this.get(`/delivery/${params.settle}/trades`, params); + getDeliveryTrades( + params: GetDeliveryTradesReq, + ): Promise> { + const { settle, ...query } = params; + return this.get(`/delivery/${settle}/trades`, query); } /** @@ -2565,109 +2543,27 @@ export class RestClient extends BaseRestClient { * Maximum of 2000 points are returned in one query. Be sure not to exceed the limit when specifying from, to and interval. * * @param params Parameters for retrieving futures candlesticks - * @returns Promise> + * @returns Promise> */ - getDeliveryCandlesticks(params: { - settle: 'usdt'; - contract: string; - from?: number; - to?: number; - limit?: number; - interval?: - | '10s' - | '30s' - | '1m' - | '5m' - | '15m' - | '30m' - | '1h' - | '2h' - | '4h' - | '6h' - | '8h' - | '12h' - | '1d' - | '7d' - | '1w' - | '30d'; - }): Promise< - APIResponse< - { - t: number; - v?: number; - c: string; - h: string; - l: string; - o: string; - }[] - > - > { - return this.get(`/delivery/${params.settle}/candlesticks`, params); + getDeliveryCandlesticks( + params: GetDeliveryCandlesticksReq, + ): Promise> { + const { settle, ...query } = params; + return this.get(`/delivery/${settle}/candlesticks`, query); } /** * List futures tickers * * @param params Parameters for listing futures tickers - * @returns Promise> + * @returns Promise> */ - getDeliveryTickers(params: { settle: 'usdt'; contract?: string }): Promise< - APIResponse< - { - contract: string; - last: string; - change_percentage: string; - total_size: string; - low_24h: string; - high_24h: string; - volume_24h: string; - volume_24h_btc?: string; - volume_24h_usd?: string; - volume_24h_base: string; - volume_24h_quote: string; - volume_24h_settle: string; - mark_price: string; - funding_rate: string; - funding_rate_indicative: string; - index_price: string; - quanto_base_rate?: string; - basis_rate: string; - basis_value: string; - lowest_ask: string; - highest_bid: string; - }[] - > - > { - return this.get(`/delivery/${params.settle}/tickers`, params); + getDeliveryTickers(params: { + settle: 'usdt'; + contract?: string; + }): Promise> { + const { settle, ...query } = params; + return this.get(`/delivery/${settle}/tickers`, query); } /** @@ -2690,125 +2586,34 @@ export class RestClient extends BaseRestClient { }[] > > { - return this.get(`/delivery/${params.settle}/insurance`, params); + const { settle, ...query } = params; + return this.get(`/delivery/${settle}/insurance`, query); } /** * Query futures account * * @param params Parameters for querying futures account - * @returns Promise> + * @returns Promise> */ - getDeliveryAccount(params: { settle: 'usdt' }): Promise< - APIResponse<{ - 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; - 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; - }; - }> - > { - return this.getPrivate(`/delivery/${params.settle}/accounts`, params); + getDeliveryAccount(params: { + settle: 'usdt'; + }): Promise> { + const { settle, ...query } = params; + return this.getPrivate(`/delivery/${settle}/accounts`, query); } /** * Query account book * * @param params Parameters for querying account book - * @returns Promise> + * @returns Promise> */ - getDeliveryBook(params: { - settle: 'usdt'; - limit?: number; - from?: number; - to?: number; - type?: - | 'dnw' - | 'pnl' - | 'fee' - | 'refr' - | 'fund' - | 'point_dnw' - | 'point_fee' - | 'point_refr' - | 'bonus_offset'; - }): Promise< - APIResponse< - { - time: number; - change: string; - balance: string; - type: - | 'dnw' - | 'pnl' - | 'fee' - | 'refr' - | 'fund' - | 'point_dnw' - | 'point_fee' - | 'point_refr' - | 'bonus_offset'; - text: string; - contract?: string; - trade_id?: string; - }[] - > - > { - return this.getPrivate(`/delivery/${params.settle}/account_book`, params); + getDeliveryBook( + params: GetDeliveryBookReq, + ): Promise> { + const { settle, ...query } = params; + return this.getPrivate(`/delivery/${settle}/account_book`, query); } /** @@ -2820,7 +2625,7 @@ export class RestClient extends BaseRestClient { getDeliveryPositions(params: { settle: 'usdt'; }): Promise> { - return this.getPrivate(`/delivery/${params.settle}/positions`, params); + return this.getPrivate(`/delivery/${params.settle}/positions`); } /** @@ -2835,7 +2640,6 @@ export class RestClient extends BaseRestClient { }): Promise> { return this.getPrivate( `/delivery/${params.settle}/positions/${params.contract}`, - params, ); } @@ -2850,9 +2654,10 @@ export class RestClient extends BaseRestClient { contract: string; change: string; }): Promise> { + const { settle, contract, ...query } = params; return this.postPrivate( - `/delivery/${params.settle}/positions/${params.contract}/margin`, - { query: params }, + `/delivery/${settle}/positions/${contract}/margin`, + { query: query }, ); } @@ -2867,9 +2672,10 @@ export class RestClient extends BaseRestClient { contract: string; leverage: string; }): Promise> { + const { settle, contract, ...query } = params; return this.postPrivate( - `/delivery/${params.settle}/positions/${params.contract}/leverage`, - { query: params }, + `/delivery/${settle}/positions/${contract}/leverage`, + { query: query }, ); } @@ -2884,9 +2690,10 @@ export class RestClient extends BaseRestClient { contract: string; risk_limit: string; }): Promise> { + const { settle, contract, ...query } = params; return this.postPrivate( - `/delivery/${params.settle}/positions/${params.contract}/risk_limit`, - { query: params }, + `/delivery/${settle}/positions/${contract}/risk_limit`, + { query: query }, ); } @@ -2899,12 +2706,10 @@ export class RestClient extends BaseRestClient { * @returns Promise> */ submitDeliveryOrder( - params: { - settle: 'usdt'; - }, - body: FuturesOrder, + params: SubmitDeliveryFuturesOrderReq, ): Promise> { - return this.postPrivate(`/delivery/${params.settle}/orders`, { body }); + const { settle, ...body } = params; + return this.postPrivate(`/delivery/${settle}/orders`, { body: body }); } /** @@ -2915,18 +2720,12 @@ export class RestClient extends BaseRestClient { * @param params Parameters for listing futures orders * @returns Promise> */ - getDeliveryOrders(params: { - settle: 'usdt'; - contract?: string; - status: 'open' | 'finished'; - limit?: number; - offset?: number; - last_id?: string; - count_total?: 0 | 1; - }): Promise> { - return this.getPrivate(`/delivery/${params.settle}/orders`, params); + getDeliveryOrders( + params: GetDeliveryOrdersReq, + ): Promise> { + const { settle, ...query } = params; + return this.getPrivate(`/delivery/${settle}/orders`, query); } - /** * Cancel all open orders matched * @@ -2940,8 +2739,9 @@ export class RestClient extends BaseRestClient { contract: string; side?: 'ask' | 'bid'; }): Promise> { - return this.deletePrivate(`/delivery/${params.settle}/orders`, { - query: params, + const { settle, ...query } = params; + return this.deletePrivate(`/delivery/${settle}/orders`, { + query: query, }); } @@ -2981,172 +2781,52 @@ export class RestClient extends BaseRestClient { * List personal trading history * * @param params Parameters for listing personal trading history - * @returns Promise> + * @returns Promise> */ - getDeliveryTradingHistory(params: { - settle: 'usdt'; - contract?: string; - order?: number; - limit?: number; - offset?: number; - last_id?: string; - count_total?: 0 | 1; - }): Promise< - APIResponse< - { - id: number; - create_time: number; - contract: string; - order_id: string; - size: number; - price: string; - role: 'taker' | 'maker'; - text: string; - fee: string; - point_fee: string; - }[] - > - > { - return this.getPrivate(`/delivery/${params.settle}/my_trades`, params); + getDeliveryTradingHistory( + params: GetDeliveryTradingHistoryReq, + ): Promise> { + const { settle, ...query } = params; + return this.getPrivate(`/delivery/${settle}/my_trades`, query); } /** * List position close history * * @param params Parameters for listing position close history - * @returns Promise> + * @returns Promise> */ - getDeliveryClosedPositions(params: { - settle: 'usdt'; - contract?: string; - limit?: number; - }): Promise< - APIResponse< - { - time: number; - contract: string; - side: 'long' | 'short'; - pnl: string; - pnl_pnl: string; - pnl_fund: string; - pnl_fee: string; - text: string; - max_size: string; - first_open_time: number; - long_price: string; - short_price: string; - }[] - > - > { - return this.getPrivate(`/delivery/${params.settle}/position_close`, params); + getDeliveryClosedPositions( + params: GetDeliveryClosedPositionsReq, + ): Promise> { + const { settle, ...query } = params; + return this.getPrivate(`/delivery/${settle}/position_close`, query); } /** * List liquidation history * * @param params Parameters for listing liquidation history - * @returns Promise> + * @returns Promise> */ - getDeliveryLiquidationHistory(params: { - settle: 'usdt'; - contract?: string; - limit?: number; - at?: number; - }): Promise< - APIResponse< - { - time: number; - contract: string; - leverage?: string; - size: number; - margin?: string; - entry_price?: string; - liq_price?: string; - mark_price?: string; - order_id?: number; - order_price: string; - fill_price: string; - left: number; - }[] - > - > { - return this.getPrivate(`/delivery/${params.settle}/liquidates`, params); + getDeliveryLiquidationHistory( + params: GetDeliveryLiquidationHistoryReq, + ): Promise> { + const { settle, ...query } = params; + return this.getPrivate(`/delivery/${settle}/liquidates`, query); } /** * List settlement history * * @param params Parameters for listing settlement history - * @returns Promise> + * @returns Promise> */ - getDeliverySettlementHistory(params: { - settle: 'usdt'; - contract?: string; - limit?: number; - at?: number; - }): Promise< - APIResponse< - { - time: number; - contract: string; - leverage: string; - size: number; - margin: string; - entry_price: string; - settle_price: string; - profit: string; - fee: string; - }[] - > - > { - return this.getPrivate(`/delivery/${params.settle}/settlements`, params); + getDeliverySettlementHistory( + params: GetDeliverySettlementHistoryReq, + ): Promise> { + const { settle, ...query } = params; + return this.getPrivate(`/delivery/${settle}/settlements`, query); } /** @@ -3156,14 +2836,11 @@ export class RestClient extends BaseRestClient { * @returns Promise> */ submitDeliveryTriggeredOrder( - params: { - settle: 'usdt'; - }, - body: FuturesPriceTriggeredOrder, + params: submitDeliveryTriggeredOrderReq, ): Promise> { - return this.postPrivate(`/delivery/${params.settle}/price_orders`, { - query: params, - body, + const { settle, ...body } = params; + return this.postPrivate(`/delivery/${settle}/price_orders`, { + body: body, }); } @@ -3173,14 +2850,11 @@ export class RestClient extends BaseRestClient { * @param params Parameters for listing all auto orders * @returns Promise> */ - getDeliveryAutoOrders(params: { - settle: 'usdt'; - status: 'open' | 'finished'; - contract?: string; - limit?: number; - offset?: number; - }): Promise> { - return this.getPrivate(`/delivery/${params.settle}/price_orders`, params); + getDeliveryAutoOrders( + params: GetDeliveryAutoOrdersReq, + ): Promise> { + const { settle, ...query } = params; + return this.getPrivate(`/delivery/${settle}/price_orders`, query); } /** @@ -3193,8 +2867,9 @@ export class RestClient extends BaseRestClient { settle: 'usdt'; contract: string; }): Promise> { - return this.deletePrivate(`/delivery/${params.settle}/price_orders`, { - query: params, + const { settle, ...query } = params; + return this.deletePrivate(`/delivery/${settle}/price_orders`, { + query: query, }); } @@ -3210,7 +2885,6 @@ export class RestClient extends BaseRestClient { }): Promise> { return this.getPrivate( `/delivery/${params.settle}/price_orders/${params.order_id}`, - params, ); } diff --git a/src/types/requests/shared.types.ts b/src/types/requests/shared.types.ts index 154fd01..477c9c5 100644 --- a/src/types/requests/shared.types.ts +++ b/src/types/requests/shared.types.ts @@ -551,3 +551,134 @@ export interface GetFuturesAutoOrdersReq { * DELIVERY * ========================================================================================================================== */ + +export interface GetDeliveryOrderBookReq { + settle: 'usdt'; + contract: string; + interval?: '0' | '0.1' | '0.01'; + limit?: number; + with_id?: boolean; +} + +export interface GetDeliveryTradesReq { + settle: 'usdt'; + contract: string; + limit?: number; + last_id?: string; + from?: number; + to?: number; +} + +export interface GetDeliveryCandlesticksReq { + settle: 'usdt'; + contract: string; + from?: number; + to?: number; + limit?: number; + interval?: + | '10s' + | '30s' + | '1m' + | '5m' + | '15m' + | '30m' + | '1h' + | '2h' + | '4h' + | '6h' + | '8h' + | '12h' + | '1d' + | '7d' + | '1w' + | '30d'; +} + +export interface GetDeliveryBookReq { + settle: 'usdt'; + limit?: number; + from?: number; + to?: number; + type?: + | 'dnw' + | 'pnl' + | 'fee' + | 'refr' + | 'fund' + | 'point_dnw' + | 'point_fee' + | 'point_refr' + | 'bonus_offset'; +} + +export interface SubmitDeliveryFuturesOrderReq { + settle: 'usdt'; + contract: string; + size: number; + iceberg?: number; + price?: string; + close?: boolean; + reduce_only?: boolean; + tif?: string; + text?: string; + auto_size?: string; + stp_act?: string; +} + +export interface GetDeliveryOrdersReq { + settle: 'usdt'; + contract?: string; + status: 'open' | 'finished'; + limit?: number; + offset?: number; + last_id?: string; + count_total?: 0 | 1; +} + +export interface GetDeliveryTradingHistoryReq { + settle: 'usdt'; + contract?: string; + order?: number; + limit?: number; + offset?: number; + last_id?: string; + count_total?: 0 | 1; +} + +export interface GetDeliveryClosedPositionsReq { + settle: 'usdt'; + contract?: string; + limit?: number; +} + +export interface GetDeliveryLiquidationHistoryReq { + settle: 'usdt'; + contract?: string; + limit?: number; + at?: number; +} + +export interface GetDeliverySettlementHistoryReq { + settle: 'usdt'; + contract?: string; + limit?: number; + at?: number; +} + +export interface submitDeliveryTriggeredOrderReq + extends FuturesPriceTriggeredOrder { + settle: 'usdt'; +} + +export interface GetDeliveryAutoOrdersReq { + settle: 'usdt'; + status: 'open' | 'finished'; + contract?: string; + limit?: number; + offset?: number; +} + +/**========================================================================================================================== + * OPTIONS + * ========================================================================================================================== + */ diff --git a/src/types/response/shared.types.ts b/src/types/response/shared.types.ts index 380b4df..8079990 100644 --- a/src/types/response/shared.types.ts +++ b/src/types/response/shared.types.ts @@ -971,3 +971,161 @@ export interface DeleteFuturesBatchOrdersResp { * DELIVERY * ========================================================================================================================== */ + +export interface GetDeliveryOrderBookResp { + id?: number; + current: number; + update: number; + asks: { p: string; s: number }[]; + bids: { p: string; s: number }[]; +} + +export interface GetDeliveryTradesResp { + id: number; + create_time: number; + create_time_ms: number; + contract: string; + size: number; + price: string; + is_internal?: boolean; +} + +export interface GetDeliveryCandlesticksResp { + t: number; + v?: number; + c: string; + h: string; + l: string; + o: string; +} + +export interface GetDeliveryTickersResp { + contract: string; + last: string; + change_percentage: string; + total_size: string; + low_24h: string; + high_24h: string; + volume_24h: string; + volume_24h_btc?: string; + volume_24h_usd?: string; + volume_24h_base: string; + volume_24h_quote: string; + volume_24h_settle: string; + mark_price: string; + funding_rate: string; + funding_rate_indicative: string; + index_price: string; + quanto_base_rate?: string; + basis_rate: string; + basis_value: string; + lowest_ask: string; + highest_bid: string; +} + +export interface GetDeliveryAccountResp { + 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; + 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 GetDeliveryBookResp { + time: number; + change: string; + balance: string; + type: + | 'dnw' + | 'pnl' + | 'fee' + | 'refr' + | 'fund' + | 'point_dnw' + | 'point_fee' + | 'point_refr' + | 'bonus_offset'; + text: string; + contract?: string; + trade_id?: string; +} + +export interface GetDeliveryTradingHistoryResp { + id: number; + create_time: number; + contract: string; + order_id: string; + size: number; + price: string; + role: 'taker' | 'maker'; + text: string; + fee: string; + point_fee: string; +} + +export interface GetDeliveryClosedPositionsResp { + time: number; + contract: string; + side: 'long' | 'short'; + pnl: string; + pnl_pnl: string; + pnl_fund: string; + pnl_fee: string; + text: string; + max_size: string; + first_open_time: number; + long_price: string; + short_price: string; +} + +export interface GetDeliveryLiquidationHistoryResp { + time: number; + contract: string; + leverage?: string; + size: number; + margin?: string; + entry_price?: string; + liq_price?: string; + mark_price?: string; + order_id?: number; + order_price: string; + fill_price: string; + left: number; +} + +export interface GetDeliverySettlementHistoryResp { + time: number; + contract: string; + leverage: string; + size: number; + margin: string; + entry_price: string; + settle_price: string; + profit: string; + fee: string; +} + +/**========================================================================================================================== + * OPTIONS + * ========================================================================================================================== + */ From b318dbb46f3487e138f82b25c12413c7a87d5392 Mon Sep 17 00:00:00 2001 From: Jerko J <83344666+JJ-Cro@users.noreply.github.com> Date: Wed, 22 May 2024 13:02:06 +0200 Subject: [PATCH 29/36] chore(): refactored all types and functions --- src/RestClient.ts | 2189 ++++------------------------ src/types/requests/shared.types.ts | 257 ++++ src/types/response/shared.types.ts | 563 +++++++ 3 files changed, 1141 insertions(+), 1868 deletions(-) diff --git a/src/RestClient.ts b/src/RestClient.ts index 20f88d4..aae44e2 100644 --- a/src/RestClient.ts +++ b/src/RestClient.ts @@ -1,7 +1,7 @@ -// double check if schemas are requests // double check if names are set to what the call represents(get, delete, update etc...) // check in all non-get calls that query params and body params are as it should be // check all inputs where we have a path to make sure all is right. +// check for voids import { AxiosRequestConfig } from 'axios'; @@ -12,6 +12,7 @@ import { } from './lib/BaseRestClient.js'; import { RestClientOptions } from './lib/requestUtils.js'; import { + CreateStpGroupReq, CreateSubAccountApiKeyReq, DeleteAllFuturesOrdersReq, DeleteSpotOrderReq, @@ -42,13 +43,31 @@ import { GetFuturesStatsReq, GetFuturesTradesReq, GetFuturesTradingHistoryReq, + GetLendingInterestRecordsReq, + GetLendingOrdersReq, + GetLendingRecordsReq, GetLiquidationHistoryReq, + GetLoanCollateralRecordsReq, + GetLoanOrdersReq, + GetLoanRepaymentHistoryReq, GetMainSubTransfersReq, GetMarginBalanceHistoryReq, GetMarginUNIInterestRecordsReq, GetMarginUNILoanRecordsReq, GetMarginUNILoansReq, GetMarginUNIMaxBorrowReq, + GetMultiLoanAdjustmentRecordsReq, + GetMultiLoanOrdersReq, + GetMultiLoanRepayRecordsReq, + GetOptionsAccountChangeReq, + GetOptionsCandlesticksReq, + GetOptionsMySettlementsReq, + GetOptionsOrderBookReq, + GetOptionsOrdersReq, + GetOptionsPersonalHistoryReq, + GetOptionsSettlementHistoryReq, + GetOptionsTradesReq, + GetOptionsUnderlyingCandlesticksReq, GetRiskLimitTiersReq, GetSavedAddressReq, GetSmallBalanceHistoryReq, @@ -59,11 +78,14 @@ import { GetSpotOrdersReq, GetSpotTradesReq, GetSpotTradingHistoryReq, + GetStructuredProductListReq, + GetStructuredProductOrdersReq, GetUnifiedInterestRecordsReq, GetUnifiedLoanRecordsReq, GetUnifiedLoansReq, GetWithdrawalDepositRecordsReq, PortfolioMarginCalculatorReq, + RepayMultiLoanReq, SetUnifiedAccountModeReq, SubmitCrossMarginBorrowLoanReq, SubmitDeliveryFuturesOrderReq, @@ -73,11 +95,17 @@ import { submitFuturesBatchOrdersReq, SubmitFuturesOrderReq, SubmitFuturesPriceTriggeredOrderReq, + SubmitLendOrRedeemReq, + SubmitLoanOrderReq, + SubmitMultiLoanOrderReq, + SubmitOptionsOrderReq, SubmitSpotClosePosCrossDisabledReq, SubmitSpotOrderReq, SubmitUnifiedBorrowOrRepayReq, UpdateDualModePositionLeverageReq, UpdateDualModePositionMarginReq, + UpdateLoanCollateralReq, + UpdateMultiLoanReq, UpdateSpotBatchOrdersReq, UpdateSpotOrderReq, UpdateSubAccountApiKeyReq, @@ -85,10 +113,12 @@ import { import { APIResponse, CreateDepositAddressResp, + CreateStpGroupResp, CreateSubAccountApiKeyResp, DeleteFuturesBatchOrdersResp, DeleteSpotBatchOrdersResp, FlashSwapOrderResp, + GetAccountDetailResp, GetBalancesResp, GetCrossMarginAccountHistoryResp, GetCrossMarginAccountResp, @@ -104,6 +134,8 @@ import { GetDeliveryTickersResp, GetDeliveryTradesResp, GetDeliveryTradingHistoryResp, + GetDualInvestmentOrdersResp, + GetDualInvestmentProductsResp, GetFlashSwapCurrencyPairsResp, GetFuturesAccountResp, GetFuturesAutoDeleveragingHistoryResp, @@ -116,14 +148,42 @@ import { GetFuturesTradesResp, GetFuturesTradingHistoryResp, GetIndexConstituentsResp, + GetLendingCurrenciesResp, + GetLendingInterestRecordsResp, GetLendingMarketsResp, + GetLendingOrdersResp, + GetLendingRecordsResp, GetLiquidationHistoryResp, + GetLoanCollateralizationRatioResp, + GetLoanCollateralRecordsResp, + GetLoanOrdersResp, + GetLoanRepaymentHistoryResp, GetMarginAccountsResp, GetMarginBalanceHistoryResp, GetMarginUNIInterestRecordsResp, GetMarginUNILoanRecordsResp, GetMarginUNILoansResp, GetMarginUNIMaxBorrowResp, + GetMultiLoanAdjustmentRecordsResp, + GetMultiLoanCurrencyQuotaResp, + GetMultiLoanFixedRatesResp, + GetMultiLoanOrdersResp, + GetMultiLoanRatioResp, + GetMultiLoanRepayRecordsResp, + GetMultiLoanSupportedCurrenciesResp, + GetOptionsAccountChangeResp, + GetOptionsAccountResp, + GetOptionsCandlesticksResp, + GetOptionsContractsResp, + GetOptionsLiquidationResp, + GetOptionsMySettlementsResp, + GetOptionsOrderBookResp, + GetOptionsPersonalHistoryResp, + GetOptionsPositionsUnderlyingResp, + GetOptionsSettlementHistoryResp, + GetOptionsTickersResp, + GetOptionsTradesResp, + GetOptionsUnderlyingCandlesticksResp, GetPremiumIndexKLineResp, GetRiskLimitTiersResp, GetSavedAddressResp, @@ -140,6 +200,8 @@ import { GetSpotTickerResp, GetSpotTradesResp, GetSpotTradingHistoryResp, + GetStructuredProductListResp, + GetStructuredProductOrdersResp, GetTradingFeesResp, GetUnifiedAccountInfoResp, GetUnifiedCurrencyDiscountTiersResp, @@ -149,6 +211,7 @@ import { GetUnifiedRiskUnitDetailsResp, GetWithdrawalStatusResp, PortfolioMarginCalculatorResp, + RepayMultiLoanResp, SubAccountCrossMarginBalancesResp, SubAccountFuturesBalancesResp, SubAccountMarginBalancesResp, @@ -156,8 +219,10 @@ import { SubAccountTransferRecordResp, SubmitCrossMarginBorrowLoanResp, SubmitFlashSwapOrderPreviewResp, + SubmitOptionsOrderResp, SubmitSpotBatchOrdersResp, ToggleFuturesDualModeResp, + UpdateMultiLoanResp, } from './types/response/shared.types.js'; import { CancelBatchOrder, @@ -299,7 +364,7 @@ export class RestClient extends BaseRestClient { * @param params Transfer parameters * @returns Promise> */ - submitTransfer(body: { + submitTransfer(params: { currency: string; from: | 'spot' @@ -313,7 +378,7 @@ export class RestClient extends BaseRestClient { currency_pair?: string; settle?: string; }): Promise> { - return this.postPrivate('/wallet/transfers', { body: body }); + return this.postPrivate('/wallet/transfers', { body: params }); } /** @@ -324,7 +389,7 @@ export class RestClient extends BaseRestClient { * @param params Transfer parameters * @returns Promise> */ - submitMainSubTransfer(body: { + submitMainSubTransfer(params: { currency: string; sub_account: string; direction: 'to' | 'from'; @@ -332,7 +397,7 @@ export class RestClient extends BaseRestClient { client_order_id?: string; sub_account_type?: 'spot' | 'futures' | 'cross_margin' | 'delivery'; }): Promise> { - return this.postPrivate('/wallet/sub_account_transfers', { body: body }); + return this.postPrivate('/wallet/sub_account_transfers', { body: params }); } /** @@ -359,7 +424,7 @@ export class RestClient extends BaseRestClient { * @param params Transfer parameters * @returns Promise> */ - submitSubToSubTransfer(body: { + submitSubToSubTransfer(params: { currency: string; sub_account_type?: string; sub_account_from: string; @@ -369,7 +434,7 @@ export class RestClient extends BaseRestClient { amount: string; }): Promise> { return this.postPrivate('/wallet/sub_account_to_sub_account', { - body: body, + body: params, }); } @@ -502,10 +567,10 @@ export class RestClient extends BaseRestClient { * @param params Parameters for converting small balance * @returns Promise> */ - convertSmallBalance(body?: { + convertSmallBalance(params?: { currency?: string[]; }): Promise> { - return this.postPrivate('/wallet/small_balance', { body: body }); + return this.postPrivate('/wallet/small_balance', { body: params }); } /** @@ -531,13 +596,13 @@ export class RestClient extends BaseRestClient { * @param params Parameters for creating a new sub-account * @returns Promise> */ - createSubAccount(body: { + createSubAccount(params: { remark?: string; login_name: string; password?: string; email?: string; }): Promise> { - return this.postPrivate('/sub_accounts', { body: body }); + return this.postPrivate('/sub_accounts', { body: params }); } /** @@ -719,9 +784,9 @@ export class RestClient extends BaseRestClient { * @returns Promise> */ submitUnifiedBorrowOrRepay( - body: SubmitUnifiedBorrowOrRepayReq, + params: SubmitUnifiedBorrowOrRepayReq, ): Promise> { - return this.postPrivate('/unified/loans', { body: body }); + return this.postPrivate('/unified/loans', { body: params }); } /** @@ -779,10 +844,10 @@ export class RestClient extends BaseRestClient { * @param params Parameters for setting the mode of the unified account * @returns Promise> */ - setUnifiedAccountMode( - body: SetUnifiedAccountModeReq, + updateUnifiedAccountMode( + params: SetUnifiedAccountModeReq, ): Promise> { - return this.putPrivate('/unified/unified_mode', { body: body }); + return this.putPrivate('/unified/unified_mode', { body: params }); } /** @@ -834,9 +899,9 @@ export class RestClient extends BaseRestClient { * @returns Promise> */ portfolioMarginCalculator( - body: PortfolioMarginCalculatorReq, + params: PortfolioMarginCalculatorReq, ): Promise> { - return this.post('/unified/portfolio_calculator', { body: body }); + return this.post('/unified/portfolio_calculator', { body: params }); } /**========================================================================================================================== @@ -1023,9 +1088,9 @@ export class RestClient extends BaseRestClient { * @returns Promise> */ submitSpotBatchOrders( - body: Order[], + params: Order[], ): Promise> { - return this.postPrivate('/spot/batch_orders', { body: body }); + return this.postPrivate('/spot/batch_orders', { body: params }); } /** @@ -1055,9 +1120,9 @@ export class RestClient extends BaseRestClient { * @returns Promise> */ submitSpotClosePosCrossDisabled( - body: SubmitSpotClosePosCrossDisabledReq, + params: SubmitSpotClosePosCrossDisabledReq, ): Promise> { - return this.postPrivate('/spot/cross_liquidate_orders', { body: body }); + return this.postPrivate('/spot/cross_liquidate_orders', { body: params }); } /** @@ -1068,8 +1133,8 @@ export class RestClient extends BaseRestClient { * @param params Parameters for creating an order * @returns Promise> */ - submitSpotOrder(body: SubmitSpotOrderReq): Promise> { - return this.postPrivate('/spot/orders', { body: body }); + submitSpotOrder(params: SubmitSpotOrderReq): Promise> { + return this.postPrivate('/spot/orders', { body: params }); } /** @@ -1111,9 +1176,9 @@ export class RestClient extends BaseRestClient { * @returns Promise> */ deleteSpotBatchOrders( - body: CancelBatchOrder[], + params: CancelBatchOrder[], ): Promise> { - return this.postPrivate('/spot/cancel_batch_orders', { body: body }); + return this.postPrivate('/spot/cancel_batch_orders', { body: params }); } /** @@ -1212,7 +1277,7 @@ export class RestClient extends BaseRestClient { * triggerTime: number; * }>> */ - submitSpotCountdownOrders(body: { + submitSpotCountdownOrders(params: { timeout: number; currency_pair?: string; }): Promise< @@ -1220,7 +1285,7 @@ export class RestClient extends BaseRestClient { triggerTime: number; }> > { - return this.postPrivate('/spot/countdown_cancel_all', { body: body }); + return this.postPrivate('/spot/countdown_cancel_all', { body: params }); } /** @@ -1232,9 +1297,9 @@ export class RestClient extends BaseRestClient { * @returns Promise> */ updateSpotBatchOrders( - body: UpdateSpotBatchOrdersReq[], + params: UpdateSpotBatchOrdersReq[], ): Promise> { - return this.postPrivate('/spot/amend_batch_orders', { body: body }); + return this.postPrivate('/spot/amend_batch_orders', { body: params }); } /** @@ -1245,12 +1310,12 @@ export class RestClient extends BaseRestClient { * id: number; * }>> */ - submitSpotPriceTriggerOrder(body: SpotPriceTriggeredOrder): Promise< + submitSpotPriceTriggerOrder(params: SpotPriceTriggeredOrder): Promise< APIResponse<{ id: number; }> > { - return this.postPrivate('/spot/price_orders', { body: body }); + return this.postPrivate('/spot/price_orders', { body: params }); } /** @@ -1458,9 +1523,9 @@ export class RestClient extends BaseRestClient { * @returns Promise> */ submitCrossMarginBorrowLoan( - body: SubmitCrossMarginBorrowLoanReq, + params: SubmitCrossMarginBorrowLoanReq, ): Promise> { - return this.postPrivate('/margin/cross/loans', { body: body }); + return this.postPrivate('/margin/cross/loans', { body: params }); } /** @@ -1496,11 +1561,11 @@ export class RestClient extends BaseRestClient { * @param params Parameters for cross margin repayments * @returns Promise> */ - submitCrossMarginRepayment(body: { + submitCrossMarginRepayment(params: { currency: string; amount: string; }): Promise> { - return this.postPrivate('/margin/cross/repayments', { body: body }); + return this.postPrivate('/margin/cross/repayments', { body: params }); } /** @@ -1617,7 +1682,7 @@ export class RestClient extends BaseRestClient { * @param params Parameters for retrieving estimated interest rates * @returns Promise> */ - estimateInterestRate(params: { + getEstimatedInterestRate(params: { currencies: string[]; }): Promise> { return this.getPrivate('/margin/uni/estimate_rate', params); @@ -1629,14 +1694,14 @@ export class RestClient extends BaseRestClient { * @param params Parameters for borrowing or repaying * @returns Promise */ - submitMarginUNIBorrowOrRepay(body: { + submitMarginUNIBorrowOrRepay(params: { currency: string; type: 'borrow' | 'repay'; amount: string; currency_pair: string; repaid_all?: boolean; }): Promise { - return this.postPrivate('/margin/uni/loans', { body: body }); + return this.postPrivate('/margin/uni/loans', { body: params }); } /** @@ -1712,9 +1777,9 @@ export class RestClient extends BaseRestClient { * @returns Promise> */ submitFlashSwapOrder( - body: SubmitFlashSwapOrderReq, + params: SubmitFlashSwapOrderReq, ): Promise> { - return this.postPrivate('/flash_swap/orders', { body: body }); + return this.postPrivate('/flash_swap/orders', { body: params }); } /** @@ -1748,9 +1813,9 @@ export class RestClient extends BaseRestClient { * @returns Promise> */ submitFlashSwapOrderPreview( - body: SubmitFlashSwapOrderPreviewReq, + params: SubmitFlashSwapOrderPreviewReq, ): Promise> { - return this.postPrivate('/flash_swap/orders/preview', { body }); + return this.postPrivate('/flash_swap/orders/preview', { body: params }); } /**========================================================================================================================== @@ -2085,7 +2150,7 @@ export class RestClient extends BaseRestClient { * @param params Parameters for enabling or disabling dual mode * @returns Promise> */ - toggleFuturesDualMode(params: { + updateFuturesDualMode(params: { settle: 'btc' | 'usdt' | 'usd'; dual_mode: boolean; }): Promise> { @@ -2935,70 +3000,12 @@ export class RestClient extends BaseRestClient { * List all the contracts with specified underlying and expiration time * * @param params Parameters for listing contracts - * @returns Promise> + * @returns Promise> */ getOptionsContracts(params: { underlying: string; expiration?: number; - }): Promise< - APIResponse< - { - name: string; - tag: string; - create_time: number; - expiration_time: number; - is_call: boolean; - strike_price: string; - last_price: string; - mark_price: string; - orderbook_id: number; - trade_id: number; - trade_size: number; - position_size: number; - underlying: string; - underlying_price: string; - multiplier: string; - order_price_round: string; - mark_price_round: string; - maker_fee_rate: string; - taker_fee_rate: string; - price_limit_fee_rate: string; - ref_discount_rate: string; - ref_rebate_rate: string; - order_price_deviate: string; - order_size_min: number; - order_size_max: number; - orders_limit: number; - }[] - > - > { + }): Promise> { return this.get(`/options/contracts`, params); } @@ -3006,99 +3013,23 @@ export class RestClient extends BaseRestClient { * Query specified contract detail * * @param params Parameters for querying specified contract detail - * @returns Promise> + * @returns Promise> */ - getOptionsContract(params: { contract: string }): Promise< - APIResponse<{ - name: string; - tag: string; - create_time: number; - expiration_time: number; - is_call: boolean; - strike_price: string; - last_price: string; - mark_price: string; - orderbook_id: number; - trade_id: number; - trade_size: number; - position_size: number; - underlying: string; - underlying_price: string; - multiplier: string; - order_price_round: string; - mark_price_round: string; - maker_fee_rate: string; - taker_fee_rate: string; - price_limit_fee_rate: string; - ref_discount_rate: string; - ref_rebate_rate: string; - order_price_deviate: string; - order_size_min: number; - order_size_max: number; - orders_limit: number; - }> - > { - return this.get(`/options/contracts/${params.contract}`, params); + getOptionsContract(params: { + contract: string; + }): Promise> { + return this.get(`/options/contracts/${params.contract}`); } /** * List settlement history * * @param params Parameters for listing settlement history - * @returns Promise> + * @returns Promise> */ - getOptionsSettlementHistory(params: { - underlying: string; - limit?: number; - offset?: number; - from?: number; - to?: number; - }): Promise< - APIResponse< - { - time: number; - contract: string; - profit: string; - fee: string; - strike_price: string; - settle_price: string; - }[] - > - > { + getOptionsSettlementHistory( + params: GetOptionsSettlementHistoryReq, + ): Promise> { return this.get(`/options/settlements`, params); } @@ -3106,70 +3037,26 @@ export class RestClient extends BaseRestClient { * Get specified contract's settlement * * @param params Parameters for retrieving specified contract's settlement - * @returns Promise> + * @returns Promise> */ getOptionsContractSettlement(params: { contract: string; underlying: string; at: number; - }): Promise< - APIResponse<{ - time: number; - contract: string; - profit: string; - fee: string; - strike_price: string; - settle_price: string; - }> - > { - return this.get(`/options/settlements/${params.contract}`, params); + }): Promise> { + const { contract, ...query } = params; + return this.get(`/options/settlements/${contract}`, query); } /** * List my options settlements * * @param params Parameters for listing my options settlements - * @returns Promise> + * @returns Promise> */ - getOptionsMySettlements(params: { - underlying: string; - contract?: string; - limit?: number; - offset?: number; - from?: number; - to?: number; - }): Promise< - APIResponse< - { - time: number; - underlying: string; - contract: string; - strike_price: string; - settle_price: string; - size: number; - settle_profit: string; - fee: string; - realised_pnl: string; - }[] - > - > { + getOptionsMySettlements( + params: GetOptionsMySettlementsReq, + ): Promise> { return this.getPrivate(`/options/my_settlements`, params); } @@ -3179,28 +3066,11 @@ export class RestClient extends BaseRestClient { * Bids will be sorted by price from high to low, while asks sorted reversely * * @param params Parameters for retrieving options order book - * @returns Promise> + * @returns Promise> */ - getOptionsOrderBook(params: { - contract: string; - interval?: '0' | '0.1' | '0.01'; - limit?: number; - with_id?: boolean; - }): Promise< - APIResponse<{ - id?: number; - current: number; - update: number; - asks: { p: string; s: number }[]; - bids: { p: string; s: number }[]; - }> - > { + getOptionsOrderBook( + params: GetOptionsOrderBookReq, + ): Promise> { return this.get(`/options/order_book`, params); } @@ -3208,51 +3078,11 @@ export class RestClient extends BaseRestClient { * List tickers of options contracts * * @param params Parameters for listing tickers of options contracts - * @returns Promise> + * @returns Promise> */ - getOptionsTickers(params: { underlying: string }): Promise< - APIResponse< - { - name: string; - last_price: string; - mark_price: string; - index_price: string; - ask1_size: number; - ask1_price: string; - bid1_size: number; - bid1_price: string; - position_size: number; - mark_iv: string; - bid_iv: string; - ask_iv: string; - leverage: string; - delta: string; - gamma: string; - vega: string; - theta: string; - rho: string; - }[] - > - > { + getOptionsTickers(params: { + underlying: string; + }): Promise> { return this.get(`/options/tickers`, params); } @@ -3280,33 +3110,11 @@ export class RestClient extends BaseRestClient { * Get options candlesticks * * @param params Parameters for retrieving options candlesticks - * @returns Promise> + * @returns Promise> */ - getOptionsCandlesticks(params: { - contract: string; - limit?: number; - from?: number; - to?: number; - interval?: '1m' | '5m' | '15m' | '30m' | '1h'; - }): Promise< - APIResponse< - { - t: number; - v?: number; - c: string; - h: string; - l: string; - o: string; - }[] - > - > { + getOptionsCandlesticks( + params: GetOptionsCandlesticksReq, + ): Promise> { return this.get(`/options/candlesticks`, params); } @@ -3314,35 +3122,11 @@ export class RestClient extends BaseRestClient { * Mark price candlesticks of an underlying * * @param params Parameters for retrieving mark price candlesticks of an underlying - * @returns Promise> + * @returns Promise> */ - getOptionsUnderlyingCandlesticks(params: { - underlying: string; - limit?: number; - from?: number; - to?: number; - interval?: '1m' | '5m' | '15m' | '30m' | '1h'; - }): Promise< - APIResponse< - { - t: number; - v?: number; - c: string; - h: string; - l: string; - o: string; - sum: string; - }[] - > - > { + getOptionsUnderlyingCandlesticks( + params: GetOptionsUnderlyingCandlesticksReq, + ): Promise> { return this.get(`/options/underlying/candlesticks`, params); } @@ -3350,69 +3134,20 @@ export class RestClient extends BaseRestClient { * Options trade history * * @param params Parameters for retrieving options trade history - * @returns Promise> + * @returns Promise> */ - getOptionsTrades(params: { - contract?: string; - type?: 'C' | 'P'; - limit?: number; - offset?: number; - from?: number; - to?: number; - }): Promise< - APIResponse< - { - id: number; - create_time: number; - create_time_ms: number; - contract: string; - size: number; - price: string; - is_internal?: boolean; - }[] - > - > { + getOptionsTrades( + params: GetOptionsTradesReq, + ): Promise> { return this.get(`/options/trades`, params); } /** * List options account * - * @returns Promise> + * @returns Promise> */ - getOptionsAccount(): Promise< - APIResponse<{ - user: number; - total: string; - short_enabled: boolean; - unrealised_pnl: string; - init_margin: string; - maint_margin: string; - order_margin: string; - available: string; - point: string; - currency: string; - }> - > { + getOptionsAccount(): Promise> { return this.getPrivate(`/options/accounts`); } @@ -3420,31 +3155,11 @@ export class RestClient extends BaseRestClient { * List account changing history * * @param params Parameters for listing account changing history - * @returns Promise> + * @returns Promise> */ - getOptionsAccountChange(params: { - limit?: number; - offset?: number; - from?: number; - to?: number; - type?: 'dnw' | 'prem' | 'fee' | 'refr' | 'set'; - }): Promise< - APIResponse< - { - time: number; - change: string; - balance: string; - type: 'dnw' | 'prem' | 'fee' | 'refr' | 'set'; - text: string; - }[] - > - > { + getOptionsAccountChange( + params?: GetOptionsAccountChangeReq, + ): Promise> { return this.getPrivate(`/options/account_book`, params); } @@ -3452,109 +3167,23 @@ export class RestClient extends BaseRestClient { * List user's positions of specified underlying * * @param params Parameters for listing user's positions of specified underlying - * @returns Promise> + * @returns Promise> */ - - getOptionsPositionsUnderlying(params: { underlying?: string }): Promise< - APIResponse< - { - user: number; - underlying: string; - underlying_price: string; - contract: string; - size: number; - entry_price: string; - mark_price: string; - mark_iv: string; - realised_pnl: string; - unrealised_pnl: string; - pending_orders: number; - close_order: { - id: number; - price: string; - is_liq: boolean; - } | null; - delta: string; - gamma: string; - vega: string; - theta: string; - }[] - > - > { + getOptionsPositionsUnderlying(params: { + underlying?: string; + }): Promise> { return this.getPrivate(`/options/positions`, params); } + /** * Get specified contract position * * @param params Parameters for retrieving specified contract position - * @returns Promise> + * @returns Promise> */ - getOptionsPositionContract(params: { contract: string }): Promise< - APIResponse<{ - user: number; - underlying: string; - underlying_price: string; - contract: string; - size: number; - entry_price: string; - mark_price: string; - mark_iv: string; - realised_pnl: string; - unrealised_pnl: string; - pending_orders: number; - close_order: { - id: number; - price: string; - is_liq: boolean; - } | null; - delta: string; - gamma: string; - vega: string; - theta: string; - }> - > { + getOptionsPositionContract(params: { + contract: string; + }): Promise> { return this.getPrivate(`/options/positions/${params.contract}`, params); } @@ -3562,30 +3191,12 @@ export class RestClient extends BaseRestClient { * List user's liquidation history of specified underlying * * @param params Parameters for listing user's liquidation history of specified underlying - * @returns Promise> + * @returns Promise> */ getOptionsLiquidation(params: { underlying: string; contract?: string; - }): Promise< - APIResponse< - { - time: number; - contract: string; - side: 'long' | 'short'; - pnl: string; - text: string; - settle_size: string; - }[] - > - > { + }): Promise> { return this.getPrivate(`/options/position_close`, params); } @@ -3593,144 +3204,23 @@ export class RestClient extends BaseRestClient { * Create an options order * * @param params Parameters for creating an options order - * @returns Promise> + * @returns Promise> */ - submitOptionsOrder(body: { - contract: string; - size: number; - iceberg?: number; - price?: string; - close?: boolean; - reduce_only?: boolean; - tif?: 'gtc' | 'ioc' | 'poc'; - text?: string; - }): Promise< - APIResponse<{ - id: number; - user: number; - create_time: number; - finish_time: number; - finish_as: - | 'filled' - | 'cancelled' - | 'liquidated' - | 'ioc' - | 'auto_deleveraged' - | 'reduce_only' - | 'position_closed'; - status: 'open' | 'finished'; - contract: string; - size: number; - iceberg: number; - price: string; - is_close: boolean; - is_reduce_only: boolean; - is_liq: boolean; - tif: 'gtc' | 'ioc' | 'poc'; - left: number; - fill_price: string; - text: string; - tkfr: string; - mkfr: string; - refu: number; - refr: string; - }> - > { - return this.postPrivate(`/options/orders`, { body }); + submitOptionsOrder( + params: SubmitOptionsOrderReq, + ): Promise> { + return this.postPrivate(`/options/orders`, { body: params }); } /** * List options orders * * @param params Parameters for listing options orders - * @returns Promise> + * @returns Promise> */ - getOptionsOrders(params: { - contract?: string; - underlying?: string; - status: 'open' | 'finished'; - limit?: number; - offset?: number; - from?: number; - to?: number; - }): Promise< - APIResponse< - { - id: number; - user: number; - create_time: number; - finish_time: number; - finish_as: - | 'filled' - | 'cancelled' - | 'liquidated' - | 'ioc' - | 'auto_deleveraged' - | 'reduce_only' - | 'position_closed'; - status: 'open' | 'finished'; - contract: string; - size: number; - iceberg: number; - price: string; - is_close: boolean; - is_reduce_only: boolean; - is_liq: boolean; - tif: 'gtc' | 'ioc' | 'poc'; - left: number; - fill_price: string; - text: string; - tkfr: string; - mkfr: string; - refu: number; - refr: string; - }[] - > - > { + getOptionsOrders( + params: GetOptionsOrdersReq, + ): Promise> { return this.getPrivate(`/options/orders`, params); } @@ -3738,68 +3228,13 @@ export class RestClient extends BaseRestClient { * Cancel all open orders matched * * @param params Parameters for canceling all open orders matched - * @returns Promise> + * @returns Promise> */ deleteOptionsOrders(params: { contract?: string; underlying?: string; side?: 'ask' | 'bid'; - }): Promise< - APIResponse< - { - id: number; - user: number; - create_time: number; - finish_time: number; - finish_as: - | 'filled' - | 'cancelled' - | 'liquidated' - | 'ioc' - | 'auto_deleveraged' - | 'reduce_only' - | 'position_closed'; - status: 'open' | 'finished'; - contract: string; - size: number; - iceberg: number; - price: string; - is_close: boolean; - is_reduce_only: boolean; - is_liq: boolean; - tif: 'gtc' | 'ioc' | 'poc'; - left: number; - fill_price: string; - text: string; - tkfr: string; - mkfr: string; - refu: number; - refr: string; - }[] - > - > { + }): Promise> { return this.deletePrivate(`/options/orders`, { query: params }); } @@ -3807,62 +3242,11 @@ export class RestClient extends BaseRestClient { * Get a single order * * @param params Parameters for retrieving a single order - * @returns Promise> + * @returns Promise> */ - getOptionsOrder(params: { order_id: number }): Promise< - APIResponse<{ - id: number; - user: number; - create_time: number; - finish_time: number; - finish_as: - | 'filled' - | 'cancelled' - | 'liquidated' - | 'ioc' - | 'auto_deleveraged' - | 'reduce_only' - | 'position_closed'; - status: 'open' | 'finished'; - contract: string; - size: number; - iceberg: number; - price: string; - is_close: boolean; - is_reduce_only: boolean; - is_liq: boolean; - tif: 'gtc' | 'ioc' | 'poc'; - left: number; - fill_price: string; - text: string; - tkfr: string; - mkfr: string; - refu: number; - refr: string; - }> - > { + getOptionsOrder(params: { + order_id: number; + }): Promise> { return this.getPrivate(`/options/orders/${params.order_id}`); } @@ -3870,62 +3254,11 @@ export class RestClient extends BaseRestClient { * Cancel a single order * * @param params Parameters for canceling a single order - * @returns Promise> + * @returns Promise> */ - deleteOptionsOrder(params: { order_id: number }): Promise< - APIResponse<{ - id: number; - user: number; - create_time: number; - finish_time: number; - finish_as: - | 'filled' - | 'cancelled' - | 'liquidated' - | 'ioc' - | 'auto_deleveraged' - | 'reduce_only' - | 'position_closed'; - status: 'open' | 'finished'; - contract: string; - size: number; - iceberg: number; - price: string; - is_close: boolean; - is_reduce_only: boolean; - is_liq: boolean; - tif: 'gtc' | 'ioc' | 'poc'; - left: number; - fill_price: string; - text: string; - tkfr: string; - mkfr: string; - refu: number; - refr: string; - }> - > { + deleteOptionsOrder(params: { + order_id: number; + }): Promise> { return this.deletePrivate(`/options/orders/${params.order_id}`); } @@ -3933,38 +3266,11 @@ export class RestClient extends BaseRestClient { * List personal trading history * * @param params Parameters for listing personal trading history - * @returns Promise> + * @returns Promise> */ - getOptionsPersonalHistory(params: { - underlying: string; - contract?: string; - limit?: number; - offset?: number; - from?: number; - to?: number; - }): Promise< - APIResponse< - { - id: number; - create_time: number; - contract: string; - order_id: number; - size: number; - price: string; - underlying_price: string; - role: 'taker' | 'maker'; - }[] - > - > { + getOptionsPersonalHistory( + params: GetOptionsPersonalHistoryReq, + ): Promise> { return this.getPrivate(`/options/my_trades`, params); } @@ -3976,25 +3282,9 @@ export class RestClient extends BaseRestClient { /** * List currencies for lending * - * @returns Promise> + * @returns Promise> */ - getLendingCurrencies(): Promise< - APIResponse< - { - currency: string; - min_lend_amount: string; - max_lend_amount: string; - max_rate: string; - min_rate: string; - }[] - > - > { + getLendingCurrencies(): Promise> { return this.get(`/earn/uni/currencies`); } @@ -4002,78 +3292,33 @@ export class RestClient extends BaseRestClient { * Get currency detail for lending * * @param params Parameters for retrieving currency detail for lending - * @returns Promise> + * @returns Promise> */ - getLendingCurrency(params: { currency: string }): Promise< - APIResponse<{ - currency: string; - min_lend_amount: string; - max_lend_amount: string; - max_rate: string; - min_rate: string; - }> - > { - return this.get(`/earn/uni/currencies/${params.currency}`, params); + getLendingCurrency(params: { + currency: string; + }): Promise> { + return this.get(`/earn/uni/currencies/${params.currency}`); } /** * Lend or redeem * * @param params Parameters for lending or redeeming - * @returns Promise> + * @returns Promise> */ - submitLendOrRedeem(body: { - currency: string; - amount: string; - type: 'lend' | 'redeem'; - min_rate?: string; - }): Promise> { - return this.postPrivate(`/earn/uni/lends`, { body }); + submitLendOrRedeem(params: SubmitLendOrRedeemReq): Promise> { + return this.postPrivate(`/earn/uni/lends`, { body: params }); } /** * List user's lending orders * * @param params Parameters for listing user's lending orders - * @returns Promise> + * @returns Promise> */ - getLendingOrders(params?: { - currency?: string; - page?: number; - limit?: number; - }): Promise< - APIResponse< - { - currency: string; - current_amount: string; - amount: string; - lent_amount: string; - frozen_amount: string; - min_rate: string; - interest_status: string; - reinvest_left_amount: string; - create_time: number; - update_time: number; - }[] - > - > { + getLendingOrders( + params?: GetLendingOrdersReq, + ): Promise> { return this.getPrivate(`/earn/uni/lends`, params); } @@ -4096,36 +3341,11 @@ export class RestClient extends BaseRestClient { * List records of lending * * @param params Parameters for listing records of lending - * @returns Promise> + * @returns Promise> */ - getLendingRecords(params?: { - currency?: string; - page?: number; - limit?: number; - from?: number; - to?: number; - type?: 'lend' | 'redeem'; - }): Promise< - APIResponse< - { - currency: string; - amount: string; - last_wallet_amount: string; - last_lent_amount: string; - last_frozen_amount: string; - type: 'lend' | 'redeem'; - create_time: number; - }[] - > - > { + getLendingRecords( + params?: GetLendingRecordsReq, + ): Promise> { return this.getPrivate(`/earn/uni/lend_records`, params); } @@ -4151,33 +3371,11 @@ export class RestClient extends BaseRestClient { * List interest records * * @param params Parameters for listing interest records - * @returns Promise> + * @returns Promise> */ - getLendingInterestRecords(params?: { - currency?: string; - page?: number; - limit?: number; - from?: number; - to?: number; - }): Promise< - APIResponse< - { - status: number; - currency: string; - actual_rate: string; - interest: string; - interest_status: string; - create_time: number; - }[] - > - > { + getLendingInterestRecords( + params?: GetLendingInterestRecordsReq, + ): Promise> { return this.getPrivate(`/earn/uni/interest_records`, params); } @@ -4187,11 +3385,11 @@ export class RestClient extends BaseRestClient { * @param params Parameters for setting interest reinvestment toggle * @returns Promise> */ - updateInterestReinvestment(body: { + updateInterestReinvestment(params: { currency: string; status: boolean; }): Promise> { - return this.putPrivate(`/earn/uni/interest_reinvest`, { body }); + return this.putPrivate(`/earn/uni/interest_reinvest`, { body: params }); } /** @@ -4223,111 +3421,32 @@ export class RestClient extends BaseRestClient { * @param params Parameters for placing an order * @returns Promise> */ - submitLoanOrder(body: { - collateral_amount: string; - collateral_currency: string; - borrow_amount: string; - borrow_currency: string; - }): Promise> { - return this.postPrivate(`/loan/collateral/orders`, { body }); + submitLoanOrder( + params: SubmitLoanOrderReq, + ): Promise> { + return this.postPrivate(`/loan/collateral/orders`, { body: params }); } /** * List Orders * * @param params Parameters for listing orders - * @returns Promise> + * @returns Promise> */ - getLoanOrders(params?: { - page?: number; - limit?: number; - collateral_currency?: string; - borrow_currency?: string; - }): Promise< - APIResponse< - { - order_id: number; - collateral_currency: string; - collateral_amount: string; - borrow_currency: string; - borrow_amount: string; - repaid_amount: string; - repaid_principal: string; - repaid_interest: string; - init_ltv: string; - current_ltv: string; - liquidate_ltv: string; - status: string; - borrow_time: number; - left_repay_total: string; - left_repay_principal: string; - left_repay_interest: string; - }[] - > - > { + getLoanOrders( + params?: GetLoanOrdersReq, + ): Promise> { return this.getPrivate(`/loan/collateral/orders`, params); } - /** * Get a single order * * @param params Parameters for retrieving a single order - * @returns Promise> + * @returns Promise> */ - getLoanOrder(params: { order_id: number }): Promise< - APIResponse<{ - order_id: number; - collateral_currency: string; - collateral_amount: string; - borrow_currency: string; - borrow_amount: string; - repaid_amount: string; - repaid_principal: string; - repaid_interest: string; - init_ltv: string; - current_ltv: string; - liquidate_ltv: string; - status: string; - borrow_time: number; - left_repay_total: string; - left_repay_principal: string; - left_repay_interest: string; - }> - > { + getLoanOrder(params: { + order_id: number; + }): Promise> { return this.getPrivate(`/loan/collateral/orders/${params.order_id}`); } @@ -4340,7 +3459,7 @@ export class RestClient extends BaseRestClient { * repaid_interest: string; * }>> */ - submitLoanRepay(body: { + submitLoanRepay(params: { order_id: number; repay_amount: string; repaid_all: boolean; @@ -4350,56 +3469,18 @@ export class RestClient extends BaseRestClient { repaid_interest: string; }> > { - return this.postPrivate(`/loan/collateral/repay`, { body }); + return this.postPrivate(`/loan/collateral/repay`, { body: params }); } /** * Repayment history * * @param params Parameters for retrieving repayment history - * @returns Promise> + * @returns Promise> */ - getLoanRepaymentHistory(params: { - source: 'repay' | 'liquidate'; - borrow_currency?: string; - collateral_currency?: string; - page?: number; - limit?: number; - from?: number; - to?: number; - }): Promise< - APIResponse< - { - order_id: number; - record_id: number; - repaid_amount: string; - borrow_currency: string; - collateral_currency: string; - init_ltv: string; - borrow_time: number; - repay_time: number; - total_interest: string; - before_left_principal: string; - after_left_principal: string; - before_left_collateral: string; - after_left_collateral: string; - }[] - > - > { + getLoanRepaymentHistory( + params: GetLoanRepaymentHistoryReq, + ): Promise> { return this.getPrivate(`/loan/collateral/repay_records`, params); } @@ -4407,57 +3488,23 @@ export class RestClient extends BaseRestClient { * Increase or redeem collateral * * @param params Parameters for increasing or redeeming collateral - * @returns Promise> + * @returns Promise> */ - updateLoanCollateral(body: { - order_id: number; - collateral_currency: string; - collateral_amount: string; - type: 'append' | 'redeem'; - }): Promise> { - return this.postPrivate(`/loan/collateral/collaterals`, { body }); + updateLoanCollateral( + params: UpdateLoanCollateralReq, + ): Promise> { + return this.postPrivate(`/loan/collateral/collaterals`, { body: params }); } /** * Query collateral adjustment records * * @param params Parameters for querying collateral adjustment records - * @returns Promise> + * @returns Promise> */ - getLoanCollateralRecords(params?: { - page?: number; - limit?: number; - from?: number; - to?: number; - borrow_currency?: string; - collateral_currency?: string; - }): Promise< - APIResponse< - { - order_id: number; - record_id: number; - borrow_currency: string; - borrow_amount: string; - collateral_currency: string; - before_collateral: string; - after_collateral: string; - before_ltv: string; - after_ltv: string; - operate_time: number; - }[] - > - > { + getLoanCollateralRecords( + params?: GetLoanCollateralRecordsReq, + ): Promise> { return this.getPrivate(`/loan/collateral/collaterals`, params); } @@ -4482,30 +3529,12 @@ export class RestClient extends BaseRestClient { * Query user's collateralization ratio * * @param params Parameters for querying user's collateralization ratio - * @returns Promise> + * @returns Promise> */ getLoanCollateralizationRatio(params: { collateral_currency: string; borrow_currency: string; - }): Promise< - APIResponse<{ - collateral_currency: string; - borrow_currency: string; - init_ltv: string; - alert_ltv: string; - liquidate_ltv: string; - min_borrow_amount: string; - left_borrowable_amount: string; - }> - > { + }): Promise> { return this.getPrivate(`/loan/collateral/ltv`, params); } @@ -4540,91 +3569,21 @@ export class RestClient extends BaseRestClient { * @param params Parameters for creating a multi-collateral order * @returns Promise> */ - submitMultiLoanOrder(body: { - order_id?: string; - order_type?: string; - fixed_type?: string; - fixed_rate?: string; - auto_renew?: boolean; - auto_repay?: boolean; - borrow_currency: string; - borrow_amount: string; - collateral_currencies?: { - currency?: string; - amount?: string; - }[]; - }): Promise> { - return this.postPrivate(`/loan/multi_collateral/orders`, { body }); + submitMultiLoanOrder( + params: SubmitMultiLoanOrderReq, + ): Promise> { + return this.postPrivate(`/loan/multi_collateral/orders`, { body: params }); } /** * List Multi-Collateral Orders * * @param params Parameters for listing multi-collateral orders - * @returns Promise> + * @returns Promise> */ - getMultiLoanOrders(params?: { - page?: number; - limit?: number; - sort?: string; - order_type?: string; - }): Promise< - APIResponse< - { - order_id: string; - order_type: string; - fixed_type: string; - fixed_rate: string; - expire_time: number; - auto_renew: boolean; - auto_repay: boolean; - current_ltv: string; - status: string; - borrow_time: number; - total_left_repay_usdt: string; - total_left_collateral_usdt: string; - borrow_currencies: { - currency: string; - index_price: string; - left_repay_principal: string; - left_repay_interest: string; - left_repay_usdt: string; - }[]; - collateral_currencies: { - currency: string; - index_price: string; - left_collateral: string; - left_collateral_usdt: string; - }[]; - }[] - > - > { + getMultiLoanOrders( + params?: GetMultiLoanOrdersReq, + ): Promise> { return this.getPrivate(`/loan/multi_collateral/orders`, params); } @@ -4632,218 +3591,35 @@ export class RestClient extends BaseRestClient { * Get Multi-Collateral Order Detail * * @param params Parameters for retrieving a multi-collateral order detail - * @returns Promise> + * @returns Promise> */ - getMultiLoanOrder(params: { order_id: string }): Promise< - APIResponse<{ - order_id: string; - order_type: string; - fixed_type: string; - fixed_rate: string; - expire_time: number; - auto_renew: boolean; - auto_repay: boolean; - current_ltv: string; - status: string; - borrow_time: number; - total_left_repay_usdt: string; - total_left_collateral_usdt: string; - borrow_currencies: { - currency: string; - index_price: string; - left_repay_principal: string; - left_repay_interest: string; - left_repay_usdt: string; - }[]; - collateral_currencies: { - currency: string; - index_price: string; - left_collateral: string; - left_collateral_usdt: string; - }[]; - }> - > { - return this.getPrivate( - `/loan/multi_collateral/orders/${params.order_id}`, - params, - ); + getMultiLoanOrder(params: { + order_id: string; + }): Promise> { + return this.getPrivate(`/loan/multi_collateral/orders/${params.order_id}`); } /** * Repay Multi-Collateral Loan * * @param params Parameters for repaying a multi-collateral loan - * @returns Promise> + * @returns Promise> */ - repayMultiLoan(body: { - order_id: number; - repay_items: { - currency?: string; - amount?: string; - repaid_all?: boolean; - }[]; - }): Promise< - APIResponse<{ - order_id: number; - repaid_currencies: { - succeeded: boolean; - label?: string; - message?: string; - currency: string; - repaid_principal: string; - repaid_interest: string; - }[]; - }> - > { - return this.postPrivate(`/loan/multi_collateral/repay`, { body }); + repayMultiLoan( + params: RepayMultiLoanReq, + ): Promise> { + return this.postPrivate(`/loan/multi_collateral/repay`, { body: params }); } /** * List Multi-Collateral Repay Records * * @param params Parameters for listing multi-collateral repay records - * @returns Promise> + * @returns Promise> */ - getMultiLoanRepayRecords(params: { - type: 'repay' | 'liquidate'; - borrow_currency?: string; - page?: number; - limit?: number; - from?: number; - to?: number; - }): Promise< - APIResponse< - { - order_id: number; - record_id: number; - init_ltv: string; - before_ltv: string; - after_ltv: string; - borrow_time: number; - repay_time: number; - borrow_currencies: { - currency: string; - index_price: string; - before_amount: string; - before_amount_usdt: string; - after_amount: string; - after_amount_usdt: string; - }[]; - collateral_currencies: { - currency: string; - index_price: string; - before_amount: string; - before_amount_usdt: string; - after_amount: string; - after_amount_usdt: string; - }[]; - repaid_currencies: { - currency: string; - index_price: string; - repaid_amount: string; - repaid_principal: string; - repaid_interest: string; - repaid_amount_usdt: string; - }[]; - total_interest_list: { - currency: string; - index_price: string; - amount: string; - amount_usdt: string; - }[]; - left_repay_interest_list: { - currency: string; - index_price: string; - before_amount: string; - before_amount_usdt: string; - after_amount: string; - after_amount_usdt: string; - }[]; - }[] - > - > { + getMultiLoanRepayRecords( + params: GetMultiLoanRepayRecordsReq, + ): Promise> { return this.getPrivate(`/loan/multi_collateral/repay`, params); } @@ -4851,100 +3627,25 @@ export class RestClient extends BaseRestClient { * Operate Multi-Collateral * * @param params Parameters for operating multi-collateral - * @returns Promise> + * @returns Promise> */ - operateMultiLoan(body: { - order_id: number; - type: 'append' | 'redeem'; - collaterals?: { - currency?: string; - amount?: string; - }[]; - }): Promise< - APIResponse<{ - order_id: number; - collateral_currencies: { - succeeded: boolean; - label?: string; - message?: string; - currency: string; - amount: string; - }[]; - }> - > { - return this.postPrivate(`/loan/multi_collateral/mortgage`, { body }); + updateMultiLoan( + params: UpdateMultiLoanReq, + ): Promise> { + return this.postPrivate(`/loan/multi_collateral/mortgage`, { + body: params, + }); } /** * Query collateral adjustment records * * @param params Parameters for querying collateral adjustment records - * @returns Promise> + * @returns Promise> */ - getMultiLoanAdjustmentRecords(params?: { - page?: number; - limit?: number; - from?: number; - to?: number; - collateral_currency?: string; - }): Promise< - APIResponse< - { - order_id: number; - record_id: number; - before_ltv: string; - after_ltv: string; - operate_time: number; - borrow_currencies: { - currency: string; - index_price: string; - before_amount: string; - before_amount_usdt: string; - after_amount: string; - after_amount_usdt: string; - }[]; - collateral_currencies: { - currency: string; - index_price: string; - before_amount: string; - before_amount_usdt: string; - after_amount: string; - after_amount_usdt: string; - }[]; - }[] - > - > { + getMultiLoanAdjustmentRecords( + params?: GetMultiLoanAdjustmentRecordsReq, + ): Promise> { return this.getPrivate(`/loan/multi_collateral/mortgage`, params); } @@ -4952,58 +3653,22 @@ export class RestClient extends BaseRestClient { * List User Currency Quota * * @param params Parameters for listing user currency quota - * @returns Promise> + * @returns Promise> */ getMultiLoanCurrencyQuota(params: { type: 'collateral' | 'borrow'; currency: string; - }): Promise< - APIResponse< - { - currency: string; - index_price: string; - min_quota: string; - left_quota: string; - left_quote_usdt: string; - }[] - > - > { + }): Promise> { return this.getPrivate(`/loan/multi_collateral/currency_quota`, params); } /** * Query supported borrowing and collateral currencies in Multi-Collateral * - * @returns Promise> + * @returns Promise> */ getMultiLoanSupportedCurrencies(): Promise< - APIResponse<{ - loan_currencies: { - currency: string; - price: string; - }[]; - collateral_currencies: { - currency: string; - index_price: string; - discount: string; - }[]; - }> + APIResponse > { return this.get(`/loan/multi_collateral/currencies`); } @@ -5011,42 +3676,18 @@ export class RestClient extends BaseRestClient { /** * Get Multi-Collateral ratio * - * @returns Promise> + * @returns Promise> */ - getMultiLoanRatio(): Promise< - APIResponse<{ - init_ltv: string; - alert_ltv: string; - liquidate_ltv: string; - }> - > { + getMultiLoanRatio(): Promise> { return this.get(`/loan/multi_collateral/ltv`); } /** * Query fixed interest rates for the currency for 7 days and 30 days * - * @returns Promise> + * @returns Promise> */ - getMultiLoanFixedRates(): Promise< - APIResponse< - { - currency: string; - rate_7d: string; - rate_30d: string; - update_time: number; - }[] - > - > { + getMultiLoanFixedRates(): Promise> { return this.get(`/loan/multi_collateral/fixed_rate`); } @@ -5061,50 +3702,20 @@ export class RestClient extends BaseRestClient { * @param params Parameters for ETH2 swap * @returns Promise> */ - submitEth2Swap(body: { + submitEth2Swap(params: { side: '1' | '2'; amount: string; }): Promise> { - return this.postPrivate(`/earn/staking/eth2/swap`, { body }); + return this.postPrivate(`/earn/staking/eth2/swap`, { body: params }); } /** * Dual Investment product list * - * @returns Promise> + * @returns Promise> */ getDualInvestmentProducts(): Promise< - APIResponse< - { - id: number; - instrument_name: string; - invest_currency: string; - exercise_currency: string; - exercise_price: number; - delivery_time: number; - min_copies: number; - max_copies: number; - per_value: string; - apy_display: string; - start_time: number; - end_time: number; - status: 'NOTSTARTED' | 'ONGOING' | 'ENDED'; - }[] - > + APIResponse > { return this.get(`/earn/dual/investment_plan`); } @@ -5112,110 +3723,35 @@ export class RestClient extends BaseRestClient { /** * Dual Investment order list * - * @returns Promise> + * @returns Promise> */ getDualInvestmentOrders(): Promise< - APIResponse< - { - 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; - }[] - > + APIResponse > { return this.getPrivate(`/earn/dual/orders`); } - /** * Place Dual Investment order * * @param params Parameters for placing a dual investment order * @returns Promise> */ - submitDualInvestmentOrder(body: { + submitDualInvestmentOrder(params: { plan_id: string; copies: string; }): Promise> { - return this.postPrivate(`/earn/dual/orders`, { body }); + return this.postPrivate(`/earn/dual/orders`, { body: params }); } /** * Structured Product List * * @param params Parameters for listing structured products - * @returns Promise> + * @returns Promise> */ - getStructuredProductList(params: { - status: string; - type?: string; - page?: number; - limit?: number; - }): Promise< - APIResponse< - { - id: number; - type: string; - name_en: string; - investment_coin: string; - investment_period: string; - min_annual_rate: string; - mid_annual_rate: string; - max_annual_rate: string; - watch_market: string; - start_time: number; - end_time: number; - status: 'in_process' | 'will_begin' | 'wait_settlement' | 'done'; - }[] - > - > { + getStructuredProductList( + params: GetStructuredProductListReq, + ): Promise> { return this.get(`/earn/structured/products`, params); } @@ -5223,48 +3759,24 @@ export class RestClient extends BaseRestClient { * Structured Product Order List * * @param params Parameters for listing structured product orders - * @returns Promise> + * @returns Promise> */ - getStructuredProductOrders(params?: { - from?: number; - to?: number; - page?: number; - limit?: number; - }): Promise< - APIResponse< - { - id: number; - pid: string; - lock_coin: string; - amount: string; - status: 'SUCCESS' | 'FAILED' | 'DONE'; - income: string; - create_time: number; - }[] - > - > { + getStructuredProductOrders( + params?: GetStructuredProductOrdersReq, + ): Promise> { return this.getPrivate(`/earn/structured/orders`, params); } - /** * Place Structured Product Order * * @param params Parameters for placing a structured product order - * @returns Promise> + * @returns Promise> */ - submitStructuredProductOrder(body: { + submitStructuredProductOrder(params: { pid?: string; amount?: string; - }): Promise> { - return this.postPrivate(`/earn/structured/orders`, { body }); + }): Promise> { + return this.postPrivate(`/earn/structured/orders`, { body: params }); } /**========================================================================================================================== @@ -5275,27 +3787,9 @@ export class RestClient extends BaseRestClient { /** * Get account detail * - * @returns Promise> + * @returns Promise> */ - getAccountDetail(): Promise< - APIResponse<{ - user_id: number; - ip_whitelist: string[]; - currency_pairs: string[]; - key: { - mode: number; - }; - tier: number; - }> - > { + getAccountDetail(): Promise> { return this.getPrivate(`/account/detail`); } @@ -5303,50 +3797,23 @@ export class RestClient extends BaseRestClient { * Create STP Group * * @param params Parameters for creating an STP group - * @returns Promise> + * @returns Promise> */ - createStpGroup(body: { - id?: number; - name: string; - creator_id?: number; - create_time?: number; - }): Promise< - APIResponse<{ - id: number; - name: string; - creator_id: number; - create_time: number; - }> - > { - return this.postPrivate(`/account/stp_groups`, { body }); + createStpGroup( + params: CreateStpGroupReq, + ): Promise> { + return this.postPrivate(`/account/stp_groups`, { body: params }); } /** * List STP Groups * * @param params Parameters for listing STP groups - * @returns Promise> + * @returns Promise> */ - getStpGroups(params?: { name?: string }): Promise< - APIResponse< - { - id: number; - name: string; - creator_id: number; - create_time: number; - }[] - > - > { + getStpGroups(params?: { + name?: string; + }): Promise> { return this.getPrivate(`/account/stp_groups`, params); } @@ -5369,10 +3836,7 @@ export class RestClient extends BaseRestClient { }[] > > { - return this.getPrivate( - `/account/stp_groups/${params.stp_id}/users`, - params, - ); + return this.getPrivate(`/account/stp_groups/${params.stp_id}/users`); } /** @@ -5385,10 +3849,7 @@ export class RestClient extends BaseRestClient { * create_time: number; * }[]>> */ - addUsersToStpGroup( - params: { stp_id: number }, - body: number[], - ): Promise< + addUsersToStpGroup(params: { stp_id: number; body: number[] }): Promise< APIResponse< { user_id: number; @@ -5397,8 +3858,9 @@ export class RestClient extends BaseRestClient { }[] > > { - return this.postPrivate(`/account/stp_groups/${params.stp_id}/users`, { - body, + const { stp_id, ...body } = params; + return this.postPrivate(`/account/stp_groups/${stp_id}/users`, { + body: body, }); } @@ -5421,18 +3883,9 @@ export class RestClient extends BaseRestClient { }[] > > { - return this.deletePrivate(`/account/stp_groups/${params.stp_id}/users`, { - query: params, + const { stp_id, ...query } = params; + return this.deletePrivate(`/account/stp_groups/${stp_id}/users`, { + query: query, }); } - - /** - * - */ /** - * - */ /** - * - */ /** - * - */ } diff --git a/src/types/requests/shared.types.ts b/src/types/requests/shared.types.ts index 477c9c5..899feaf 100644 --- a/src/types/requests/shared.types.ts +++ b/src/types/requests/shared.types.ts @@ -682,3 +682,260 @@ export interface GetDeliveryAutoOrdersReq { * 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 GetOptionsCandlesticksReq { + contract: string; + limit?: number; + from?: number; + to?: number; + interval?: '1m' | '5m' | '15m' | '30m' | '1h'; +} + +export interface GetOptionsUnderlyingCandlesticksReq { + underlying: string; + limit?: number; + from?: number; + to?: number; + interval?: '1m' | '5m' | '15m' | '30m' | '1h'; +} + +export interface GetOptionsTradesReq { + contract?: string; + type?: 'C' | 'P'; + limit?: number; + offset?: number; + from?: number; + to?: number; +} + +export interface GetOptionsAccountChangeReq { + limit?: number; + offset?: number; + from?: number; + to?: number; + type?: 'dnw' | 'prem' | 'fee' | 'refr' | 'set'; +} + +export interface SubmitOptionsOrderReq { + contract: string; + size: number; + iceberg?: number; + price?: string; + close?: boolean; + reduce_only?: boolean; + tif?: 'gtc' | 'ioc' | 'poc'; + text?: string; +} + +export interface GetOptionsOrdersReq { + contract?: string; + underlying?: string; + status: 'open' | 'finished'; + limit?: number; + offset?: number; + from?: number; + to?: number; +} + +export interface GetOptionsPersonalHistoryReq { + underlying: string; + contract?: string; + limit?: number; + offset?: number; + from?: number; + to?: number; +} + +/**========================================================================================================================== + * EARN UNI + * ========================================================================================================================== + */ + +export interface SubmitLendOrRedeemReq { + currency: string; + amount: string; + type: 'lend' | 'redeem'; + min_rate?: string; +} + +export interface GetLendingOrdersReq { + currency?: string; + page?: number; + limit?: number; +} + +export interface GetLendingRecordsReq { + currency?: string; + page?: number; + limit?: number; + from?: number; + to?: number; + type?: 'lend' | 'redeem'; +} + +export interface GetLendingInterestRecordsReq { + currency?: string; + page?: number; + limit?: number; + from?: number; + to?: number; +} + +/**========================================================================================================================== + * COLLATERAL LOAN + * ========================================================================================================================== + */ + +export interface SubmitLoanOrderReq { + collateral_amount: string; + collateral_currency: string; + borrow_amount: string; + borrow_currency: string; +} + +export interface GetLoanOrdersReq { + page?: number; + limit?: number; + collateral_currency?: string; + borrow_currency?: string; +} + +export interface GetLoanRepaymentHistoryReq { + source: 'repay' | 'liquidate'; + borrow_currency?: string; + collateral_currency?: string; + page?: number; + limit?: number; + from?: number; + to?: number; +} + +export interface UpdateLoanCollateralReq { + order_id: number; + collateral_currency: string; + collateral_amount: string; + type: 'append' | 'redeem'; +} + +export interface GetLoanCollateralRecordsReq { + page?: number; + limit?: number; + from?: number; + to?: number; + borrow_currency?: string; + collateral_currency?: string; +} + +/**========================================================================================================================== + * MULTI COLLATERAL LOAN + * ========================================================================================================================== + */ + +export interface SubmitMultiLoanOrderReq { + order_id?: string; + order_type?: string; + fixed_type?: string; + fixed_rate?: string; + auto_renew?: boolean; + auto_repay?: boolean; + borrow_currency: string; + borrow_amount: string; + collateral_currencies?: { + currency?: string; + amount?: string; + }[]; +} +export interface GetMultiLoanOrdersReq { + page?: number; + limit?: number; + sort?: string; + order_type?: string; +} + +export interface RepayMultiLoanReq { + order_id: number; + repay_items: { + currency?: string; + amount?: string; + repaid_all?: boolean; + }[]; +} + +export interface GetMultiLoanRepayRecordsReq { + type: 'repay' | 'liquidate'; + borrow_currency?: string; + page?: number; + limit?: number; + from?: number; + to?: number; +} + +export interface UpdateMultiLoanReq { + order_id: number; + type: 'append' | 'redeem'; + collaterals?: { + currency?: string; + amount?: string; + }[]; +} + +export interface GetMultiLoanAdjustmentRecordsReq { + page?: number; + limit?: number; + from?: number; + to?: number; + collateral_currency?: string; +} + +/**========================================================================================================================== + * EARN + * ========================================================================================================================== + */ + +export interface GetStructuredProductListReq { + status: string; + type?: string; + page?: number; + limit?: number; +} + +export interface GetStructuredProductOrdersReq { + from?: number; + to?: number; + page?: number; + limit?: number; +} + +/**========================================================================================================================== + * ACCOUNT + * ========================================================================================================================== + */ + +export interface CreateStpGroupReq { + name: string; + id?: number; + creator_id?: number; + create_time?: number; +} diff --git a/src/types/response/shared.types.ts b/src/types/response/shared.types.ts index 8079990..80438ee 100644 --- a/src/types/response/shared.types.ts +++ b/src/types/response/shared.types.ts @@ -1129,3 +1129,566 @@ export interface GetDeliverySettlementHistoryResp { * OPTIONS * ========================================================================================================================== */ + +export interface GetOptionsContractsResp { + name: string; + tag: string; + create_time: number; + expiration_time: number; + is_call: boolean; + strike_price: string; + last_price: string; + mark_price: string; + orderbook_id: number; + trade_id: number; + trade_size: number; + position_size: number; + underlying: string; + underlying_price: string; + multiplier: string; + order_price_round: string; + mark_price_round: string; + maker_fee_rate: string; + taker_fee_rate: string; + price_limit_fee_rate: string; + ref_discount_rate: string; + ref_rebate_rate: string; + order_price_deviate: string; + order_size_min: number; + order_size_max: number; + orders_limit: number; +} + +export interface GetOptionsSettlementHistoryResp { + time: number; + contract: string; + profit: string; + fee: string; + strike_price: string; + settle_price: string; +} + +export interface GetOptionsMySettlementsResp { + time: number; + underlying: string; + contract: string; + strike_price: string; + settle_price: string; + size: number; + settle_profit: string; + fee: string; + realised_pnl: string; +} + +export interface GetOptionsOrderBookResp { + id?: number; + current: number; + update: number; + asks: { p: string; s: number }[]; + bids: { p: string; s: number }[]; +} + +export interface GetOptionsTickersResp { + name: string; + last_price: string; + mark_price: string; + index_price: string; + ask1_size: number; + ask1_price: string; + bid1_size: number; + bid1_price: string; + position_size: number; + mark_iv: string; + bid_iv: string; + ask_iv: string; + leverage: string; + delta: string; + gamma: string; + vega: string; + theta: string; + rho: string; +} + +export interface GetOptionsCandlesticksResp { + t: number; + v?: number; + c: string; + h: string; + l: string; + o: string; +} + +export interface GetOptionsUnderlyingCandlesticksResp { + t: number; + v?: number; + c: string; + h: string; + l: string; + o: string; + sum: string; +} + +export interface GetOptionsTradesResp { + id: number; + create_time: number; + create_time_ms: number; + contract: string; + size: number; + price: string; + is_internal?: boolean; +} + +export interface GetOptionsAccountResp { + user: number; + total: string; + short_enabled: boolean; + unrealised_pnl: string; + init_margin: string; + maint_margin: string; + order_margin: string; + available: string; + point: string; + currency: string; +} +export interface GetOptionsAccountChangeResp { + time: number; + change: string; + balance: string; + type: 'dnw' | 'prem' | 'fee' | 'refr' | 'set'; + text: string; +} + +export interface GetOptionsPositionsUnderlyingResp { + user: number; + underlying: string; + underlying_price: string; + contract: string; + size: number; + entry_price: string; + mark_price: string; + mark_iv: string; + realised_pnl: string; + unrealised_pnl: string; + pending_orders: number; + close_order: { + id: number; + price: string; + is_liq: boolean; + } | null; + delta: string; + gamma: string; + vega: string; + theta: string; +} + +export interface GetOptionsLiquidationResp { + time: number; + contract: string; + side: 'long' | 'short'; + pnl: string; + text: string; + settle_size: string; +} + +export interface SubmitOptionsOrderResp { + id: number; + user: number; + create_time: number; + finish_time: number; + finish_as: + | 'filled' + | 'cancelled' + | 'liquidated' + | 'ioc' + | 'auto_deleveraged' + | 'reduce_only' + | 'position_closed'; + status: 'open' | 'finished'; + contract: string; + size: number; + iceberg: number; + price: string; + is_close: boolean; + is_reduce_only: boolean; + is_liq: boolean; + tif: 'gtc' | 'ioc' | 'poc'; + left: number; + fill_price: string; + text: string; + tkfr: string; + mkfr: string; + refu: number; + refr: string; +} + +export interface GetOptionsPersonalHistoryResp { + id: number; + create_time: number; + contract: string; + order_id: number; + size: number; + price: string; + underlying_price: string; + role: 'taker' | 'maker'; +} + +/**========================================================================================================================== + * EARN UNI + * ========================================================================================================================== + */ + +export interface GetLendingCurrenciesResp { + currency: string; + min_lend_amount: string; + max_lend_amount: string; + max_rate: string; + min_rate: string; +} + +export interface GetLendingOrdersResp { + currency: string; + current_amount: string; + amount: string; + lent_amount: string; + frozen_amount: string; + min_rate: string; + interest_status: string; + reinvest_left_amount: string; + create_time: number; + update_time: number; +} + +export interface GetLendingRecordsResp { + currency: string; + amount: string; + last_wallet_amount: string; + last_lent_amount: string; + last_frozen_amount: string; + type: 'lend' | 'redeem'; + create_time: number; +} + +export interface GetLendingInterestRecordsResp { + status: number; + currency: string; + actual_rate: string; + interest: string; + interest_status: string; + create_time: number; +} + +/**========================================================================================================================== + * COLLATERAL LOAN + * ========================================================================================================================== + */ + +export interface GetLoanOrdersResp { + order_id: number; + collateral_currency: string; + collateral_amount: string; + borrow_currency: string; + borrow_amount: string; + repaid_amount: string; + repaid_principal: string; + repaid_interest: string; + init_ltv: string; + current_ltv: string; + liquidate_ltv: string; + status: string; + borrow_time: number; + left_repay_total: string; + left_repay_principal: string; + left_repay_interest: string; +} + +export interface GetLoanRepaymentHistoryResp { + order_id: number; + record_id: number; + repaid_amount: string; + borrow_currency: string; + collateral_currency: string; + init_ltv: string; + borrow_time: number; + repay_time: number; + total_interest: string; + before_left_principal: string; + after_left_principal: string; + before_left_collateral: string; + after_left_collateral: string; +} + +export interface GetLoanCollateralRecordsResp { + order_id: number; + record_id: number; + borrow_currency: string; + borrow_amount: string; + collateral_currency: string; + before_collateral: string; + after_collateral: string; + before_ltv: string; + after_ltv: string; + operate_time: number; +} + +export interface GetLoanCollateralizationRatioResp { + collateral_currency: string; + borrow_currency: string; + init_ltv: string; + alert_ltv: string; + liquidate_ltv: string; + min_borrow_amount: string; + left_borrowable_amount: string; +} + +/**========================================================================================================================== + * MULTI COLLATERAL LOAN + * ========================================================================================================================== + */ + +export interface GetMultiLoanOrdersResp { + order_id: string; + order_type: string; + fixed_type: string; + fixed_rate: string; + expire_time: number; + auto_renew: boolean; + auto_repay: boolean; + current_ltv: string; + status: string; + borrow_time: number; + total_left_repay_usdt: string; + total_left_collateral_usdt: string; + borrow_currencies: { + currency: string; + index_price: string; + left_repay_principal: string; + left_repay_interest: string; + left_repay_usdt: string; + }[]; + collateral_currencies: { + currency: string; + index_price: string; + left_collateral: string; + left_collateral_usdt: string; + }[]; +} + +export interface RepayMultiLoanResp { + order_id: number; + repaid_currencies: { + succeeded: boolean; + label?: string; + message?: string; + currency: string; + repaid_principal: string; + repaid_interest: string; + }[]; +} + +export interface GetMultiLoanRepayRecordsResp { + order_id: number; + record_id: number; + init_ltv: string; + before_ltv: string; + after_ltv: string; + borrow_time: number; + repay_time: number; + borrow_currencies: { + currency: string; + index_price: string; + before_amount: string; + before_amount_usdt: string; + after_amount: string; + after_amount_usdt: string; + }[]; + collateral_currencies: { + currency: string; + index_price: string; + before_amount: string; + before_amount_usdt: string; + after_amount: string; + after_amount_usdt: string; + }[]; + repaid_currencies: { + currency: string; + index_price: string; + repaid_amount: string; + repaid_principal: string; + repaid_interest: string; + repaid_amount_usdt: string; + }[]; + total_interest_list: { + currency: string; + index_price: string; + amount: string; + amount_usdt: string; + }[]; + left_repay_interest_list: { + currency: string; + index_price: string; + before_amount: string; + before_amount_usdt: string; + after_amount: string; + after_amount_usdt: string; + }[]; +} + +export interface UpdateMultiLoanResp { + order_id: number; + collateral_currencies: { + succeeded: boolean; + label?: string; + message?: string; + currency: string; + amount: string; + }[]; +} + +export interface GetMultiLoanAdjustmentRecordsResp { + order_id: number; + record_id: number; + before_ltv: string; + after_ltv: string; + operate_time: number; + borrow_currencies: { + currency: string; + index_price: string; + before_amount: string; + before_amount_usdt: string; + after_amount: string; + after_amount_usdt: string; + }[]; + collateral_currencies: { + currency: string; + index_price: string; + before_amount: string; + before_amount_usdt: string; + after_amount: string; + after_amount_usdt: string; + }[]; +} + +export interface GetMultiLoanCurrencyQuotaResp { + currency: string; + index_price: string; + min_quota: string; + left_quota: string; + left_quote_usdt: string; +} + +export interface GetMultiLoanSupportedCurrenciesResp { + loan_currencies: { + currency: string; + price: string; + }[]; + collateral_currencies: { + currency: string; + index_price: string; + discount: string; + }[]; +} + +export interface GetMultiLoanRatioResp { + init_ltv: string; + alert_ltv: string; + liquidate_ltv: string; +} + +export interface GetMultiLoanFixedRatesResp { + currency: string; + rate_7d: string; + rate_30d: string; + update_time: number; +} + +/**========================================================================================================================== + * EARN + * ========================================================================================================================== + */ + +export interface GetDualInvestmentProductsResp { + id: number; + instrument_name: string; + invest_currency: string; + exercise_currency: string; + exercise_price: number; + delivery_time: number; + min_copies: number; + max_copies: number; + per_value: string; + apy_display: string; + start_time: number; + end_time: number; + status: 'NOTSTARTED' | 'ONGOING' | 'ENDED'; +} + +export interface GetDualInvestmentOrdersResp { + id: number; + plan_id: number; + copies: string; + invest_amount: string; + settlement_amount: string; + create_time: number; + complete_time: number; + status: + | 'INIT' + | 'SETTLEMENT_SUCCESS' + | 'SETTLEMENT_PROCESSING' + | 'CANCELED' + | 'FAILED'; + invest_currency: string; + exercise_currency: string; + exercise_price: string; + settlement_price: string; + settlement_currency: string; + apy_display: string; + apy_settlement: string; + delivery_time: number; +} + +export interface GetStructuredProductListResp { + id: number; + type: string; + name_en: string; + investment_coin: string; + investment_period: string; + min_annual_rate: string; + mid_annual_rate: string; + max_annual_rate: string; + watch_market: string; + start_time: number; + end_time: number; + status: 'in_process' | 'will_begin' | 'wait_settlement' | 'done'; +} + +export interface GetStructuredProductOrdersResp { + id: number; + pid: string; + lock_coin: string; + amount: string; + status: 'SUCCESS' | 'FAILED' | 'DONE'; + income: string; + create_time: number; +} + +/**========================================================================================================================== + * ACCOUNT + * ========================================================================================================================== + */ + +export interface GetAccountDetailResp { + user_id: number; + ip_whitelist: string[]; + currency_pairs: string[]; + key: { + mode: number; + }; + tier: number; +} + +export interface CreateStpGroupResp { + id: number; + name: string; + creator_id: number; + create_time: number; +} From 1d004e8465dd8b20c131c36d4350c1f8fbd4af45 Mon Sep 17 00:00:00 2001 From: Jerko J <83344666+JJ-Cro@users.noreply.github.com> Date: Wed, 22 May 2024 14:51:31 +0200 Subject: [PATCH 30/36] feat(): added examples, finished adding all types, minor changes --- .gitignore | 2 + examples/futures/getBalances.ts | 25 ++++ examples/futures/getOrders.ts | 35 +++++ examples/futures/getTickers.ts | 34 +++++ examples/futures/submitLimitOrder.ts | 31 +++++ examples/futures/submitMarketOrder.ts | 29 +++++ examples/rest-private.ts | 6 +- examples/spot/getBalances.ts | 25 ++++ examples/spot/getOrders.ts | 35 +++++ examples/spot/getTickers.ts | 31 +++++ examples/spot/submitLimitOrder.ts | 32 +++++ examples/spot/submitMarketOrder.ts | 31 +++++ src/RestClient.ts | 177 ++++++++------------------ src/types/requests/shared.types.ts | 44 +++++++ src/types/response/shared.types.ts | 6 + 15 files changed, 417 insertions(+), 126 deletions(-) create mode 100644 examples/futures/getBalances.ts create mode 100644 examples/futures/getOrders.ts create mode 100644 examples/futures/getTickers.ts create mode 100644 examples/futures/submitLimitOrder.ts create mode 100644 examples/futures/submitMarketOrder.ts create mode 100644 examples/spot/getBalances.ts create mode 100644 examples/spot/getOrders.ts create mode 100644 examples/spot/getTickers.ts create mode 100644 examples/spot/submitLimitOrder.ts create mode 100644 examples/spot/submitMarketOrder.ts diff --git a/.gitignore b/.gitignore index 512e5d9..8f61009 100644 --- a/.gitignore +++ b/.gitignore @@ -23,3 +23,5 @@ bundleReport.html .history/ dist coverage +localtest.sh + diff --git a/examples/futures/getBalances.ts b/examples/futures/getBalances.ts new file mode 100644 index 0000000..3d2a3bc --- /dev/null +++ b/examples/futures/getBalances.ts @@ -0,0 +1,25 @@ +import { RestClient } from '../../src'; + +const account = { + key: process.env.API_KEY || 'yourApiHere', + secret: process.env.API_SECRET || 'yourSecretHere', +}; + +const gateRestClient = new RestClient({ + apiKey: account.key, + apiSecret: account.secret, +}); + +async function getFuturesBalances() { + try { + console.log('Using API keys:', account); + + // GET specific ticker + const ticker = await gateRestClient.getFuturesAccount({ settle: 'usdt' }); + console.log('Response: ', ticker); + } catch (e) { + console.error(`Error in execution: `, e); + } +} + +getFuturesBalances(); diff --git a/examples/futures/getOrders.ts b/examples/futures/getOrders.ts new file mode 100644 index 0000000..2d95044 --- /dev/null +++ b/examples/futures/getOrders.ts @@ -0,0 +1,35 @@ +import { RestClient } from '../../src'; + +const account = { + key: process.env.API_KEY || 'yourApiHere', + secret: process.env.API_SECRET || 'yourSecretHere', +}; + +const gateRestClient = new RestClient({ + apiKey: account.key, + apiSecret: account.secret, +}); + +async function getFuturesOrders() { + try { + console.log('Using API keys:', account); + + // get open orders + const orders = await gateRestClient.getFuturesOrders({ + settle: 'usdt', + status: 'open', + }); + console.log('Response: ', orders); + + // get finished orders + const orders1 = await gateRestClient.getFuturesOrders({ + settle: 'usdt', + status: 'finished', + }); + console.log('Response: ', orders1); + } catch (e) { + console.error(`Error in execution: `, e); + } +} + +getFuturesOrders(); diff --git a/examples/futures/getTickers.ts b/examples/futures/getTickers.ts new file mode 100644 index 0000000..8f3419a --- /dev/null +++ b/examples/futures/getTickers.ts @@ -0,0 +1,34 @@ +import { RestClient } from '../../src'; + +const account = { + key: process.env.API_KEY || 'yourApiHere', + secret: process.env.API_SECRET || 'yourSecretHere', +}; + +const gateRestClient = new RestClient({ + apiKey: account.key, + apiSecret: account.secret, +}); + +async function getFuturesTicker() { + try { + console.log('Using API keys:', account); + + // GET specific ticker + const ticker = await gateRestClient.getFuturesTickers({ + settle: 'usdt', + }); + console.log('Response: ', ticker); + + /* GET all tickers */ + const allTickers = await gateRestClient.getFuturesTickers({ + settle: 'usdt', + contract: 'BTC_USDT', + }); + console.log('Response: ', allTickers); + } catch (e) { + console.error(`Error in execution: `, e); + } +} + +getFuturesTicker(); diff --git a/examples/futures/submitLimitOrder.ts b/examples/futures/submitLimitOrder.ts new file mode 100644 index 0000000..e37b8ab --- /dev/null +++ b/examples/futures/submitLimitOrder.ts @@ -0,0 +1,31 @@ +import { RestClient } from '../../src'; + +const account = { + key: process.env.API_KEY || 'yourApiHere', + secret: process.env.API_SECRET || 'yourSecretHere', +}; + +const gateRestClient = new RestClient({ + apiKey: account.key, + apiSecret: account.secret, +}); + +async function submitFuturesOrder() { + try { + console.log('Using API keys:', account); + + const result = await gateRestClient.submitFuturesOrder({ + settle: 'usdt', + contract: 'BTC_USDT', + size: 0.1, // positive for long, negative for short + price: '45000', + tif: 'gtc', + }); + + console.log('Response: ', result); + } catch (e) { + console.error(`Error in execution: `, e); + } +} + +submitFuturesOrder(); diff --git a/examples/futures/submitMarketOrder.ts b/examples/futures/submitMarketOrder.ts new file mode 100644 index 0000000..90ba63d --- /dev/null +++ b/examples/futures/submitMarketOrder.ts @@ -0,0 +1,29 @@ +import { RestClient } from '../../src'; + +const account = { + key: process.env.API_KEY || 'yourApiHere', + secret: process.env.API_SECRET || 'yourSecretHere', +}; + +const gateRestClient = new RestClient({ + apiKey: account.key, + apiSecret: account.secret, +}); + +async function submitFuturesOrder() { + try { + console.log('Using API keys:', account); + + const result = await gateRestClient.submitFuturesOrder({ + settle: 'usdt', + contract: 'BTC_USDT', + size: 0.1, // positive for long, negative for short + }); + + console.log('Response: ', result); + } catch (e) { + console.error(`Error in execution: `, e); + } +} + +submitFuturesOrder(); diff --git a/examples/rest-private.ts b/examples/rest-private.ts index af99b83..841e554 100644 --- a/examples/rest-private.ts +++ b/examples/rest-private.ts @@ -3,10 +3,8 @@ import { RestClient } from '../src'; async function start() { try { const account = { - key: process.env.API_KEY || 'a4ed617b3c02b6a9d4900be5446f402d', - secret: - process.env.API_SECRET || - '68151540a9808cd12bb57ed31e2fa868f5022879bf969eb27cfd7125c0dcea6e', + key: process.env.API_KEY || 'yourApiHere', + secret: process.env.API_SECRET || 'YourSecretHere', }; console.log('using creds: ', account); diff --git a/examples/spot/getBalances.ts b/examples/spot/getBalances.ts new file mode 100644 index 0000000..88a93fb --- /dev/null +++ b/examples/spot/getBalances.ts @@ -0,0 +1,25 @@ +import { RestClient } from '../../src'; + +const account = { + key: process.env.API_KEY || 'yourApiHere', + secret: process.env.API_SECRET || 'yourSecretHere', +}; + +const gateRestClient = new RestClient({ + apiKey: account.key, + apiSecret: account.secret, +}); + +async function getSpotBalances() { + try { + console.log('Using API keys:', account); + + // GET specific ticker + const ticker = await gateRestClient.getSpotAccounts(); + console.log('Response: ', ticker); + } catch (e) { + console.error(`Error in execution: `, e); + } +} + +getSpotBalances(); diff --git a/examples/spot/getOrders.ts b/examples/spot/getOrders.ts new file mode 100644 index 0000000..d51a1c1 --- /dev/null +++ b/examples/spot/getOrders.ts @@ -0,0 +1,35 @@ +import { RestClient } from '../../src'; + +const account = { + key: process.env.API_KEY || 'yourApiHere', + secret: process.env.API_SECRET || 'yourSecretHere', +}; + +const gateRestClient = new RestClient({ + apiKey: account.key, + apiSecret: account.secret, +}); + +async function getSpotOrders() { + try { + console.log('Using API keys:', account); + + // get open orders + const orders = await gateRestClient.getSpotOrders({ + currency_pair: 'BTC_USDT', + status: 'open', + }); + console.log('Response: ', orders); + + // get finished orders + const orders1 = await gateRestClient.getSpotOrders({ + currency_pair: 'BTC_USDT', + status: 'finished', + }); + console.log('Response: ', orders1); + } catch (e) { + console.error(`Error in execution: `, e); + } +} + +getSpotOrders(); diff --git a/examples/spot/getTickers.ts b/examples/spot/getTickers.ts new file mode 100644 index 0000000..82cee2f --- /dev/null +++ b/examples/spot/getTickers.ts @@ -0,0 +1,31 @@ +import { RestClient } from '../../src'; + +const account = { + key: process.env.API_KEY || 'yourApiHere', + secret: process.env.API_SECRET || 'yourSecretHere', +}; + +const gateRestClient = new RestClient({ + apiKey: account.key, + apiSecret: account.secret, +}); + +async function getSpotTicker() { + try { + console.log('Using API keys:', account); + + // GET specific ticker + const ticker = await gateRestClient.getSpotTicker({ + currency_pair: 'BTC_USDT', + }); + console.log('Response: ', ticker); + + /* GET all tickers */ + const allTickers = await gateRestClient.getSpotTicker(); + console.log('Response: ', allTickers); + } catch (e) { + console.error(`Error in execution: `, e); + } +} + +getSpotTicker(); diff --git a/examples/spot/submitLimitOrder.ts b/examples/spot/submitLimitOrder.ts new file mode 100644 index 0000000..a94c465 --- /dev/null +++ b/examples/spot/submitLimitOrder.ts @@ -0,0 +1,32 @@ +import { RestClient } from '../../src'; + +const account = { + key: process.env.API_KEY || 'yourApiHere', + secret: process.env.API_SECRET || 'yourSecretHere', +}; + +const gateRestClient = new RestClient({ + apiKey: account.key, + apiSecret: account.secret, +}); + +async function submitSpotOrder() { + try { + console.log('Using API keys:', account); + + const result = await gateRestClient.submitSpotOrder({ + currency_pair: 'BTC_USDT', + side: 'buy', + type: 'limit', + amount: '0.10', + price: '45000', + time_in_force: 'gtc', + }); + + console.log('Response: ', result); + } catch (e) { + console.error(`Error in execution: `, e); + } +} + +submitSpotOrder(); diff --git a/examples/spot/submitMarketOrder.ts b/examples/spot/submitMarketOrder.ts new file mode 100644 index 0000000..6481b14 --- /dev/null +++ b/examples/spot/submitMarketOrder.ts @@ -0,0 +1,31 @@ +import { RestClient } from '../../src'; + +const account = { + key: process.env.API_KEY || 'yourApiHere', + secret: process.env.API_SECRET || 'yourSecretHere', +}; + +const gateRestClient = new RestClient({ + apiKey: account.key, + apiSecret: account.secret, +}); + +async function submitSpotOrder() { + try { + console.log('Using API keys:', account); + + const result = await gateRestClient.submitSpotOrder({ + currency_pair: 'BTC_USDT', + side: 'buy', + type: 'market', + amount: '10', + time_in_force: 'ioc', + }); + + console.log('Response: ', result); + } catch (e) { + console.error(`Error in execution: `, e); + } +} + +submitSpotOrder(); diff --git a/src/RestClient.ts b/src/RestClient.ts index aae44e2..52423c4 100644 --- a/src/RestClient.ts +++ b/src/RestClient.ts @@ -1,8 +1,3 @@ -// double check if names are set to what the call represents(get, delete, update etc...) -// check in all non-get calls that query params and body params are as it should be -// check all inputs where we have a path to make sure all is right. -// check for voids - import { AxiosRequestConfig } from 'axios'; import { @@ -14,6 +9,7 @@ import { RestClientOptions } from './lib/requestUtils.js'; import { CreateStpGroupReq, CreateSubAccountApiKeyReq, + CreateSubAccountReq, DeleteAllFuturesOrdersReq, DeleteSpotOrderReq, GetCrossMarginAccountHistoryReq, @@ -97,11 +93,15 @@ import { SubmitFuturesPriceTriggeredOrderReq, SubmitLendOrRedeemReq, SubmitLoanOrderReq, + SubmitMainSubTransferReq, SubmitMultiLoanOrderReq, SubmitOptionsOrderReq, SubmitSpotClosePosCrossDisabledReq, SubmitSpotOrderReq, + SubmitSubToSubTransferReq, + SubmitTransferReq, SubmitUnifiedBorrowOrRepayReq, + SubmitWithdrawReq, UpdateDualModePositionLeverageReq, UpdateDualModePositionMarginReq, UpdateLoanCollateralReq, @@ -212,6 +212,7 @@ import { GetWithdrawalStatusResp, PortfolioMarginCalculatorResp, RepayMultiLoanResp, + StpResp, SubAccountCrossMarginBalancesResp, SubAccountFuturesBalancesResp, SubAccountMarginBalancesResp, @@ -271,14 +272,7 @@ export class RestClient extends BaseRestClient { * @param params Withdrawal parameters * @returns Promise> */ - submitWithdraw(params: { - withdraw_order_id?: string; - amount: string; - currency: string; - address?: string; - memo?: string; - chain: string; - }): Promise> { + submitWithdraw(params: SubmitWithdrawReq): Promise> { return this.postPrivate('/withdrawals', { query: params }); } @@ -364,20 +358,9 @@ export class RestClient extends BaseRestClient { * @param params Transfer parameters * @returns Promise> */ - submitTransfer(params: { - 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; - }): Promise> { + submitTransfer( + params: SubmitTransferReq, + ): Promise> { return this.postPrivate('/wallet/transfers', { body: params }); } @@ -389,14 +372,9 @@ export class RestClient extends BaseRestClient { * @param params Transfer parameters * @returns Promise> */ - submitMainSubTransfer(params: { - currency: string; - sub_account: string; - direction: 'to' | 'from'; - amount: string; - client_order_id?: string; - sub_account_type?: 'spot' | 'futures' | 'cross_margin' | 'delivery'; - }): Promise> { + submitMainSubTransfer( + params: SubmitMainSubTransferReq, + ): Promise> { return this.postPrivate('/wallet/sub_account_transfers', { body: params }); } @@ -424,15 +402,9 @@ export class RestClient extends BaseRestClient { * @param params Transfer parameters * @returns Promise> */ - submitSubToSubTransfer(params: { - currency: string; - sub_account_type?: 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; - }): Promise> { + submitSubToSubTransfer( + params: SubmitSubToSubTransferReq, + ): Promise> { return this.postPrivate('/wallet/sub_account_to_sub_account', { body: params, }); @@ -565,11 +537,11 @@ export class RestClient extends BaseRestClient { * Convert small balance * * @param params Parameters for converting small balance - * @returns Promise> + * @returns Promise> */ convertSmallBalance(params?: { currency?: string[]; - }): Promise> { + }): Promise> { return this.postPrivate('/wallet/small_balance', { body: params }); } @@ -596,12 +568,9 @@ export class RestClient extends BaseRestClient { * @param params Parameters for creating a new sub-account * @returns Promise> */ - createSubAccount(params: { - remark?: string; - login_name: string; - password?: string; - email?: string; - }): Promise> { + createSubAccount( + params: CreateSubAccountReq, + ): Promise> { return this.postPrivate('/sub_accounts', { body: params }); } @@ -701,9 +670,9 @@ export class RestClient extends BaseRestClient { * Lock the sub-account * * @param params Parameters containing the sub-account user ID - * @returns Promise> + * @returns Promise> */ - lockSubAccount(params: { user_id: number }): Promise> { + lockSubAccount(params: { user_id: number }): Promise> { return this.postPrivate(`/sub_accounts/${params.user_id}/lock`); } @@ -711,9 +680,9 @@ export class RestClient extends BaseRestClient { * Unlock the sub-account * * @param params Parameters containing the sub-account user ID - * @returns Promise> + * @returns Promise> */ - unlockSubAccount(params: { user_id: number }): Promise> { + unlockSubAccount(params: { user_id: number }): Promise> { return this.postPrivate(`/sub_accounts/${params.user_id}/unlock`); } /**========================================================================================================================== @@ -781,11 +750,11 @@ export class RestClient extends BaseRestClient { * For repayment, the option to repay the entire borrowed amount is available by setting the parameter repaid_all=true * * @param params Parameters for borrowing or repaying - * @returns Promise> + * @returns Promise> */ submitUnifiedBorrowOrRepay( params: SubmitUnifiedBorrowOrRepayReq, - ): Promise> { + ): Promise> { return this.postPrivate('/unified/loans', { body: params }); } @@ -842,11 +811,11 @@ export class RestClient extends BaseRestClient { * Switching between different account modes requires only passing the parameters corresponding to the target account mode. It also supports opening or closing configuration switches for the corresponding account mode when switching. * * @param params Parameters for setting the mode of the unified account - * @returns Promise> + * @returns Promise> */ updateUnifiedAccountMode( params: SetUnifiedAccountModeReq, - ): Promise> { + ): Promise> { return this.putPrivate('/unified/unified_mode', { body: params }); } @@ -928,16 +897,7 @@ export class RestClient extends BaseRestClient { * Get details of a specific currency * * @param params Parameters for retrieving details of a specific currency - * @returns Promise> + * @returns Promise> */ getSpotCurrency(params: { currency: string; @@ -1194,7 +1154,8 @@ export class RestClient extends BaseRestClient { currency_pair: string; account?: 'spot' | 'margin' | 'cross_margin' | 'unified'; }): Promise> { - return this.getPrivate(`/spot/orders/${params.order_id}`, params); + const { order_id, ...query } = params; + return this.getPrivate(`/spot/orders/${order_id}`, query); } /** @@ -3184,7 +3145,7 @@ export class RestClient extends BaseRestClient { getOptionsPositionContract(params: { contract: string; }): Promise> { - return this.getPrivate(`/options/positions/${params.contract}`, params); + return this.getPrivate(`/options/positions/${params.contract}`); } /** @@ -3328,12 +3289,12 @@ export class RestClient extends BaseRestClient { * Currently only supports amending the minimum interest rate (hour) * * @param params Parameters for amending lending order - * @returns Promise> + * @returns Promise> */ updateLendingOrder(params: { currency?: string; min_rate?: string; - }): Promise> { + }): Promise> { return this.patchPrivate(`/earn/uni/lends`, { query: params }); } @@ -3383,12 +3344,12 @@ export class RestClient extends BaseRestClient { * Set interest reinvestment toggle * * @param params Parameters for setting interest reinvestment toggle - * @returns Promise> + * @returns Promise> */ updateInterestReinvestment(params: { currency: string; status: boolean; - }): Promise> { + }): Promise> { return this.putPrivate(`/earn/uni/interest_reinvest`, { body: params }); } @@ -3700,12 +3661,12 @@ export class RestClient extends BaseRestClient { * ETH2 swap * * @param params Parameters for ETH2 swap - * @returns Promise> + * @returns Promise> */ submitEth2Swap(params: { side: '1' | '2'; amount: string; - }): Promise> { + }): Promise> { return this.postPrivate(`/earn/staking/eth2/swap`, { body: params }); } @@ -3734,12 +3695,12 @@ export class RestClient extends BaseRestClient { * Place Dual Investment order * * @param params Parameters for placing a dual investment order - * @returns Promise> + * @returns Promise> */ submitDualInvestmentOrder(params: { plan_id: string; copies: string; - }): Promise> { + }): Promise> { return this.postPrivate(`/earn/dual/orders`, { body: params }); } @@ -3821,21 +3782,11 @@ export class RestClient extends BaseRestClient { * List users of the STP group * * @param params Parameters for listing users of the STP group - * @returns Promise> + * @returns Promise> */ - getStpGroupUsers(params: { stp_id: number }): Promise< - APIResponse< - { - user_id: number; - stp_id: number; - create_time: number; - }[] - > - > { + getStpGroupUsers(params: { + stp_id: number; + }): Promise> { return this.getPrivate(`/account/stp_groups/${params.stp_id}/users`); } @@ -3843,21 +3794,12 @@ export class RestClient extends BaseRestClient { * Add users to the STP group * * @param params Parameters for adding users to the STP group - * @returns Promise> + * @returns Promise> */ - addUsersToStpGroup(params: { stp_id: number; body: number[] }): Promise< - APIResponse< - { - user_id: number; - stp_id: number; - create_time: number; - }[] - > - > { + addUsersToStpGroup(params: { + stp_id: number; + body: number[]; + }): Promise> { const { stp_id, ...body } = params; return this.postPrivate(`/account/stp_groups/${stp_id}/users`, { body: body, @@ -3868,21 +3810,12 @@ export class RestClient extends BaseRestClient { * Delete the user in the STP group * * @param params Parameters for deleting users from the STP group - * @returns Promise> + * @returns Promise> */ - deleteUserFromStpGroup(params: { stp_id: number; user_id: number }): Promise< - APIResponse< - { - user_id: number; - stp_id: number; - create_time: number; - }[] - > - > { + deleteUserFromStpGroup(params: { + stp_id: number; + user_id: number; + }): Promise> { const { stp_id, ...query } = params; return this.deletePrivate(`/account/stp_groups/${stp_id}/users`, { query: query, diff --git a/src/types/requests/shared.types.ts b/src/types/requests/shared.types.ts index 899feaf..40fbe9b 100644 --- a/src/types/requests/shared.types.ts +++ b/src/types/requests/shared.types.ts @@ -1,5 +1,14 @@ import { FuturesOrder, FuturesPriceTriggeredOrder } from 'types/shared'; +export interface SubmitWithdrawReq { + amount: string; + currency: string; + chain: string; + withdraw_order_id?: string; + address?: string; + memo?: string; +} + export interface GetWithdrawalDepositRecordsReq { currency?: string; from?: number; @@ -16,6 +25,34 @@ export interface GetMainSubTransfersReq { offset?: number; } +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'; +} + +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 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; +} + export interface CreateSubAccountApiKeyReq { user_id: number; mode?: number; // Mode: 1 - classic, 2 - portfolio account @@ -40,6 +77,13 @@ export interface UpdateSubAccountApiKeyReq extends CreateSubAccountApiKeyReq { key: string; } +export interface CreateSubAccountReq { + login_name: string; + remark?: string; + password?: string; + email?: string; +} + export interface GetSavedAddressReq { currency: string; chain?: string; diff --git a/src/types/response/shared.types.ts b/src/types/response/shared.types.ts index 80438ee..7a30ce2 100644 --- a/src/types/response/shared.types.ts +++ b/src/types/response/shared.types.ts @@ -1692,3 +1692,9 @@ export interface CreateStpGroupResp { creator_id: number; create_time: number; } + +export interface StpResp { + user_id: number; + stp_id: number; + create_time: number; +} From 68338adf44ffadcd71eab65fe4b69adc44f62559 Mon Sep 17 00:00:00 2001 From: Jerko J <83344666+JJ-Cro@users.noreply.github.com> Date: Fri, 24 May 2024 00:02:54 +0200 Subject: [PATCH 31/36] chore(): separated types per group, added rebates endpoints and types --- src/RestClient.ts | 334 ++-- src/types/requests/account.ts | 0 src/types/requests/delivery.ts | 0 src/types/requests/earn.ts | 0 src/types/requests/earnuni.ts | 0 src/types/requests/flashswap.ts | 0 src/types/requests/futures.ts | 0 src/types/requests/margin.ts | 0 src/types/requests/marginuni.ts | 0 src/types/requests/options.ts | 0 src/types/requests/rebate.ts | 29 + src/types/requests/spot.ts | 0 src/types/requests/subaccount.ts | 0 src/types/requests/unified.ts | 0 src/types/requests/wallet.ts | 0 src/types/requests/withdrawal.ts | 0 src/types/response/account.ts | 27 + src/types/response/collateralloan.ts | 62 + src/types/response/delivery.ts | 157 ++ src/types/response/earn.ts | 69 + src/types/response/earnuni.ts | 44 + src/types/response/flashswap.ts | 35 + src/types/response/futures.ts | 234 +++ src/types/response/margin.ts | 102 ++ src/types/response/marginuni.ts | 44 + src/types/response/multicollateralLoan.ts | 160 ++ src/types/response/options.ts | 206 +++ src/types/response/rebate.ts | 55 + src/types/response/shared.types.ts | 1696 --------------------- src/types/response/spot.ts | 193 +++ src/types/response/subaccount.ts | 35 + src/types/response/unified.ts | 121 ++ src/types/response/wallet.ts | 197 +++ src/types/response/withdrawal.ts | 0 34 files changed, 1989 insertions(+), 1811 deletions(-) create mode 100644 src/types/requests/account.ts create mode 100644 src/types/requests/delivery.ts create mode 100644 src/types/requests/earn.ts create mode 100644 src/types/requests/earnuni.ts create mode 100644 src/types/requests/flashswap.ts create mode 100644 src/types/requests/futures.ts create mode 100644 src/types/requests/margin.ts create mode 100644 src/types/requests/marginuni.ts create mode 100644 src/types/requests/options.ts create mode 100644 src/types/requests/rebate.ts create mode 100644 src/types/requests/spot.ts create mode 100644 src/types/requests/subaccount.ts create mode 100644 src/types/requests/unified.ts create mode 100644 src/types/requests/wallet.ts create mode 100644 src/types/requests/withdrawal.ts create mode 100644 src/types/response/account.ts create mode 100644 src/types/response/collateralloan.ts create mode 100644 src/types/response/delivery.ts create mode 100644 src/types/response/earn.ts create mode 100644 src/types/response/earnuni.ts create mode 100644 src/types/response/flashswap.ts create mode 100644 src/types/response/futures.ts create mode 100644 src/types/response/margin.ts create mode 100644 src/types/response/marginuni.ts create mode 100644 src/types/response/multicollateralLoan.ts create mode 100644 src/types/response/options.ts create mode 100644 src/types/response/rebate.ts create mode 100644 src/types/response/spot.ts create mode 100644 src/types/response/subaccount.ts create mode 100644 src/types/response/unified.ts create mode 100644 src/types/response/wallet.ts create mode 100644 src/types/response/withdrawal.ts diff --git a/src/RestClient.ts b/src/RestClient.ts index 52423c4..e002c62 100644 --- a/src/RestClient.ts +++ b/src/RestClient.ts @@ -1,4 +1,159 @@ import { AxiosRequestConfig } from 'axios'; +import { + GetAgencyCommissionHistoryReq, + GetAgencyTransactionHistoryReq, + GetBrokerCommissionHistoryReq, + GetBrokerTransactionHistoryReq, +} from 'types/requests/rebate.js'; +import { + CreateStpGroupResp, + GetAccountDetailResp, + StpResp, +} from 'types/response/account.js'; +import { + GetLoanCollateralizationRatioResp, + GetLoanCollateralRecordsResp, + GetLoanOrdersResp, + GetLoanRepaymentHistoryResp, +} from 'types/response/collateralloan.js'; +import { + GetDeliveryAccountResp, + GetDeliveryBookResp, + GetDeliveryCandlesticksResp, + GetDeliveryClosedPositionsResp, + GetDeliveryLiquidationHistoryResp, + GetDeliveryOrderBookResp, + GetDeliverySettlementHistoryResp, + GetDeliveryTickersResp, + GetDeliveryTradesResp, + GetDeliveryTradingHistoryResp, +} from 'types/response/delivery.js'; +import { + GetDualInvestmentOrdersResp, + GetDualInvestmentProductsResp, + GetStructuredProductListResp, + GetStructuredProductOrdersResp, +} from 'types/response/earn.js'; +import { + GetLendingCurrenciesResp, + GetLendingInterestRecordsResp, + GetLendingOrdersResp, + GetLendingRecordsResp, +} from 'types/response/earnuni.js'; +import { + FlashSwapOrderResp, + GetFlashSwapCurrencyPairsResp, + SubmitFlashSwapOrderPreviewResp, +} from 'types/response/flashswap.js'; +import { + DeleteFuturesBatchOrdersResp, + GetFuturesAccountResp, + GetFuturesAutoDeleveragingHistoryResp, + GetFuturesCandlesticksResp, + GetFuturesLiquidationHistoryResp, + GetFuturesOrderBookResp, + GetFuturesPositionHistoryResp, + GetFuturesStatsResp, + GetFuturesTickersResp, + GetFuturesTradesResp, + GetFuturesTradingHistoryResp, + GetIndexConstituentsResp, + GetLiquidationHistoryResp, + GetPremiumIndexKLineResp, + GetRiskLimitTiersResp, + ToggleFuturesDualModeResp, +} from 'types/response/futures.js'; +import { + GetCrossMarginAccountHistoryResp, + GetCrossMarginAccountResp, + GetCrossMarginCurrenciesResp, + GetMarginAccountsResp, + GetMarginBalanceHistoryResp, + SubmitCrossMarginBorrowLoanResp, +} from 'types/response/margin.js'; +import { + GetLendingMarketsResp, + GetMarginUNIInterestRecordsResp, + GetMarginUNILoanRecordsResp, + GetMarginUNILoansResp, + GetMarginUNIMaxBorrowResp, +} from 'types/response/marginuni.js'; +import { + GetMultiLoanAdjustmentRecordsResp, + GetMultiLoanCurrencyQuotaResp, + GetMultiLoanFixedRatesResp, + GetMultiLoanOrdersResp, + GetMultiLoanRatioResp, + GetMultiLoanRepayRecordsResp, + GetMultiLoanSupportedCurrenciesResp, + RepayMultiLoanResp, + UpdateMultiLoanResp, +} from 'types/response/multicollateralLoan.js'; +import { + GetOptionsAccountChangeResp, + GetOptionsAccountResp, + GetOptionsCandlesticksResp, + GetOptionsContractsResp, + GetOptionsLiquidationResp, + GetOptionsMySettlementsResp, + GetOptionsOrderBookResp, + GetOptionsPersonalHistoryResp, + GetOptionsPositionsUnderlyingResp, + GetOptionsSettlementHistoryResp, + GetOptionsTickersResp, + GetOptionsTradesResp, + GetOptionsUnderlyingCandlesticksResp, + SubmitOptionsOrderResp, +} from 'types/response/options.js'; +import { + GetAgencyCommissionHistoryResp, + GetAgencyTransactionHistoryResp, + GetBrokerCommissionHistoryResp, + GetBrokerTransactionHistoryResp, +} from 'types/response/rebate.js'; +import { + DeleteSpotBatchOrdersResp, + GetSpotAccountBookResp, + GetSpotAccountsResp, + GetSpotBatchFeeRatesResp, + GetSpotCandlesticksResp, + GetSpotCurrenciesResp, + GetSpotFeeRatesResp, + GetSpotOpenOrdersResp, + GetSpotOrderBookResp, + GetSpotTickerResp, + GetSpotTradesResp, + GetSpotTradingHistoryResp, + SubmitSpotBatchOrdersResp, +} from 'types/response/spot.js'; +import { + CreateSubAccountApiKeyResp, + SubAccountResp, +} from 'types/response/subaccount.js'; +import { + GetUnifiedAccountInfoResp, + GetUnifiedCurrencyDiscountTiersResp, + GetUnifiedInterestRecordsResp, + GetUnifiedLoanRecordsResp, + GetUnifiedLoansResp, + GetUnifiedRiskUnitDetailsResp, + PortfolioMarginCalculatorResp, +} from 'types/response/unified.js'; +import { + APIResponse, + CreateDepositAddressResp, + GetBalancesResp, + GetCurrencyChainsResp, + GetSavedAddressResp, + GetSmallBalanceHistoryResp, + GetSmallBalancesResp, + GetTradingFeesResp, + GetWithdrawalStatusResp, + SubAccountCrossMarginBalancesResp, + SubAccountFuturesBalancesResp, + SubAccountMarginBalancesResp, + SubAccountTransferRecordResp, +} from 'types/response/wallet.js'; import { BaseRestClient, @@ -110,121 +265,6 @@ import { UpdateSpotOrderReq, UpdateSubAccountApiKeyReq, } from './types/requests/shared.types.js'; -import { - APIResponse, - CreateDepositAddressResp, - CreateStpGroupResp, - CreateSubAccountApiKeyResp, - DeleteFuturesBatchOrdersResp, - DeleteSpotBatchOrdersResp, - FlashSwapOrderResp, - GetAccountDetailResp, - GetBalancesResp, - GetCrossMarginAccountHistoryResp, - GetCrossMarginAccountResp, - GetCrossMarginCurrenciesResp, - GetCurrencyChainsResp, - GetDeliveryAccountResp, - GetDeliveryBookResp, - GetDeliveryCandlesticksResp, - GetDeliveryClosedPositionsResp, - GetDeliveryLiquidationHistoryResp, - GetDeliveryOrderBookResp, - GetDeliverySettlementHistoryResp, - GetDeliveryTickersResp, - GetDeliveryTradesResp, - GetDeliveryTradingHistoryResp, - GetDualInvestmentOrdersResp, - GetDualInvestmentProductsResp, - GetFlashSwapCurrencyPairsResp, - GetFuturesAccountResp, - GetFuturesAutoDeleveragingHistoryResp, - GetFuturesCandlesticksResp, - GetFuturesLiquidationHistoryResp, - GetFuturesOrderBookResp, - GetFuturesPositionHistoryResp, - GetFuturesStatsResp, - GetFuturesTickersResp, - GetFuturesTradesResp, - GetFuturesTradingHistoryResp, - GetIndexConstituentsResp, - GetLendingCurrenciesResp, - GetLendingInterestRecordsResp, - GetLendingMarketsResp, - GetLendingOrdersResp, - GetLendingRecordsResp, - GetLiquidationHistoryResp, - GetLoanCollateralizationRatioResp, - GetLoanCollateralRecordsResp, - GetLoanOrdersResp, - GetLoanRepaymentHistoryResp, - GetMarginAccountsResp, - GetMarginBalanceHistoryResp, - GetMarginUNIInterestRecordsResp, - GetMarginUNILoanRecordsResp, - GetMarginUNILoansResp, - GetMarginUNIMaxBorrowResp, - GetMultiLoanAdjustmentRecordsResp, - GetMultiLoanCurrencyQuotaResp, - GetMultiLoanFixedRatesResp, - GetMultiLoanOrdersResp, - GetMultiLoanRatioResp, - GetMultiLoanRepayRecordsResp, - GetMultiLoanSupportedCurrenciesResp, - GetOptionsAccountChangeResp, - GetOptionsAccountResp, - GetOptionsCandlesticksResp, - GetOptionsContractsResp, - GetOptionsLiquidationResp, - GetOptionsMySettlementsResp, - GetOptionsOrderBookResp, - GetOptionsPersonalHistoryResp, - GetOptionsPositionsUnderlyingResp, - GetOptionsSettlementHistoryResp, - GetOptionsTickersResp, - GetOptionsTradesResp, - GetOptionsUnderlyingCandlesticksResp, - GetPremiumIndexKLineResp, - GetRiskLimitTiersResp, - GetSavedAddressResp, - GetSmallBalanceHistoryResp, - GetSmallBalancesResp, - GetSpotAccountBookResp, - GetSpotAccountsResp, - GetSpotBatchFeeRatesResp, - GetSpotCandlesticksResp, - GetSpotCurrenciesResp, - GetSpotFeeRatesResp, - GetSpotOpenOrdersResp, - GetSpotOrderBookResp, - GetSpotTickerResp, - GetSpotTradesResp, - GetSpotTradingHistoryResp, - GetStructuredProductListResp, - GetStructuredProductOrdersResp, - GetTradingFeesResp, - GetUnifiedAccountInfoResp, - GetUnifiedCurrencyDiscountTiersResp, - GetUnifiedInterestRecordsResp, - GetUnifiedLoanRecordsResp, - GetUnifiedLoansResp, - GetUnifiedRiskUnitDetailsResp, - GetWithdrawalStatusResp, - PortfolioMarginCalculatorResp, - RepayMultiLoanResp, - StpResp, - SubAccountCrossMarginBalancesResp, - SubAccountFuturesBalancesResp, - SubAccountMarginBalancesResp, - SubAccountResp, - SubAccountTransferRecordResp, - SubmitCrossMarginBorrowLoanResp, - SubmitFlashSwapOrderPreviewResp, - SubmitOptionsOrderResp, - SubmitSpotBatchOrdersResp, - ToggleFuturesDualModeResp, - UpdateMultiLoanResp, -} from './types/response/shared.types.js'; import { CancelBatchOrder, Contract, @@ -3821,4 +3861,68 @@ export class RestClient extends BaseRestClient { query: query, }); } + + /**========================================================================================================================== + * REBATES + * ========================================================================================================================== + */ + + /** + * The agency obtains the transaction history of the recommended user. + * Record time range cannot exceed 30 days. + * + * @param params Parameters for retrieving transaction history + * @returns Promise> + */ + getAgencyTransactionHistory( + params: GetAgencyTransactionHistoryReq, + ): Promise> { + return this.getPrivate('/rebate/agency/transaction_history', params); + } + + /** + * The agency obtains the commission history of the recommended user. + * Record time range cannot exceed 30 days. + * + * @param params Parameters for retrieving commission history + * @returns Promise> + */ + getAgencyCommissionHistory( + params: GetAgencyCommissionHistoryReq, + ): Promise> { + return this.getPrivate('/rebate/agency/commission_history', params); + } + + /** + * The broker obtains the user's commission rebate records. + * Record time range cannot exceed 30 days. + * + * @param params Parameters for retrieving commission rebate records + * @returns Promise> + */ + getBrokerCommissionHistory( + params: GetBrokerCommissionHistoryReq, + ): Promise> { + return this.getPrivate('/rebate/broker/commission_history', params); + } + + /** + * The broker obtains the user's trading history. + * Record time range cannot exceed 30 days. + * + * @param params Parameters for retrieving trading history + * @returns Promise> + */ + getBrokerTransactionHistory( + params: GetBrokerTransactionHistoryReq, + ): Promise> { + return this.getPrivate('/rebate/broker/transaction_history', params); + } + + /** + * User retrieves rebate information. + */ + getUserRebateInfo(): Promise> { + return this.getPrivate('/rebate/user/info'); + } } diff --git a/src/types/requests/account.ts b/src/types/requests/account.ts new file mode 100644 index 0000000..e69de29 diff --git a/src/types/requests/delivery.ts b/src/types/requests/delivery.ts new file mode 100644 index 0000000..e69de29 diff --git a/src/types/requests/earn.ts b/src/types/requests/earn.ts new file mode 100644 index 0000000..e69de29 diff --git a/src/types/requests/earnuni.ts b/src/types/requests/earnuni.ts new file mode 100644 index 0000000..e69de29 diff --git a/src/types/requests/flashswap.ts b/src/types/requests/flashswap.ts new file mode 100644 index 0000000..e69de29 diff --git a/src/types/requests/futures.ts b/src/types/requests/futures.ts new file mode 100644 index 0000000..e69de29 diff --git a/src/types/requests/margin.ts b/src/types/requests/margin.ts new file mode 100644 index 0000000..e69de29 diff --git a/src/types/requests/marginuni.ts b/src/types/requests/marginuni.ts new file mode 100644 index 0000000..e69de29 diff --git a/src/types/requests/options.ts b/src/types/requests/options.ts new file mode 100644 index 0000000..e69de29 diff --git a/src/types/requests/rebate.ts b/src/types/requests/rebate.ts new file mode 100644 index 0000000..ded6a1d --- /dev/null +++ b/src/types/requests/rebate.ts @@ -0,0 +1,29 @@ +export interface GetAgencyTransactionHistoryReq { + currency_pair?: string; + user_id?: number; + from?: number; + to?: number; + limit?: number; + offset?: number; +} + +export interface GetAgencyCommissionHistoryReq { + currency?: string; + user_id?: number; + from?: number; + to?: number; + limit?: number; + offset?: number; +} + +export interface GetBrokerCommissionHistoryReq { + limit?: number; + offset?: number; + user_id?: number; +} + +export interface GetBrokerTransactionHistoryReq { + limit?: number; + offset?: number; + user_id?: number; +} diff --git a/src/types/requests/spot.ts b/src/types/requests/spot.ts new file mode 100644 index 0000000..e69de29 diff --git a/src/types/requests/subaccount.ts b/src/types/requests/subaccount.ts new file mode 100644 index 0000000..e69de29 diff --git a/src/types/requests/unified.ts b/src/types/requests/unified.ts new file mode 100644 index 0000000..e69de29 diff --git a/src/types/requests/wallet.ts b/src/types/requests/wallet.ts new file mode 100644 index 0000000..e69de29 diff --git a/src/types/requests/withdrawal.ts b/src/types/requests/withdrawal.ts new file mode 100644 index 0000000..e69de29 diff --git a/src/types/response/account.ts b/src/types/response/account.ts new file mode 100644 index 0000000..64cf16a --- /dev/null +++ b/src/types/response/account.ts @@ -0,0 +1,27 @@ +/**========================================================================================================================== + * ACCOUNT + * ========================================================================================================================== + */ + +export interface GetAccountDetailResp { + user_id: number; + ip_whitelist: string[]; + currency_pairs: string[]; + key: { + mode: number; + }; + tier: number; +} + +export interface CreateStpGroupResp { + id: number; + name: string; + creator_id: number; + create_time: number; +} + +export interface StpResp { + user_id: number; + stp_id: number; + create_time: number; +} diff --git a/src/types/response/collateralloan.ts b/src/types/response/collateralloan.ts new file mode 100644 index 0000000..ceac447 --- /dev/null +++ b/src/types/response/collateralloan.ts @@ -0,0 +1,62 @@ +/**========================================================================================================================== + * COLLATERAL LOAN + * ========================================================================================================================== + */ + +export interface GetLoanOrdersResp { + order_id: number; + collateral_currency: string; + collateral_amount: string; + borrow_currency: string; + borrow_amount: string; + repaid_amount: string; + repaid_principal: string; + repaid_interest: string; + init_ltv: string; + current_ltv: string; + liquidate_ltv: string; + status: string; + borrow_time: number; + left_repay_total: string; + left_repay_principal: string; + left_repay_interest: string; +} + +export interface GetLoanRepaymentHistoryResp { + order_id: number; + record_id: number; + repaid_amount: string; + borrow_currency: string; + collateral_currency: string; + init_ltv: string; + borrow_time: number; + repay_time: number; + total_interest: string; + before_left_principal: string; + after_left_principal: string; + before_left_collateral: string; + after_left_collateral: string; +} + +export interface GetLoanCollateralRecordsResp { + order_id: number; + record_id: number; + borrow_currency: string; + borrow_amount: string; + collateral_currency: string; + before_collateral: string; + after_collateral: string; + before_ltv: string; + after_ltv: string; + operate_time: number; +} + +export interface GetLoanCollateralizationRatioResp { + collateral_currency: string; + borrow_currency: string; + init_ltv: string; + alert_ltv: string; + liquidate_ltv: string; + min_borrow_amount: string; + left_borrowable_amount: string; +} diff --git a/src/types/response/delivery.ts b/src/types/response/delivery.ts new file mode 100644 index 0000000..9681f67 --- /dev/null +++ b/src/types/response/delivery.ts @@ -0,0 +1,157 @@ +/**========================================================================================================================== + * DELIVERY + * ========================================================================================================================== + */ + +export interface GetDeliveryOrderBookResp { + id?: number; + current: number; + update: number; + asks: { p: string; s: number }[]; + bids: { p: string; s: number }[]; +} + +export interface GetDeliveryTradesResp { + id: number; + create_time: number; + create_time_ms: number; + contract: string; + size: number; + price: string; + is_internal?: boolean; +} + +export interface GetDeliveryCandlesticksResp { + t: number; + v?: number; + c: string; + h: string; + l: string; + o: string; +} + +export interface GetDeliveryTickersResp { + contract: string; + last: string; + change_percentage: string; + total_size: string; + low_24h: string; + high_24h: string; + volume_24h: string; + volume_24h_btc?: string; + volume_24h_usd?: string; + volume_24h_base: string; + volume_24h_quote: string; + volume_24h_settle: string; + mark_price: string; + funding_rate: string; + funding_rate_indicative: string; + index_price: string; + quanto_base_rate?: string; + basis_rate: string; + basis_value: string; + lowest_ask: string; + highest_bid: string; +} + +export interface GetDeliveryAccountResp { + 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; + 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 GetDeliveryBookResp { + time: number; + change: string; + balance: string; + type: + | 'dnw' + | 'pnl' + | 'fee' + | 'refr' + | 'fund' + | 'point_dnw' + | 'point_fee' + | 'point_refr' + | 'bonus_offset'; + text: string; + contract?: string; + trade_id?: string; +} + +export interface GetDeliveryTradingHistoryResp { + id: number; + create_time: number; + contract: string; + order_id: string; + size: number; + price: string; + role: 'taker' | 'maker'; + text: string; + fee: string; + point_fee: string; +} + +export interface GetDeliveryClosedPositionsResp { + time: number; + contract: string; + side: 'long' | 'short'; + pnl: string; + pnl_pnl: string; + pnl_fund: string; + pnl_fee: string; + text: string; + max_size: string; + first_open_time: number; + long_price: string; + short_price: string; +} + +export interface GetDeliveryLiquidationHistoryResp { + time: number; + contract: string; + leverage?: string; + size: number; + margin?: string; + entry_price?: string; + liq_price?: string; + mark_price?: string; + order_id?: number; + order_price: string; + fill_price: string; + left: number; +} + +export interface GetDeliverySettlementHistoryResp { + time: number; + contract: string; + leverage: string; + size: number; + margin: string; + entry_price: string; + settle_price: string; + profit: string; + fee: string; +} diff --git a/src/types/response/earn.ts b/src/types/response/earn.ts new file mode 100644 index 0000000..2311cc7 --- /dev/null +++ b/src/types/response/earn.ts @@ -0,0 +1,69 @@ +/**========================================================================================================================== + * EARN + * ========================================================================================================================== + */ + +export interface GetDualInvestmentProductsResp { + id: number; + instrument_name: string; + invest_currency: string; + exercise_currency: string; + exercise_price: number; + delivery_time: number; + min_copies: number; + max_copies: number; + per_value: string; + apy_display: string; + start_time: number; + end_time: number; + status: 'NOTSTARTED' | 'ONGOING' | 'ENDED'; +} + +export interface GetDualInvestmentOrdersResp { + id: number; + plan_id: number; + copies: string; + invest_amount: string; + settlement_amount: string; + create_time: number; + complete_time: number; + status: + | 'INIT' + | 'SETTLEMENT_SUCCESS' + | 'SETTLEMENT_PROCESSING' + | 'CANCELED' + | 'FAILED'; + invest_currency: string; + exercise_currency: string; + exercise_price: string; + settlement_price: string; + settlement_currency: string; + apy_display: string; + apy_settlement: string; + delivery_time: number; +} + +export interface GetStructuredProductListResp { + id: number; + type: string; + name_en: string; + investment_coin: string; + investment_period: string; + min_annual_rate: string; + mid_annual_rate: string; + max_annual_rate: string; + watch_market: string; + start_time: number; + end_time: number; + status: 'in_process' | 'will_begin' | 'wait_settlement' | 'done'; +} + +export interface GetStructuredProductOrdersResp { + id: number; + pid: string; + lock_coin: string; + amount: string; + status: 'SUCCESS' | 'FAILED' | 'DONE'; + income: string; + create_time: number; +} diff --git a/src/types/response/earnuni.ts b/src/types/response/earnuni.ts new file mode 100644 index 0000000..dea8e49 --- /dev/null +++ b/src/types/response/earnuni.ts @@ -0,0 +1,44 @@ +/**========================================================================================================================== + * EARN UNI + * ========================================================================================================================== + */ + +export interface GetLendingCurrenciesResp { + currency: string; + min_lend_amount: string; + max_lend_amount: string; + max_rate: string; + min_rate: string; +} + +export interface GetLendingOrdersResp { + currency: string; + current_amount: string; + amount: string; + lent_amount: string; + frozen_amount: string; + min_rate: string; + interest_status: string; + reinvest_left_amount: string; + create_time: number; + update_time: number; +} + +export interface GetLendingRecordsResp { + currency: string; + amount: string; + last_wallet_amount: string; + last_lent_amount: string; + last_frozen_amount: string; + type: 'lend' | 'redeem'; + create_time: number; +} + +export interface GetLendingInterestRecordsResp { + status: number; + currency: string; + actual_rate: string; + interest: string; + interest_status: string; + create_time: number; +} diff --git a/src/types/response/flashswap.ts b/src/types/response/flashswap.ts new file mode 100644 index 0000000..08e9b5e --- /dev/null +++ b/src/types/response/flashswap.ts @@ -0,0 +1,35 @@ +/**========================================================================================================================== + * FLASH SWAP + * ========================================================================================================================== + */ + +export interface GetFlashSwapCurrencyPairsResp { + currency_pair: string; + sell_currency: string; + buy_currency: string; + sell_min_amount: string; + sell_max_amount: string; + buy_min_amount: string; + buy_max_amount: string; +} + +export interface FlashSwapOrderResp { + id: number; + create_time: number; + user_id: number; + sell_currency: string; + sell_amount: string; + buy_currency: string; + buy_amount: string; + price: string; + status: number; +} + +export interface SubmitFlashSwapOrderPreviewResp { + preview_id: string; + sell_currency: string; + sell_amount: string; + buy_currency: string; + buy_amount: string; + price: string; +} diff --git a/src/types/response/futures.ts b/src/types/response/futures.ts new file mode 100644 index 0000000..7ceee53 --- /dev/null +++ b/src/types/response/futures.ts @@ -0,0 +1,234 @@ +/**========================================================================================================================== + * FUTURES + * ========================================================================================================================== + */ + +export interface GetFuturesOrderBookResp { + id?: number; + current: number; + update: number; + asks: { p: string; s: number }[]; + bids: { p: string; s: number }[]; +} + +export interface GetFuturesTradesResp { + id: number; + create_time: number; + create_time_ms: number; + contract: string; + size: number; + price: string; + is_internal?: boolean; +} + +export interface GetFuturesCandlesticksResp { + t: number; + v?: number; + c: string; + h: string; + l: string; + o: string; + sum: string; +} + +export interface GetPremiumIndexKLineResp { + t: number; + c: string; + h: string; + l: string; + o: string; +} + +export interface GetFuturesTickersResp { + contract: string; + last: string; + change_percentage: string; + total_size: string; + low_24h: string; + high_24h: string; + volume_24h: string; + volume_24h_btc?: string; + volume_24h_usd?: string; + volume_24h_base: string; + volume_24h_quote: string; + volume_24h_settle: string; + mark_price: string; + funding_rate: string; + funding_rate_indicative: string; + index_price: string; + quanto_base_rate?: string; + basis_rate: string; + basis_value: string; + lowest_ask: string; + highest_bid: string; +} + +export interface GetFuturesStatsResp { + time: number; + lsr_taker: number; + lsr_account: number; + long_liq_size: number; + long_liq_amount: number; + long_liq_usd: number; + short_liq_size: number; + short_liq_amount: number; + short_liq_usd: number; + open_interest: number; + open_interest_usd: number; + top_lsr_account: number; + top_lsr_size: number; +} + +export interface GetIndexConstituentsResp { + index: string; + constituents: { + exchange: string; + symbols: string[]; + }[]; +} + +export interface GetLiquidationHistoryResp { + time: number; + contract: string; + size: number; + order_price: string; + fill_price: string; + left: number; +} + +export interface GetRiskLimitTiersResp { + tier: number; + risk_limit: string; + initial_rate: string; + maintenance_rate: string; + leverage_max: string; + contract: string; +} + +export interface GetFuturesAccountResp { + 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; + 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 GetFuturesAccountBookResp { + time: number; + change: string; + balance: string; + type: string; + text: string; + contract?: string; + trade_id: string; +} + +export interface ToggleFuturesDualModeResp { + 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; + 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 GetFuturesTradingHistoryResp { + id: number; + create_time: number; + contract: string; + order_id: string; + size: number; + price: string; + role: 'taker' | 'maker'; + text: string; + fee: string; + point_fee: string; +} + +export interface GetFuturesPositionHistoryResp { + time: number; + contract: string; + side: 'long' | 'short'; + pnl: string; + pnl_pnl: string; + pnl_fund: string; + pnl_fee: string; + text: string; + max_size: string; + first_open_time: number; + long_price: string; + short_price: string; +} + +export interface GetFuturesLiquidationHistoryResp { + time: number; + contract: string; + leverage: string; + size: number; + margin: string; + entry_price: string; + liq_price: string; + mark_price: string; + order_id: number; + order_price: string; + fill_price: string; + left: number; +} +export interface GetFuturesAutoDeleveragingHistoryResp { + time: number; + user: number; + order_id: number; + contract: string; + leverage: string; + cross_leverage_limit: string; + entry_price: string; + fill_price: string; + trade_size: number; + position_size: number; +} + +export interface DeleteFuturesBatchOrdersResp { + user_id: number; + id: string; + succeeded: boolean; + message: string; +} diff --git a/src/types/response/margin.ts b/src/types/response/margin.ts new file mode 100644 index 0000000..6190117 --- /dev/null +++ b/src/types/response/margin.ts @@ -0,0 +1,102 @@ +/**========================================================================================================================== + * MARGIN + * ========================================================================================================================== + */ + +export interface GetMarginAccountsResp { + 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 GetMarginBalanceHistoryResp { + id: string; + time: string; + time_ms: number; + currency: string; + currency_pair: string; + change: string; + balance: string; + type: string; +} + +export interface GetCrossMarginCurrenciesResp { + name: string; + rate: string; + prec: string; + discount: string; + min_borrow_amount: string; + user_max_borrow_amount: string; + total_max_borrow_amount: string; + price: string; + loanable: boolean; + status: number; +} + +export interface GetCrossMarginAccountResp { + user_id: number; + refresh_time: number; + locked: boolean; + balances: { + [currency: string]: { + available: string; + freeze: string; + borrowed: string; + interest: string; + negative_liab: string; + futures_pos_liab: string; + equity: string; + total_freeze: string; + total_liab: string; + }; + }; + total: string; + borrowed: string; + interest: string; + risk: string; + total_initial_margin: string; + total_margin_balance: string; + total_maintenance_margin: string; + total_initial_margin_rate: string; + total_maintenance_margin_rate: string; + total_available_margin: string; + portfolio_margin_total: string; + portfolio_margin_total_liab: string; + portfolio_margin_total_equity: string; +} + +export interface GetCrossMarginAccountHistoryResp { + id: string; + time: number; + currency: string; + change: string; + balance: string; + type: string; +} + +export interface SubmitCrossMarginBorrowLoanResp { + id: string; + create_time: number; + update_time: number; + currency: string; + amount: string; + text?: string; + status: number; + repaid: string; + repaid_interest: string; + unpaid_interest: string; +} diff --git a/src/types/response/marginuni.ts b/src/types/response/marginuni.ts new file mode 100644 index 0000000..c7de663 --- /dev/null +++ b/src/types/response/marginuni.ts @@ -0,0 +1,44 @@ +/**========================================================================================================================== + * MARGIN UNI + * ========================================================================================================================== + */ + +export interface GetLendingMarketsResp { + currency_pair: string; + base_min_borrow_amount: string; + quote_min_borrow_amount: string; + leverage: string; +} + +export interface GetMarginUNILoansResp { + currency: string; + currency_pair: string; + amount: string; + type: string; + create_time: number; + update_time: number; +} + +export interface GetMarginUNILoanRecordsResp { + type: string; + currency_pair: string; + currency: string; + amount: string; + create_time: number; +} + +export interface GetMarginUNIInterestRecordsResp { + currency: string; + currency_pair: string; + actual_rate: string; + interest: string; + status: number; + type: string; + create_time: number; +} + +export interface GetMarginUNIMaxBorrowResp { + currency: string; + currency_pair: string; + borrowable: string; +} diff --git a/src/types/response/multicollateralLoan.ts b/src/types/response/multicollateralLoan.ts new file mode 100644 index 0000000..07952d3 --- /dev/null +++ b/src/types/response/multicollateralLoan.ts @@ -0,0 +1,160 @@ +/**========================================================================================================================== + * MULTI COLLATERAL LOAN + * ========================================================================================================================== + */ + +export interface GetMultiLoanOrdersResp { + order_id: string; + order_type: string; + fixed_type: string; + fixed_rate: string; + expire_time: number; + auto_renew: boolean; + auto_repay: boolean; + current_ltv: string; + status: string; + borrow_time: number; + total_left_repay_usdt: string; + total_left_collateral_usdt: string; + borrow_currencies: { + currency: string; + index_price: string; + left_repay_principal: string; + left_repay_interest: string; + left_repay_usdt: string; + }[]; + collateral_currencies: { + currency: string; + index_price: string; + left_collateral: string; + left_collateral_usdt: string; + }[]; +} + +export interface RepayMultiLoanResp { + order_id: number; + repaid_currencies: { + succeeded: boolean; + label?: string; + message?: string; + currency: string; + repaid_principal: string; + repaid_interest: string; + }[]; +} + +export interface GetMultiLoanRepayRecordsResp { + order_id: number; + record_id: number; + init_ltv: string; + before_ltv: string; + after_ltv: string; + borrow_time: number; + repay_time: number; + borrow_currencies: { + currency: string; + index_price: string; + before_amount: string; + before_amount_usdt: string; + after_amount: string; + after_amount_usdt: string; + }[]; + collateral_currencies: { + currency: string; + index_price: string; + before_amount: string; + before_amount_usdt: string; + after_amount: string; + after_amount_usdt: string; + }[]; + repaid_currencies: { + currency: string; + index_price: string; + repaid_amount: string; + repaid_principal: string; + repaid_interest: string; + repaid_amount_usdt: string; + }[]; + total_interest_list: { + currency: string; + index_price: string; + amount: string; + amount_usdt: string; + }[]; + left_repay_interest_list: { + currency: string; + index_price: string; + before_amount: string; + before_amount_usdt: string; + after_amount: string; + after_amount_usdt: string; + }[]; +} + +export interface UpdateMultiLoanResp { + order_id: number; + collateral_currencies: { + succeeded: boolean; + label?: string; + message?: string; + currency: string; + amount: string; + }[]; +} + +export interface GetMultiLoanAdjustmentRecordsResp { + order_id: number; + record_id: number; + before_ltv: string; + after_ltv: string; + operate_time: number; + borrow_currencies: { + currency: string; + index_price: string; + before_amount: string; + before_amount_usdt: string; + after_amount: string; + after_amount_usdt: string; + }[]; + collateral_currencies: { + currency: string; + index_price: string; + before_amount: string; + before_amount_usdt: string; + after_amount: string; + after_amount_usdt: string; + }[]; +} + +export interface GetMultiLoanCurrencyQuotaResp { + currency: string; + index_price: string; + min_quota: string; + left_quota: string; + left_quote_usdt: string; +} + +export interface GetMultiLoanSupportedCurrenciesResp { + loan_currencies: { + currency: string; + price: string; + }[]; + collateral_currencies: { + currency: string; + index_price: string; + discount: string; + }[]; +} + +export interface GetMultiLoanRatioResp { + init_ltv: string; + alert_ltv: string; + liquidate_ltv: string; +} + +export interface GetMultiLoanFixedRatesResp { + currency: string; + rate_7d: string; + rate_30d: string; + update_time: number; +} diff --git a/src/types/response/options.ts b/src/types/response/options.ts new file mode 100644 index 0000000..5406283 --- /dev/null +++ b/src/types/response/options.ts @@ -0,0 +1,206 @@ +/**========================================================================================================================== + * OPTIONS + * ========================================================================================================================== + */ + +export interface GetOptionsContractsResp { + name: string; + tag: string; + create_time: number; + expiration_time: number; + is_call: boolean; + strike_price: string; + last_price: string; + mark_price: string; + orderbook_id: number; + trade_id: number; + trade_size: number; + position_size: number; + underlying: string; + underlying_price: string; + multiplier: string; + order_price_round: string; + mark_price_round: string; + maker_fee_rate: string; + taker_fee_rate: string; + price_limit_fee_rate: string; + ref_discount_rate: string; + ref_rebate_rate: string; + order_price_deviate: string; + order_size_min: number; + order_size_max: number; + orders_limit: number; +} + +export interface GetOptionsSettlementHistoryResp { + time: number; + contract: string; + profit: string; + fee: string; + strike_price: string; + settle_price: string; +} + +export interface GetOptionsMySettlementsResp { + time: number; + underlying: string; + contract: string; + strike_price: string; + settle_price: string; + size: number; + settle_profit: string; + fee: string; + realised_pnl: string; +} + +export interface GetOptionsOrderBookResp { + id?: number; + current: number; + update: number; + asks: { p: string; s: number }[]; + bids: { p: string; s: number }[]; +} + +export interface GetOptionsTickersResp { + name: string; + last_price: string; + mark_price: string; + index_price: string; + ask1_size: number; + ask1_price: string; + bid1_size: number; + bid1_price: string; + position_size: number; + mark_iv: string; + bid_iv: string; + ask_iv: string; + leverage: string; + delta: string; + gamma: string; + vega: string; + theta: string; + rho: string; +} + +export interface GetOptionsCandlesticksResp { + t: number; + v?: number; + c: string; + h: string; + l: string; + o: string; +} + +export interface GetOptionsUnderlyingCandlesticksResp { + t: number; + v?: number; + c: string; + h: string; + l: string; + o: string; + sum: string; +} + +export interface GetOptionsTradesResp { + id: number; + create_time: number; + create_time_ms: number; + contract: string; + size: number; + price: string; + is_internal?: boolean; +} + +export interface GetOptionsAccountResp { + user: number; + total: string; + short_enabled: boolean; + unrealised_pnl: string; + init_margin: string; + maint_margin: string; + order_margin: string; + available: string; + point: string; + currency: string; +} +export interface GetOptionsAccountChangeResp { + time: number; + change: string; + balance: string; + type: 'dnw' | 'prem' | 'fee' | 'refr' | 'set'; + text: string; +} + +export interface GetOptionsPositionsUnderlyingResp { + user: number; + underlying: string; + underlying_price: string; + contract: string; + size: number; + entry_price: string; + mark_price: string; + mark_iv: string; + realised_pnl: string; + unrealised_pnl: string; + pending_orders: number; + close_order: { + id: number; + price: string; + is_liq: boolean; + } | null; + delta: string; + gamma: string; + vega: string; + theta: string; +} + +export interface GetOptionsLiquidationResp { + time: number; + contract: string; + side: 'long' | 'short'; + pnl: string; + text: string; + settle_size: string; +} + +export interface SubmitOptionsOrderResp { + id: number; + user: number; + create_time: number; + finish_time: number; + finish_as: + | 'filled' + | 'cancelled' + | 'liquidated' + | 'ioc' + | 'auto_deleveraged' + | 'reduce_only' + | 'position_closed'; + status: 'open' | 'finished'; + contract: string; + size: number; + iceberg: number; + price: string; + is_close: boolean; + is_reduce_only: boolean; + is_liq: boolean; + tif: 'gtc' | 'ioc' | 'poc'; + left: number; + fill_price: string; + text: string; + tkfr: string; + mkfr: string; + refu: number; + refr: string; +} + +export interface GetOptionsPersonalHistoryResp { + id: number; + create_time: number; + contract: string; + order_id: number; + size: number; + price: string; + underlying_price: string; + role: 'taker' | 'maker'; +} diff --git a/src/types/response/rebate.ts b/src/types/response/rebate.ts new file mode 100644 index 0000000..d178674 --- /dev/null +++ b/src/types/response/rebate.ts @@ -0,0 +1,55 @@ +export interface GetAgencyTransactionHistoryResp { + total: number; + list: { + transaction_time: number; + user_id: number; + group_name: string; + fee: string; + fee_asset: string; + currency_pair: string; + amount: string; + amount_asset: string; + source: string; + }[]; +} + +export interface GetAgencyCommissionHistoryResp { + total: number; + list: { + commission_time: number; + user_id: number; + group_name: string; + commission_amount: string; + commission_asset: string; + source: string; + }[]; +} + +export interface GetBrokerCommissionHistoryResp { + total: number; + list: { + commission_time: number; + user_id: number; + group_name: string; + amount: string; + fee: string; + fee_asset: string; + rebate_fee: string; + source: string; + currency_pair: string; + }[]; +} + +export interface GetBrokerTransactionHistoryResp { + total: number; + list: { + transaction_time: number; + user_id: number; + group_name: string; + fee: string; + currency_pair: string; + amount: string; + fee_asset: string; + source: string; + }[]; +} diff --git a/src/types/response/shared.types.ts b/src/types/response/shared.types.ts index 7a30ce2..fd40910 100644 --- a/src/types/response/shared.types.ts +++ b/src/types/response/shared.types.ts @@ -1,1700 +1,4 @@ -import { Order } from '../shared'; -export interface APIResponse { - success: boolean; - data: TData; - timestamp: number; -} -export interface GetCurrencyChainsResp { - 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 CreateDepositAddressResp { - currency: string; - address: string; - multichain_addresses: { - chain: string; - address: string; - payment_id: string; - payment_name: string; - obtain_failed: number; - }[]; -} -export interface SubAccountTransferRecordResp { - 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 GetWithdrawalStatusResp { - 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 SubAccountMarginBalancesResp { - uid: string; - available: { - 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; - 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 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 GetSavedAddressResp { - currency: string; - chain: string; - address: string; - name: string; - tag: string; - verified: string; -} - -export interface GetTradingFeesResp { - 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; - }; - }; -} - -export interface GetSmallBalancesResp { - currency: string; - available_balance: string; - estimated_as_btc: string; - convertible_to_gt: string; -} - -export interface GetSmallBalanceHistoryResp { - id: string; - currency: string; - amount: string; - gt_amount: string; - create_time: number; -} - -export interface SubAccountResp { - remark?: string; - login_name: string; - password?: string; - email?: string; - state: number; - type: number; - user_id: number; - create_time: number; -} - -export interface CreateSubAccountApiKeyResp { - user_id: string; - mode?: number; - name?: string; - perms?: { - name?: - | 'wallet' - | 'spot' - | 'futures' - | 'delivery' - | 'earn' - | 'options' - | 'account' - | 'unified' - | 'loan'; - read_only?: boolean; - }[]; - ip_whitelist?: string[]; - key: string; - state: number; - created_at: number; - updated_at: number; - last_access: number; -} - -export interface GetUnifiedAccountInfoResp { - user_id: number; - refresh_time: number; - locked: boolean; - balances: { - [key: string]: { - available: string; - freeze: string; - borrowed: string; - negative_liab: string; - futures_pos_liab: string; - equity: string; - total_freeze: string; - total_liab: string; - spot_in_use: string; - }; - }; - total: string; - borrowed: 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; - unified_account_total: string; - unified_account_total_liab: string; - unified_account_total_equity: string; - leverage: string; - spot_order_loss: string; - spot_hedge: boolean; -} - -export interface GetUnifiedLoansResp { - currency: string; - currency_pair: string; - amount: string; - type: 'platform' | 'margin'; - create_time: number; - update_time: number; -} - -export interface GetUnifiedLoanRecordsResp { - 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; -} -export interface GetUnifiedInterestRecordsResp { - currency: string; - currency_pair: string; - actual_rate: string; - interest: string; - status: number; - type: 'platform' | 'margin'; - create_time: number; -} - -export interface GetUnifiedRiskUnitDetailsResp { - 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 GetUnifiedCurrencyDiscountTiersResp { - currency: string; - discount_tiers: { - tier: string; - discount: string; - lower_limit: string; - upper_limit: string; - }[]; -} - -export interface PortfolioMarginCalculatorResp { - 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; - }[]; - }[]; -} - -/**========================================================================================================================== - * SPOT - * ========================================================================================================================== - */ - -export interface GetSpotCurrenciesResp { - currency: string; - delisted: boolean; - withdraw_disabled: boolean; - withdraw_delayed: boolean; - deposit_disabled: boolean; - trade_disabled: boolean; - fixed_rate: string; - chain: string; -} - -export interface GetSpotTickerResp { - currency_pair: string; - last: string; - lowest_ask: string; - highest_bid: 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 GetSpotOrderBookResp { - id?: number; - current: number; - update: number; - asks: [string, string][]; - bids: [string, string][]; -} - -export interface GetSpotTradesResp { - 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; -} - -export type GetSpotCandlesticksResp = [ - [ - 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 GetSpotFeeRatesResp { - 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; - currency_pair: string; - debit_fee: number; -} - -export interface GetSpotBatchFeeRatesResp { - [key: string]: { - 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; - currency_pair: string; - debit_fee: number; - }; -} - -export interface GetSpotAccountsResp { - currency: string; - available: string; - locked: string; - update_id: number; -} - -export interface GetSpotAccountBookResp { - id: string; - time: number; - currency: string; - change: string; - balance: string; - type: string; - text: 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' | '-'; - finish_as: 'open' | 'filled' | 'cancelled' | 'ioc' | 'stp'; -} - -export interface GetSpotOpenOrdersResp { - currency_pair: string; - total: number; - orders: Order[]; -} - -export interface DeleteSpotBatchOrdersResp { - currency_pair: string; - id: string; - succeeded: boolean; - label: string; - message: string; - account: string; -} - -export interface GetSpotTradingHistoryResp { - 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; -} - -/**========================================================================================================================== - * MARGIN - * ========================================================================================================================== - */ - -export interface GetMarginAccountsResp { - 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 GetMarginBalanceHistoryResp { - id: string; - time: string; - time_ms: number; - currency: string; - currency_pair: string; - change: string; - balance: string; - type: string; -} - -export interface GetCrossMarginCurrenciesResp { - name: string; - rate: string; - prec: string; - discount: string; - min_borrow_amount: string; - user_max_borrow_amount: string; - total_max_borrow_amount: string; - price: string; - loanable: boolean; - status: number; -} - -export interface GetCrossMarginAccountResp { - user_id: number; - refresh_time: number; - locked: boolean; - balances: { - [currency: string]: { - available: string; - freeze: string; - borrowed: string; - interest: string; - negative_liab: string; - futures_pos_liab: string; - equity: string; - total_freeze: string; - total_liab: string; - }; - }; - total: string; - borrowed: string; - interest: string; - risk: string; - total_initial_margin: string; - total_margin_balance: string; - total_maintenance_margin: string; - total_initial_margin_rate: string; - total_maintenance_margin_rate: string; - total_available_margin: string; - portfolio_margin_total: string; - portfolio_margin_total_liab: string; - portfolio_margin_total_equity: string; -} - -export interface GetCrossMarginAccountHistoryResp { - id: string; - time: number; - currency: string; - change: string; - balance: string; - type: string; -} - -export interface SubmitCrossMarginBorrowLoanResp { - id: string; - create_time: number; - update_time: number; - currency: string; - amount: string; - text?: string; - status: number; - repaid: string; - repaid_interest: string; - unpaid_interest: string; -} - -/**========================================================================================================================== - * MARGIN UNI - * ========================================================================================================================== - */ - -export interface GetLendingMarketsResp { - currency_pair: string; - base_min_borrow_amount: string; - quote_min_borrow_amount: string; - leverage: string; -} - -export interface GetMarginUNILoansResp { - currency: string; - currency_pair: string; - amount: string; - type: string; - create_time: number; - update_time: number; -} - -export interface GetMarginUNILoanRecordsResp { - type: string; - currency_pair: string; - currency: string; - amount: string; - create_time: number; -} - -export interface GetMarginUNIInterestRecordsResp { - currency: string; - currency_pair: string; - actual_rate: string; - interest: string; - status: number; - type: string; - create_time: number; -} - -export interface GetMarginUNIMaxBorrowResp { - currency: string; - currency_pair: string; - borrowable: string; -} - -/**========================================================================================================================== - * FLASH SWAP - * ========================================================================================================================== - */ - -export interface GetFlashSwapCurrencyPairsResp { - currency_pair: string; - sell_currency: string; - buy_currency: string; - sell_min_amount: string; - sell_max_amount: string; - buy_min_amount: string; - buy_max_amount: string; -} - -export interface FlashSwapOrderResp { - id: number; - create_time: number; - user_id: number; - sell_currency: string; - sell_amount: string; - buy_currency: string; - buy_amount: string; - price: string; - status: number; -} - -export interface SubmitFlashSwapOrderPreviewResp { - preview_id: string; - sell_currency: string; - sell_amount: string; - buy_currency: string; - buy_amount: string; - price: string; -} - -/**========================================================================================================================== - * FUTURES - * ========================================================================================================================== - */ - -export interface GetFuturesOrderBookResp { - id?: number; - current: number; - update: number; - asks: { p: string; s: number }[]; - bids: { p: string; s: number }[]; -} - -export interface GetFuturesTradesResp { - id: number; - create_time: number; - create_time_ms: number; - contract: string; - size: number; - price: string; - is_internal?: boolean; -} - -export interface GetFuturesCandlesticksResp { - t: number; - v?: number; - c: string; - h: string; - l: string; - o: string; - sum: string; -} - -export interface GetPremiumIndexKLineResp { - t: number; - c: string; - h: string; - l: string; - o: string; -} - -export interface GetFuturesTickersResp { - contract: string; - last: string; - change_percentage: string; - total_size: string; - low_24h: string; - high_24h: string; - volume_24h: string; - volume_24h_btc?: string; - volume_24h_usd?: string; - volume_24h_base: string; - volume_24h_quote: string; - volume_24h_settle: string; - mark_price: string; - funding_rate: string; - funding_rate_indicative: string; - index_price: string; - quanto_base_rate?: string; - basis_rate: string; - basis_value: string; - lowest_ask: string; - highest_bid: string; -} - -export interface GetFuturesStatsResp { - time: number; - lsr_taker: number; - lsr_account: number; - long_liq_size: number; - long_liq_amount: number; - long_liq_usd: number; - short_liq_size: number; - short_liq_amount: number; - short_liq_usd: number; - open_interest: number; - open_interest_usd: number; - top_lsr_account: number; - top_lsr_size: number; -} - -export interface GetIndexConstituentsResp { - index: string; - constituents: { - exchange: string; - symbols: string[]; - }[]; -} - -export interface GetLiquidationHistoryResp { - time: number; - contract: string; - size: number; - order_price: string; - fill_price: string; - left: number; -} - -export interface GetRiskLimitTiersResp { - tier: number; - risk_limit: string; - initial_rate: string; - maintenance_rate: string; - leverage_max: string; - contract: string; -} - -export interface GetFuturesAccountResp { - 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; - 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 GetFuturesAccountBookResp { - time: number; - change: string; - balance: string; - type: string; - text: string; - contract?: string; - trade_id: string; -} - -export interface ToggleFuturesDualModeResp { - 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; - 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 GetFuturesTradingHistoryResp { - id: number; - create_time: number; - contract: string; - order_id: string; - size: number; - price: string; - role: 'taker' | 'maker'; - text: string; - fee: string; - point_fee: string; -} - -export interface GetFuturesPositionHistoryResp { - time: number; - contract: string; - side: 'long' | 'short'; - pnl: string; - pnl_pnl: string; - pnl_fund: string; - pnl_fee: string; - text: string; - max_size: string; - first_open_time: number; - long_price: string; - short_price: string; -} - -export interface GetFuturesLiquidationHistoryResp { - time: number; - contract: string; - leverage: string; - size: number; - margin: string; - entry_price: string; - liq_price: string; - mark_price: string; - order_id: number; - order_price: string; - fill_price: string; - left: number; -} -export interface GetFuturesAutoDeleveragingHistoryResp { - time: number; - user: number; - order_id: number; - contract: string; - leverage: string; - cross_leverage_limit: string; - entry_price: string; - fill_price: string; - trade_size: number; - position_size: number; -} - -export interface DeleteFuturesBatchOrdersResp { - user_id: number; - id: string; - succeeded: boolean; - message: string; -} - -/**========================================================================================================================== - * DELIVERY - * ========================================================================================================================== - */ - -export interface GetDeliveryOrderBookResp { - id?: number; - current: number; - update: number; - asks: { p: string; s: number }[]; - bids: { p: string; s: number }[]; -} - -export interface GetDeliveryTradesResp { - id: number; - create_time: number; - create_time_ms: number; - contract: string; - size: number; - price: string; - is_internal?: boolean; -} - -export interface GetDeliveryCandlesticksResp { - t: number; - v?: number; - c: string; - h: string; - l: string; - o: string; -} - -export interface GetDeliveryTickersResp { - contract: string; - last: string; - change_percentage: string; - total_size: string; - low_24h: string; - high_24h: string; - volume_24h: string; - volume_24h_btc?: string; - volume_24h_usd?: string; - volume_24h_base: string; - volume_24h_quote: string; - volume_24h_settle: string; - mark_price: string; - funding_rate: string; - funding_rate_indicative: string; - index_price: string; - quanto_base_rate?: string; - basis_rate: string; - basis_value: string; - lowest_ask: string; - highest_bid: string; -} - -export interface GetDeliveryAccountResp { - 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; - 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 GetDeliveryBookResp { - time: number; - change: string; - balance: string; - type: - | 'dnw' - | 'pnl' - | 'fee' - | 'refr' - | 'fund' - | 'point_dnw' - | 'point_fee' - | 'point_refr' - | 'bonus_offset'; - text: string; - contract?: string; - trade_id?: string; -} - -export interface GetDeliveryTradingHistoryResp { - id: number; - create_time: number; - contract: string; - order_id: string; - size: number; - price: string; - role: 'taker' | 'maker'; - text: string; - fee: string; - point_fee: string; -} - -export interface GetDeliveryClosedPositionsResp { - time: number; - contract: string; - side: 'long' | 'short'; - pnl: string; - pnl_pnl: string; - pnl_fund: string; - pnl_fee: string; - text: string; - max_size: string; - first_open_time: number; - long_price: string; - short_price: string; -} - -export interface GetDeliveryLiquidationHistoryResp { - time: number; - contract: string; - leverage?: string; - size: number; - margin?: string; - entry_price?: string; - liq_price?: string; - mark_price?: string; - order_id?: number; - order_price: string; - fill_price: string; - left: number; -} - -export interface GetDeliverySettlementHistoryResp { - time: number; - contract: string; - leverage: string; - size: number; - margin: string; - entry_price: string; - settle_price: string; - profit: string; - fee: string; -} - -/**========================================================================================================================== - * OPTIONS - * ========================================================================================================================== - */ - -export interface GetOptionsContractsResp { - name: string; - tag: string; - create_time: number; - expiration_time: number; - is_call: boolean; - strike_price: string; - last_price: string; - mark_price: string; - orderbook_id: number; - trade_id: number; - trade_size: number; - position_size: number; - underlying: string; - underlying_price: string; - multiplier: string; - order_price_round: string; - mark_price_round: string; - maker_fee_rate: string; - taker_fee_rate: string; - price_limit_fee_rate: string; - ref_discount_rate: string; - ref_rebate_rate: string; - order_price_deviate: string; - order_size_min: number; - order_size_max: number; - orders_limit: number; -} - -export interface GetOptionsSettlementHistoryResp { - time: number; - contract: string; - profit: string; - fee: string; - strike_price: string; - settle_price: string; -} - -export interface GetOptionsMySettlementsResp { - time: number; - underlying: string; - contract: string; - strike_price: string; - settle_price: string; - size: number; - settle_profit: string; - fee: string; - realised_pnl: string; -} - -export interface GetOptionsOrderBookResp { - id?: number; - current: number; - update: number; - asks: { p: string; s: number }[]; - bids: { p: string; s: number }[]; -} - -export interface GetOptionsTickersResp { - name: string; - last_price: string; - mark_price: string; - index_price: string; - ask1_size: number; - ask1_price: string; - bid1_size: number; - bid1_price: string; - position_size: number; - mark_iv: string; - bid_iv: string; - ask_iv: string; - leverage: string; - delta: string; - gamma: string; - vega: string; - theta: string; - rho: string; -} - -export interface GetOptionsCandlesticksResp { - t: number; - v?: number; - c: string; - h: string; - l: string; - o: string; -} - -export interface GetOptionsUnderlyingCandlesticksResp { - t: number; - v?: number; - c: string; - h: string; - l: string; - o: string; - sum: string; -} - -export interface GetOptionsTradesResp { - id: number; - create_time: number; - create_time_ms: number; - contract: string; - size: number; - price: string; - is_internal?: boolean; -} - -export interface GetOptionsAccountResp { - user: number; - total: string; - short_enabled: boolean; - unrealised_pnl: string; - init_margin: string; - maint_margin: string; - order_margin: string; - available: string; - point: string; - currency: string; -} -export interface GetOptionsAccountChangeResp { - time: number; - change: string; - balance: string; - type: 'dnw' | 'prem' | 'fee' | 'refr' | 'set'; - text: string; -} - -export interface GetOptionsPositionsUnderlyingResp { - user: number; - underlying: string; - underlying_price: string; - contract: string; - size: number; - entry_price: string; - mark_price: string; - mark_iv: string; - realised_pnl: string; - unrealised_pnl: string; - pending_orders: number; - close_order: { - id: number; - price: string; - is_liq: boolean; - } | null; - delta: string; - gamma: string; - vega: string; - theta: string; -} - -export interface GetOptionsLiquidationResp { - time: number; - contract: string; - side: 'long' | 'short'; - pnl: string; - text: string; - settle_size: string; -} - -export interface SubmitOptionsOrderResp { - id: number; - user: number; - create_time: number; - finish_time: number; - finish_as: - | 'filled' - | 'cancelled' - | 'liquidated' - | 'ioc' - | 'auto_deleveraged' - | 'reduce_only' - | 'position_closed'; - status: 'open' | 'finished'; - contract: string; - size: number; - iceberg: number; - price: string; - is_close: boolean; - is_reduce_only: boolean; - is_liq: boolean; - tif: 'gtc' | 'ioc' | 'poc'; - left: number; - fill_price: string; - text: string; - tkfr: string; - mkfr: string; - refu: number; - refr: string; -} - -export interface GetOptionsPersonalHistoryResp { - id: number; - create_time: number; - contract: string; - order_id: number; - size: number; - price: string; - underlying_price: string; - role: 'taker' | 'maker'; -} - -/**========================================================================================================================== - * EARN UNI - * ========================================================================================================================== - */ - -export interface GetLendingCurrenciesResp { - currency: string; - min_lend_amount: string; - max_lend_amount: string; - max_rate: string; - min_rate: string; -} - -export interface GetLendingOrdersResp { - currency: string; - current_amount: string; - amount: string; - lent_amount: string; - frozen_amount: string; - min_rate: string; - interest_status: string; - reinvest_left_amount: string; - create_time: number; - update_time: number; -} - -export interface GetLendingRecordsResp { - currency: string; - amount: string; - last_wallet_amount: string; - last_lent_amount: string; - last_frozen_amount: string; - type: 'lend' | 'redeem'; - create_time: number; -} - -export interface GetLendingInterestRecordsResp { - status: number; - currency: string; - actual_rate: string; - interest: string; - interest_status: string; - create_time: number; -} - -/**========================================================================================================================== - * COLLATERAL LOAN - * ========================================================================================================================== - */ - -export interface GetLoanOrdersResp { - order_id: number; - collateral_currency: string; - collateral_amount: string; - borrow_currency: string; - borrow_amount: string; - repaid_amount: string; - repaid_principal: string; - repaid_interest: string; - init_ltv: string; - current_ltv: string; - liquidate_ltv: string; - status: string; - borrow_time: number; - left_repay_total: string; - left_repay_principal: string; - left_repay_interest: string; -} - -export interface GetLoanRepaymentHistoryResp { - order_id: number; - record_id: number; - repaid_amount: string; - borrow_currency: string; - collateral_currency: string; - init_ltv: string; - borrow_time: number; - repay_time: number; - total_interest: string; - before_left_principal: string; - after_left_principal: string; - before_left_collateral: string; - after_left_collateral: string; -} - -export interface GetLoanCollateralRecordsResp { - order_id: number; - record_id: number; - borrow_currency: string; - borrow_amount: string; - collateral_currency: string; - before_collateral: string; - after_collateral: string; - before_ltv: string; - after_ltv: string; - operate_time: number; -} - -export interface GetLoanCollateralizationRatioResp { - collateral_currency: string; - borrow_currency: string; - init_ltv: string; - alert_ltv: string; - liquidate_ltv: string; - min_borrow_amount: string; - left_borrowable_amount: string; -} - -/**========================================================================================================================== - * MULTI COLLATERAL LOAN - * ========================================================================================================================== - */ - -export interface GetMultiLoanOrdersResp { - order_id: string; - order_type: string; - fixed_type: string; - fixed_rate: string; - expire_time: number; - auto_renew: boolean; - auto_repay: boolean; - current_ltv: string; - status: string; - borrow_time: number; - total_left_repay_usdt: string; - total_left_collateral_usdt: string; - borrow_currencies: { - currency: string; - index_price: string; - left_repay_principal: string; - left_repay_interest: string; - left_repay_usdt: string; - }[]; - collateral_currencies: { - currency: string; - index_price: string; - left_collateral: string; - left_collateral_usdt: string; - }[]; -} - -export interface RepayMultiLoanResp { - order_id: number; - repaid_currencies: { - succeeded: boolean; - label?: string; - message?: string; - currency: string; - repaid_principal: string; - repaid_interest: string; - }[]; -} - -export interface GetMultiLoanRepayRecordsResp { - order_id: number; - record_id: number; - init_ltv: string; - before_ltv: string; - after_ltv: string; - borrow_time: number; - repay_time: number; - borrow_currencies: { - currency: string; - index_price: string; - before_amount: string; - before_amount_usdt: string; - after_amount: string; - after_amount_usdt: string; - }[]; - collateral_currencies: { - currency: string; - index_price: string; - before_amount: string; - before_amount_usdt: string; - after_amount: string; - after_amount_usdt: string; - }[]; - repaid_currencies: { - currency: string; - index_price: string; - repaid_amount: string; - repaid_principal: string; - repaid_interest: string; - repaid_amount_usdt: string; - }[]; - total_interest_list: { - currency: string; - index_price: string; - amount: string; - amount_usdt: string; - }[]; - left_repay_interest_list: { - currency: string; - index_price: string; - before_amount: string; - before_amount_usdt: string; - after_amount: string; - after_amount_usdt: string; - }[]; -} - -export interface UpdateMultiLoanResp { - order_id: number; - collateral_currencies: { - succeeded: boolean; - label?: string; - message?: string; - currency: string; - amount: string; - }[]; -} - -export interface GetMultiLoanAdjustmentRecordsResp { - order_id: number; - record_id: number; - before_ltv: string; - after_ltv: string; - operate_time: number; - borrow_currencies: { - currency: string; - index_price: string; - before_amount: string; - before_amount_usdt: string; - after_amount: string; - after_amount_usdt: string; - }[]; - collateral_currencies: { - currency: string; - index_price: string; - before_amount: string; - before_amount_usdt: string; - after_amount: string; - after_amount_usdt: string; - }[]; -} - -export interface GetMultiLoanCurrencyQuotaResp { - currency: string; - index_price: string; - min_quota: string; - left_quota: string; - left_quote_usdt: string; -} - -export interface GetMultiLoanSupportedCurrenciesResp { - loan_currencies: { - currency: string; - price: string; - }[]; - collateral_currencies: { - currency: string; - index_price: string; - discount: string; - }[]; -} - -export interface GetMultiLoanRatioResp { - init_ltv: string; - alert_ltv: string; - liquidate_ltv: string; -} - -export interface GetMultiLoanFixedRatesResp { - currency: string; - rate_7d: string; - rate_30d: string; - update_time: number; -} - -/**========================================================================================================================== - * EARN - * ========================================================================================================================== - */ - -export interface GetDualInvestmentProductsResp { - id: number; - instrument_name: string; - invest_currency: string; - exercise_currency: string; - exercise_price: number; - delivery_time: number; - min_copies: number; - max_copies: number; - per_value: string; - apy_display: string; - start_time: number; - end_time: number; - status: 'NOTSTARTED' | 'ONGOING' | 'ENDED'; -} - -export interface GetDualInvestmentOrdersResp { - id: number; - plan_id: number; - copies: string; - invest_amount: string; - settlement_amount: string; - create_time: number; - complete_time: number; - status: - | 'INIT' - | 'SETTLEMENT_SUCCESS' - | 'SETTLEMENT_PROCESSING' - | 'CANCELED' - | 'FAILED'; - invest_currency: string; - exercise_currency: string; - exercise_price: string; - settlement_price: string; - settlement_currency: string; - apy_display: string; - apy_settlement: string; - delivery_time: number; -} - -export interface GetStructuredProductListResp { - id: number; - type: string; - name_en: string; - investment_coin: string; - investment_period: string; - min_annual_rate: string; - mid_annual_rate: string; - max_annual_rate: string; - watch_market: string; - start_time: number; - end_time: number; - status: 'in_process' | 'will_begin' | 'wait_settlement' | 'done'; -} - -export interface GetStructuredProductOrdersResp { - id: number; - pid: string; - lock_coin: string; - amount: string; - status: 'SUCCESS' | 'FAILED' | 'DONE'; - income: string; - create_time: number; -} - -/**========================================================================================================================== - * ACCOUNT - * ========================================================================================================================== - */ - -export interface GetAccountDetailResp { - user_id: number; - ip_whitelist: string[]; - currency_pairs: string[]; - key: { - mode: number; - }; - tier: number; -} - -export interface CreateStpGroupResp { - id: number; - name: string; - creator_id: number; - create_time: number; -} - -export interface StpResp { - user_id: number; - stp_id: number; - create_time: number; -} diff --git a/src/types/response/spot.ts b/src/types/response/spot.ts new file mode 100644 index 0000000..f814bf8 --- /dev/null +++ b/src/types/response/spot.ts @@ -0,0 +1,193 @@ +/**========================================================================================================================== + * SPOT + * ========================================================================================================================== + */ + +import { Order } from '../shared'; + +export interface GetSpotCurrenciesResp { + currency: string; + delisted: boolean; + withdraw_disabled: boolean; + withdraw_delayed: boolean; + deposit_disabled: boolean; + trade_disabled: boolean; + fixed_rate: string; + chain: string; +} + +export interface GetSpotTickerResp { + currency_pair: string; + last: string; + lowest_ask: string; + highest_bid: 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 GetSpotOrderBookResp { + id?: number; + current: number; + update: number; + asks: [string, string][]; + bids: [string, string][]; +} + +export interface GetSpotTradesResp { + 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; +} + +export type GetSpotCandlesticksResp = [ + [ + 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 GetSpotFeeRatesResp { + 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; + currency_pair: string; + debit_fee: number; +} + +export interface GetSpotBatchFeeRatesResp { + [key: string]: { + 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; + currency_pair: string; + debit_fee: number; + }; +} + +export interface GetSpotAccountsResp { + currency: string; + available: string; + locked: string; + update_id: number; +} + +export interface GetSpotAccountBookResp { + id: string; + time: number; + currency: string; + change: string; + balance: string; + type: string; + text: 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' | '-'; + finish_as: 'open' | 'filled' | 'cancelled' | 'ioc' | 'stp'; +} + +export interface GetSpotOpenOrdersResp { + currency_pair: string; + total: number; + orders: Order[]; +} + +export interface DeleteSpotBatchOrdersResp { + currency_pair: string; + id: string; + succeeded: boolean; + label: string; + message: string; + account: string; +} + +export interface GetSpotTradingHistoryResp { + 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; +} diff --git a/src/types/response/subaccount.ts b/src/types/response/subaccount.ts new file mode 100644 index 0000000..3100eec --- /dev/null +++ b/src/types/response/subaccount.ts @@ -0,0 +1,35 @@ +export interface SubAccountResp { + remark?: string; + login_name: string; + password?: string; + email?: string; + state: number; + type: number; + user_id: number; + create_time: number; +} + +export interface CreateSubAccountApiKeyResp { + user_id: string; + mode?: number; + name?: string; + perms?: { + name?: + | 'wallet' + | 'spot' + | 'futures' + | 'delivery' + | 'earn' + | 'options' + | 'account' + | 'unified' + | 'loan'; + read_only?: boolean; + }[]; + ip_whitelist?: string[]; + key: string; + state: number; + created_at: number; + updated_at: number; + last_access: number; +} diff --git a/src/types/response/unified.ts b/src/types/response/unified.ts new file mode 100644 index 0000000..6101f28 --- /dev/null +++ b/src/types/response/unified.ts @@ -0,0 +1,121 @@ +export interface GetUnifiedAccountInfoResp { + user_id: number; + refresh_time: number; + locked: boolean; + balances: { + [key: string]: { + available: string; + freeze: string; + borrowed: string; + negative_liab: string; + futures_pos_liab: string; + equity: string; + total_freeze: string; + total_liab: string; + spot_in_use: string; + }; + }; + total: string; + borrowed: 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; + unified_account_total: string; + unified_account_total_liab: string; + unified_account_total_equity: string; + leverage: string; + spot_order_loss: string; + spot_hedge: boolean; +} + +export interface GetUnifiedLoansResp { + currency: string; + currency_pair: string; + amount: string; + type: 'platform' | 'margin'; + create_time: number; + update_time: number; +} + +export interface GetUnifiedLoanRecordsResp { + 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; +} +export interface GetUnifiedInterestRecordsResp { + currency: string; + currency_pair: string; + actual_rate: string; + interest: string; + status: number; + type: 'platform' | 'margin'; + create_time: number; +} + +export interface GetUnifiedRiskUnitDetailsResp { + 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 GetUnifiedCurrencyDiscountTiersResp { + currency: string; + discount_tiers: { + tier: string; + discount: string; + lower_limit: string; + upper_limit: string; + }[]; +} + +export interface PortfolioMarginCalculatorResp { + 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; + }[]; + }[]; +} diff --git a/src/types/response/wallet.ts b/src/types/response/wallet.ts new file mode 100644 index 0000000..0cdf34f --- /dev/null +++ b/src/types/response/wallet.ts @@ -0,0 +1,197 @@ +export interface APIResponse { + success: boolean; + data: TData; + timestamp: number; +} + +export interface GetCurrencyChainsResp { + 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 CreateDepositAddressResp { + currency: string; + address: string; + multichain_addresses: { + chain: string; + address: string; + payment_id: string; + payment_name: string; + obtain_failed: number; + }[]; +} + +export interface SubAccountTransferRecordResp { + 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 GetWithdrawalStatusResp { + 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 SubAccountMarginBalancesResp { + uid: string; + available: { + 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; + 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 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 GetSavedAddressResp { + currency: string; + chain: string; + address: string; + name: string; + tag: string; + verified: string; +} + +export interface GetTradingFeesResp { + 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; + }; + }; +} + +export interface GetSmallBalancesResp { + currency: string; + available_balance: string; + estimated_as_btc: string; + convertible_to_gt: string; +} + +export interface GetSmallBalanceHistoryResp { + id: string; + currency: string; + amount: string; + gt_amount: string; + create_time: number; +} diff --git a/src/types/response/withdrawal.ts b/src/types/response/withdrawal.ts new file mode 100644 index 0000000..e69de29 From 58c8d088a8334fe90d04e92ef34aa495bd260abe Mon Sep 17 00:00:00 2001 From: Jerko J <83344666+JJ-Cro@users.noreply.github.com> Date: Fri, 24 May 2024 14:41:32 +0200 Subject: [PATCH 32/36] chore(): Separated all types into categories --- src/RestClient.ts | 234 ++--- src/types/requests/account.ts | 11 + src/types/requests/collateralLoan.ts | 44 + src/types/requests/delivery.ts | 132 +++ src/types/requests/earn.ts | 18 + src/types/requests/earnuni.ts | 34 + src/types/requests/flashswap.ts | 32 + src/types/requests/futures.ts | 178 ++++ src/types/requests/margin.ts | 53 ++ src/types/requests/marginuni.ts | 33 + src/types/requests/multicollateralLoan.ts | 60 ++ src/types/requests/options.ts | 89 ++ src/types/requests/shared.types.ts | 985 ---------------------- src/types/requests/spot.ts | 127 +++ src/types/requests/subaccount.ts | 30 + src/types/requests/unified.ts | 68 ++ src/types/requests/wallet.ts | 56 ++ src/types/requests/withdrawal.ts | 13 + 18 files changed, 1108 insertions(+), 1089 deletions(-) create mode 100644 src/types/requests/collateralLoan.ts create mode 100644 src/types/requests/multicollateralLoan.ts diff --git a/src/RestClient.ts b/src/RestClient.ts index e002c62..0e241ef 100644 --- a/src/RestClient.ts +++ b/src/RestClient.ts @@ -1,10 +1,140 @@ import { AxiosRequestConfig } from 'axios'; +import { CreateStpGroupReq } from 'types/requests/account.js'; +import { + GetLoanCollateralRecordsReq, + GetLoanOrdersReq, + GetLoanRepaymentHistoryReq, + SubmitLoanOrderReq, + UpdateLoanCollateralReq, +} from 'types/requests/collateralLoan.js'; +import { + GetDeliveryAutoOrdersReq, + GetDeliveryBookReq, + GetDeliveryCandlesticksReq, + GetDeliveryClosedPositionsReq, + GetDeliveryLiquidationHistoryReq, + GetDeliveryOrderBookReq, + GetDeliveryOrdersReq, + GetDeliverySettlementHistoryReq, + GetDeliveryTradesReq, + GetDeliveryTradingHistoryReq, + SubmitDeliveryFuturesOrderReq, + submitDeliveryTriggeredOrderReq, +} from 'types/requests/delivery.js'; +import { + GetStructuredProductListReq, + GetStructuredProductOrdersReq, +} from 'types/requests/earn.js'; +import { + GetLendingInterestRecordsReq, + GetLendingOrdersReq, + GetLendingRecordsReq, + SubmitLendOrRedeemReq, +} from 'types/requests/earnuni.js'; +import { + GetFlashSwapOrdersReq, + SubmitFlashSwapOrderPreviewReq, + SubmitFlashSwapOrderReq, +} from 'types/requests/flashswap.js'; +import { + DeleteAllFuturesOrdersReq, + GetFuturesAccountBookReq, + GetFuturesAutoOrdersReq, + GetFuturesCandlesticksReq, + GetFuturesLiquidationHistoryReq, + GetFuturesOrderBookReq, + GetFuturesOrdersByTimeRangeReq, + GetFuturesOrdersReq, + GetFuturesPositionHistoryReq, + GetFuturesPositionsReq, + GetFuturesStatsReq, + GetFuturesTradesReq, + GetFuturesTradingHistoryReq, + GetLiquidationHistoryReq, + GetRiskLimitTiersReq, + submitFuturesBatchOrdersReq, + SubmitFuturesOrderReq, + SubmitFuturesPriceTriggeredOrderReq, + UpdateDualModePositionLeverageReq, + UpdateDualModePositionMarginReq, +} from 'types/requests/futures.js'; +import { + GetCrossMarginAccountHistoryReq, + GetCrossMarginBorrowHistoryReq, + GetCrossMarginInterestRecordsReq, + GetCrossMarginRepaymentsReq, + GetMarginBalanceHistoryReq, + SubmitCrossMarginBorrowLoanReq, +} from 'types/requests/margin.js'; +import { + GetMarginUNIInterestRecordsReq, + GetMarginUNILoanRecordsReq, + GetMarginUNILoansReq, + GetMarginUNIMaxBorrowReq, +} from 'types/requests/marginuni.js'; +import { + GetMultiLoanAdjustmentRecordsReq, + GetMultiLoanOrdersReq, + GetMultiLoanRepayRecordsReq, + RepayMultiLoanReq, + SubmitMultiLoanOrderReq, + UpdateMultiLoanReq, +} from 'types/requests/multicollateralLoan.js'; +import { + GetOptionsAccountChangeReq, + GetOptionsCandlesticksReq, + GetOptionsMySettlementsReq, + GetOptionsOrderBookReq, + GetOptionsOrdersReq, + GetOptionsPersonalHistoryReq, + GetOptionsSettlementHistoryReq, + GetOptionsTradesReq, + GetOptionsUnderlyingCandlesticksReq, + SubmitOptionsOrderReq, +} from 'types/requests/options.js'; import { GetAgencyCommissionHistoryReq, GetAgencyTransactionHistoryReq, GetBrokerCommissionHistoryReq, GetBrokerTransactionHistoryReq, } from 'types/requests/rebate.js'; +import { + DeleteSpotOrderReq, + GetSpotAccountBookReq, + GetSpotAutoOrdersReq, + GetSpotCandlesticksReq, + GetSpotOrderBookReq, + GetSpotOrdersReq, + GetSpotTradesReq, + GetSpotTradingHistoryReq, + SubmitSpotClosePosCrossDisabledReq, + SubmitSpotOrderReq, + UpdateSpotBatchOrdersReq, + UpdateSpotOrderReq, +} from 'types/requests/spot.js'; +import { + CreateSubAccountApiKeyReq, + CreateSubAccountReq, + UpdateSubAccountApiKeyReq, +} from 'types/requests/subaccount.js'; +import { + GetUnifiedInterestRecordsReq, + GetUnifiedLoanRecordsReq, + GetUnifiedLoansReq, + PortfolioMarginCalculatorReq, + SetUnifiedAccountModeReq, + SubmitUnifiedBorrowOrRepayReq, +} from 'types/requests/unified.js'; +import { + GetMainSubTransfersReq, + GetSavedAddressReq, + GetSmallBalanceHistoryReq, + GetWithdrawalDepositRecordsReq, + SubmitMainSubTransferReq, + SubmitSubToSubTransferReq, + SubmitTransferReq, +} from 'types/requests/wallet.js'; +import { SubmitWithdrawReq } from 'types/requests/withdrawal.js'; import { CreateStpGroupResp, GetAccountDetailResp, @@ -161,110 +291,6 @@ import { RestClientType, } from './lib/BaseRestClient.js'; import { RestClientOptions } from './lib/requestUtils.js'; -import { - CreateStpGroupReq, - CreateSubAccountApiKeyReq, - CreateSubAccountReq, - DeleteAllFuturesOrdersReq, - DeleteSpotOrderReq, - GetCrossMarginAccountHistoryReq, - GetCrossMarginBorrowHistoryReq, - GetCrossMarginInterestRecordsReq, - GetCrossMarginRepaymentsReq, - GetDeliveryAutoOrdersReq, - GetDeliveryBookReq, - GetDeliveryCandlesticksReq, - GetDeliveryClosedPositionsReq, - GetDeliveryLiquidationHistoryReq, - GetDeliveryOrderBookReq, - GetDeliveryOrdersReq, - GetDeliverySettlementHistoryReq, - GetDeliveryTradesReq, - GetDeliveryTradingHistoryReq, - GetFlashSwapOrdersReq, - GetFuturesAccountBookReq, - GetFuturesAutoOrdersReq, - GetFuturesCandlesticksReq, - GetFuturesLiquidationHistoryReq, - GetFuturesOrderBookReq, - GetFuturesOrdersByTimeRangeReq, - GetFuturesOrdersReq, - GetFuturesPositionHistoryReq, - GetFuturesPositionsReq, - GetFuturesStatsReq, - GetFuturesTradesReq, - GetFuturesTradingHistoryReq, - GetLendingInterestRecordsReq, - GetLendingOrdersReq, - GetLendingRecordsReq, - GetLiquidationHistoryReq, - GetLoanCollateralRecordsReq, - GetLoanOrdersReq, - GetLoanRepaymentHistoryReq, - GetMainSubTransfersReq, - GetMarginBalanceHistoryReq, - GetMarginUNIInterestRecordsReq, - GetMarginUNILoanRecordsReq, - GetMarginUNILoansReq, - GetMarginUNIMaxBorrowReq, - GetMultiLoanAdjustmentRecordsReq, - GetMultiLoanOrdersReq, - GetMultiLoanRepayRecordsReq, - GetOptionsAccountChangeReq, - GetOptionsCandlesticksReq, - GetOptionsMySettlementsReq, - GetOptionsOrderBookReq, - GetOptionsOrdersReq, - GetOptionsPersonalHistoryReq, - GetOptionsSettlementHistoryReq, - GetOptionsTradesReq, - GetOptionsUnderlyingCandlesticksReq, - GetRiskLimitTiersReq, - GetSavedAddressReq, - GetSmallBalanceHistoryReq, - GetSpotAccountBookReq, - GetSpotAutoOrdersReq, - GetSpotCandlesticksReq, - GetSpotOrderBookReq, - GetSpotOrdersReq, - GetSpotTradesReq, - GetSpotTradingHistoryReq, - GetStructuredProductListReq, - GetStructuredProductOrdersReq, - GetUnifiedInterestRecordsReq, - GetUnifiedLoanRecordsReq, - GetUnifiedLoansReq, - GetWithdrawalDepositRecordsReq, - PortfolioMarginCalculatorReq, - RepayMultiLoanReq, - SetUnifiedAccountModeReq, - SubmitCrossMarginBorrowLoanReq, - SubmitDeliveryFuturesOrderReq, - submitDeliveryTriggeredOrderReq, - SubmitFlashSwapOrderPreviewReq, - SubmitFlashSwapOrderReq, - submitFuturesBatchOrdersReq, - SubmitFuturesOrderReq, - SubmitFuturesPriceTriggeredOrderReq, - SubmitLendOrRedeemReq, - SubmitLoanOrderReq, - SubmitMainSubTransferReq, - SubmitMultiLoanOrderReq, - SubmitOptionsOrderReq, - SubmitSpotClosePosCrossDisabledReq, - SubmitSpotOrderReq, - SubmitSubToSubTransferReq, - SubmitTransferReq, - SubmitUnifiedBorrowOrRepayReq, - SubmitWithdrawReq, - UpdateDualModePositionLeverageReq, - UpdateDualModePositionMarginReq, - UpdateLoanCollateralReq, - UpdateMultiLoanReq, - UpdateSpotBatchOrdersReq, - UpdateSpotOrderReq, - UpdateSubAccountApiKeyReq, -} from './types/requests/shared.types.js'; import { CancelBatchOrder, Contract, diff --git a/src/types/requests/account.ts b/src/types/requests/account.ts index e69de29..2c6a455 100644 --- a/src/types/requests/account.ts +++ b/src/types/requests/account.ts @@ -0,0 +1,11 @@ +/**========================================================================================================================== + * ACCOUNT + * ========================================================================================================================== + */ + +export interface CreateStpGroupReq { + name: string; + id?: number; + creator_id?: number; + create_time?: number; +} diff --git a/src/types/requests/collateralLoan.ts b/src/types/requests/collateralLoan.ts new file mode 100644 index 0000000..7f25a00 --- /dev/null +++ b/src/types/requests/collateralLoan.ts @@ -0,0 +1,44 @@ +/**========================================================================================================================== + * COLLATERAL LOAN + * ========================================================================================================================== + */ + +export interface SubmitLoanOrderReq { + collateral_amount: string; + collateral_currency: string; + borrow_amount: string; + borrow_currency: string; +} + +export interface GetLoanOrdersReq { + page?: number; + limit?: number; + collateral_currency?: string; + borrow_currency?: string; +} + +export interface GetLoanRepaymentHistoryReq { + source: 'repay' | 'liquidate'; + borrow_currency?: string; + collateral_currency?: string; + page?: number; + limit?: number; + from?: number; + to?: number; +} + +export interface UpdateLoanCollateralReq { + order_id: number; + collateral_currency: string; + collateral_amount: string; + type: 'append' | 'redeem'; +} + +export interface GetLoanCollateralRecordsReq { + page?: number; + limit?: number; + from?: number; + to?: number; + borrow_currency?: string; + collateral_currency?: string; +} diff --git a/src/types/requests/delivery.ts b/src/types/requests/delivery.ts index e69de29..13edba6 100644 --- a/src/types/requests/delivery.ts +++ b/src/types/requests/delivery.ts @@ -0,0 +1,132 @@ +/**========================================================================================================================== + * DELIVERY + * ========================================================================================================================== + */ + +import { FuturesPriceTriggeredOrder } from 'types/shared'; + +export interface GetDeliveryOrderBookReq { + settle: 'usdt'; + contract: string; + interval?: '0' | '0.1' | '0.01'; + limit?: number; + with_id?: boolean; +} + +export interface GetDeliveryTradesReq { + settle: 'usdt'; + contract: string; + limit?: number; + last_id?: string; + from?: number; + to?: number; +} + +export interface GetDeliveryCandlesticksReq { + settle: 'usdt'; + contract: string; + from?: number; + to?: number; + limit?: number; + interval?: + | '10s' + | '30s' + | '1m' + | '5m' + | '15m' + | '30m' + | '1h' + | '2h' + | '4h' + | '6h' + | '8h' + | '12h' + | '1d' + | '7d' + | '1w' + | '30d'; +} + +export interface GetDeliveryBookReq { + settle: 'usdt'; + limit?: number; + from?: number; + to?: number; + type?: + | 'dnw' + | 'pnl' + | 'fee' + | 'refr' + | 'fund' + | 'point_dnw' + | 'point_fee' + | 'point_refr' + | 'bonus_offset'; +} + +export interface SubmitDeliveryFuturesOrderReq { + settle: 'usdt'; + contract: string; + size: number; + iceberg?: number; + price?: string; + close?: boolean; + reduce_only?: boolean; + tif?: string; + text?: string; + auto_size?: string; + stp_act?: string; +} + +export interface GetDeliveryOrdersReq { + settle: 'usdt'; + contract?: string; + status: 'open' | 'finished'; + limit?: number; + offset?: number; + last_id?: string; + count_total?: 0 | 1; +} + +export interface GetDeliveryTradingHistoryReq { + settle: 'usdt'; + contract?: string; + order?: number; + limit?: number; + offset?: number; + last_id?: string; + count_total?: 0 | 1; +} + +export interface GetDeliveryClosedPositionsReq { + settle: 'usdt'; + contract?: string; + limit?: number; +} + +export interface GetDeliveryLiquidationHistoryReq { + settle: 'usdt'; + contract?: string; + limit?: number; + at?: number; +} + +export interface GetDeliverySettlementHistoryReq { + settle: 'usdt'; + contract?: string; + limit?: number; + at?: number; +} + +export interface submitDeliveryTriggeredOrderReq + extends FuturesPriceTriggeredOrder { + settle: 'usdt'; +} + +export interface GetDeliveryAutoOrdersReq { + settle: 'usdt'; + status: 'open' | 'finished'; + contract?: string; + limit?: number; + offset?: number; +} diff --git a/src/types/requests/earn.ts b/src/types/requests/earn.ts index e69de29..1bf00e4 100644 --- a/src/types/requests/earn.ts +++ b/src/types/requests/earn.ts @@ -0,0 +1,18 @@ +/**========================================================================================================================== + * EARN + * ========================================================================================================================== + */ + +export interface GetStructuredProductListReq { + status: string; + type?: string; + page?: number; + limit?: number; +} + +export interface GetStructuredProductOrdersReq { + from?: number; + to?: number; + page?: number; + limit?: number; +} diff --git a/src/types/requests/earnuni.ts b/src/types/requests/earnuni.ts index e69de29..63b07f1 100644 --- a/src/types/requests/earnuni.ts +++ b/src/types/requests/earnuni.ts @@ -0,0 +1,34 @@ +/**========================================================================================================================== + * EARN UNI + * ========================================================================================================================== + */ + +export interface SubmitLendOrRedeemReq { + currency: string; + amount: string; + type: 'lend' | 'redeem'; + min_rate?: string; +} + +export interface GetLendingOrdersReq { + currency?: string; + page?: number; + limit?: number; +} + +export interface GetLendingRecordsReq { + currency?: string; + page?: number; + limit?: number; + from?: number; + to?: number; + type?: 'lend' | 'redeem'; +} + +export interface GetLendingInterestRecordsReq { + currency?: string; + page?: number; + limit?: number; + from?: number; + to?: number; +} diff --git a/src/types/requests/flashswap.ts b/src/types/requests/flashswap.ts index e69de29..a16ef6f 100644 --- a/src/types/requests/flashswap.ts +++ b/src/types/requests/flashswap.ts @@ -0,0 +1,32 @@ +/**========================================================================================================================== + * FLASH SWAP + * ========================================================================================================================== + */ + +export interface SubmitFlashSwapOrderReq { + preview_id: string; + sell_currency: string; + sell_amount: string; + buy_currency: string; + buy_amount: string; +} + +export interface GetFlashSwapOrdersReq { + status?: number; + sell_currency?: string; + buy_currency?: string; + reverse?: boolean; + limit?: number; + page?: number; +} + +export interface GetFlashSwapOrderReq { + order_id: number; +} + +export interface SubmitFlashSwapOrderPreviewReq { + sell_currency: string; + sell_amount?: string; + buy_currency: string; + buy_amount?: string; +} diff --git a/src/types/requests/futures.ts b/src/types/requests/futures.ts index e69de29..d925293 100644 --- a/src/types/requests/futures.ts +++ b/src/types/requests/futures.ts @@ -0,0 +1,178 @@ +/**========================================================================================================================== + * FUTURES + * ========================================================================================================================== + */ + +import { FuturesOrder, FuturesPriceTriggeredOrder } from 'types/shared'; + +export interface GetFuturesOrderBookReq { + settle: 'btc' | 'usdt' | 'usd'; + contract: string; + interval?: string; + limit?: number; + with_id?: boolean; +} + +export interface GetFuturesTradesReq { + settle: 'btc' | 'usdt' | 'usd'; + contract: string; + limit?: number; + offset?: number; + last_id?: string; + from?: number; + to?: number; +} + +export interface GetFuturesCandlesticksReq { + settle: 'btc' | 'usdt' | 'usd'; + contract: string; + from?: number; + to?: number; + limit?: number; + interval?: string; +} + +export interface GetFuturesStatsReq { + settle: 'btc' | 'usdt' | 'usd'; + contract: string; + from?: number; + interval?: string; + limit?: number; +} + +export interface GetLiquidationHistoryReq { + settle: 'btc' | 'usdt' | 'usd'; + contract?: string; + from?: number; + to?: number; + limit?: number; +} + +export interface GetRiskLimitTiersReq { + settle: 'btc' | 'usdt' | 'usd'; + contract: string; + limit?: number; + offset?: number; +} + +export interface GetFuturesAccountBookReq { + settle: 'btc' | 'usdt' | 'usd'; + contract?: string; + limit?: number; + offset?: number; + from?: number; + to?: number; + type?: + | 'dnw' + | 'pnl' + | 'fee' + | 'refr' + | 'fund' + | 'point_dnw' + | 'point_fee' + | 'point_refr' + | 'bonus_offset'; +} + +export interface GetFuturesPositionsReq { + settle: 'btc' | 'usdt' | 'usd'; + holding?: boolean; + limit?: number; + offset?: number; +} + +export interface UpdateDualModePositionMarginReq { + settle: 'btc' | 'usdt' | 'usd'; + contract: string; + change: string; + dual_side: 'dual_long' | 'dual_short'; +} + +export interface UpdateDualModePositionLeverageReq { + settle: 'btc' | 'usdt' | 'usd'; + contract: string; + leverage: string; + cross_leverage_limit?: string; +} + +export interface SubmitFuturesOrderReq { + settle: 'btc' | 'usdt' | 'usd'; + contract: string; + size: number; + iceberg?: number; + price?: string; + close?: boolean; + reduce_only?: boolean; + tif?: string; + text?: string; + auto_size?: string; + stp_act?: string; +} + +export interface GetFuturesOrdersReq { + settle: 'btc' | 'usdt' | 'usd'; + contract?: string; + status: string; + limit?: number; + offset?: number; + last_id?: string; +} + +export interface DeleteAllFuturesOrdersReq { + settle: 'btc' | 'usdt' | 'usd'; + contract: string; + side?: string; +} + +export interface GetFuturesOrdersByTimeRangeReq { + settle: 'btc' | 'usdt' | 'usd'; + contract?: string; + from?: number; + to?: number; + limit?: number; + offset?: number; +} + +export interface submitFuturesBatchOrdersReq extends FuturesOrder { + settle: 'btc' | 'usdt' | 'usd'; +} + +export interface GetFuturesTradingHistoryReq { + settle: 'btc' | 'usdt' | 'usd'; + contract?: string; + order?: number; + limit?: number; + offset?: number; + last_id?: string; +} + +export interface GetFuturesPositionHistoryReq { + settle: 'btc' | 'usdt' | 'usd'; + contract?: string; + limit?: number; + offset?: number; + from?: number; + to?: number; + side?: 'long' | 'short'; + pnl?: string; +} + +export interface GetFuturesLiquidationHistoryReq { + settle: 'btc' | 'usdt' | 'usd'; + contract?: string; + limit?: number; + at?: number; +} + +export interface SubmitFuturesPriceTriggeredOrderReq + extends FuturesPriceTriggeredOrder { + settle: 'btc' | 'usdt' | 'usd'; +} + +export interface GetFuturesAutoOrdersReq { + settle: 'btc' | 'usdt' | 'usd'; + status: 'open' | 'finished'; + contract?: string; + limit?: number; + offset?: number; +} diff --git a/src/types/requests/margin.ts b/src/types/requests/margin.ts index e69de29..1333495 100644 --- a/src/types/requests/margin.ts +++ b/src/types/requests/margin.ts @@ -0,0 +1,53 @@ +/**========================================================================================================================== + * MARGIN + * ========================================================================================================================== + */ + +export interface GetMarginBalanceHistoryReq { + currency?: string; + currency_pair?: string; + type?: string; + from?: number; + to?: number; + page?: number; + limit?: number; +} + +export interface GetCrossMarginAccountHistoryReq { + currency?: string; + from?: number; + to?: number; + page?: number; + limit?: number; + type?: string; +} + +export interface SubmitCrossMarginBorrowLoanReq { + currency: string; + amount: string; + text?: string; +} + +export interface GetCrossMarginBorrowHistoryReq { + status: number; + currency?: string; + limit?: number; + offset?: number; + reverse?: boolean; +} + +export interface GetCrossMarginRepaymentsReq { + currency?: string; + loan_id?: string; + limit?: number; + offset?: number; + reverse?: boolean; +} + +export interface GetCrossMarginInterestRecordsReq { + currency?: string; + page?: number; + limit?: number; + from?: number; + to?: number; +} diff --git a/src/types/requests/marginuni.ts b/src/types/requests/marginuni.ts index e69de29..96b2435 100644 --- a/src/types/requests/marginuni.ts +++ b/src/types/requests/marginuni.ts @@ -0,0 +1,33 @@ +/**========================================================================================================================== + * MARGIN UNI + * ========================================================================================================================== + */ + +export interface GetMarginUNILoansReq { + currency_pair?: string; + currency?: string; + page?: number; + limit?: number; +} + +export interface GetMarginUNILoanRecordsReq { + type?: 'borrow' | 'repay'; + currency?: string; + currency_pair?: string; + page?: number; + limit?: number; +} + +export interface GetMarginUNIInterestRecordsReq { + currency_pair?: string; + currency?: string; + page?: number; + limit?: number; + from?: number; + to?: number; +} + +export interface GetMarginUNIMaxBorrowReq { + currency: string; + currency_pair: string; +} diff --git a/src/types/requests/multicollateralLoan.ts b/src/types/requests/multicollateralLoan.ts new file mode 100644 index 0000000..4e7cbe6 --- /dev/null +++ b/src/types/requests/multicollateralLoan.ts @@ -0,0 +1,60 @@ +/**========================================================================================================================== + * MULTI COLLATERAL LOAN + * ========================================================================================================================== + */ + +export interface SubmitMultiLoanOrderReq { + order_id?: string; + order_type?: string; + fixed_type?: string; + fixed_rate?: string; + auto_renew?: boolean; + auto_repay?: boolean; + borrow_currency: string; + borrow_amount: string; + collateral_currencies?: { + currency?: string; + amount?: string; + }[]; +} +export interface GetMultiLoanOrdersReq { + page?: number; + limit?: number; + sort?: string; + order_type?: string; +} + +export interface RepayMultiLoanReq { + order_id: number; + repay_items: { + currency?: string; + amount?: string; + repaid_all?: boolean; + }[]; +} + +export interface GetMultiLoanRepayRecordsReq { + type: 'repay' | 'liquidate'; + borrow_currency?: string; + page?: number; + limit?: number; + from?: number; + to?: number; +} + +export interface UpdateMultiLoanReq { + order_id: number; + type: 'append' | 'redeem'; + collaterals?: { + currency?: string; + amount?: string; + }[]; +} + +export interface GetMultiLoanAdjustmentRecordsReq { + page?: number; + limit?: number; + from?: number; + to?: number; + collateral_currency?: string; +} diff --git a/src/types/requests/options.ts b/src/types/requests/options.ts index e69de29..98f4a85 100644 --- a/src/types/requests/options.ts +++ b/src/types/requests/options.ts @@ -0,0 +1,89 @@ +/**========================================================================================================================== + * 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 GetOptionsCandlesticksReq { + contract: string; + limit?: number; + from?: number; + to?: number; + interval?: '1m' | '5m' | '15m' | '30m' | '1h'; +} + +export interface GetOptionsUnderlyingCandlesticksReq { + underlying: string; + limit?: number; + from?: number; + to?: number; + interval?: '1m' | '5m' | '15m' | '30m' | '1h'; +} + +export interface GetOptionsTradesReq { + contract?: string; + type?: 'C' | 'P'; + limit?: number; + offset?: number; + from?: number; + to?: number; +} + +export interface GetOptionsAccountChangeReq { + limit?: number; + offset?: number; + from?: number; + to?: number; + type?: 'dnw' | 'prem' | 'fee' | 'refr' | 'set'; +} + +export interface SubmitOptionsOrderReq { + contract: string; + size: number; + iceberg?: number; + price?: string; + close?: boolean; + reduce_only?: boolean; + tif?: 'gtc' | 'ioc' | 'poc'; + text?: string; +} + +export interface GetOptionsOrdersReq { + contract?: string; + underlying?: string; + status: 'open' | 'finished'; + limit?: number; + offset?: number; + from?: number; + to?: number; +} + +export interface GetOptionsPersonalHistoryReq { + underlying: string; + contract?: string; + limit?: number; + offset?: number; + from?: number; + to?: number; +} diff --git a/src/types/requests/shared.types.ts b/src/types/requests/shared.types.ts index 40fbe9b..e69de29 100644 --- a/src/types/requests/shared.types.ts +++ b/src/types/requests/shared.types.ts @@ -1,985 +0,0 @@ -import { FuturesOrder, FuturesPriceTriggeredOrder } from 'types/shared'; - -export interface SubmitWithdrawReq { - amount: string; - currency: string; - chain: string; - withdraw_order_id?: string; - address?: string; - memo?: string; -} - -export interface GetWithdrawalDepositRecordsReq { - currency?: string; - from?: number; - to?: number; - limit?: number; - offset?: number; -} - -export interface GetMainSubTransfersReq { - sub_uid?: string; - from?: number; - to?: number; - limit?: number; - offset?: number; -} - -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'; -} - -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 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; -} - -export interface CreateSubAccountApiKeyReq { - user_id: number; - mode?: number; // Mode: 1 - classic, 2 - portfolio account - name?: string; // API key name - perms?: { - name?: - | 'wallet' - | 'spot' - | 'futures' - | 'delivery' - | 'earn' - | 'options' - | 'account' - | 'unified' - | 'loan'; // Permission name - read_only?: boolean; // Read only - }[]; - ip_whitelist?: string[]; // IP white list -} - -export interface UpdateSubAccountApiKeyReq extends CreateSubAccountApiKeyReq { - key: string; -} - -export interface CreateSubAccountReq { - login_name: string; - remark?: string; - password?: string; - email?: string; -} - -export interface GetSavedAddressReq { - currency: string; - chain?: string; - limit?: string; - page?: number; -} - -export interface GetSmallBalanceHistoryReq { - currency?: string; - page?: number; - limit?: number; -} - -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; - type?: 'platform' | 'margin'; -} - -export interface SetUnifiedAccountModeReq { - mode: 'classic' | 'multi_currency' | 'portfolio'; - settings?: { - usdt_futures?: boolean; - spot_hedge?: 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; -} - -/**========================================================================================================================== - * SPOT - * ========================================================================================================================== - */ - -export interface GetSpotOrderBookReq { - currency_pair: string; - interval?: string; - limit?: number; - with_id?: boolean; -} - -export interface GetSpotTradesReq { - currency_pair: string; - limit?: number; - last_id?: string; - reverse?: boolean; - from?: number; - to?: number; - page?: number; -} - -export interface GetSpotCandlesticksReq { - currency_pair: string; - limit?: number; - from?: number; - to?: number; - interval?: - | '10s' - | '1m' - | '5m' - | '15m' - | '30m' - | '1h' - | '4h' - | '8h' - | '1d' - | '7d' - | '30d'; -} - -export interface GetSpotAccountBookReq { - currency?: string; - from?: number; - to?: number; - page?: number; - limit?: number; - type?: string; -} - -export interface SubmitSpotClosePosCrossDisabledReq { - text?: string; - currency_pair: string; - amount: string; - price: string; - action_mode?: 'ACK' | 'RESULT' | 'FULL'; -} - -export interface GetSpotOrdersReq { - currency_pair: string; - status: 'open' | 'finished'; - page?: number; - limit?: number; - account?: 'spot' | 'margin' | 'cross_margin' | 'unified'; - from?: number; - to?: number; - side?: 'buy' | 'sell'; -} - -export interface DeleteSpotOrderReq { - order_id: string; - currency_pair: string; - account?: 'spot' | 'margin' | 'cross_margin' | 'unified'; - action_mode?: 'ACK' | 'RESULT' | 'FULL'; -} - -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 UpdateSpotBatchOrdersReq { - order_id?: string; - currency_pair?: string; - amount?: string; - price?: string; - amend_text?: string; -} - -export interface GetSpotAutoOrdersReq { - status: 'open' | 'finished'; - market?: string; - account?: 'normal' | 'margin' | 'cross_margin'; - limit?: number; - offset?: number; -} - -export interface SubmitSpotOrderReq { - 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; -} - -export interface UpdateSpotOrderReq { - order_id: string; - currency_pair: string; - account?: 'spot' | 'margin' | 'cross_margin' | 'unified'; - amount?: string; - price?: string; - amend_text?: string; - action_mode?: 'ACK' | 'RESULT' | 'FULL'; -} -/**========================================================================================================================== - * MARGIN - * ========================================================================================================================== - */ - -export interface GetMarginBalanceHistoryReq { - currency?: string; - currency_pair?: string; - type?: string; - from?: number; - to?: number; - page?: number; - limit?: number; -} - -export interface GetCrossMarginAccountHistoryReq { - currency?: string; - from?: number; - to?: number; - page?: number; - limit?: number; - type?: string; -} - -export interface SubmitCrossMarginBorrowLoanReq { - currency: string; - amount: string; - text?: string; -} - -export interface GetCrossMarginBorrowHistoryReq { - status: number; - currency?: string; - limit?: number; - offset?: number; - reverse?: boolean; -} - -export interface GetCrossMarginRepaymentsReq { - currency?: string; - loan_id?: string; - limit?: number; - offset?: number; - reverse?: boolean; -} - -export interface GetCrossMarginInterestRecordsReq { - currency?: string; - page?: number; - limit?: number; - from?: number; - to?: number; -} - -/**========================================================================================================================== - * MARGIN UNI - * ========================================================================================================================== - */ - -export interface GetMarginUNILoansReq { - currency_pair?: string; - currency?: string; - page?: number; - limit?: number; -} - -export interface GetMarginUNILoanRecordsReq { - type?: 'borrow' | 'repay'; - currency?: string; - currency_pair?: string; - page?: number; - limit?: number; -} - -export interface GetMarginUNIInterestRecordsReq { - currency_pair?: string; - currency?: string; - page?: number; - limit?: number; - from?: number; - to?: number; -} - -export interface GetMarginUNIMaxBorrowReq { - currency: string; - currency_pair: string; -} - -/**========================================================================================================================== - * FLASH SWAP - * ========================================================================================================================== - */ - -export interface SubmitFlashSwapOrderReq { - preview_id: string; - sell_currency: string; - sell_amount: string; - buy_currency: string; - buy_amount: string; -} - -export interface GetFlashSwapOrdersReq { - status?: number; - sell_currency?: string; - buy_currency?: string; - reverse?: boolean; - limit?: number; - page?: number; -} - -export interface GetFlashSwapOrderReq { - order_id: number; -} - -export interface SubmitFlashSwapOrderPreviewReq { - sell_currency: string; - sell_amount?: string; - buy_currency: string; - buy_amount?: string; -} - -/**========================================================================================================================== - * FUTURES - * ========================================================================================================================== - */ - -export interface GetFuturesOrderBookReq { - settle: 'btc' | 'usdt' | 'usd'; - contract: string; - interval?: string; - limit?: number; - with_id?: boolean; -} - -export interface GetFuturesTradesReq { - settle: 'btc' | 'usdt' | 'usd'; - contract: string; - limit?: number; - offset?: number; - last_id?: string; - from?: number; - to?: number; -} - -export interface GetFuturesCandlesticksReq { - settle: 'btc' | 'usdt' | 'usd'; - contract: string; - from?: number; - to?: number; - limit?: number; - interval?: string; -} - -export interface GetFuturesStatsReq { - settle: 'btc' | 'usdt' | 'usd'; - contract: string; - from?: number; - interval?: string; - limit?: number; -} - -export interface GetLiquidationHistoryReq { - settle: 'btc' | 'usdt' | 'usd'; - contract?: string; - from?: number; - to?: number; - limit?: number; -} - -export interface GetRiskLimitTiersReq { - settle: 'btc' | 'usdt' | 'usd'; - contract: string; - limit?: number; - offset?: number; -} - -export interface GetFuturesAccountBookReq { - settle: 'btc' | 'usdt' | 'usd'; - contract?: string; - limit?: number; - offset?: number; - from?: number; - to?: number; - type?: - | 'dnw' - | 'pnl' - | 'fee' - | 'refr' - | 'fund' - | 'point_dnw' - | 'point_fee' - | 'point_refr' - | 'bonus_offset'; -} - -export interface GetFuturesPositionsReq { - settle: 'btc' | 'usdt' | 'usd'; - holding?: boolean; - limit?: number; - offset?: number; -} - -export interface UpdateDualModePositionMarginReq { - settle: 'btc' | 'usdt' | 'usd'; - contract: string; - change: string; - dual_side: 'dual_long' | 'dual_short'; -} - -export interface UpdateDualModePositionLeverageReq { - settle: 'btc' | 'usdt' | 'usd'; - contract: string; - leverage: string; - cross_leverage_limit?: string; -} - -export interface SubmitFuturesOrderReq { - settle: 'btc' | 'usdt' | 'usd'; - contract: string; - size: number; - iceberg?: number; - price?: string; - close?: boolean; - reduce_only?: boolean; - tif?: string; - text?: string; - auto_size?: string; - stp_act?: string; -} - -export interface GetFuturesOrdersReq { - settle: 'btc' | 'usdt' | 'usd'; - contract?: string; - status: string; - limit?: number; - offset?: number; - last_id?: string; -} - -export interface DeleteAllFuturesOrdersReq { - settle: 'btc' | 'usdt' | 'usd'; - contract: string; - side?: string; -} - -export interface GetFuturesOrdersByTimeRangeReq { - settle: 'btc' | 'usdt' | 'usd'; - contract?: string; - from?: number; - to?: number; - limit?: number; - offset?: number; -} - -export interface submitFuturesBatchOrdersReq extends FuturesOrder { - settle: 'btc' | 'usdt' | 'usd'; -} - -export interface GetFuturesTradingHistoryReq { - settle: 'btc' | 'usdt' | 'usd'; - contract?: string; - order?: number; - limit?: number; - offset?: number; - last_id?: string; -} - -export interface GetFuturesPositionHistoryReq { - settle: 'btc' | 'usdt' | 'usd'; - contract?: string; - limit?: number; - offset?: number; - from?: number; - to?: number; - side?: 'long' | 'short'; - pnl?: string; -} - -export interface GetFuturesLiquidationHistoryReq { - settle: 'btc' | 'usdt' | 'usd'; - contract?: string; - limit?: number; - at?: number; -} - -export interface SubmitFuturesPriceTriggeredOrderReq - extends FuturesPriceTriggeredOrder { - settle: 'btc' | 'usdt' | 'usd'; -} - -export interface GetFuturesAutoOrdersReq { - settle: 'btc' | 'usdt' | 'usd'; - status: 'open' | 'finished'; - contract?: string; - limit?: number; - offset?: number; -} - -/**========================================================================================================================== - * DELIVERY - * ========================================================================================================================== - */ - -export interface GetDeliveryOrderBookReq { - settle: 'usdt'; - contract: string; - interval?: '0' | '0.1' | '0.01'; - limit?: number; - with_id?: boolean; -} - -export interface GetDeliveryTradesReq { - settle: 'usdt'; - contract: string; - limit?: number; - last_id?: string; - from?: number; - to?: number; -} - -export interface GetDeliveryCandlesticksReq { - settle: 'usdt'; - contract: string; - from?: number; - to?: number; - limit?: number; - interval?: - | '10s' - | '30s' - | '1m' - | '5m' - | '15m' - | '30m' - | '1h' - | '2h' - | '4h' - | '6h' - | '8h' - | '12h' - | '1d' - | '7d' - | '1w' - | '30d'; -} - -export interface GetDeliveryBookReq { - settle: 'usdt'; - limit?: number; - from?: number; - to?: number; - type?: - | 'dnw' - | 'pnl' - | 'fee' - | 'refr' - | 'fund' - | 'point_dnw' - | 'point_fee' - | 'point_refr' - | 'bonus_offset'; -} - -export interface SubmitDeliveryFuturesOrderReq { - settle: 'usdt'; - contract: string; - size: number; - iceberg?: number; - price?: string; - close?: boolean; - reduce_only?: boolean; - tif?: string; - text?: string; - auto_size?: string; - stp_act?: string; -} - -export interface GetDeliveryOrdersReq { - settle: 'usdt'; - contract?: string; - status: 'open' | 'finished'; - limit?: number; - offset?: number; - last_id?: string; - count_total?: 0 | 1; -} - -export interface GetDeliveryTradingHistoryReq { - settle: 'usdt'; - contract?: string; - order?: number; - limit?: number; - offset?: number; - last_id?: string; - count_total?: 0 | 1; -} - -export interface GetDeliveryClosedPositionsReq { - settle: 'usdt'; - contract?: string; - limit?: number; -} - -export interface GetDeliveryLiquidationHistoryReq { - settle: 'usdt'; - contract?: string; - limit?: number; - at?: number; -} - -export interface GetDeliverySettlementHistoryReq { - settle: 'usdt'; - contract?: string; - limit?: number; - at?: number; -} - -export interface submitDeliveryTriggeredOrderReq - extends FuturesPriceTriggeredOrder { - settle: 'usdt'; -} - -export interface GetDeliveryAutoOrdersReq { - settle: 'usdt'; - status: 'open' | 'finished'; - contract?: string; - limit?: number; - offset?: number; -} - -/**========================================================================================================================== - * 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 GetOptionsCandlesticksReq { - contract: string; - limit?: number; - from?: number; - to?: number; - interval?: '1m' | '5m' | '15m' | '30m' | '1h'; -} - -export interface GetOptionsUnderlyingCandlesticksReq { - underlying: string; - limit?: number; - from?: number; - to?: number; - interval?: '1m' | '5m' | '15m' | '30m' | '1h'; -} - -export interface GetOptionsTradesReq { - contract?: string; - type?: 'C' | 'P'; - limit?: number; - offset?: number; - from?: number; - to?: number; -} - -export interface GetOptionsAccountChangeReq { - limit?: number; - offset?: number; - from?: number; - to?: number; - type?: 'dnw' | 'prem' | 'fee' | 'refr' | 'set'; -} - -export interface SubmitOptionsOrderReq { - contract: string; - size: number; - iceberg?: number; - price?: string; - close?: boolean; - reduce_only?: boolean; - tif?: 'gtc' | 'ioc' | 'poc'; - text?: string; -} - -export interface GetOptionsOrdersReq { - contract?: string; - underlying?: string; - status: 'open' | 'finished'; - limit?: number; - offset?: number; - from?: number; - to?: number; -} - -export interface GetOptionsPersonalHistoryReq { - underlying: string; - contract?: string; - limit?: number; - offset?: number; - from?: number; - to?: number; -} - -/**========================================================================================================================== - * EARN UNI - * ========================================================================================================================== - */ - -export interface SubmitLendOrRedeemReq { - currency: string; - amount: string; - type: 'lend' | 'redeem'; - min_rate?: string; -} - -export interface GetLendingOrdersReq { - currency?: string; - page?: number; - limit?: number; -} - -export interface GetLendingRecordsReq { - currency?: string; - page?: number; - limit?: number; - from?: number; - to?: number; - type?: 'lend' | 'redeem'; -} - -export interface GetLendingInterestRecordsReq { - currency?: string; - page?: number; - limit?: number; - from?: number; - to?: number; -} - -/**========================================================================================================================== - * COLLATERAL LOAN - * ========================================================================================================================== - */ - -export interface SubmitLoanOrderReq { - collateral_amount: string; - collateral_currency: string; - borrow_amount: string; - borrow_currency: string; -} - -export interface GetLoanOrdersReq { - page?: number; - limit?: number; - collateral_currency?: string; - borrow_currency?: string; -} - -export interface GetLoanRepaymentHistoryReq { - source: 'repay' | 'liquidate'; - borrow_currency?: string; - collateral_currency?: string; - page?: number; - limit?: number; - from?: number; - to?: number; -} - -export interface UpdateLoanCollateralReq { - order_id: number; - collateral_currency: string; - collateral_amount: string; - type: 'append' | 'redeem'; -} - -export interface GetLoanCollateralRecordsReq { - page?: number; - limit?: number; - from?: number; - to?: number; - borrow_currency?: string; - collateral_currency?: string; -} - -/**========================================================================================================================== - * MULTI COLLATERAL LOAN - * ========================================================================================================================== - */ - -export interface SubmitMultiLoanOrderReq { - order_id?: string; - order_type?: string; - fixed_type?: string; - fixed_rate?: string; - auto_renew?: boolean; - auto_repay?: boolean; - borrow_currency: string; - borrow_amount: string; - collateral_currencies?: { - currency?: string; - amount?: string; - }[]; -} -export interface GetMultiLoanOrdersReq { - page?: number; - limit?: number; - sort?: string; - order_type?: string; -} - -export interface RepayMultiLoanReq { - order_id: number; - repay_items: { - currency?: string; - amount?: string; - repaid_all?: boolean; - }[]; -} - -export interface GetMultiLoanRepayRecordsReq { - type: 'repay' | 'liquidate'; - borrow_currency?: string; - page?: number; - limit?: number; - from?: number; - to?: number; -} - -export interface UpdateMultiLoanReq { - order_id: number; - type: 'append' | 'redeem'; - collaterals?: { - currency?: string; - amount?: string; - }[]; -} - -export interface GetMultiLoanAdjustmentRecordsReq { - page?: number; - limit?: number; - from?: number; - to?: number; - collateral_currency?: string; -} - -/**========================================================================================================================== - * EARN - * ========================================================================================================================== - */ - -export interface GetStructuredProductListReq { - status: string; - type?: string; - page?: number; - limit?: number; -} - -export interface GetStructuredProductOrdersReq { - from?: number; - to?: number; - page?: number; - limit?: number; -} - -/**========================================================================================================================== - * ACCOUNT - * ========================================================================================================================== - */ - -export interface CreateStpGroupReq { - name: string; - id?: number; - creator_id?: number; - create_time?: number; -} diff --git a/src/types/requests/spot.ts b/src/types/requests/spot.ts index e69de29..29ad303 100644 --- a/src/types/requests/spot.ts +++ b/src/types/requests/spot.ts @@ -0,0 +1,127 @@ +/**========================================================================================================================== + * SPOT + * ========================================================================================================================== + */ + +export interface GetSpotOrderBookReq { + currency_pair: string; + interval?: string; + limit?: number; + with_id?: boolean; +} + +export interface GetSpotTradesReq { + currency_pair: string; + limit?: number; + last_id?: string; + reverse?: boolean; + from?: number; + to?: number; + page?: number; +} + +export interface GetSpotCandlesticksReq { + currency_pair: string; + limit?: number; + from?: number; + to?: number; + interval?: + | '10s' + | '1m' + | '5m' + | '15m' + | '30m' + | '1h' + | '4h' + | '8h' + | '1d' + | '7d' + | '30d'; +} + +export interface GetSpotAccountBookReq { + currency?: string; + from?: number; + to?: number; + page?: number; + limit?: number; + type?: string; +} + +export interface SubmitSpotClosePosCrossDisabledReq { + text?: string; + currency_pair: string; + amount: string; + price: string; + action_mode?: 'ACK' | 'RESULT' | 'FULL'; +} + +export interface GetSpotOrdersReq { + currency_pair: string; + status: 'open' | 'finished'; + page?: number; + limit?: number; + account?: 'spot' | 'margin' | 'cross_margin' | 'unified'; + from?: number; + to?: number; + side?: 'buy' | 'sell'; +} + +export interface DeleteSpotOrderReq { + order_id: string; + currency_pair: string; + account?: 'spot' | 'margin' | 'cross_margin' | 'unified'; + action_mode?: 'ACK' | 'RESULT' | 'FULL'; +} + +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 UpdateSpotBatchOrdersReq { + order_id?: string; + currency_pair?: string; + amount?: string; + price?: string; + amend_text?: string; +} + +export interface GetSpotAutoOrdersReq { + status: 'open' | 'finished'; + market?: string; + account?: 'normal' | 'margin' | 'cross_margin'; + limit?: number; + offset?: number; +} + +export interface SubmitSpotOrderReq { + 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; +} + +export interface UpdateSpotOrderReq { + order_id: string; + currency_pair: string; + account?: 'spot' | 'margin' | 'cross_margin' | 'unified'; + amount?: string; + price?: string; + amend_text?: string; + action_mode?: 'ACK' | 'RESULT' | 'FULL'; +} diff --git a/src/types/requests/subaccount.ts b/src/types/requests/subaccount.ts index e69de29..8f3c00a 100644 --- a/src/types/requests/subaccount.ts +++ b/src/types/requests/subaccount.ts @@ -0,0 +1,30 @@ +export interface CreateSubAccountReq { + login_name: string; + remark?: string; + password?: string; + email?: string; +} + +export interface CreateSubAccountApiKeyReq { + user_id: number; + mode?: number; // Mode: 1 - classic, 2 - portfolio account + name?: string; // API key name + perms?: { + name?: + | 'wallet' + | 'spot' + | 'futures' + | 'delivery' + | 'earn' + | 'options' + | 'account' + | 'unified' + | 'loan'; // Permission name + read_only?: boolean; // Read only + }[]; + ip_whitelist?: string[]; // IP white list +} + +export interface UpdateSubAccountApiKeyReq extends CreateSubAccountApiKeyReq { + key: string; +} diff --git a/src/types/requests/unified.ts b/src/types/requests/unified.ts index e69de29..7bbcf9a 100644 --- a/src/types/requests/unified.ts +++ b/src/types/requests/unified.ts @@ -0,0 +1,68 @@ +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; + type?: 'platform' | 'margin'; +} + +export interface SetUnifiedAccountModeReq { + mode: 'classic' | 'multi_currency' | 'portfolio'; + settings?: { + usdt_futures?: boolean; + spot_hedge?: 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; +} diff --git a/src/types/requests/wallet.ts b/src/types/requests/wallet.ts index e69de29..e969236 100644 --- a/src/types/requests/wallet.ts +++ b/src/types/requests/wallet.ts @@ -0,0 +1,56 @@ +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; +} + +export interface GetMainSubTransfersReq { + sub_uid?: string; + from?: number; + to?: number; + limit?: number; + offset?: number; +} + +export interface GetSavedAddressReq { + currency: string; + chain?: string; + limit?: string; + page?: number; +} + +export interface GetSmallBalanceHistoryReq { + currency?: string; + page?: number; + limit?: number; +} + +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'; +} diff --git a/src/types/requests/withdrawal.ts b/src/types/requests/withdrawal.ts index e69de29..ffbc1ca 100644 --- a/src/types/requests/withdrawal.ts +++ b/src/types/requests/withdrawal.ts @@ -0,0 +1,13 @@ +/**================================================================================================================================ + * WITHDRAW + * ========================================================================================================================== + */ + +export interface SubmitWithdrawReq { + amount: string; + currency: string; + chain: string; + withdraw_order_id?: string; + address?: string; + memo?: string; +} From 5d9a3e6c2b06aa23ee88f1df7f2083d12fce0d61 Mon Sep 17 00:00:00 2001 From: Jerko J <83344666+JJ-Cro@users.noreply.github.com> Date: Fri, 24 May 2024 14:52:15 +0200 Subject: [PATCH 33/36] chore(): Fixed imports for types --- src/RestClient.ts | 80 +++++++++++++++++++++++------------------------ 1 file changed, 40 insertions(+), 40 deletions(-) diff --git a/src/RestClient.ts b/src/RestClient.ts index 0e241ef..b3a865d 100644 --- a/src/RestClient.ts +++ b/src/RestClient.ts @@ -1,12 +1,19 @@ import { AxiosRequestConfig } from 'axios'; -import { CreateStpGroupReq } from 'types/requests/account.js'; + +import { + BaseRestClient, + REST_CLIENT_TYPE_ENUM, + RestClientType, +} from './lib/BaseRestClient.js'; +import { RestClientOptions } from './lib/requestUtils.js'; +import { CreateStpGroupReq } from './types/requests/account.js'; import { GetLoanCollateralRecordsReq, GetLoanOrdersReq, GetLoanRepaymentHistoryReq, SubmitLoanOrderReq, UpdateLoanCollateralReq, -} from 'types/requests/collateralLoan.js'; +} from './types/requests/collateralLoan.js'; import { GetDeliveryAutoOrdersReq, GetDeliveryBookReq, @@ -20,22 +27,22 @@ import { GetDeliveryTradingHistoryReq, SubmitDeliveryFuturesOrderReq, submitDeliveryTriggeredOrderReq, -} from 'types/requests/delivery.js'; +} from './types/requests/delivery.js'; import { GetStructuredProductListReq, GetStructuredProductOrdersReq, -} from 'types/requests/earn.js'; +} from './types/requests/earn.js'; import { GetLendingInterestRecordsReq, GetLendingOrdersReq, GetLendingRecordsReq, SubmitLendOrRedeemReq, -} from 'types/requests/earnuni.js'; +} from './types/requests/earnuni.js'; import { GetFlashSwapOrdersReq, SubmitFlashSwapOrderPreviewReq, SubmitFlashSwapOrderReq, -} from 'types/requests/flashswap.js'; +} from './types/requests/flashswap.js'; import { DeleteAllFuturesOrdersReq, GetFuturesAccountBookReq, @@ -57,7 +64,7 @@ import { SubmitFuturesPriceTriggeredOrderReq, UpdateDualModePositionLeverageReq, UpdateDualModePositionMarginReq, -} from 'types/requests/futures.js'; +} from './types/requests/futures.js'; import { GetCrossMarginAccountHistoryReq, GetCrossMarginBorrowHistoryReq, @@ -65,13 +72,13 @@ import { GetCrossMarginRepaymentsReq, GetMarginBalanceHistoryReq, SubmitCrossMarginBorrowLoanReq, -} from 'types/requests/margin.js'; +} from './types/requests/margin.js'; import { GetMarginUNIInterestRecordsReq, GetMarginUNILoanRecordsReq, GetMarginUNILoansReq, GetMarginUNIMaxBorrowReq, -} from 'types/requests/marginuni.js'; +} from './types/requests/marginuni.js'; import { GetMultiLoanAdjustmentRecordsReq, GetMultiLoanOrdersReq, @@ -79,7 +86,7 @@ import { RepayMultiLoanReq, SubmitMultiLoanOrderReq, UpdateMultiLoanReq, -} from 'types/requests/multicollateralLoan.js'; +} from './types/requests/multicollateralLoan.js'; import { GetOptionsAccountChangeReq, GetOptionsCandlesticksReq, @@ -91,13 +98,13 @@ import { GetOptionsTradesReq, GetOptionsUnderlyingCandlesticksReq, SubmitOptionsOrderReq, -} from 'types/requests/options.js'; +} from './types/requests/options.js'; import { GetAgencyCommissionHistoryReq, GetAgencyTransactionHistoryReq, GetBrokerCommissionHistoryReq, GetBrokerTransactionHistoryReq, -} from 'types/requests/rebate.js'; +} from './types/requests/rebate.js'; import { DeleteSpotOrderReq, GetSpotAccountBookReq, @@ -111,12 +118,12 @@ import { SubmitSpotOrderReq, UpdateSpotBatchOrdersReq, UpdateSpotOrderReq, -} from 'types/requests/spot.js'; +} from './types/requests/spot.js'; import { CreateSubAccountApiKeyReq, CreateSubAccountReq, UpdateSubAccountApiKeyReq, -} from 'types/requests/subaccount.js'; +} from './types/requests/subaccount.js'; import { GetUnifiedInterestRecordsReq, GetUnifiedLoanRecordsReq, @@ -124,7 +131,7 @@ import { PortfolioMarginCalculatorReq, SetUnifiedAccountModeReq, SubmitUnifiedBorrowOrRepayReq, -} from 'types/requests/unified.js'; +} from './types/requests/unified.js'; import { GetMainSubTransfersReq, GetSavedAddressReq, @@ -133,19 +140,19 @@ import { SubmitMainSubTransferReq, SubmitSubToSubTransferReq, SubmitTransferReq, -} from 'types/requests/wallet.js'; -import { SubmitWithdrawReq } from 'types/requests/withdrawal.js'; +} from './types/requests/wallet.js'; +import { SubmitWithdrawReq } from './types/requests/withdrawal.js'; import { CreateStpGroupResp, GetAccountDetailResp, StpResp, -} from 'types/response/account.js'; +} from './types/response/account.js'; import { GetLoanCollateralizationRatioResp, GetLoanCollateralRecordsResp, GetLoanOrdersResp, GetLoanRepaymentHistoryResp, -} from 'types/response/collateralloan.js'; +} from './types/response/collateralloan.js'; import { GetDeliveryAccountResp, GetDeliveryBookResp, @@ -157,24 +164,24 @@ import { GetDeliveryTickersResp, GetDeliveryTradesResp, GetDeliveryTradingHistoryResp, -} from 'types/response/delivery.js'; +} from './types/response/delivery.js'; import { GetDualInvestmentOrdersResp, GetDualInvestmentProductsResp, GetStructuredProductListResp, GetStructuredProductOrdersResp, -} from 'types/response/earn.js'; +} from './types/response/earn.js'; import { GetLendingCurrenciesResp, GetLendingInterestRecordsResp, GetLendingOrdersResp, GetLendingRecordsResp, -} from 'types/response/earnuni.js'; +} from './types/response/earnuni.js'; import { FlashSwapOrderResp, GetFlashSwapCurrencyPairsResp, SubmitFlashSwapOrderPreviewResp, -} from 'types/response/flashswap.js'; +} from './types/response/flashswap.js'; import { DeleteFuturesBatchOrdersResp, GetFuturesAccountResp, @@ -192,7 +199,7 @@ import { GetPremiumIndexKLineResp, GetRiskLimitTiersResp, ToggleFuturesDualModeResp, -} from 'types/response/futures.js'; +} from './types/response/futures.js'; import { GetCrossMarginAccountHistoryResp, GetCrossMarginAccountResp, @@ -200,14 +207,14 @@ import { GetMarginAccountsResp, GetMarginBalanceHistoryResp, SubmitCrossMarginBorrowLoanResp, -} from 'types/response/margin.js'; +} from './types/response/margin.js'; import { GetLendingMarketsResp, GetMarginUNIInterestRecordsResp, GetMarginUNILoanRecordsResp, GetMarginUNILoansResp, GetMarginUNIMaxBorrowResp, -} from 'types/response/marginuni.js'; +} from './types/response/marginuni.js'; import { GetMultiLoanAdjustmentRecordsResp, GetMultiLoanCurrencyQuotaResp, @@ -218,7 +225,7 @@ import { GetMultiLoanSupportedCurrenciesResp, RepayMultiLoanResp, UpdateMultiLoanResp, -} from 'types/response/multicollateralLoan.js'; +} from './types/response/multicollateralLoan.js'; import { GetOptionsAccountChangeResp, GetOptionsAccountResp, @@ -234,13 +241,13 @@ import { GetOptionsTradesResp, GetOptionsUnderlyingCandlesticksResp, SubmitOptionsOrderResp, -} from 'types/response/options.js'; +} from './types/response/options.js'; import { GetAgencyCommissionHistoryResp, GetAgencyTransactionHistoryResp, GetBrokerCommissionHistoryResp, GetBrokerTransactionHistoryResp, -} from 'types/response/rebate.js'; +} from './types/response/rebate.js'; import { DeleteSpotBatchOrdersResp, GetSpotAccountBookResp, @@ -255,11 +262,11 @@ import { GetSpotTradesResp, GetSpotTradingHistoryResp, SubmitSpotBatchOrdersResp, -} from 'types/response/spot.js'; +} from './types/response/spot.js'; import { CreateSubAccountApiKeyResp, SubAccountResp, -} from 'types/response/subaccount.js'; +} from './types/response/subaccount.js'; import { GetUnifiedAccountInfoResp, GetUnifiedCurrencyDiscountTiersResp, @@ -268,7 +275,7 @@ import { GetUnifiedLoansResp, GetUnifiedRiskUnitDetailsResp, PortfolioMarginCalculatorResp, -} from 'types/response/unified.js'; +} from './types/response/unified.js'; import { APIResponse, CreateDepositAddressResp, @@ -283,14 +290,7 @@ import { SubAccountFuturesBalancesResp, SubAccountMarginBalancesResp, SubAccountTransferRecordResp, -} from 'types/response/wallet.js'; - -import { - BaseRestClient, - REST_CLIENT_TYPE_ENUM, - RestClientType, -} from './lib/BaseRestClient.js'; -import { RestClientOptions } from './lib/requestUtils.js'; +} from './types/response/wallet.js'; import { CancelBatchOrder, Contract, From 13b829f7346d0b2c14419ea2d49c278fe3fa4f18 Mon Sep 17 00:00:00 2001 From: Tiago Siebler Date: Thu, 30 May 2024 12:42:57 +0100 Subject: [PATCH 34/36] feat(): prep work for gate WS client --- README.md | 36 ++- src/WebsocketClient.ts | 331 +++++++++++----------------- src/lib/BaseWSClient.ts | 229 ++++++++----------- src/lib/requestUtils.ts | 2 +- src/lib/websocket/WsStore.ts | 8 +- src/lib/websocket/websocket-util.ts | 100 +++++++-- src/types/websockets/client.ts | 5 +- src/types/websockets/requests.ts | 27 ++- 8 files changed, 367 insertions(+), 371 deletions(-) diff --git a/README.md b/README.md index 49950f2..b22ee9d 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,5 @@ # gateio-api + [![Tests](https://circleci.com/gh/tiagosiebler/gateio-api.svg?style=shield)](https://circleci.com/gh/tiagosiebler/gateio-api) [![npm version](https://img.shields.io/npm/v/gateio-api)][1] [![npm size](https://img.shields.io/bundlephobia/min/gateio-api/latest)][1] [![npm downloads](https://img.shields.io/npm/dt/gateio-api)][1] [![last commit](https://img.shields.io/github/last-commit/tiagosiebler/gateio-api)][1] @@ -11,14 +12,18 @@ WARNING: This package is still early beta, following the designs of my other con Node.js connector for the gateio APIs and WebSockets, with TypeScript & browser support. ## Installation + `npm install --save gateio-api` ## Issues & Discussion + - Issues? Check the [issues tab](https://github.com/tiagosiebler/gateio-api/issues). - Discuss & collaborate with other node devs? Join our [Node.js Algo Traders](https://t.me/nodetraders) engineering community on telegram. ## Related projects + Check out my related projects: + - Try my connectors: - [binance](https://www.npmjs.com/package/binance) - [bybit-api](https://www.npmjs.com/package/bybit-api) @@ -31,11 +36,15 @@ Check out my related projects: - [awesome-crypto-examples](https://github.com/tiagosiebler/awesome-crypto-examples) ## Documentation + Most methods accept JS objects. These can be populated using parameters specified by gateio's API documentation. + - [Gate.io API Documentation](https://www.gate.io/docs/developers/apiv4/en/). ## Structure + This project uses typescript. Resources are stored in 3 key structures: + - [src](./src) - the whole connector written in typescript - [lib](./lib) - the javascript version of the project (compiled from typescript). This should not be edited directly, as it will be overwritten with each release. - [dist](./dist) - the packed bundle of the project for use in browser environments. @@ -44,6 +53,7 @@ This project uses typescript. Resources are stored in 3 key structures: --- # Usage + @@ -111,7 +121,10 @@ client.getOrderBook({ symbol: 'BTCUSD' }) See [inverse-client.ts](./src/inverse-client.ts) for further information. --> ## WebSockets -Inverse, linear & spot WebSockets can be used via a shared `WebsocketClient`. However, make sure to make one instance of WebsocketClient per market type (spot vs inverse vs linear vs linearfutures): + +All available WebSockets can be used via a shared `WebsocketClient`. The WebSocket client will automatically open/track/manage connections as needed. Each unique connection (one per server URL) is tracked using a WsKey (each WsKey is a string - [WS_KEY_MAP](src/lib/websocket/websocket-util.ts). + +Any subscribe/unsubscribe events will need to include a WsKey, so the WebSocket client understands which connection the event should be routed to. See examples below or in the [examples](./examples/) folder on GitHub. ```javascript const { WebsocketClient } = require('gateio-api'); @@ -165,7 +178,7 @@ ws.subscribe(['position', 'execution', 'trade']); ws.subscribe('kline.BTCUSD.1m'); // Listen to events coming from websockets. This is the primary data source -ws.on('update', data => { +ws.on('update', (data) => { console.log('update', data); }); @@ -175,7 +188,7 @@ ws.on('open', ({ wsKey, event }) => { }); // Optional: Listen to responses to websocket queries (e.g. the response after subscribing to a topic) -ws.on('response', response => { +ws.on('response', (response) => { console.log('response', response); }); @@ -186,12 +199,11 @@ ws.on('close', () => { // Optional: Listen to raw error events. // Note: responses to invalid topics are currently only sent in the "response" event. -ws.on('error', err => { +ws.on('error', (err) => { console.error('ERR', err); }); ``` - See [websocket-client.ts](./src/websocket-client.ts) for further information. Note: for linear websockets, pass `linear: true` in the constructor options when instancing the `WebsocketClient`. To connect to both linear and inverse websockets, make two instances of the WebsocketClient. @@ -199,6 +211,7 @@ Note: for linear websockets, pass `linear: true` in the constructor options when --- ## Customise Logging + Pass a custom logger which supports the log methods `silly`, `debug`, `notice`, `info`, `warning` and `error`, or override methods from the default logger as desired. ```javascript @@ -207,14 +220,13 @@ const { WebsocketClient, DefaultLogger } = require('gateio-api'); // Disable all logging on the silly level DefaultLogger.silly = () => {}; -const ws = new WebsocketClient( - { key: 'xxx', secret: 'yyy' }, - DefaultLogger -); +const ws = new WebsocketClient({ key: 'xxx', secret: 'yyy' }, DefaultLogger); ``` ## Browser Usage + Build a bundle using webpack: + - `npm install` - `npm build` - `npm pack` @@ -224,17 +236,23 @@ The bundle can be found in `dist/`. Altough usage should be largely consistent, --- ## Contributions & Thanks + ### Donations + #### tiagosiebler + Support my efforts to make algo trading accessible to all - register with my referral links: + - [Bybit](https://www.bybit.com/en-US/register?affiliate_id=9410&language=en-US&group_id=0&group_type=1) - [Binance](https://www.binance.com/en/register?ref=20983262) - [OKX](https://www.okx.com/join/18504944) - [FTX](https://ftx.com/referrals#a=ftxapigithub) Or buy me a coffee using any of these: + - BTC: `1C6GWZL1XW3jrjpPTS863XtZiXL1aTK7Jk` - ETH (ERC20): `0xd773d8e6a50758e1ada699bb6c4f98bb4abf82da` ### Contributions & Pull Requests + Contributions are encouraged, I will review any incoming pull requests. See the issues tab for todo items. diff --git a/src/WebsocketClient.ts b/src/WebsocketClient.ts index 14fb187..874bc22 100644 --- a/src/WebsocketClient.ts +++ b/src/WebsocketClient.ts @@ -8,48 +8,76 @@ import { WS_BASE_URL_MAP, WS_KEY_MAP, WsKey, + WsMarket, + WsTopicRequest, } from './lib/websocket/websocket-util.js'; -import { WsMarket } from './types/websockets/client.js'; import { WsOperation, - WsRequestOperation, + WsRequestOperationGate, } from './types/websockets/requests.js'; -export const WS_LOGGER_CATEGORY = { category: 'woo-ws' }; +export const WS_LOGGER_CATEGORY = { category: 'gate-ws' }; /** Any WS keys in this list will trigger auth on connect, if credentials are available */ -const PRIVATE_WS_KEYS: WsKey[] = [WS_KEY_MAP.privateV1]; +const PRIVATE_WS_KEYS: WsKey[] = []; /** Any WS keys in this list will ALWAYS skip the authentication process, even if credentials are available */ -export const PUBLIC_WS_KEYS: WsKey[] = [WS_KEY_MAP.publicV1]; +export const PUBLIC_WS_KEYS: WsKey[] = []; /** - * WS topics are always a string for woo. Some exchanges use complex objects + * WS topics are always a string for gate. Some exchanges use complex objects */ -export type WsTopic = - | 'balance' - | 'executionreport' - | 'algoexecutionreportv2' - | 'position' - | 'marginassignment'; - -export class WebsocketClient extends BaseWebsocketClient< - WsMarket, - WsKey, - WsTopic -> { +export type WsTopic = string; + +// /** +// * Used to split sub/unsub logic by websocket connection. Groups & dedupes requests into per-WsKey arrays +// */ +// function arrangeTopicsIntoWsKeyGroups( +// requestOperations: WsRequest[], +// ): Record[]> { +// const topicsByWsKey: Record[]> = { +// [WS_KEY_MAP.spotV4]: [], +// [WS_KEY_MAP.perpFuturesUSDTV4]: [], +// [WS_KEY_MAP.perpFuturesBTCV4]: [], +// [WS_KEY_MAP.deliveryFuturesUSDTV4]: [], +// [WS_KEY_MAP.deliveryFuturesBTCV4]: [], +// [WS_KEY_MAP.optionsV4]: [], +// [WS_KEY_MAP.announcementsV4]: [], +// }; + +// for (const request of requestOperations) { +// const wsKeyForTopic = request.wsKey; + +// const requestsForWsKey = topicsByWsKey[wsKeyForTopic]; + +// const requestAlreadyInList = requestsForWsKey.find((p) => +// isDeepObjectMatch(p, request), +// ); +// if (!requestAlreadyInList) { +// requestsForWsKey.push(request); +// } +// } + +// return topicsByWsKey; +// } + +export class WebsocketClient extends BaseWebsocketClient { /** * Request connection of all dependent (public & private) websockets, instead of waiting for automatic connection by library */ public connectAll(): Promise[] { return [ - this.connect(WS_KEY_MAP.publicV1), - this.connect(WS_KEY_MAP.privateV1), + this.connect(WS_KEY_MAP.spotV4), + this.connect(WS_KEY_MAP.perpFuturesUSDTV4), + this.connect(WS_KEY_MAP.deliveryFuturesUSDTV4), + this.connect(WS_KEY_MAP.optionsV4), + this.connect(WS_KEY_MAP.announcementsV4), ]; } /** - * Request subscription to one or more topics. + * Request subscription to one or more topics. Pass topics as either an array of strings, or array of objects (if the topic has parameters). + * Objects should be formatted as {topic: string, params: object}. * * - Subscriptions are automatically routed to the correct websocket connection. * - Authentication/connection is automatic. @@ -57,35 +85,27 @@ export class WebsocketClient extends BaseWebsocketClient< * * Call `unsubscribe(topics)` to remove topics */ - public subscribe(topics: WsTopic[]) { - const topicsByWsKey = this.arrangeTopicsIntoWsKeyGroups(topics); - - for (const untypedWsKey in topicsByWsKey) { - const typedWsKey = untypedWsKey as WsKey; - const topics = topicsByWsKey[typedWsKey]; - - if (topics.length) { - this.subscribeTopicsForWsKey(topics, typedWsKey); - } + public subscribe( + requests: (WsTopicRequest | WsTopic)[], + wsKey: WsKey, + ) { + if (requests.length) { + this.subscribeTopicsForWsKey(requests, wsKey); } } /** - * Unsubscribe from one or more topics. + * Unsubscribe from one or more topics. Similar to subscribe() but in reverse. * * - Requests are automatically routed to the correct websocket connection. * - These topics will be removed from the topic cache, so they won't be subscribed to again. */ - public unsubscribe(topics: WsTopic[]) { - const topicsByWsKey = this.arrangeTopicsIntoWsKeyGroups(topics); - - for (const untypedWsKey in topicsByWsKey) { - const typedWsKey = untypedWsKey as WsKey; - const topics = topicsByWsKey[typedWsKey]; - - if (topics.length) { - this.unsubscribeTopicsForWsKey(topics, typedWsKey); - } + public unsubscribe( + requests: (WsTopicRequest | WsTopic)[], + wsKey: WsKey, + ) { + if (requests.length) { + this.unsubscribeTopicsForWsKey(requests, wsKey); } } @@ -96,27 +116,11 @@ export class WebsocketClient extends BaseWebsocketClient< */ protected sendPingEvent(wsKey: WsKey) { - switch (wsKey) { - case WS_KEY_MAP.publicV1: - case WS_KEY_MAP.privateV1: { - return this.tryWsSend(wsKey, '{"event":"ping"}'); - } - default: { - throw neverGuard(wsKey, `Unhandled ping format: "${wsKey}"`); - } - } + return this.tryWsSend(wsKey, '{"event":"ping"}'); } protected sendPongEvent(wsKey: WsKey) { - switch (wsKey) { - case WS_KEY_MAP.publicV1: - case WS_KEY_MAP.privateV1: { - return this.tryWsSend(wsKey, '{"event":"pong"}'); - } - default: { - throw neverGuard(wsKey, `Unhandled ping format: "${wsKey}"`); - } - } + return this.tryWsSend(wsKey, '{"event":"pong"}'); } protected isWsPing(msg: any): boolean { @@ -139,6 +143,9 @@ export class WebsocketClient extends BaseWebsocketClient< return false; } + /** + * Parse incoming events into categories + */ protected resolveEmittableEvents(event: MessageEventLike): EmittableEvent[] { const results: EmittableEvent[] = []; @@ -217,14 +224,20 @@ export class WebsocketClient extends BaseWebsocketClient< /** * Determines if a topic is for a private channel, using a hardcoded list of strings */ - protected isPrivateChannel(topic: WsTopic): boolean { - const topicName = topic.toLowerCase(); + protected isPrivateTopicRequest(request: WsTopicRequest): boolean { + const topicName = request?.topic?.toLowerCase(); + if (!topicName) { + return false; + } + const privateTopics = [ - 'balance', - 'executionreport', - 'algoexecutionreportv2', - 'position', - 'marginassignment', + 'todo', + 'todo', + 'todo', + 'todo', + 'todo', + 'todo', + 'todo', ]; if (topicName && privateTopics.includes(topicName)) { @@ -234,29 +247,22 @@ export class WebsocketClient extends BaseWebsocketClient< return false; } - protected getWsKeyForMarket(_market: WsMarket, isPrivate: boolean): WsKey { - return isPrivate ? WS_KEY_MAP.privateV1 : WS_KEY_MAP.publicV1; - } - - protected getWsMarketForWsKey(key: WsKey): WsMarket { - switch (key) { - case 'publicV1': - case 'privateV1': { - return 'all'; - } - default: { - throw neverGuard(key, `Unhandled ws key "${key}"`); - } - } + /** + * Not in use for gate.io + */ + // eslint-disable-next-line @typescript-eslint/no-unused-vars + protected getWsKeyForTopic(_topic: WsTopic): WsKey { + return 'announcementsV4'; } - protected getWsKeyForTopic(topic: WsTopic): WsKey { - const market = this.getMarketForTopic(topic); - const isPrivateTopic = this.isPrivateChannel(topic); - - return this.getWsKeyForMarket(market, isPrivateTopic); + // eslint-disable-next-line @typescript-eslint/no-unused-vars + protected getWsMarketForWsKey(_wsKey: WsKey): WsMarket { + return 'all'; } + /** + * Not in use for gate.io + */ protected getPrivateWSKeys(): WsKey[] { return PRIVATE_WS_KEYS; } @@ -266,36 +272,24 @@ export class WebsocketClient extends BaseWebsocketClient< return this.options.wsUrl; } - const applicationId = this.options.apiApplicationId; - const networkKey = 'livenet'; + const useTestnet = this.options.useTestnet; + const networkKey = useTestnet ? 'testnet' : 'livenet'; - switch (wsKey) { - case WS_KEY_MAP.publicV1: { - return WS_BASE_URL_MAP.publicV1.all[networkKey] + '/' + applicationId; - } - case WS_KEY_MAP.privateV1: { - return WS_BASE_URL_MAP.privateV1.all[networkKey] + '/' + applicationId; - } - default: { - this.logger.error('getWsUrl(): Unhandled wsKey: ', { - ...WS_LOGGER_CATEGORY, - wsKey, - }); - throw neverGuard(wsKey, `getWsUrl(): Unhandled wsKey`); - } - } + const baseUrl = WS_BASE_URL_MAP[wsKey][networkKey]; + return baseUrl; } /** Force subscription requests to be sent in smaller batches, if a number is returned */ protected getMaxTopicsPerSubscribeEvent(wsKey: WsKey): number | null { switch (wsKey) { - case 'publicV1': - case 'privateV1': { - // Return a number if there's a limit on the number of sub topics per rq - return 1; - } + // case 'publicV1': + // case 'privateV1': { + // // Return a number if there's a limit on the number of sub topics per rq + // return 1; + // } default: { - throw neverGuard(wsKey, `getWsKeyForTopic(): Unhandled wsKey`); + return 1; + // throw neverGuard(wsKey, `getWsKeyForTopic(): Unhandled wsKey`); } } } @@ -303,9 +297,10 @@ export class WebsocketClient extends BaseWebsocketClient< /** * Map one or more topics into fully prepared "subscribe request" events (already stringified and ready to send) */ - protected getWsSubscribeEventsForTopics( - topics: WsTopic[], + protected getWsOperationEventsForTopics( + topics: WsTopicRequest[], wsKey: WsKey, + operation: WsOperation, ): string[] { // console.log(new Date(), `called getWsSubscribeEventsForTopics()`, topics); // console.trace(); @@ -313,59 +308,10 @@ export class WebsocketClient extends BaseWebsocketClient< return []; } - const market = this.getWsMarketForWsKey(wsKey); - - const subscribeEvents: string[] = []; - - const maxTopicsPerEvent = this.getMaxTopicsPerSubscribeEvent(wsKey); - if ( - maxTopicsPerEvent && - maxTopicsPerEvent !== null && - topics.length > maxTopicsPerEvent - ) { - for (let i = 0; i < topics.length; i += maxTopicsPerEvent) { - const batch = topics.slice(i, i + maxTopicsPerEvent); - const subscribeRequestEvents = this.getWsRequestEvent( - market, - 'subscribe', - batch, - ); - - for (const event of subscribeRequestEvents) { - subscribeEvents.push(JSON.stringify(event)); - } - } - - return subscribeEvents; - } - - const subscribeRequestEvents = this.getWsRequestEvent( - market, - 'subscribe', - topics, - ); - - for (const event of subscribeRequestEvents) { - subscribeEvents.push(JSON.stringify(event)); - } - return subscribeEvents; - } - - /** - * Map one or more topics into fully prepared "unsubscribe request" events (already stringified and ready to send) - */ - protected getWsUnsubscribeEventsForTopics( - topics: WsTopic[], - wsKey: WsKey, - ): string[] { - if (!topics.length) { - return []; - } + // Events that are ready to send (usually stringified JSON) + const jsonStringEvents: string[] = []; const market = this.getWsMarketForWsKey(wsKey); - - const subscribeEvents: string[] = []; - const maxTopicsPerEvent = this.getMaxTopicsPerSubscribeEvent(wsKey); if ( maxTopicsPerEvent && @@ -376,27 +322,28 @@ export class WebsocketClient extends BaseWebsocketClient< const batch = topics.slice(i, i + maxTopicsPerEvent); const subscribeRequestEvents = this.getWsRequestEvent( market, - 'unsubscribe', + operation, batch, ); for (const event of subscribeRequestEvents) { - subscribeEvents.push(JSON.stringify(event)); + jsonStringEvents.push(JSON.stringify(event)); } } - return subscribeEvents; + return jsonStringEvents; } const subscribeRequestEvents = this.getWsRequestEvent( market, - 'unsubscribe', + operation, topics, ); + for (const event of subscribeRequestEvents) { - subscribeEvents.push(JSON.stringify(event)); + jsonStringEvents.push(JSON.stringify(event)); } - return subscribeEvents; + return jsonStringEvents; } /** @@ -405,17 +352,23 @@ export class WebsocketClient extends BaseWebsocketClient< private getWsRequestEvent( market: WsMarket, operation: WsOperation, - topics: WsTopic[], - ): WsRequestOperation[] { + requests: WsTopicRequest[], + ): WsRequestOperationGate[] { + const timeInSeconds = +(Date.now() / 1000).toFixed(0); switch (market) { case 'all': { - return topics.map((topic) => { - const wsRequestEvent: WsRequestOperation = { - id: `${operation}_${topic}`, + return requests.map((request) => { + const wsRequestEvent: WsRequestOperationGate = { + time: timeInSeconds, + channel: request.topic, event: operation, - topic: topic, + // payload: 'todo', }; + if (request.params) { + wsRequestEvent.payload = request.params; + } + return wsRequestEvent; }); } @@ -427,11 +380,7 @@ export class WebsocketClient extends BaseWebsocketClient< protected async getWsAuthRequestEvent(wsKey: WsKey): Promise { const market = this.getWsMarketForWsKey(wsKey); - if ( - !this.options.apiKey || - !this.options.apiSecret || - !this.options.apiApplicationId - ) { + if (!this.options.apiKey || !this.options.apiSecret) { throw new Error( `Cannot auth - missing api key, secret or memo in config`, ); @@ -484,28 +433,4 @@ export class WebsocketClient extends BaseWebsocketClient< throw new Error(`Could not resolve "market" for topic: "${topic}"`); } - - /** - * Used to split sub/unsub logic by websocket connection - */ - private arrangeTopicsIntoWsKeyGroups( - topics: WsTopic[], - ): Record { - const topicsByWsKey: Record = { - privateV1: [], - publicV1: [], - }; - - for (const untypedTopic of topics) { - const topic = untypedTopic as WsTopic; - const wsKeyForTopic = this.getWsKeyForTopic(topic); - - const wsKeyTopicList = topicsByWsKey[wsKeyForTopic]; - if (!wsKeyTopicList.includes(topic)) { - wsKeyTopicList.push(topic); - } - } - - return topicsByWsKey; - } } diff --git a/src/lib/BaseWSClient.ts b/src/lib/BaseWSClient.ts index 8281bb2..27cad12 100644 --- a/src/lib/BaseWSClient.ts +++ b/src/lib/BaseWSClient.ts @@ -5,9 +5,14 @@ import { WebsocketClientOptions, WSClientConfigurableOptions, } from '../types/websockets/client.js'; +import { WsOperation } from '../types/websockets/requests.js'; import { WS_LOGGER_CATEGORY } from '../WebsocketClient.js'; import { DefaultLogger } from './logger.js'; import { isMessageEvent, MessageEventLike } from './requestUtils.js'; +import { + WsTopicRequest, + WsTopicRequestOrStringTopic, +} from './websocket/websocket-util.js'; import { WsStore } from './websocket/WsStore.js'; import { WsConnectionStateEnum } from './websocket/WsStore.types.js'; @@ -36,13 +41,7 @@ export interface EmittableEvent { } // Type safety for on and emit handlers: https://stackoverflow.com/a/61609010/880837 -export interface BaseWebsocketClient< - // eslint-disable-next-line @typescript-eslint/no-unused-vars - TWSMarket extends string, - TWSKey extends string, - // eslint-disable-next-line @typescript-eslint/no-unused-vars - TWSTopic = any, -> { +export interface BaseWebsocketClient { on>( event: U, listener: WSClientEventMap[U], @@ -54,16 +53,47 @@ export interface BaseWebsocketClient< ): boolean; } +/** + * Users can conveniently pass topics as strings or objects (object has topic name + optional params). + * + * This method normalises topics into objects (object has topic name + optional params). + */ +function getNormalisedTopicRequests( + wsTopicRequests: WsTopicRequestOrStringTopic[], +): WsTopicRequest[] { + const normalisedTopicRequests: WsTopicRequest[] = []; + + for (const wsTopicRequest of wsTopicRequests) { + // passed as string, convert to object + if (typeof wsTopicRequest === 'string') { + const topicRequest: WsTopicRequest = { + topic: wsTopicRequest, + params: undefined, + }; + normalisedTopicRequests.push(topicRequest); + continue; + } + + // already a normalised object, thanks to user + normalisedTopicRequests.push(wsTopicRequest); + } + return normalisedTopicRequests; +} + +/** + * Base WebSocket abstraction layer. Handles connections, tracking each connection as a unique "WS Key" + */ // eslint-disable-next-line @typescript-eslint/no-unsafe-declaration-merging export abstract class BaseWebsocketClient< - TWSMarket extends string, - TWSKey extends string, /** - * The "topic" being subscribed to, not the event sent to subscribe to one or more topics + * The WS connections supported by the client, each identified by a unique primary key */ - TWSTopic extends string | object, + TWSKey extends string, > extends EventEmitter { - private wsStore: WsStore; + /** + * State store to track a list of topics (topic requests) we are expected to be subscribed to if reconnected + */ + private wsStore: WsStore>; protected logger: typeof DefaultLogger; protected options: WebsocketClientOptions; @@ -86,11 +116,6 @@ export abstract class BaseWebsocketClient< }; } - protected abstract getWsKeyForMarket( - market: TWSMarket, - isPrivate?: boolean, - ): TWSKey; - protected abstract sendPingEvent(wsKey: TWSKey, ws: WebSocket): void; protected abstract sendPongEvent(wsKey: TWSKey, ws: WebSocket): void; @@ -99,30 +124,24 @@ export abstract class BaseWebsocketClient< protected abstract getWsAuthRequestEvent(wsKey: TWSKey): Promise; - protected abstract getWsMarketForWsKey(key: TWSKey): TWSMarket; - - protected abstract isPrivateChannel(subscribeEvent: TWSTopic): boolean; + protected abstract isPrivateTopicRequest( + request: WsTopicRequest, + ): boolean; protected abstract getPrivateWSKeys(): TWSKey[]; protected abstract getWsUrl(wsKey: TWSKey): string; + protected abstract getMaxTopicsPerSubscribeEvent( wsKey: TWSKey, ): number | null; /** - * Returns a list of string events that can be individually sent upstream to complete subscribing to these topics - */ - protected abstract getWsSubscribeEventsForTopics( - topics: TWSTopic[], - wsKey: TWSKey, - ): string[]; - - /** - * Returns a list of string events that can be individually sent upstream to complete unsubscribing to these topics + * Returns a list of string events that can be individually sent upstream to complete subscribing/unsubscribing/etc to these topics */ - protected abstract getWsUnsubscribeEventsForTopics( - topics: TWSTopic[], + protected abstract getWsOperationEventsForTopics( + topics: WsTopicRequest[], wsKey: TWSKey, + operation: WsOperation, ): string[]; /** @@ -142,6 +161,8 @@ export abstract class BaseWebsocketClient< } /** + * Don't call directly! Use subscribe() instead! + * * Subscribe to one or more topics on a WS connection (identified by WS Key). * * - Topics are automatically cached @@ -149,12 +170,17 @@ export abstract class BaseWebsocketClient< * - Authentication is automatically handled * - Topics are automatically resubscribed to, if something happens to the connection, unless you call unsubsribeTopicsForWsKey(topics, key). * - * @param wsTopics array of topics to subscribe to + * @param wsRequests array of topics to subscribe to * @param wsKey ws key referring to the ws connection these topics should be subscribed on */ - public subscribeTopicsForWsKey(wsTopics: TWSTopic[], wsKey: TWSKey) { + protected subscribeTopicsForWsKey( + wsTopicRequests: WsTopicRequestOrStringTopic[], + wsKey: TWSKey, + ) { + const normalisedTopicRequests = getNormalisedTopicRequests(wsTopicRequests); + // Store topics, so future automation (post-auth, post-reconnect) has everything needed to resubscribe automatically - for (const topic of wsTopics) { + for (const topic of normalisedTopicRequests) { this.wsStore.addTopic(wsKey, topic); } @@ -181,19 +207,25 @@ export abstract class BaseWebsocketClient< if (isPrivateConnection && !isAuthenticated) { /** * If not authenticated yet and auth is required, don't request topics yet. - * Topics will automatically subscribe post-auth success. + * + * Auth should already automatically be in progress, so no action needed from here. Topics will automatically subscribe post-auth success. */ return false; } // Finally, request subscription to topics if the connection is healthy and ready - this.requestSubscribeTopics(wsKey, wsTopics); + this.requestSubscribeTopics(wsKey, normalisedTopicRequests); } - public unsubscribeTopicsForWsKey(wsTopics: TWSTopic[], wsKey: TWSKey) { + protected unsubscribeTopicsForWsKey( + wsTopicRequests: WsTopicRequestOrStringTopic[], + wsKey: TWSKey, + ) { + const normalisedTopicRequests = getNormalisedTopicRequests(wsTopicRequests); + // Store topics, so future automation (post-auth, post-reconnect) has everything needed to resubscribe automatically - for (const topic of wsTopics) { - this.wsStore.addTopic(wsKey, topic); + for (const topic of normalisedTopicRequests) { + this.wsStore.deleteTopic(wsKey, topic); } const isConnected = this.wsStore.isConnectionState( @@ -201,7 +233,8 @@ export abstract class BaseWebsocketClient< WsConnectionStateEnum.CONNECTED, ); - // If not connected, don't need to do anything + // If not connected, don't need to do anything. + // Removing the topic from the store is enough to stop it from being resubscribed to on reconnect. if (!isConnected) { return; } @@ -218,93 +251,11 @@ export abstract class BaseWebsocketClient< } // Finally, request subscription to topics if the connection is healthy and ready - this.requestUnsubscribeTopics(wsKey, wsTopics); + this.requestUnsubscribeTopics(wsKey, normalisedTopicRequests); } - // /** - // * Subscribe to topics & track/persist them. They will be automatically resubscribed to if the connection drops/reconnects. - // * @param wsTopics topic or list of topics - // * @param isPrivate optional - the library will try to detect private topics, you can use this to mark a topic as private (if the topic isn't recognised yet) - // */ - // public subscribe( - // wsTopics: TWSTopic[] | TWSTopic, - // market: TWSMarket, - // isPrivate?: boolean, - // ) { - // const topics = Array.isArray(wsTopics) ? wsTopics : [wsTopics]; - - // const topicsByWsKey = - - // topics.forEach((topic) => { - // const isPrivateTopic = isPrivate || this.isPrivateChannel(topic); - // const wsKey = this.getWsKeyForMarket(market, isPrivateTopic); - - // // Persist this topic to the expected topics list - // this.wsStore.addTopic(wsKey, topic); - - // // if connected, send subscription request - // if ( - // this.wsStore.isConnectionState(wsKey, WsConnectionStateEnum.CONNECTED) - // ) { - // // if not authenticated, dont sub to private topics yet. - // // This'll happen automatically once authenticated - // if (isPrivateTopic && !this.wsStore.get(wsKey)?.isAuthenticated) { - // return; - // } - - // console.log(`subscribe(), `, { - // wsTopics, - // isPrivate, - // isAuthenticated: this.wsStore.get(wsKey)?.isAuthenticated, - // }); - // // TODO: this might need tidying up. - // // !!Takes many topics and then feeds them one by one, to a method that supports many topics - // return this.requestSubscribeTopics(wsKey, [topic]); - // } - - // // start connection process if it hasn't yet begun. Topics are automatically subscribed to on-connect - // if ( - // !this.wsStore.isConnectionState( - // wsKey, - // WsConnectionStateEnum.CONNECTING, - // ) && - // !this.wsStore.isConnectionState( - // wsKey, - // WsConnectionStateEnum.RECONNECTING, - // ) - // ) { - // return this.connect(wsKey); - // } - // }); - // } - - // /** - // * Unsubscribe from topics & remove them from memory. They won't be re-subscribed to if the connection reconnects. - // * @param wsTopics topic or list of topics - // * @param isPrivateTopic optional - the library will try to detect private topics, you can use this to mark a topic as private (if the topic isn't recognised yet) - // */ - // public unsubscribe( - // wsTopics: TWSTopic[] | TWSTopic, - // market: TWSMarket, - // isPrivateTopic?: boolean, - // ) { - // const topics = Array.isArray(wsTopics) ? wsTopics : [wsTopics]; - // topics.forEach((topic) => { - // const wsKey = this.getWsKeyForMarket(market, isPrivateTopic); - - // this.wsStore.deleteTopic(wsKey, topic); - - // // unsubscribe request only necessary if active connection exists - // if ( - // this.wsStore.isConnectionState(wsKey, WsConnectionStateEnum.CONNECTED) - // ) { - // this.requestUnsubscribeTopics(wsKey, [topic]); - // } - // }); - // } - /** Get the WsStore that tracks websockets & topics */ - public getWsStore(): WsStore { + public getWsStore(): WsStore> { return this.wsStore; } @@ -410,6 +361,7 @@ export abstract class BaseWebsocketClient< ...WS_LOGGER_CATEGORY, wsKey, }); + // TODO:! const request = await this.getWsAuthRequestEvent(wsKey); @@ -499,14 +451,18 @@ export abstract class BaseWebsocketClient< * * @private Use the `subscribe(topics)` or `subscribeTopicsForWsKey(topics, wsKey)` method to subscribe to topics. Send WS message to subscribe to topics. */ - private requestSubscribeTopics(wsKey: TWSKey, topics: TWSTopic[]) { + private requestSubscribeTopics( + wsKey: TWSKey, + topics: WsTopicRequest[], + ) { if (!topics.length) { return; } - const subscribeWsMessages = this.getWsSubscribeEventsForTopics( + const subscribeWsMessages = this.getWsOperationEventsForTopics( topics, wsKey, + 'subscribe', ); this.logger.trace( @@ -530,18 +486,22 @@ export abstract class BaseWebsocketClient< * * @private Use the `unsubscribe(topics)` method to unsubscribe from topics. Send WS message to unsubscribe from topics. */ - private requestUnsubscribeTopics(wsKey: TWSKey, topics: TWSTopic[]) { - if (!topics.length) { + private requestUnsubscribeTopics( + wsKey: TWSKey, + wsTopicRequests: WsTopicRequest[], + ) { + if (!wsTopicRequests.length) { return; } - const subscribeWsMessages = this.getWsUnsubscribeEventsForTopics( - topics, + const subscribeWsMessages = this.getWsOperationEventsForTopics( + wsTopicRequests, wsKey, + 'unsubscribe', ); this.logger.trace( - `Unsubscribing to ${topics.length} "${wsKey}" topics in ${subscribeWsMessages.length} batches. Events: "${JSON.stringify(topics)}"`, + `Unsubscribing to ${wsTopicRequests.length} "${wsKey}" topics in ${subscribeWsMessages.length} batches. Events: "${JSON.stringify(wsTopicRequests)}"`, ); for (const wsMessage of subscribeWsMessages) { @@ -550,7 +510,7 @@ export abstract class BaseWebsocketClient< } this.logger.trace( - `Finished unsubscribing to ${topics.length} "${wsKey}" topics in ${subscribeWsMessages.length} batches.`, + `Finished unsubscribing to ${wsTopicRequests.length} "${wsKey}" topics in ${subscribeWsMessages.length} batches.`, ); } @@ -633,8 +593,9 @@ export abstract class BaseWebsocketClient< // Private topics will be resubscribed to once reconnected const topics = [...this.wsStore.getTopics(wsKey)]; const publicTopics = topics.filter( - (topic) => !this.isPrivateChannel(topic), + (topic) => !this.isPrivateTopicRequest(topic), ); + this.requestSubscribeTopics(wsKey, publicTopics); this.logger.trace(`Enabled ping timer`, { ...WS_LOGGER_CATEGORY, wsKey }); @@ -651,7 +612,7 @@ export abstract class BaseWebsocketClient< const topics = [...this.wsStore.getTopics(wsKey)]; const privateTopics = topics.filter((topic) => - this.isPrivateChannel(topic), + this.isPrivateTopicRequest(topic), ); if (privateTopics.length) { diff --git a/src/lib/requestUtils.ts b/src/lib/requestUtils.ts index 59c12a8..1d1480e 100644 --- a/src/lib/requestUtils.ts +++ b/src/lib/requestUtils.ts @@ -20,7 +20,7 @@ export interface RestClientOptions { /** * Optionally override API protocol + domain - * e.g baseUrl: 'https://api.woo.org' + * e.g baseUrl: 'https://api.gate.io' **/ baseUrl?: string; diff --git a/src/lib/websocket/WsStore.ts b/src/lib/websocket/WsStore.ts index ebdfc31..41ae5c5 100644 --- a/src/lib/websocket/WsStore.ts +++ b/src/lib/websocket/WsStore.ts @@ -6,7 +6,7 @@ import { WsConnectionStateEnum, WsStoredState } from './WsStore.types.js'; /** * Simple comparison of two objects, only checks 1-level deep (nested objects won't match) */ -function isDeepObjectMatch(object1: unknown, object2: unknown) { +export function isDeepObjectMatch(object1: unknown, object2: unknown): boolean { if (typeof object1 === 'string' && typeof object2 === 'string') { return object1 === object2; } @@ -150,6 +150,12 @@ export class WsStore< } // Since topics are objects we can't rely on the set to detect duplicates + /** + * Find matching "topic" request from the store + * @param key + * @param topic + * @returns + */ getMatchingTopic(key: WsKey, topic: TWSTopicSubscribeEventArgs) { // if (typeof topic === 'string') { // return this.getMatchingTopic(key, { channel: topic }); diff --git a/src/lib/websocket/websocket-util.ts b/src/lib/websocket/websocket-util.ts index d8ae08c..ab6b428 100644 --- a/src/lib/websocket/websocket-util.ts +++ b/src/lib/websocket/websocket-util.ts @@ -1,11 +1,67 @@ -/** Should be one WS key per unique URL */ +/** + * Should be one WS key per unique URL. Some URLs may need a suffix. + */ export const WS_KEY_MAP = { - publicV1: 'publicV1', - privateV1: 'privateV1', + /** + * Spot & Margin + * https://www.gate.io/docs/developers/apiv4/ws/en/ + */ + spotV4: 'spotV4', + /** + * Perpetual futures (USDT) + * https://www.gate.io/docs/developers/futures/ws/en/#gate-io-futures-websocket-v4 + */ + perpFuturesUSDTV4: 'perpFuturesUSDTV4', + /** + * Perpetual futures (BTC) + * https://www.gate.io/docs/developers/futures/ws/en/#gate-io-futures-websocket-v4 + */ + perpFuturesBTCV4: 'perpFuturesBTCV4', + /** + * Delivery Futures (USDT) + * https://www.gate.io/docs/developers/delivery/ws/en/ + */ + deliveryFuturesUSDTV4: 'deliveryFuturesUSDTV4', + /** + * Delivery Futures (BTC) + * https://www.gate.io/docs/developers/delivery/ws/en/ + */ + deliveryFuturesBTCV4: 'deliveryFuturesBTCV4', + /** + * Options + * https://www.gate.io/docs/developers/options/ws/en/ + */ + optionsV4: 'optionsV4', + /** + * Announcements V4 + * https://www.gate.io/docs/developers/options/ws/en/ + */ + announcementsV4: 'announcementsV4', } as const; /** 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 WsMarket = 'all'; + +/** + * Normalised internal format for a request (subscribe/unsubscribe/etc) on a topic, with optional parameters. + * + * - WsKey: the WS connection this event is for + * - 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 { + topic: TWSTopic; + params?: 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. @@ -24,19 +80,35 @@ type NetworkMap< export const WS_BASE_URL_MAP: Record< WsKey, - Record<'all', NetworkMap<'livenet' | 'staging'>> + NetworkMap<'livenet' | 'testnet'> > = { - publicV1: { - all: { - livenet: 'wss://wss.woo.org/ws/stream/', - staging: 'wss://wss.staging.woo.org/ws/stream', - }, + spotV4: { + livenet: 'wss://api.gateio.ws/ws/v4/', + testnet: 'NoTestnetForSpotWebsockets!', + }, + perpFuturesUSDTV4: { + livenet: 'wss://fx-ws.gateio.ws/v4/ws/usdt', + testnet: 'wss://fx-ws-testnet.gateio.ws/v4/ws/usdt', + }, + perpFuturesBTCV4: { + livenet: 'wss://fx-ws.gateio.ws/v4/ws/btc', + testnet: 'wss://fx-ws-testnet.gateio.ws/v4/ws/btc', + }, + deliveryFuturesUSDTV4: { + livenet: 'wss://fx-ws.gateio.ws/v4/ws/delivery/usdt', + testnet: 'wss://fx-ws-testnet.gateio.ws/v4/ws/delivery/usdt', + }, + deliveryFuturesBTCV4: { + livenet: 'wss://fx-ws.gateio.ws/v4/ws/delivery/btc', + testnet: 'wss://fx-ws-testnet.gateio.ws/v4/ws/delivery/btc', + }, + optionsV4: { + livenet: 'wss://op-ws.gateio.live/v4/ws', + testnet: 'wss://op-ws-testnet.gateio.live/v4/ws', }, - privateV1: { - all: { - livenet: 'wss://wss.woo.org/v2/ws/private/stream', - staging: 'wss://wss.staging.woo.org/v2/ws/private/stream', - }, + announcementsV4: { + livenet: 'wss://api.gateio.ws/ws/v4/ann', + testnet: 'NoTestnetForAnnouncementsWebSockets!', }, }; diff --git a/src/types/websockets/client.ts b/src/types/websockets/client.ts index f84fa07..ab861df 100644 --- a/src/types/websockets/client.ts +++ b/src/types/websockets/client.ts @@ -18,8 +18,7 @@ export interface WSClientConfigurableOptions { /** Your API secret */ apiSecret?: string; - /** Your application ID, given to you when creating your API keys */ - apiApplicationId?: string; + useTestnet?: boolean; /** Define a recv window when preparing a private websocket signature. This is in milliseconds, so 5000 == 5 seconds */ recvWindow?: number; @@ -55,5 +54,3 @@ export interface WebsocketClientOptions extends WSClientConfigurableOptions { reconnectTimeout: number; recvWindow: number; } - -export type WsMarket = 'all'; diff --git a/src/types/websockets/requests.ts b/src/types/websockets/requests.ts index a41b310..88c09ed 100644 --- a/src/types/websockets/requests.ts +++ b/src/types/websockets/requests.ts @@ -1,7 +1,24 @@ export type WsOperation = 'subscribe' | 'unsubscribe' | 'auth'; -export type WsRequestOperation = { - id: string; - event: WsOperation; - topic: TWSTopic; -}; +export interface WsRequestAuthGate { + method: 'api_key'; + KEY: string; + SIGN: string; +} + +export interface WsRequestPing { + time: number; + channel: 'spot.ping' | 'futures.ping' | 'options.ping' | 'announcement.ping'; +} + +export interface WsRequestOperationGate< + TWSTopic extends string, + TWSPayload = any, +> { + time: number; + id?: number; + channel: TWSTopic; + auth?: WsRequestAuthGate; + event?: WsOperation; + payload?: TWSPayload; +} From 00107339d41fe21464e0e19db59d67b0fd2a320a Mon Sep 17 00:00:00 2001 From: Tiago Siebler Date: Thu, 30 May 2024 13:19:12 +0100 Subject: [PATCH 35/36] feat(): working public topics --- examples/ws-public.ts | 104 ++++++++++++++++++++++++++++ src/WebsocketClient.ts | 102 +++++++++++++++++++++++---- src/lib/BaseWSClient.ts | 7 +- src/lib/websocket/websocket-util.ts | 5 +- 4 files changed, 203 insertions(+), 15 deletions(-) create mode 100644 examples/ws-public.ts diff --git a/examples/ws-public.ts b/examples/ws-public.ts new file mode 100644 index 0000000..9662789 --- /dev/null +++ b/examples/ws-public.ts @@ -0,0 +1,104 @@ +// eslint-disable-next-line @typescript-eslint/no-unused-vars +import { LogParams, WebsocketClient } from '../src'; +import { WsTopicRequest } from '../src/lib/websocket/websocket-util'; + +// const customLogger = { +// // eslint-disable-next-line @typescript-eslint/no-unused-vars +// trace: (...params: LogParams): void => { +// console.log('trace', ...params); +// }, +// info: (...params: LogParams): void => { +// console.log('info', ...params); +// }, +// error: (...params: LogParams): void => { +// console.error('error', ...params); +// }, +// }; + +async function start() { + const client = new WebsocketClient(); + + // Optional, inject a custom logger + // const client = new WebsocketClient({}, customLogger); + + client.on('open', (data) => { + console.log('connected ', data?.wsKey); + }); + + // Data received + client.on('update', (data) => { + console.info('data received: ', JSON.stringify(data)); + }); + + // Something happened, attempting to reconenct + client.on('reconnect', (data) => { + console.log('reconnect: ', data); + }); + + // Reconnect successful + client.on('reconnected', (data) => { + console.log('reconnected: ', data); + }); + + // Connection closed. If unexpected, expect reconnect -> reconnected. + client.on('close', (data) => { + console.error('close: ', data); + }); + + // Reply to a request, e.g. "subscribe"/"unsubscribe"/"authenticate" + client.on('response', (data) => { + console.info('server reply: ', JSON.stringify(data), '\n'); + }); + + client.on('exception', (data) => { + console.error('exception: ', data); + }); + + client.on('authenticated', (data) => { + console.error('authenticated: ', data); + }); + + try { + const tickersRequestWithParams: WsTopicRequest = { + topic: 'spot.tickers', + params: ['BTC_USDT', 'ETH_USDT', 'MATIC_USDT'], + }; + + const rawTradesRequestWithParams: WsTopicRequest = { + topic: 'spot.trades', + params: ['BTC_USDT', 'ETH_USDT', 'MATIC_USDT'], + }; + + // const topicWithoutParamsAsString = 'spot.balances'; + + // This has the same effect as above, it's just a different way of messaging which topic this is for + // const topicWithoutParamsAsObject: WsTopicRequest = { + // topic: 'spot.balances', + // }; + + /** + * Either send one topic (with optional params) at a time + */ + // client.subscribe(tickersRequestWithParams, 'spotV4'); + + /** + * Or send multiple topics in a batch (grouped by ws connection (WsKey)) + */ + client.subscribe( + [tickersRequestWithParams, rawTradesRequestWithParams], + 'spotV4', + ); + + // /** + // * You can also use strings for topics that don't have any parameters, even if you mix multiple requests into one function call: + // */ + // client.subscribe( + // [tickersRequestWithParams, rawTradesRequestWithParams, topicWithoutParamsAsString], + // 'spotV4', + // ); + } catch (e) { + console.error(`Req error: `, e); + } +} + +start(); diff --git a/src/WebsocketClient.ts b/src/WebsocketClient.ts index 874bc22..13b02e1 100644 --- a/src/WebsocketClient.ts +++ b/src/WebsocketClient.ts @@ -14,6 +14,7 @@ import { import { WsOperation, WsRequestOperationGate, + WsRequestPing, } from './types/websockets/requests.js'; export const WS_LOGGER_CATEGORY = { category: 'gate-ws' }; @@ -86,9 +87,16 @@ export class WebsocketClient extends BaseWebsocketClient { * Call `unsubscribe(topics)` to remove topics */ public subscribe( - requests: (WsTopicRequest | WsTopic)[], + requests: + | (WsTopicRequest | WsTopic) + | (WsTopicRequest | WsTopic)[], wsKey: WsKey, ) { + if (!Array.isArray(requests)) { + this.subscribeTopicsForWsKey([requests], wsKey); + return; + } + if (requests.length) { this.subscribeTopicsForWsKey(requests, wsKey); } @@ -101,9 +109,16 @@ export class WebsocketClient extends BaseWebsocketClient { * - These topics will be removed from the topic cache, so they won't be subscribed to again. */ public unsubscribe( - requests: (WsTopicRequest | WsTopic)[], + requests: + | (WsTopicRequest | WsTopic) + | (WsTopicRequest | WsTopic)[], wsKey: WsKey, ) { + if (!Array.isArray(requests)) { + this.unsubscribeTopicsForWsKey([requests], wsKey); + return; + } + if (requests.length) { this.unsubscribeTopicsForWsKey(requests, wsKey); } @@ -116,27 +131,80 @@ export class WebsocketClient extends BaseWebsocketClient { */ protected sendPingEvent(wsKey: WsKey) { - return this.tryWsSend(wsKey, '{"event":"ping"}'); + let pingChannel: WsRequestPing['channel']; + + switch (wsKey) { + case 'deliveryFuturesBTCV4': + case 'deliveryFuturesUSDTV4': + case 'perpFuturesBTCV4': + case 'perpFuturesUSDTV4': { + pingChannel = 'futures.ping'; + break; + } + case 'announcementsV4': { + pingChannel = 'announcement.ping'; + break; + } + case 'optionsV4': { + pingChannel = 'options.ping'; + break; + } + case 'spotV4': { + pingChannel = 'spot.ping'; + break; + } + default: { + throw neverGuard(wsKey, `Unhandled WsKey "${wsKey}"`); + } + } + + const timeInMs = Date.now(); + const timeInS = (timeInMs / 1000).toFixed(0); + return this.tryWsSend( + wsKey, + `{ "time": ${timeInS}, "channel": "${pingChannel}" }`, + ); } protected sendPongEvent(wsKey: WsKey) { - return this.tryWsSend(wsKey, '{"event":"pong"}'); - } + try { + this.logger.trace(`Sending upstream ws PONG: `, { + ...WS_LOGGER_CATEGORY, + wsMessage: 'PONG', + wsKey, + }); + if (!wsKey) { + throw new Error( + 'Cannot send PONG due to no known websocket for this wsKey', + ); + } + const wsState = this.getWsStore().get(wsKey); + if (!wsState || !wsState?.ws) { + throw new Error( + `${wsKey} socket not connected yet, call "connectAll()" first then try again when the "open" event arrives`, + ); + } - protected isWsPing(msg: any): boolean { - if (typeof msg?.data === 'string' && msg.data.includes('"event":"ping"')) { - return true; + // Send a protocol layer pong + wsState.ws.pong(); + } catch (e) { + this.logger.error(`Failed to send WS PONG`, { + ...WS_LOGGER_CATEGORY, + wsMessage: 'PONG', + wsKey, + exception: e, + }); } - // this.logger.info(`Not a ping: `, { - // data: msg?.data, - // type: typeof msg?.data, - // }); + } + // Unused, pings for gate are protocol layer pings + // eslint-disable-next-line @typescript-eslint/no-unused-vars + protected isWsPing(_msg: any): boolean { return false; } protected isWsPong(msg: any): boolean { - if (typeof msg?.data === 'string' && msg.data.includes('"event":"pong"')) { + if (typeof msg?.data === 'string' && msg.data.includes('.pong"')) { return true; } @@ -165,6 +233,14 @@ export class WebsocketClient extends BaseWebsocketClient { return results; } + if (eventAction === 'update') { + results.push({ + eventType: 'update', + event: parsed, + }); + return results; + } + // These are request/reply pattern events (e.g. after subscribing to topics or authenticating) if (responseEvents.includes(eventAction)) { results.push({ diff --git a/src/lib/BaseWSClient.ts b/src/lib/BaseWSClient.ts index 27cad12..2d5d736 100644 --- a/src/lib/BaseWSClient.ts +++ b/src/lib/BaseWSClient.ts @@ -626,7 +626,11 @@ export abstract class BaseWebsocketClient< this.clearPongTimer(wsKey); if (this.isWsPong(event)) { - this.logger.trace('Received pong', { ...WS_LOGGER_CATEGORY, wsKey }); + this.logger.trace('Received pong', { + ...WS_LOGGER_CATEGORY, + wsKey, + event, + }); return; } @@ -634,6 +638,7 @@ export abstract class BaseWebsocketClient< this.logger.trace('Received ping', { ...WS_LOGGER_CATEGORY, wsKey, + event, }); this.sendPongEvent(wsKey, ws); return; diff --git a/src/lib/websocket/websocket-util.ts b/src/lib/websocket/websocket-util.ts index ab6b428..82b18cd 100644 --- a/src/lib/websocket/websocket-util.ts +++ b/src/lib/websocket/websocket-util.ts @@ -50,7 +50,10 @@ export type WsMarket = 'all'; * - 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 { +export interface WsTopicRequest< + TWSTopic extends string = string, + TWSPayload = any, +> { topic: TWSTopic; params?: TWSPayload; } From c39ddd7aaa2bdf1683a3ed374d479669807fc800 Mon Sep 17 00:00:00 2001 From: Tiago Siebler Date: Thu, 30 May 2024 13:27:15 +0100 Subject: [PATCH 36/36] chore(): readme updates --- README.md | 87 ++++++++++++++++++++++++++++--------------------------- 1 file changed, 45 insertions(+), 42 deletions(-) diff --git a/README.md b/README.md index b22ee9d..8035164 100644 --- a/README.md +++ b/README.md @@ -1,15 +1,15 @@ # gateio-api -[![Tests](https://circleci.com/gh/tiagosiebler/gateio-api.svg?style=shield)](https://circleci.com/gh/tiagosiebler/gateio-api) -[![npm version](https://img.shields.io/npm/v/gateio-api)][1] [![npm size](https://img.shields.io/bundlephobia/min/gateio-api/latest)][1] [![npm downloads](https://img.shields.io/npm/dt/gateio-api)][1] +[![E2E Tests](https://github.com/tiagosiebler/gateio-api/actions/workflows/e2etest.yml/badge.svg?branch=master)](https://github.com/tiagosiebler/gateio-api/actions/workflows/e2etest.yml) +[![npm version](https://img.shields.io/npm/v/gateio-api)][1] +[![npm size](https://img.shields.io/bundlephobia/min/gateio-api/latest)][1] +[![npm downloads](https://img.shields.io/npm/dt/gateio-api)][1] [![last commit](https://img.shields.io/github/last-commit/tiagosiebler/gateio-api)][1] [![CodeFactor](https://www.codefactor.io/repository/github/tiagosiebler/gateio-api/badge)](https://www.codefactor.io/repository/github/tiagosiebler/gateio-api) [1]: https://www.npmjs.com/package/gateio-api -WARNING: This package is still early beta, following the designs of my other connectors. If you want to stay informed when this may be ready for testing, please get in touch via telegram. - -Node.js connector for the gateio APIs and WebSockets, with TypeScript & browser support. +Node.js & TypeScript SDK for Gate.io REST APIs and WebSockets. ## Installation @@ -22,16 +22,18 @@ Node.js connector for the gateio APIs and WebSockets, with TypeScript & browser ## Related projects -Check out my related projects: +Check out my related JavaScript/TypeScript/Node.js projects: -- Try my connectors: - - [binance](https://www.npmjs.com/package/binance) - - [bybit-api](https://www.npmjs.com/package/bybit-api) - - [okx-api](https://www.npmjs.com/package/okx-api) - - [bitget-api](https://www.npmjs.com/package/bitget-api) - - [ftx-api](https://www.npmjs.com/package/ftx-api) +- Try my API & WebSocket SDKs: + - [Bybit-api Node.js SDK](https://www.npmjs.com/package/bybit-api) + - [Binance Node.js SDK](https://www.npmjs.com/package/binance) + - [Okx-api Node.js SDK](https://www.npmjs.com/package/okx-api) + - [Gateio-api Nodejs SDK](https://www.npmjs.com/package/bitmart-api) + - [Bitget-api Node.js SDK](https://www.npmjs.com/package/bitget-api) + - [Bitmart-api Nodejs SDK](https://www.npmjs.com/package/bitmart-api) - Try my misc utilities: - - [orderbooks](https://www.npmjs.com/package/orderbooks) + - [orderbooks node.js](https://www.npmjs.com/package/orderbooks) + - [accountstate](https://www.npmjs.com/package/accountstate) - Check out my examples: - [awesome-crypto-examples](https://github.com/tiagosiebler/awesome-crypto-examples) @@ -143,13 +145,6 @@ const wsConfig = { // defaults to false == testnet. Set to true for livenet. // livenet: true - // NOTE: to listen to multiple markets (spot vs inverse vs linear vs linearfutures) at once, make one WebsocketClient instance per market - - // defaults to inverse: - // market: 'inverse' - // market: 'linear' - // market: 'spot' - // how long to wait (in ms) before deciding the connection should be terminated & reconnected // pongTimeout: 1000, @@ -164,22 +159,35 @@ const wsConfig = { // config for axios used for HTTP requests. E.g for proxy support // requestOptions: { } - - // override which URL to use for websocket connections - // wsUrl: 'wss://stream.bytick.com/realtime' }; const ws = new WebsocketClient(wsConfig); +const tickersRequestWithParams = { + topic: 'spot.tickers', + params: ['BTC_USDT', 'ETH_USDT', 'MATIC_USDT'], +}; + +const rawTradesRequestWithParams = { + topic: 'spot.trades', + params: ['BTC_USDT', 'ETH_USDT', 'MATIC_USDT'], +}; + // subscribe to multiple topics at once -ws.subscribe(['position', 'execution', 'trade']); +ws.subscribe([tickersRequestWithParams, rawTradesRequestWithParams], 'spotV4'); // and/or subscribe to individual topics on demand -ws.subscribe('kline.BTCUSD.1m'); +ws.subscribe( + { + topic: 'spot.trades', + params: ['BTC_USDT', 'ETH_USDT', 'MATIC_USDT'], + }, + 'spotV4', +); // Listen to events coming from websockets. This is the primary data source ws.on('update', (data) => { - console.log('update', data); + console.log('data', data); }); // Optional: Listen to websocket connection open event (automatic after subscribing to one or more topics) @@ -197,6 +205,11 @@ ws.on('close', () => { console.log('connection closed'); }); +// Optional: listen to internal exceptions. Useful for debugging if something weird happens +ws.on('exception', (data) => { + console.error('exception: ', data); +}); + // Optional: Listen to raw error events. // Note: responses to invalid topics are currently only sent in the "response" event. ws.on('error', (err) => { @@ -206,8 +219,6 @@ ws.on('error', (err) => { See [websocket-client.ts](./src/websocket-client.ts) for further information. -Note: for linear websockets, pass `linear: true` in the constructor options when instancing the `WebsocketClient`. To connect to both linear and inverse websockets, make two instances of the WebsocketClient. - --- ## Customise Logging @@ -237,21 +248,13 @@ The bundle can be found in `dist/`. Altough usage should be largely consistent, ## Contributions & Thanks -### Donations - -#### tiagosiebler - -Support my efforts to make algo trading accessible to all - register with my referral links: - -- [Bybit](https://www.bybit.com/en-US/register?affiliate_id=9410&language=en-US&group_id=0&group_type=1) -- [Binance](https://www.binance.com/en/register?ref=20983262) -- [OKX](https://www.okx.com/join/18504944) -- [FTX](https://ftx.com/referrals#a=ftxapigithub) - -Or buy me a coffee using any of these: +Have my projects helped you? Share the love, there are many ways you can show your thanks: -- BTC: `1C6GWZL1XW3jrjpPTS863XtZiXL1aTK7Jk` -- ETH (ERC20): `0xd773d8e6a50758e1ada699bb6c4f98bb4abf82da` +- Star & share my projects. +- Are my projects useful? Sponsor me on Github and support my effort to maintain & improve them: https://github.com/sponsors/tiagosiebler +- Have an interesting project? Get in touch & invite me to it. +- Or buy me all the coffee: + - ETH(ERC20): `0xA3Bda8BecaB4DCdA539Dc16F9C54a592553Be06C` ### Contributions & Pull Requests