From ad3f25e52886671a8986059c44c93b024ce02bfe Mon Sep 17 00:00:00 2001 From: "JJ-Cro (Codex)" Date: Mon, 16 Nov 2026 12:19:34 +0100 Subject: [PATCH 1/2] feat(v3.2.9): fix UTA requests and add institutional lending risk fields - Recognize matching WebSocket account and position snapshots (fixes #182) - Send UTA withdrawals to the documented withdrawal endpoint (fixes #183) - Correct account switch statuses and expose the failure reason (fixes #184) - Send top-level requestTime on WS API order requests so receiveWindow takes effect; can be overridden via requestFlags.requestTime (fixes #185) - Add institutional lending client types, risk units, and Hedge risk metrics - Update REST market-order slippage documentation to support three decimal places - Bump the SDK to 3.2.9 and the Node.js pin to v24.22.3 --- .nvmrc | 2 +- package-lock.json | 4 ++-- package.json | 2 +- src/rest-client-v3.ts | 12 +++++++++--- src/types/request/v3/loan.ts | 1 + src/types/request/v3/trade.ts | 2 +- src/types/response/v3/loan.ts | 8 ++++++++ src/types/websockets/ws-api-request.ts | 2 +- src/types/websockets/ws-api.ts | 2 ++ src/util/type-guards.ts | 8 ++++---- src/websocket-api-client.ts | 6 +++++- src/websocket-client-v3.ts | 16 ++++++++++++++-- 12 files changed, 49 insertions(+), 16 deletions(-) diff --git a/.nvmrc b/.nvmrc index 5bcf9c6e..22fbfc06 100644 --- a/.nvmrc +++ b/.nvmrc @@ -1 +1 @@ -v24.18.0 +v24.22.3 diff --git a/package-lock.json b/package-lock.json index 5c36a31d..6590e180 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "bitget-api", - "version": "3.2.8", + "version": "3.2.9", "lockfileVersion": 2, "requires": true, "packages": { "": { "name": "bitget-api", - "version": "3.2.8", + "version": "3.2.9", "license": "MIT", "dependencies": { "@types/ws": "8.18.1", diff --git a/package.json b/package.json index d0da1f38..85355403 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "bitget-api", - "version": "3.2.8", + "version": "3.2.9", "description": "Complete Node.js & JavaScript SDK for Bitget V1-V3 REST APIs & WebSockets, with TypeScript & end-to-end tests.", "scripts": { "test": "jest", diff --git a/src/rest-client-v3.ts b/src/rest-client-v3.ts index c04d69cc..8ec23b2e 100644 --- a/src/rest-client-v3.ts +++ b/src/rest-client-v3.ts @@ -2015,7 +2015,9 @@ export class RestClientV3 extends BaseRestClient { */ getUnifiedAccountSwitchStatus(): Promise< APIResponse<{ - status: 'processProcessing' | 'successSuccess' | 'failFailed'; + status: 'process' | 'success' | 'fail'; + /** Only returned when status is fail */ + reason?: string; }> > { return this.getPrivate('/api/v3/account/switch-status'); @@ -2313,7 +2315,7 @@ export class RestClientV3 extends BaseRestClient { submitWithdraw( params: WithdrawRequestV3, ): Promise> { - return this.postPrivate('/api/v3/account/withdraw', params); + return this.postPrivate('/api/v3/account/withdrawal', params); } /** @@ -2352,7 +2354,7 @@ export class RestClientV3 extends BaseRestClient { /** * Place Order. * Market orders always run as IOC (staff-confirmed, t.me/bitgetOpenapi/153169). - * bboLevel is limit only. slippageTolerance is market only (default 0.02, range 0.01-0.05). + * bboLevel is limit only. slippageTolerance is market only (default 0.02, range [0.001, 0.05], up to 3 decimals). * Futures qty must be a multiple of quantityMultiplier, with at most quantityPrecision decimals. */ submitNewOrder( @@ -2599,6 +2601,10 @@ export class RestClientV3 extends BaseRestClient { getLoanRiskUnit(): Promise< APIResponse<{ riskUnitId: string[]; + riskUnitList: { + unitId: string; + clientType: 'Hedge' | 'HFT'; + }[]; }> > { return this.getPrivate('/api/v3/ins-loan/risk-unit'); diff --git a/src/types/request/v3/loan.ts b/src/types/request/v3/loan.ts index ee5c758c..4fe1c765 100644 --- a/src/types/request/v3/loan.ts +++ b/src/types/request/v3/loan.ts @@ -15,6 +15,7 @@ export interface GetRepaidHistoryRequestV3 { export interface GetProductInfosRequestV3 { productId: string; + clientType?: 'Hedge' | 'HFT'; } export interface GetLoanOrderRequestV3 { diff --git a/src/types/request/v3/trade.ts b/src/types/request/v3/trade.ts index 74ff344d..04cad254 100644 --- a/src/types/request/v3/trade.ts +++ b/src/types/request/v3/trade.ts @@ -273,7 +273,7 @@ export interface PlaceOrderRequestV3 { pxAmendType?: 'yes' | 'no'; /** Limit orders only. queue1, queue5, counterparty1, or counterparty5 */ bboLevel?: 'queue1' | 'queue5' | 'counterparty1' | 'counterparty5'; - /** Market orders only. Decimal, default 0.02, range 0.01-0.05 */ + /** Market orders only. Default 0.02, range [0.001, 0.05], up to 3 decimals */ slippageTolerance?: string; /** * rToken routing. Accepted: internal_market | lit_market. Omit for default. diff --git a/src/types/response/v3/loan.ts b/src/types/response/v3/loan.ts index c18f1ce1..e2fa1be5 100644 --- a/src/types/response/v3/loan.ts +++ b/src/types/response/v3/loan.ts @@ -44,6 +44,10 @@ export interface LoanProductInfoV3 { usdcContractOpenLine: string; liquidationLine: string; stopLiquidationLine: string; + /** Delta exceed threshold. Hedge only */ + deltaThreshold?: string; + /** Position leverage ratio threshold. Hedge only */ + leverageThreshold?: string; } export interface LoanOrderV3 { @@ -96,6 +100,10 @@ export interface BalanceInfoV3 { export interface LTVConvertResponseV3 { ltv: string; + /** Current risk unit delta. Hedge only; empty for HFT */ + delta: string; + /** Current position leverage ratio. Hedge only; empty for HFT */ + leverageRatio: string; subAccountUids: string[]; unpaidUsdtAmount: string; usdtBalance: string; diff --git a/src/types/websockets/ws-api-request.ts b/src/types/websockets/ws-api-request.ts index ed3377f2..e034d7eb 100644 --- a/src/types/websockets/ws-api-request.ts +++ b/src/types/websockets/ws-api-request.ts @@ -21,7 +21,7 @@ export interface WSAPIPlaceOrderRequestV3 { slOrderType?: 'limit' | 'market'; tpLimitPrice?: string; slLimitPrice?: string; - /** Order TTL in ms [10, 60000]. Only effective when requestTime is also set on the envelope */ + /** Order TTL in ms [10, 60000]. Sets the envelope requestTime to String(Date.now()) unless overridden via requestFlags.requestTime */ receiveWindow?: string; /** Spot only. Default: no */ autoBorrow?: 'yes' | 'no'; diff --git a/src/types/websockets/ws-api.ts b/src/types/websockets/ws-api.ts index d78fe08e..d8011461 100644 --- a/src/types/websockets/ws-api.ts +++ b/src/types/websockets/ws-api.ts @@ -56,6 +56,8 @@ export interface WSAPIRequestBitgetV3 { export interface WSAPIRequestFlags { /** If true, will skip auth requirement for WS API connection */ authIsOptional?: boolean | undefined; + /** Client-side timestamp in ms. Overrides the envelope timestamp, which defaults to String(Date.now()) when any order has receiveWindow */ + requestTime?: string; } export type Exact = { diff --git a/src/util/type-guards.ts b/src/util/type-guards.ts index 06271723..f4071214 100644 --- a/src/util/type-guards.ts +++ b/src/util/type-guards.ts @@ -13,9 +13,9 @@ import { function isWsEvent(event: unknown): event is WsBaseEvent { return ( typeof event === 'object' && - event && - (typeof event as any)['action'] === 'string' && - (typeof event as any)['data'] + event !== null && + typeof (event as any)['action'] === 'string' && + Array.isArray((event as any)['data']) ); } @@ -29,7 +29,7 @@ function isWsChannelEvent(event: WsBaseEvent): event is WsSnapshotChannelEvent { if ( typeof event['arg'] === 'object' && event['arg'] && - typeof (typeof event['arg'] as any)['channel'] === 'string' + typeof (event['arg'] as any)['channel'] === 'string' ) { return true; } diff --git a/src/websocket-api-client.ts b/src/websocket-api-client.ts index 21a829b5..f20a09e1 100644 --- a/src/websocket-api-client.ts +++ b/src/websocket-api-client.ts @@ -6,7 +6,7 @@ import { CancelOrderResponseV3, ModifyOrderResponseV3, } from './types/response/v3/trade.js'; -import { WSAPIResponse } from './types/websockets/ws-api.js'; +import { WSAPIRequestFlags, WSAPIResponse } from './types/websockets/ws-api.js'; import { WSAPIPlaceOrderRequestV3 } from './types/websockets/ws-api-request.js'; import { WSAPIPlaceOrderResponseV3 } from './types/websockets/ws-api-response.js'; import { @@ -85,12 +85,14 @@ export class WebsocketAPIClient { submitNewOrder( category: BitgetInstTypeV3, params: WSAPIPlaceOrderRequestV3, + requestFlags?: WSAPIRequestFlags, ): Promise> { return this.wsClient.sendWSAPIRequest( WS_KEY_MAP.v3Private, 'place-order', category, params, + requestFlags, ); } @@ -104,12 +106,14 @@ export class WebsocketAPIClient { placeBatchOrders( category: BitgetInstTypeV3, params: WSAPIPlaceOrderRequestV3[], + requestFlags?: WSAPIRequestFlags, ): Promise> { return this.wsClient.sendWSAPIRequest( WS_KEY_MAP.v3Private, 'batch-place', category, params, + requestFlags, ); } diff --git a/src/websocket-client-v3.ts b/src/websocket-client-v3.ts index da1f6833..26e605be 100644 --- a/src/websocket-client-v3.ts +++ b/src/websocket-client-v3.ts @@ -530,13 +530,25 @@ export class WebsocketClientV3 extends BaseWebsocketClient< const isPlaceOrder = operation === 'place-order' || operation === 'batch-place'; + // Ensure "args" is always wrapped as array + const args = Array.isArray(params) ? params : [params]; + let requestTime = requestFlags?.requestTime; + if ( + requestTime === undefined && + args.some( + (arg) => 'receiveWindow' in arg && arg.receiveWindow !== undefined, + ) + ) { + requestTime = String(Date.now()); + } + const request: WSAPIRequestBitgetV3 = { op: 'trade', id: `${this.getNewRequestId()}`, category: category, topic: operation, - // Ensure "args" is always wrapped as array - args: Array.isArray(params) ? params : [params], + args, + ...(requestTime !== undefined ? { requestTime } : {}), ...(isPlaceOrder ? { apiCode: CHANNEL_API_CODE } : {}), }; From 90b8f8839eeefc4980f5ca582c200b62247891dc Mon Sep 17 00:00:00 2001 From: JJ-Cro sync bot Date: Mon, 16 Nov 2026 13:07:19 +0100 Subject: [PATCH 2/2] chore: regenerate endpoint docs and examples --- docs/endpointFunctionList.md | 346 +- llms.txt | 13085 +++++++++++++++++---------------- 2 files changed, 6731 insertions(+), 6700 deletions(-) diff --git a/docs/endpointFunctionList.md b/docs/endpointFunctionList.md index 3b958a5d..063d9082 100644 --- a/docs/endpointFunctionList.md +++ b/docs/endpointFunctionList.md @@ -525,174 +525,174 @@ This table includes all endpoints from the official Exchange API docs and corres | [getEligibleDiscountRate()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L1993) | :closed_lock_with_key: | GET | `/api/v3/account/eligible-discount-rate` | | [downgradeAccountToClassic()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L2008) | :closed_lock_with_key: | POST | `/api/v3/account/switch` | | [getUnifiedAccountSwitchStatus()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L2016) | :closed_lock_with_key: | GET | `/api/v3/account/switch-status` | -| [getTaxRecords()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L2032) | :closed_lock_with_key: | GET | `/api/v3/tax/records` | -| [createSubAccount()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L2047) | :closed_lock_with_key: | POST | `/api/v3/user/create-sub` | -| [createAgentSubAccount()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L2056) | :closed_lock_with_key: | POST | `/api/v3/user/sub-account/agent-create` | -| [freezeSubAccount()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L2065) | :closed_lock_with_key: | POST | `/api/v3/user/freeze-sub` | -| [deleteSubAccount()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L2071) | :closed_lock_with_key: | POST | `/api/v3/user/delete-sub` | -| [getSubUnifiedAssets()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L2080) | :closed_lock_with_key: | GET | `/api/v3/account/sub-unified-assets` | -| [getSubAccountList()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L2089) | :closed_lock_with_key: | GET | `/api/v3/user/sub-list` | -| [createSubAccountApiKey()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L2102) | :closed_lock_with_key: | POST | `/api/v3/user/create-sub-api` | -| [updateSubAccountApiKey()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L2111) | :closed_lock_with_key: | POST | `/api/v3/user/update-sub-api` | -| [deleteSubAccountApiKey()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L2120) | :closed_lock_with_key: | POST | `/api/v3/user/delete-sub-api` | -| [getSubAccountApiKeys()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L2129) | :closed_lock_with_key: | GET | `/api/v3/user/sub-api-list` | -| [getRateLimitQuota()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L2143) | :closed_lock_with_key: | GET | `/api/v3/user/rate-limit-quota` | -| [setRateLimitQuota()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L2154) | :closed_lock_with_key: | POST | `/api/v3/user/set-rate-limit-quota` | -| [createStpGroup()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L2164) | :closed_lock_with_key: | POST | `/api/v3/account/create-stp-groups` | -| [getStpGroups()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L2174) | :closed_lock_with_key: | GET | `/api/v3/account/stp-groups` | -| [addStpGroupMembers()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L2184) | :closed_lock_with_key: | POST | `/api/v3/account/add-groups-members` | -| [removeStpGroupMembers()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L2196) | :closed_lock_with_key: | POST | `/api/v3/account/remove-groups-members` | -| [getTransferableCoins()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L2211) | :closed_lock_with_key: | GET | `/api/v3/account/transferable-coins` | -| [submitTransfer()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L2220) | :closed_lock_with_key: | POST | `/api/v3/account/transfer` | -| [subAccountTransfer()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L2229) | :closed_lock_with_key: | POST | `/api/v3/account/sub-transfer` | -| [getSubTransferRecords()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L2241) | :closed_lock_with_key: | GET | `/api/v3/account/sub-transfer-record` | -| [subMasterTransfer()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L2253) | :closed_lock_with_key: | POST | `/api/v3/account/sub-master-transfer` | -| [getDepositAddress()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L2271) | :closed_lock_with_key: | GET | `/api/v3/account/deposit-address` | -| [getSubDepositAddress()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L2280) | :closed_lock_with_key: | GET | `/api/v3/account/sub-deposit-address` | -| [getDepositRecords()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L2289) | :closed_lock_with_key: | GET | `/api/v3/account/deposit-records` | -| [getSubDepositRecords()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L2298) | :closed_lock_with_key: | POST | `/api/v3/account/sub-deposit-records` | -| [submitWithdraw()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L2313) | :closed_lock_with_key: | POST | `/api/v3/account/withdraw` | -| [getWithdrawRecords()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L2322) | :closed_lock_with_key: | GET | `/api/v3/account/withdrawal-records` | -| [getWithdrawAddressBook()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L2331) | :closed_lock_with_key: | GET | `/api/v3/account/withdraw-address` | -| [cancelWithdrawal()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L2340) | :closed_lock_with_key: | POST | `/api/v3/account/cancel-withdrawal` | -| [submitNewOrder()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L2358) | :closed_lock_with_key: | POST | `/api/v3/trade/place-order` | -| [modifyOrder()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L2367) | :closed_lock_with_key: | POST | `/api/v3/trade/modify-order` | -| [placeRealityOrder()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L2376) | :closed_lock_with_key: | POST | `/api/v3/trade/place-reality-order` | -| [cancelRealityOrder()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L2385) | :closed_lock_with_key: | POST | `/api/v3/trade/cancel-reality-order` | -| [getLoanData()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L2394) | :closed_lock_with_key: | GET | `/api/v3/trade/loan-data` | -| [cancelOrder()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L2401) | :closed_lock_with_key: | POST | `/api/v3/trade/cancel-order` | -| [placeBatchOrders()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L2410) | :closed_lock_with_key: | POST | `/api/v3/trade/place-batch` | -| [batchModifyOrders()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L2419) | :closed_lock_with_key: | POST | `/api/v3/trade/batch-modify-order` | -| [cancelBatchOrders()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L2428) | :closed_lock_with_key: | POST | `/api/v3/trade/cancel-batch` | -| [cancelAllOrders()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L2437) | :closed_lock_with_key: | POST | `/api/v3/trade/cancel-symbol-order` | -| [closeAllPositions()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L2446) | :closed_lock_with_key: | POST | `/api/v3/trade/close-positions` | -| [getOrderInfo()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L2455) | :closed_lock_with_key: | GET | `/api/v3/trade/order-info` | -| [getUnfilledOrders()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L2464) | :closed_lock_with_key: | GET | `/api/v3/trade/unfilled-orders` | -| [getHistoryOrders()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L2476) | :closed_lock_with_key: | GET | `/api/v3/trade/history-orders` | -| [movePositions()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L2488) | :closed_lock_with_key: | POST | `/api/v3/account/move-positions` | -| [getMovePositionHistory()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L2497) | :closed_lock_with_key: | GET | `/api/v3/account/move-position-history` | -| [getTradeFills()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L2509) | :closed_lock_with_key: | GET | `/api/v3/trade/fills` | -| [getCurrentPosition()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L2521) | :closed_lock_with_key: | GET | `/api/v3/position/current-position` | -| [getPositionHistory()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L2536) | :closed_lock_with_key: | GET | `/api/v3/position/history-position` | -| [getMaxOpenAvailable()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L2550) | :closed_lock_with_key: | POST | `/api/v3/account/max-open-available` | -| [getPositionAdlRank()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L2559) | :closed_lock_with_key: | GET | `/api/v3/position/adlRank` | -| [countdownCancelAll()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L2566) | :closed_lock_with_key: | POST | `/api/v3/trade/countdown-cancel-all` | -| [getLoanTransfered()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L2581) | :closed_lock_with_key: | GET | `/api/v3/ins-loan/transfered` | -| [getLoanSymbols()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L2590) | :closed_lock_with_key: | GET | `/api/v3/ins-loan/symbols` | -| [getLoanRiskUnit()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L2599) | :closed_lock_with_key: | GET | `/api/v3/ins-loan/risk-unit` | -| [getLoanRepaidHistory()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L2610) | :closed_lock_with_key: | GET | `/api/v3/ins-loan/repaid-history` | -| [getLoanProductInfo()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L2619) | :closed_lock_with_key: | GET | `/api/v3/ins-loan/product-infos` | -| [getLoanOrder()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L2628) | :closed_lock_with_key: | GET | `/api/v3/ins-loan/loan-order` | -| [getLoanLTVConvert()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L2637) | :closed_lock_with_key: | GET | `/api/v3/ins-loan/ltv-convert` | -| [getLoanMarginCoinInfo()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L2646) | :closed_lock_with_key: | GET | `/api/v3/ins-loan/ensure-coins-convert` | -| [bindLoanUid()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L2658) | :closed_lock_with_key: | POST | `/api/v3/ins-loan/bind-uid` | -| [getLoanCoins()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L2673) | :closed_lock_with_key: | GET | `/api/v3/loan/coins` | -| [getLoanInterest()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L2682) | :closed_lock_with_key: | GET | `/api/v3/loan/interest` | -| [loanBorrow()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L2691) | :closed_lock_with_key: | POST | `/api/v3/loan/borrow` | -| [getLoanBorrowOngoing()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L2700) | :closed_lock_with_key: | GET | `/api/v3/loan/borrow-ongoing` | -| [getLoanBorrowHistory()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L2709) | :closed_lock_with_key: | GET | `/api/v3/loan/borrow-history` | -| [loanRepay()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L2718) | :closed_lock_with_key: | POST | `/api/v3/loan/repay` | -| [getLoanRepayHistory()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L2727) | :closed_lock_with_key: | GET | `/api/v3/loan/repay-history` | -| [loanRevisePledge()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L2736) | :closed_lock_with_key: | POST | `/api/v3/loan/revise-pledge` | -| [getLoanPledgeRateHistory()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L2745) | :closed_lock_with_key: | GET | `/api/v3/loan/pledge-rate-history` | -| [getLoanDebts()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L2754) | :closed_lock_with_key: | GET | `/api/v3/loan/debts` | -| [getLoanReduces()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L2761) | :closed_lock_with_key: | GET | `/api/v3/loan/reduces` | -| [submitStrategyOrder()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L2776) | :closed_lock_with_key: | POST | `/api/v3/trade/place-strategy-order` | -| [modifyStrategyOrder()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L2785) | :closed_lock_with_key: | POST | `/api/v3/trade/modify-strategy-order` | -| [cancelStrategyOrder()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L2794) | :closed_lock_with_key: | POST | `/api/v3/trade/cancel-strategy-order` | -| [getUnfilledStrategyOrders()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L2803) | :closed_lock_with_key: | GET | `/api/v3/trade/unfilled-strategy-orders` | -| [getHistoryStrategyOrders()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L2812) | :closed_lock_with_key: | GET | `/api/v3/trade/history-strategy-orders` | -| [getStrategySubOrders()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L2822) | :closed_lock_with_key: | GET | `/api/v3/trade/strategy-sub-orders` | -| [validateGridBot()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L2837) | :closed_lock_with_key: | POST | `/api/v3/trade/grid/validate` | -| [createGridBot()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L2843) | :closed_lock_with_key: | POST | `/api/v3/trade/grid/create-bot` | -| [modifyGridBot()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L2849) | :closed_lock_with_key: | POST | `/api/v3/trade/grid/modify-bot` | -| [modifyGridInterval()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L2855) | :closed_lock_with_key: | POST | `/api/v3/trade/grid/modify-grid-interval` | -| [addGridInvestment()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L2861) | :closed_lock_with_key: | POST | `/api/v3/trade/grid/add-investment` | -| [closeGridBot()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L2867) | :closed_lock_with_key: | POST | `/api/v3/trade/grid/close-bot` | -| [getGridBotDetail()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L2873) | :closed_lock_with_key: | GET | `/api/v3/trade/grid/bot-detail` | -| [getGridBotOrderDetails()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L2879) | :closed_lock_with_key: | GET | `/api/v3/trade/grid/list-details` | -| [validateNeutralGridBot()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L2885) | :closed_lock_with_key: | POST | `/api/v3/trade/grid/validate-neutral` | -| [createNeutralGridBot()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L2891) | :closed_lock_with_key: | POST | `/api/v3/trade/grid/create-neutral-bot` | -| [modifyNeutralGridBot()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L2897) | :closed_lock_with_key: | POST | `/api/v3/trade/grid/modify-neutral-bot` | -| [modifyNeutralGridInterval()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L2903) | :closed_lock_with_key: | POST | `/api/v3/trade/grid/modify-neutral-grid-interval` | -| [getNeutralGridBotDetail()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L2912) | :closed_lock_with_key: | GET | `/api/v3/trade/grid/neutral-bot-detail` | -| [getNeutralGridBotOrderDetails()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L2918) | :closed_lock_with_key: | GET | `/api/v3/trade/grid/neutral-list-details` | -| [createBrokerSubAccount()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L2936) | :closed_lock_with_key: | POST | `/api/v3/broker/create-sub` | -| [getBrokerSubAccountList()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L2948) | :closed_lock_with_key: | GET | `/api/v3/broker/sub-list` | -| [modifyBrokerSubAccount()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L2960) | :closed_lock_with_key: | POST | `/api/v3/broker/modify-sub` | -| [brokerSubWithdrawal()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L2975) | :closed_lock_with_key: | POST | `/api/v3/broker/sub-withdrawal` | -| [getBrokerSubDepositAddress()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L2987) | :closed_lock_with_key: | POST | `/api/v3/broker/sub-deposit-address` | -| [getBrokerAllSubDepositWithdrawal()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L2999) | :closed_lock_with_key: | GET | `/api/v3/broker/all-sub-deposit-withdrawal` | -| [getBrokerCommission()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L3011) | :closed_lock_with_key: | GET | `/api/v3/broker/commission` | -| [createBrokerSubApiKey()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L3023) | :closed_lock_with_key: | POST | `/api/v3/broker/create-sub-apikey` | -| [modifyBrokerSubApiKey()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L3035) | :closed_lock_with_key: | POST | `/api/v3/broker/modify-sub-apikey` | -| [deleteBrokerSubApiKey()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L3051) | :closed_lock_with_key: | POST | `/api/v3/broker/delete-sub-apikey` | -| [getBrokerSubApiKey()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L3063) | :closed_lock_with_key: | GET | `/api/v3/broker/query-sub-apikey` | -| [getAgentCustomerList()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L3079) | :closed_lock_with_key: | GET | `/api/v3/affiliate/customer-list` | -| [getAgentCustomerAssets()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L3088) | :closed_lock_with_key: | GET | `/api/v3/affiliate/customer-asset` | -| [getAgentCustomerTradeVolume()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L3097) | :closed_lock_with_key: | GET | `/api/v3/affiliate/customer-trade-volume` | -| [getAgentCustomerDeposits()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L3106) | :closed_lock_with_key: | GET | `/api/v3/affiliate/customer-deposit` | -| [getAgentCustomerKycResult()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L3115) | :closed_lock_with_key: | GET | `/api/v3/affiliate/customer-kyc-result` | -| [getAgentCustomerCommissions()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L3124) | :closed_lock_with_key: | GET | `/api/v3/affiliate/customer-commission` | -| [getAgentSubCustomerList()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L3134) | :closed_lock_with_key: | GET | `/api/v3/affiliate/sub-customer-list` | -| [getSubAffiliateInfo()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L3143) | :closed_lock_with_key: | GET | `/api/v3/affiliate/sub-affiliate-info` | -| [getSubAffiliateCommission()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L3152) | :closed_lock_with_key: | GET | `/api/v3/affiliate/sub-affiliate-commission` | -| [modifySubaccountEmail()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L3170) | :closed_lock_with_key: | POST | `/api/v3/broker/modify-subaccount-email` | -| [getSubaccountEmail()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L3179) | :closed_lock_with_key: | GET | `/api/v3/broker/subaccount-email` | -| [getBrokerTradeVolume()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L3189) | :closed_lock_with_key: | GET | `/api/v3/broker/trade-volume` | -| [getBrokerTotalCommission()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L3198) | :closed_lock_with_key: | GET | `/api/v3/broker/total-commission` | -| [getBrokerOrderCommission()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L3207) | :closed_lock_with_key: | GET | `/api/v3/broker/order-commission` | -| [getBrokerRebateInfo()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L3216) | :closed_lock_with_key: | GET | `/api/v3/broker/rebate-info` | -| [getP2pAdList()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L3228) | :closed_lock_with_key: | GET | `/api/v3/p2p/ad-list` | -| [getP2pExchangeRate()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L3234) | :closed_lock_with_key: | GET | `/api/v3/p2p/exchange-rate` | -| [simulateP2pFee()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L3240) | :closed_lock_with_key: | POST | `/api/v3/p2p/fee-simulate` | -| [getP2pAdLimit()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L3246) | :closed_lock_with_key: | GET | `/api/v3/p2p/ad-limit` | -| [createP2pAd()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L3252) | :closed_lock_with_key: | POST | `/api/v3/p2p/ad-create` | -| [updateP2pAd()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L3258) | :closed_lock_with_key: | POST | `/api/v3/p2p/ad-update` | -| [operateP2pAd()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L3262) | :closed_lock_with_key: | POST | `/api/v3/p2p/ad-operate` | -| [getP2pAdInfo()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L3266) | :closed_lock_with_key: | GET | `/api/v3/p2p/ad-info` | -| [getP2pMyAds()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L3272) | :closed_lock_with_key: | GET | `/api/v3/p2p/my-ads` | -| [getP2pPendingOrders()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L3278) | :closed_lock_with_key: | GET | `/api/v3/p2p/pending-orders` | -| [getP2pAllOrders()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L3284) | :closed_lock_with_key: | GET | `/api/v3/p2p/all-orders` | -| [getP2pOrderInfo()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L3290) | :closed_lock_with_key: | GET | `/api/v3/p2p/order-info` | -| [confirmP2pOrderPayment()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L3296) | :closed_lock_with_key: | POST | `/api/v3/p2p/order-pay` | -| [releaseP2pOrderAsset()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L3302) | :closed_lock_with_key: | POST | `/api/v3/p2p/order-release` | -| [getP2pUserInfo()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L3308) | :closed_lock_with_key: | GET | `/api/v3/p2p/user-info` | -| [getP2pCurrencies()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L3312) | :closed_lock_with_key: | GET | `/api/v3/p2p/currencies` | -| [getP2pPayMethods()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L3316) | :closed_lock_with_key: | GET | `/api/v3/p2p/pay-method` | -| [getP2pBalance()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L3320) | :closed_lock_with_key: | GET | `/api/v3/p2p/balance` | -| [getEarnSavingsProducts()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L3335) | :closed_lock_with_key: | GET | `/api/v3/earn/savings/product` | -| [getEarnSavingsAccount()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L3344) | :closed_lock_with_key: | GET | `/api/v3/earn/savings/account` | -| [getEarnSavingsAssets()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L3351) | :closed_lock_with_key: | GET | `/api/v3/earn/savings/assets` | -| [getEarnSavingsRecords()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L3360) | :closed_lock_with_key: | GET | `/api/v3/earn/savings/records` | -| [getEarnSavingsSubscription()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L3369) | :closed_lock_with_key: | GET | `/api/v3/earn/savings/subscribe-info` | -| [earnSubscribeSavings()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L3378) | :closed_lock_with_key: | POST | `/api/v3/earn/savings/subscribe` | -| [getEarnSavingsSubscriptionResult()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L3387) | :closed_lock_with_key: | GET | `/api/v3/earn/savings/subscribe-result` | -| [earnRedeemSavings()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L3396) | :closed_lock_with_key: | POST | `/api/v3/earn/savings/redeem` | -| [getEarnSavingsRedemptionResult()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L3405) | :closed_lock_with_key: | GET | `/api/v3/earn/savings/redeem-result` | -| [getSharkfinProducts()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L3420) | :closed_lock_with_key: | GET | `/api/v3/earn/sharkfin/product` | -| [getSharkfinAccount()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L3429) | :closed_lock_with_key: | GET | `/api/v3/earn/sharkfin/account` | -| [getSharkfinAssets()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L3436) | :closed_lock_with_key: | GET | `/api/v3/earn/sharkfin/assets` | -| [getSharkfinRecords()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L3445) | :closed_lock_with_key: | GET | `/api/v3/earn/sharkfin/records` | -| [getSharkfinSubscription()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L3454) | :closed_lock_with_key: | GET | `/api/v3/earn/sharkfin/subscribe-info` | -| [subscribeSharkfin()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L3463) | :closed_lock_with_key: | POST | `/api/v3/earn/sharkfin/subscribe` | -| [getSharkfinSubscriptionResult()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L3472) | :closed_lock_with_key: | GET | `/api/v3/earn/sharkfin/subscribe-result` | -| [getEarnEliteProducts()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L3484) | :closed_lock_with_key: | GET | `/api/v3/earn/elite-product` | -| [getEarnEliteAssets()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L3488) | :closed_lock_with_key: | GET | `/api/v3/earn/elite-assets` | -| [getEarnEliteRecords()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L3492) | :closed_lock_with_key: | GET | `/api/v3/earn/elite-records` | -| [getEarnEliteSubscribeInfo()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L3498) | :closed_lock_with_key: | GET | `/api/v3/earn/elite-subscribe-info` | -| [subscribeEarnElite()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L3504) | :closed_lock_with_key: | POST | `/api/v3/earn/elite-subscribe` | -| [getEarnEliteSubscribeResult()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L3510) | :closed_lock_with_key: | GET | `/api/v3/earn/elite-subscribe-result` | -| [getEarnEliteRedeemInfo()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L3516) | :closed_lock_with_key: | GET | `/api/v3/earn/elite-redeem-info` | -| [redeemEarnElite()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L3522) | :closed_lock_with_key: | POST | `/api/v3/earn/elite-redeem` | -| [getEarnCashPlusSubscribeInfo()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L3539) | :closed_lock_with_key: | GET | `/api/v3/earn/cashplus/subscribe-info` | -| [subscribeEarnCashPlus()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L3548) | :closed_lock_with_key: | POST | `/api/v3/earn/cashplus/subscribe` | -| [getEarnCashPlusSubscribeResult()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L3557) | :closed_lock_with_key: | GET | `/api/v3/earn/cashplus/subscribe-result` | -| [getEarnCashPlusRedeemInfo()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L3567) | :closed_lock_with_key: | GET | `/api/v3/earn/cashplus/redeem-info` | -| [redeemEarnCashPlus()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L3574) | :closed_lock_with_key: | POST | `/api/v3/earn/cashplus/redeem` | -| [getEarnCashPlusRedeemResult()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L3583) | :closed_lock_with_key: | GET | `/api/v3/earn/cashplus/redeem-result` | -| [getEarnCashPlusPositions()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L3592) | :closed_lock_with_key: | GET | `/api/v3/earn/cashplus/positions` | -| [getEarnCashPlusHistoryOrders()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L3599) | :closed_lock_with_key: | GET | `/api/v3/earn/cashplus/history-orders` | +| [getTaxRecords()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L2034) | :closed_lock_with_key: | GET | `/api/v3/tax/records` | +| [createSubAccount()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L2049) | :closed_lock_with_key: | POST | `/api/v3/user/create-sub` | +| [createAgentSubAccount()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L2058) | :closed_lock_with_key: | POST | `/api/v3/user/sub-account/agent-create` | +| [freezeSubAccount()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L2067) | :closed_lock_with_key: | POST | `/api/v3/user/freeze-sub` | +| [deleteSubAccount()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L2073) | :closed_lock_with_key: | POST | `/api/v3/user/delete-sub` | +| [getSubUnifiedAssets()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L2082) | :closed_lock_with_key: | GET | `/api/v3/account/sub-unified-assets` | +| [getSubAccountList()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L2091) | :closed_lock_with_key: | GET | `/api/v3/user/sub-list` | +| [createSubAccountApiKey()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L2104) | :closed_lock_with_key: | POST | `/api/v3/user/create-sub-api` | +| [updateSubAccountApiKey()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L2113) | :closed_lock_with_key: | POST | `/api/v3/user/update-sub-api` | +| [deleteSubAccountApiKey()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L2122) | :closed_lock_with_key: | POST | `/api/v3/user/delete-sub-api` | +| [getSubAccountApiKeys()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L2131) | :closed_lock_with_key: | GET | `/api/v3/user/sub-api-list` | +| [getRateLimitQuota()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L2145) | :closed_lock_with_key: | GET | `/api/v3/user/rate-limit-quota` | +| [setRateLimitQuota()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L2156) | :closed_lock_with_key: | POST | `/api/v3/user/set-rate-limit-quota` | +| [createStpGroup()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L2166) | :closed_lock_with_key: | POST | `/api/v3/account/create-stp-groups` | +| [getStpGroups()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L2176) | :closed_lock_with_key: | GET | `/api/v3/account/stp-groups` | +| [addStpGroupMembers()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L2186) | :closed_lock_with_key: | POST | `/api/v3/account/add-groups-members` | +| [removeStpGroupMembers()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L2198) | :closed_lock_with_key: | POST | `/api/v3/account/remove-groups-members` | +| [getTransferableCoins()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L2213) | :closed_lock_with_key: | GET | `/api/v3/account/transferable-coins` | +| [submitTransfer()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L2222) | :closed_lock_with_key: | POST | `/api/v3/account/transfer` | +| [subAccountTransfer()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L2231) | :closed_lock_with_key: | POST | `/api/v3/account/sub-transfer` | +| [getSubTransferRecords()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L2243) | :closed_lock_with_key: | GET | `/api/v3/account/sub-transfer-record` | +| [subMasterTransfer()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L2255) | :closed_lock_with_key: | POST | `/api/v3/account/sub-master-transfer` | +| [getDepositAddress()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L2273) | :closed_lock_with_key: | GET | `/api/v3/account/deposit-address` | +| [getSubDepositAddress()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L2282) | :closed_lock_with_key: | GET | `/api/v3/account/sub-deposit-address` | +| [getDepositRecords()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L2291) | :closed_lock_with_key: | GET | `/api/v3/account/deposit-records` | +| [getSubDepositRecords()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L2300) | :closed_lock_with_key: | POST | `/api/v3/account/sub-deposit-records` | +| [submitWithdraw()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L2315) | :closed_lock_with_key: | POST | `/api/v3/account/withdrawal` | +| [getWithdrawRecords()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L2324) | :closed_lock_with_key: | GET | `/api/v3/account/withdrawal-records` | +| [getWithdrawAddressBook()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L2333) | :closed_lock_with_key: | GET | `/api/v3/account/withdraw-address` | +| [cancelWithdrawal()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L2342) | :closed_lock_with_key: | POST | `/api/v3/account/cancel-withdrawal` | +| [submitNewOrder()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L2360) | :closed_lock_with_key: | POST | `/api/v3/trade/place-order` | +| [modifyOrder()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L2369) | :closed_lock_with_key: | POST | `/api/v3/trade/modify-order` | +| [placeRealityOrder()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L2378) | :closed_lock_with_key: | POST | `/api/v3/trade/place-reality-order` | +| [cancelRealityOrder()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L2387) | :closed_lock_with_key: | POST | `/api/v3/trade/cancel-reality-order` | +| [getLoanData()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L2396) | :closed_lock_with_key: | GET | `/api/v3/trade/loan-data` | +| [cancelOrder()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L2403) | :closed_lock_with_key: | POST | `/api/v3/trade/cancel-order` | +| [placeBatchOrders()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L2412) | :closed_lock_with_key: | POST | `/api/v3/trade/place-batch` | +| [batchModifyOrders()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L2421) | :closed_lock_with_key: | POST | `/api/v3/trade/batch-modify-order` | +| [cancelBatchOrders()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L2430) | :closed_lock_with_key: | POST | `/api/v3/trade/cancel-batch` | +| [cancelAllOrders()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L2439) | :closed_lock_with_key: | POST | `/api/v3/trade/cancel-symbol-order` | +| [closeAllPositions()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L2448) | :closed_lock_with_key: | POST | `/api/v3/trade/close-positions` | +| [getOrderInfo()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L2457) | :closed_lock_with_key: | GET | `/api/v3/trade/order-info` | +| [getUnfilledOrders()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L2466) | :closed_lock_with_key: | GET | `/api/v3/trade/unfilled-orders` | +| [getHistoryOrders()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L2478) | :closed_lock_with_key: | GET | `/api/v3/trade/history-orders` | +| [movePositions()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L2490) | :closed_lock_with_key: | POST | `/api/v3/account/move-positions` | +| [getMovePositionHistory()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L2499) | :closed_lock_with_key: | GET | `/api/v3/account/move-position-history` | +| [getTradeFills()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L2511) | :closed_lock_with_key: | GET | `/api/v3/trade/fills` | +| [getCurrentPosition()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L2523) | :closed_lock_with_key: | GET | `/api/v3/position/current-position` | +| [getPositionHistory()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L2538) | :closed_lock_with_key: | GET | `/api/v3/position/history-position` | +| [getMaxOpenAvailable()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L2552) | :closed_lock_with_key: | POST | `/api/v3/account/max-open-available` | +| [getPositionAdlRank()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L2561) | :closed_lock_with_key: | GET | `/api/v3/position/adlRank` | +| [countdownCancelAll()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L2568) | :closed_lock_with_key: | POST | `/api/v3/trade/countdown-cancel-all` | +| [getLoanTransfered()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L2583) | :closed_lock_with_key: | GET | `/api/v3/ins-loan/transfered` | +| [getLoanSymbols()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L2592) | :closed_lock_with_key: | GET | `/api/v3/ins-loan/symbols` | +| [getLoanRiskUnit()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L2601) | :closed_lock_with_key: | GET | `/api/v3/ins-loan/risk-unit` | +| [getLoanRepaidHistory()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L2616) | :closed_lock_with_key: | GET | `/api/v3/ins-loan/repaid-history` | +| [getLoanProductInfo()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L2625) | :closed_lock_with_key: | GET | `/api/v3/ins-loan/product-infos` | +| [getLoanOrder()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L2634) | :closed_lock_with_key: | GET | `/api/v3/ins-loan/loan-order` | +| [getLoanLTVConvert()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L2643) | :closed_lock_with_key: | GET | `/api/v3/ins-loan/ltv-convert` | +| [getLoanMarginCoinInfo()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L2652) | :closed_lock_with_key: | GET | `/api/v3/ins-loan/ensure-coins-convert` | +| [bindLoanUid()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L2664) | :closed_lock_with_key: | POST | `/api/v3/ins-loan/bind-uid` | +| [getLoanCoins()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L2679) | :closed_lock_with_key: | GET | `/api/v3/loan/coins` | +| [getLoanInterest()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L2688) | :closed_lock_with_key: | GET | `/api/v3/loan/interest` | +| [loanBorrow()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L2697) | :closed_lock_with_key: | POST | `/api/v3/loan/borrow` | +| [getLoanBorrowOngoing()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L2706) | :closed_lock_with_key: | GET | `/api/v3/loan/borrow-ongoing` | +| [getLoanBorrowHistory()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L2715) | :closed_lock_with_key: | GET | `/api/v3/loan/borrow-history` | +| [loanRepay()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L2724) | :closed_lock_with_key: | POST | `/api/v3/loan/repay` | +| [getLoanRepayHistory()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L2733) | :closed_lock_with_key: | GET | `/api/v3/loan/repay-history` | +| [loanRevisePledge()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L2742) | :closed_lock_with_key: | POST | `/api/v3/loan/revise-pledge` | +| [getLoanPledgeRateHistory()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L2751) | :closed_lock_with_key: | GET | `/api/v3/loan/pledge-rate-history` | +| [getLoanDebts()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L2760) | :closed_lock_with_key: | GET | `/api/v3/loan/debts` | +| [getLoanReduces()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L2767) | :closed_lock_with_key: | GET | `/api/v3/loan/reduces` | +| [submitStrategyOrder()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L2782) | :closed_lock_with_key: | POST | `/api/v3/trade/place-strategy-order` | +| [modifyStrategyOrder()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L2791) | :closed_lock_with_key: | POST | `/api/v3/trade/modify-strategy-order` | +| [cancelStrategyOrder()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L2800) | :closed_lock_with_key: | POST | `/api/v3/trade/cancel-strategy-order` | +| [getUnfilledStrategyOrders()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L2809) | :closed_lock_with_key: | GET | `/api/v3/trade/unfilled-strategy-orders` | +| [getHistoryStrategyOrders()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L2818) | :closed_lock_with_key: | GET | `/api/v3/trade/history-strategy-orders` | +| [getStrategySubOrders()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L2828) | :closed_lock_with_key: | GET | `/api/v3/trade/strategy-sub-orders` | +| [validateGridBot()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L2843) | :closed_lock_with_key: | POST | `/api/v3/trade/grid/validate` | +| [createGridBot()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L2849) | :closed_lock_with_key: | POST | `/api/v3/trade/grid/create-bot` | +| [modifyGridBot()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L2855) | :closed_lock_with_key: | POST | `/api/v3/trade/grid/modify-bot` | +| [modifyGridInterval()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L2861) | :closed_lock_with_key: | POST | `/api/v3/trade/grid/modify-grid-interval` | +| [addGridInvestment()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L2867) | :closed_lock_with_key: | POST | `/api/v3/trade/grid/add-investment` | +| [closeGridBot()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L2873) | :closed_lock_with_key: | POST | `/api/v3/trade/grid/close-bot` | +| [getGridBotDetail()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L2879) | :closed_lock_with_key: | GET | `/api/v3/trade/grid/bot-detail` | +| [getGridBotOrderDetails()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L2885) | :closed_lock_with_key: | GET | `/api/v3/trade/grid/list-details` | +| [validateNeutralGridBot()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L2891) | :closed_lock_with_key: | POST | `/api/v3/trade/grid/validate-neutral` | +| [createNeutralGridBot()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L2897) | :closed_lock_with_key: | POST | `/api/v3/trade/grid/create-neutral-bot` | +| [modifyNeutralGridBot()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L2903) | :closed_lock_with_key: | POST | `/api/v3/trade/grid/modify-neutral-bot` | +| [modifyNeutralGridInterval()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L2909) | :closed_lock_with_key: | POST | `/api/v3/trade/grid/modify-neutral-grid-interval` | +| [getNeutralGridBotDetail()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L2918) | :closed_lock_with_key: | GET | `/api/v3/trade/grid/neutral-bot-detail` | +| [getNeutralGridBotOrderDetails()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L2924) | :closed_lock_with_key: | GET | `/api/v3/trade/grid/neutral-list-details` | +| [createBrokerSubAccount()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L2942) | :closed_lock_with_key: | POST | `/api/v3/broker/create-sub` | +| [getBrokerSubAccountList()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L2954) | :closed_lock_with_key: | GET | `/api/v3/broker/sub-list` | +| [modifyBrokerSubAccount()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L2966) | :closed_lock_with_key: | POST | `/api/v3/broker/modify-sub` | +| [brokerSubWithdrawal()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L2981) | :closed_lock_with_key: | POST | `/api/v3/broker/sub-withdrawal` | +| [getBrokerSubDepositAddress()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L2993) | :closed_lock_with_key: | POST | `/api/v3/broker/sub-deposit-address` | +| [getBrokerAllSubDepositWithdrawal()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L3005) | :closed_lock_with_key: | GET | `/api/v3/broker/all-sub-deposit-withdrawal` | +| [getBrokerCommission()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L3017) | :closed_lock_with_key: | GET | `/api/v3/broker/commission` | +| [createBrokerSubApiKey()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L3029) | :closed_lock_with_key: | POST | `/api/v3/broker/create-sub-apikey` | +| [modifyBrokerSubApiKey()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L3041) | :closed_lock_with_key: | POST | `/api/v3/broker/modify-sub-apikey` | +| [deleteBrokerSubApiKey()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L3057) | :closed_lock_with_key: | POST | `/api/v3/broker/delete-sub-apikey` | +| [getBrokerSubApiKey()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L3069) | :closed_lock_with_key: | GET | `/api/v3/broker/query-sub-apikey` | +| [getAgentCustomerList()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L3085) | :closed_lock_with_key: | GET | `/api/v3/affiliate/customer-list` | +| [getAgentCustomerAssets()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L3094) | :closed_lock_with_key: | GET | `/api/v3/affiliate/customer-asset` | +| [getAgentCustomerTradeVolume()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L3103) | :closed_lock_with_key: | GET | `/api/v3/affiliate/customer-trade-volume` | +| [getAgentCustomerDeposits()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L3112) | :closed_lock_with_key: | GET | `/api/v3/affiliate/customer-deposit` | +| [getAgentCustomerKycResult()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L3121) | :closed_lock_with_key: | GET | `/api/v3/affiliate/customer-kyc-result` | +| [getAgentCustomerCommissions()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L3130) | :closed_lock_with_key: | GET | `/api/v3/affiliate/customer-commission` | +| [getAgentSubCustomerList()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L3140) | :closed_lock_with_key: | GET | `/api/v3/affiliate/sub-customer-list` | +| [getSubAffiliateInfo()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L3149) | :closed_lock_with_key: | GET | `/api/v3/affiliate/sub-affiliate-info` | +| [getSubAffiliateCommission()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L3158) | :closed_lock_with_key: | GET | `/api/v3/affiliate/sub-affiliate-commission` | +| [modifySubaccountEmail()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L3176) | :closed_lock_with_key: | POST | `/api/v3/broker/modify-subaccount-email` | +| [getSubaccountEmail()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L3185) | :closed_lock_with_key: | GET | `/api/v3/broker/subaccount-email` | +| [getBrokerTradeVolume()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L3195) | :closed_lock_with_key: | GET | `/api/v3/broker/trade-volume` | +| [getBrokerTotalCommission()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L3204) | :closed_lock_with_key: | GET | `/api/v3/broker/total-commission` | +| [getBrokerOrderCommission()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L3213) | :closed_lock_with_key: | GET | `/api/v3/broker/order-commission` | +| [getBrokerRebateInfo()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L3222) | :closed_lock_with_key: | GET | `/api/v3/broker/rebate-info` | +| [getP2pAdList()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L3234) | :closed_lock_with_key: | GET | `/api/v3/p2p/ad-list` | +| [getP2pExchangeRate()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L3240) | :closed_lock_with_key: | GET | `/api/v3/p2p/exchange-rate` | +| [simulateP2pFee()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L3246) | :closed_lock_with_key: | POST | `/api/v3/p2p/fee-simulate` | +| [getP2pAdLimit()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L3252) | :closed_lock_with_key: | GET | `/api/v3/p2p/ad-limit` | +| [createP2pAd()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L3258) | :closed_lock_with_key: | POST | `/api/v3/p2p/ad-create` | +| [updateP2pAd()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L3264) | :closed_lock_with_key: | POST | `/api/v3/p2p/ad-update` | +| [operateP2pAd()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L3268) | :closed_lock_with_key: | POST | `/api/v3/p2p/ad-operate` | +| [getP2pAdInfo()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L3272) | :closed_lock_with_key: | GET | `/api/v3/p2p/ad-info` | +| [getP2pMyAds()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L3278) | :closed_lock_with_key: | GET | `/api/v3/p2p/my-ads` | +| [getP2pPendingOrders()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L3284) | :closed_lock_with_key: | GET | `/api/v3/p2p/pending-orders` | +| [getP2pAllOrders()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L3290) | :closed_lock_with_key: | GET | `/api/v3/p2p/all-orders` | +| [getP2pOrderInfo()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L3296) | :closed_lock_with_key: | GET | `/api/v3/p2p/order-info` | +| [confirmP2pOrderPayment()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L3302) | :closed_lock_with_key: | POST | `/api/v3/p2p/order-pay` | +| [releaseP2pOrderAsset()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L3308) | :closed_lock_with_key: | POST | `/api/v3/p2p/order-release` | +| [getP2pUserInfo()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L3314) | :closed_lock_with_key: | GET | `/api/v3/p2p/user-info` | +| [getP2pCurrencies()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L3318) | :closed_lock_with_key: | GET | `/api/v3/p2p/currencies` | +| [getP2pPayMethods()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L3322) | :closed_lock_with_key: | GET | `/api/v3/p2p/pay-method` | +| [getP2pBalance()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L3326) | :closed_lock_with_key: | GET | `/api/v3/p2p/balance` | +| [getEarnSavingsProducts()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L3341) | :closed_lock_with_key: | GET | `/api/v3/earn/savings/product` | +| [getEarnSavingsAccount()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L3350) | :closed_lock_with_key: | GET | `/api/v3/earn/savings/account` | +| [getEarnSavingsAssets()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L3357) | :closed_lock_with_key: | GET | `/api/v3/earn/savings/assets` | +| [getEarnSavingsRecords()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L3366) | :closed_lock_with_key: | GET | `/api/v3/earn/savings/records` | +| [getEarnSavingsSubscription()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L3375) | :closed_lock_with_key: | GET | `/api/v3/earn/savings/subscribe-info` | +| [earnSubscribeSavings()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L3384) | :closed_lock_with_key: | POST | `/api/v3/earn/savings/subscribe` | +| [getEarnSavingsSubscriptionResult()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L3393) | :closed_lock_with_key: | GET | `/api/v3/earn/savings/subscribe-result` | +| [earnRedeemSavings()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L3402) | :closed_lock_with_key: | POST | `/api/v3/earn/savings/redeem` | +| [getEarnSavingsRedemptionResult()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L3411) | :closed_lock_with_key: | GET | `/api/v3/earn/savings/redeem-result` | +| [getSharkfinProducts()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L3426) | :closed_lock_with_key: | GET | `/api/v3/earn/sharkfin/product` | +| [getSharkfinAccount()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L3435) | :closed_lock_with_key: | GET | `/api/v3/earn/sharkfin/account` | +| [getSharkfinAssets()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L3442) | :closed_lock_with_key: | GET | `/api/v3/earn/sharkfin/assets` | +| [getSharkfinRecords()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L3451) | :closed_lock_with_key: | GET | `/api/v3/earn/sharkfin/records` | +| [getSharkfinSubscription()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L3460) | :closed_lock_with_key: | GET | `/api/v3/earn/sharkfin/subscribe-info` | +| [subscribeSharkfin()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L3469) | :closed_lock_with_key: | POST | `/api/v3/earn/sharkfin/subscribe` | +| [getSharkfinSubscriptionResult()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L3478) | :closed_lock_with_key: | GET | `/api/v3/earn/sharkfin/subscribe-result` | +| [getEarnEliteProducts()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L3490) | :closed_lock_with_key: | GET | `/api/v3/earn/elite-product` | +| [getEarnEliteAssets()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L3494) | :closed_lock_with_key: | GET | `/api/v3/earn/elite-assets` | +| [getEarnEliteRecords()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L3498) | :closed_lock_with_key: | GET | `/api/v3/earn/elite-records` | +| [getEarnEliteSubscribeInfo()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L3504) | :closed_lock_with_key: | GET | `/api/v3/earn/elite-subscribe-info` | +| [subscribeEarnElite()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L3510) | :closed_lock_with_key: | POST | `/api/v3/earn/elite-subscribe` | +| [getEarnEliteSubscribeResult()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L3516) | :closed_lock_with_key: | GET | `/api/v3/earn/elite-subscribe-result` | +| [getEarnEliteRedeemInfo()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L3522) | :closed_lock_with_key: | GET | `/api/v3/earn/elite-redeem-info` | +| [redeemEarnElite()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L3528) | :closed_lock_with_key: | POST | `/api/v3/earn/elite-redeem` | +| [getEarnCashPlusSubscribeInfo()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L3545) | :closed_lock_with_key: | GET | `/api/v3/earn/cashplus/subscribe-info` | +| [subscribeEarnCashPlus()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L3554) | :closed_lock_with_key: | POST | `/api/v3/earn/cashplus/subscribe` | +| [getEarnCashPlusSubscribeResult()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L3563) | :closed_lock_with_key: | GET | `/api/v3/earn/cashplus/subscribe-result` | +| [getEarnCashPlusRedeemInfo()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L3573) | :closed_lock_with_key: | GET | `/api/v3/earn/cashplus/redeem-info` | +| [redeemEarnCashPlus()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L3580) | :closed_lock_with_key: | POST | `/api/v3/earn/cashplus/redeem` | +| [getEarnCashPlusRedeemResult()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L3589) | :closed_lock_with_key: | GET | `/api/v3/earn/cashplus/redeem-result` | +| [getEarnCashPlusPositions()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L3598) | :closed_lock_with_key: | GET | `/api/v3/earn/cashplus/positions` | +| [getEarnCashPlusHistoryOrders()](https://github.com/sieblyio/bitget-api/blob/master/src/rest-client-v3.ts#L3605) | :closed_lock_with_key: | GET | `/api/v3/earn/cashplus/history-orders` | # websocket-api-client.ts @@ -703,8 +703,8 @@ This client provides WebSocket API endpoints which allow for faster interactions | Function | AUTH | HTTP Method | Endpoint | | -------- | :------: | :------: | -------- | | [submitNewOrder()](https://github.com/sieblyio/bitget-api/blob/master/src/websocket-api-client.ts#L85) | | WS | `place-order` | -| [placeBatchOrders()](https://github.com/sieblyio/bitget-api/blob/master/src/websocket-api-client.ts#L104) | | WS | `batch-place` | -| [cancelOrder()](https://github.com/sieblyio/bitget-api/blob/master/src/websocket-api-client.ts#L128) | | WS | `cancel-order` | -| [cancelBatchOrders()](https://github.com/sieblyio/bitget-api/blob/master/src/websocket-api-client.ts#L147) | | WS | `batch-cancel` | -| [updateOrder()](https://github.com/sieblyio/bitget-api/blob/master/src/websocket-api-client.ts#L159) | | WS | `modify-order` | -| [batchUpdateOrders()](https://github.com/sieblyio/bitget-api/blob/master/src/websocket-api-client.ts#L171) | | WS | `batch-modify` | \ No newline at end of file +| [placeBatchOrders()](https://github.com/sieblyio/bitget-api/blob/master/src/websocket-api-client.ts#L106) | | WS | `batch-place` | +| [cancelOrder()](https://github.com/sieblyio/bitget-api/blob/master/src/websocket-api-client.ts#L132) | | WS | `cancel-order` | +| [cancelBatchOrders()](https://github.com/sieblyio/bitget-api/blob/master/src/websocket-api-client.ts#L151) | | WS | `batch-cancel` | +| [updateOrder()](https://github.com/sieblyio/bitget-api/blob/master/src/websocket-api-client.ts#L163) | | WS | `modify-order` | +| [batchUpdateOrders()](https://github.com/sieblyio/bitget-api/blob/master/src/websocket-api-client.ts#L175) | | WS | `batch-modify` | \ No newline at end of file diff --git a/llms.txt b/llms.txt index e024904e..d95f9852 100644 --- a/llms.txt +++ b/llms.txt @@ -441,6 +441,247 @@ import { RestClientV2 } from '../../../src/index.js'; // or // import { RestClientV2 } from 'bitget-api'; +================ +File: examples/V2 - Classic/Rest/rest-trade-futures.ts +================ +import { + FuturesPlaceOrderRequestV2, + RestClientV2, + WebsocketClientV2, +} from '../../../src/index.js'; +⋮---- +// or +// import { FuturesPlaceOrderRequestV2, RestClientV2, WebsocketClientV2 } from '../src'; +⋮---- +// read from environmental variables +⋮---- +// If running from CLI in unix, you can pass env vars as such: +// API_KEY_COM='lkm12n3-2ba3-1mxf-fn13-lkm12n3a' API_SECRET_COM='035B2B9637E1BDFFEE2646BFBDDB8CE4' API_PASSPHRASE_COM='ComplexPa$$!23$5^' ts-node examples/rest-trade-futures.ts +⋮---- +// note the single quotes, preventing special characters such as $ from being incorrectly passed +⋮---- +// apiKey: 'apiKeyHere', +// apiSecret: 'apiSecretHere', +// apiPass: 'apiPassHere', +⋮---- +function logWSEvent(type: string, data: any) +⋮---- +// simple sleep function +function promiseSleep(milliseconds: number) +⋮---- +/** + * This is a simple script wrapped in a immediately invoked function expression (to execute the below workflow immediately). + * + * It is designed to: + * - open a private websocket channel to log account events + * - check for any available USDT balance in the futures account + * - immediately open a minimum sized long position on BTCUSDT + * - check active positions + * - immediately send closing orders for any active futures positions + * - check positions again + * + */ +⋮---- +// Add event listeners to log websocket events on account +⋮---- +// futures private +// : account updates +⋮---- +// : position updates +⋮---- +// : order updates +⋮---- +// wait briefly for ws to be ready (could also use the response or authenticated events, to make sure topics are subscribed to before starting) +⋮---- +// const balances = allBalances.filter((bal) => Number(bal.available) != 0); +⋮---- +// Loop through any active positions and send a closing market order on each position + +================ +File: examples/V2 - Classic/Rest/rest-trade-spot.ts +================ +import { + RestClientV2, + SpotOrderRequestV2, + WebsocketClientV2, +} from '../../../src/index.js'; +⋮---- +// import { RestClientV2, WebsocketClient } from '../src/index'; +⋮---- +// read from environmental variables +⋮---- +// If running from CLI in unix, you can pass env vars as such: +// API_KEY_COM='lkm12n3-2ba3-1mxf-fn13-lkm12n3a' API_SECRET_COM='035B2B9637E1BDFFEE2646BFBDDB8CE4' API_PASSPHRASE_COM='ComplexPa$$!23$5^' ts-node examples/rest-trade-spot.ts +⋮---- +// note the single quotes, preventing special characters such as $ from being incorrectly passed +⋮---- +// apiKey: 'apiKeyHere', +// apiSecret: 'apiSecretHere', +// apiPass: 'apiPassHere', +⋮---- +function logWSEvent(type: string, data: any) +⋮---- +// simple sleep function +function promiseSleep(milliseconds: number) +⋮---- +/** This is a simple script wrapped in a immediately invoked function expression, designed to check for any available BTC balance and immediately sell the full amount for USDT */ +⋮---- +// Add event listeners to log websocket events on account +⋮---- +// Subscribe to private account topics +// spot private +// : account updates +⋮---- +// : order updates (note: symbol is required) +⋮---- +// wait briefly for ws to be ready (could also use the response or authenticated events, to make sure topics are subscribed to before starting) +⋮---- +// console.log('balance: ', JSON.stringify(balances, null, 2)); + +================ +File: examples/V2 - Classic/Websocket/ws-demo-trading.ts +================ +import { DefaultLogger, WebsocketClientV2 } from '../../../src/index.js'; +⋮---- +// or +// import { DefaultLogger, WS_KEY_MAP, WebsocketClientV2 } from 'bitget-api'; +⋮---- +// If running from CLI in unix, you can pass env vars as such: +// API_KEY_COM='lkm12n3-2ba3-1mxf-fn13-lkm12n3a' API_SECRET_COM='035B2B9637E1BDFFEE2646BFBDDB8CE4' API_PASSPHRASE_COM='ComplexPa$$!23$5^' ts-node examples/ws-private.ts +⋮---- +// restOptions: { +// optionally provide rest options, e.g. to pass through a proxy +// }, +⋮---- +// Set demoTrading to true, to route all connections to the demo trading wss URLs: +⋮---- +// If using private topics, make sure to include API keys +⋮---- +// console.log('WS raw message received ', JSON.stringify(data, null, 2)); +⋮---- +/** + * Public events + */ + +================ +File: examples/V2 - Classic/Websocket/ws-private.ts +================ +import { DefaultLogger, WebsocketClientV2 } from '../../../src/index.js'; +⋮---- +// or +// import { DefaultLogger, WS_KEY_MAP, WebsocketClientV2 } from 'bitget-api'; +⋮---- +// If running from CLI in unix, you can pass env vars as such: +// API_KEY_COM='lkm12n3-2ba3-1mxf-fn13-lkm12n3a' API_SECRET_COM='035B2B9637E1BDFFEE2646BFBDDB8CE4' API_PASSPHRASE_COM='ComplexPa$$!23$5^' ts-node examples/ws-private.ts +⋮---- +// note the single quotes, preventing special characters such as $ from being incorrectly passed +⋮---- +// restOptions: { +// optionally provide rest options, e.g. to pass through a proxy +// }, +⋮---- +// console.log('WS raw message received ', JSON.stringify(data, null, 2)); +⋮---- +// auth happens async after the ws connection opens +⋮---- +// wsClient.subscribePublicSpotTickers(['BTCUSDT', 'LTCUSDT']); +⋮---- +/** + * Private account updates + */ +⋮---- +// spot private +// : account updates +⋮---- +// : order updates (note: symbol is required) +// wsClient.subscribeTopic('SPOT', 'orders', 'BTCUSDT'); +⋮---- +// futures private +// : account updates +⋮---- +// : position updates +// wsClient.subscribeTopic('USDT-FUTURES', 'positions'); +⋮---- +// : order updates +// wsClient.subscribeTopic('USDT-FUTURES', 'orders'); +⋮---- +// : plan order updates +// wsClient.subscribeTopic('USDT-FUTURES', 'orders-algo'); +⋮---- +// wsClient +// .getWsStore() +// .getKeys() +// .forEach((wsKey) => { +// const state = wsClient.getWsStore().get(wsKey); +// console.log(`${wsKey} state: `, state.subscribedTopics.values()); +// }); +⋮---- +// setTimeout(() => { +// wsClient.unsubscribeTopic('USDT-FUTURES', 'account'); +// }, 1000 * 2); +⋮---- +// setTimeout(() => { +// wsClient +// .getWsStore() +// .getKeys() +// .forEach((wsKey) => { +// const state = wsClient.getWsStore().get(wsKey); +// console.log(`${wsKey} state: `, state.subscribedTopics.values()); +// }); +// }, 1000 * 5); + +================ +File: examples/V2 - Classic/Websocket/ws-public.ts +================ +import { + DefaultLogger, + WebsocketClientV2, + WS_KEY_MAP, +} from '../../../src/index.js'; +⋮---- +// or +// import { DefaultLogger, WS_KEY_MAP, WebsocketClientV2 } from 'bitget-api'; +⋮---- +// restOptions: { +// optionally provide rest options, e.g. to pass through a proxy +// }, +⋮---- +// console.log('WS raw message received ', JSON.stringify(data, null, 2)); +⋮---- +/** + * Public events + */ +⋮---- +// Spot public +⋮---- +// tickers +⋮---- +// candles +// wsClient.subscribeTopic('SPOT', 'candle1m', symbol); +⋮---- +// orderbook updates +// wsClient.subscribeTopic('SPOT', 'books', symbol); +⋮---- +// trades +// wsClient.subscribeTopic('SPOT', 'trade', symbol); +⋮---- +// Futures public +⋮---- +// tickers +// wsClient.subscribeTopic('USDT-FUTURES', 'ticker', symbol); +⋮---- +// candles +// wsClient.subscribeTopic('USDT-FUTURES', 'candle1m', symbol); +⋮---- +// orderbook updates +// wsClient.subscribeTopic('USDT-FUTURES', 'books', symbol); +⋮---- +// trades +// wsClient.subscribeTopic('USDT-FUTURES', 'trade', symbol); +⋮---- +// Topics are tracked per websocket type +// Get a list of subscribed topics (e.g. all public topics) (after a 5 second delay) + ================ File: examples/V3 - UTA/Rest/rest-private.ts ================ @@ -479,1166 +720,842 @@ import { RestClientV3 } from '../../../src/index.js'; // import { RestClientV3 } from 'bitget-api'; ================ -File: examples/README.md +File: examples/V3 - UTA/Rest/rest-trade-UTA-futures.ts ================ -# Examples - -These samples can be executed using `ts-node`: - -``` -ts-node ./examples/rest-spot-public.ts -``` - -Samples that require authentication can be edited directly but also support environmental variables. E.g. on mac/unix: - -``` -API_KEY_COM='yourkeyhere' API_SECRET_COM='yoursecrethere' API_PASS_COM='yourapipasshere' ts-node examples/rest-trade-futures.ts -``` - -They can also be converted to JavaScript by changing the imports to require & removing any type annotations. - -## V3 / Unified Trading Account (UTA) - -These newer examples are for Bitget's V3 APIs and WebSockets. They can be found in the examples/V3 folder. - -Refer to the V3 / UTA API documentation for more information on the V3 APIs: -https://www.bitget.com/api-doc/uta/intro - -These APIs require your account to be upgraded to the Unified Trading Account, if you plan on using the account-level REST APIs and WebSockets. Once upgraded, the V2 APIs are no longer available to you, unless you revert back to Classic Account mode. - -### WebSocket API (WS API) - -The V3/UTA API introduces order placement via a persisted WebSocket connection. This Bitget Node.js, JavaScript & TypeScript SDK supports Bitget's full V3 API offering, including the WebSocket API. - -There are two approaches to placing orders via the Bitget WebSocket APIs - -#### WebsocketAPIClient (recommended) - -This integration looks & feels like a REST API client, but uses WebSockets, via the WebsocketClient's sendWSAPIRequest method. It returns promises and has end to end types. - -This is the recommended approach to easily start sending orders via an automatically persisted WebSocket connection. A simple example is below, but for a more thorough example, check the example here: [./V3/ws-api-client-trade.ts](./V3/ws-api-client-trade.ts) - -```typescript -import { WebsocketAPIClient } from 'bitget-api'; -// or if you prefer require: -// const { WebsocketAPIClient } = require("bitget-api"); - -// Make an instance of the WS API Client class with your API keys -const wsClient = new WebsocketAPIClient({ - apiKey: API_KEY, - apiSecret: API_SECRET, - apiPass: API_PASS, - - // Whether to use the demo trading wss connection - // demoTrading: true, -}); - -async function start() { - // Start using it like a REST API. All actions are sent via a persisted WebSocket connection. - - /** - * Place Order - * https://www.bitget.com/api-doc/uta/websocket/private/Place-Order-Channel#request-parameters - */ - try { - const res = await wsClient.submitNewOrder('spot', { - orderType: 'limit', - price: '100', - qty: '0.1', - side: 'buy', - symbol: 'BTCUSDT', - timeInForce: 'gtc', - }); - - console.log(new Date(), 'WS API "submitNewOrder()" result: ', res); - } catch (e) { - console.error(new Date(), 'Exception with WS API "submitNewOrder()": ', e); - } -} - -start().catch((e) => console.error('Exception in example: '.e)); -``` - -#### ws.sendWSAPIRequest(wsKey, command, category, operation) - -This is the "raw" integration within the existing WebSocket client. It uses an automatically persisted & authenticated connection to send events through Bitget's WebSocket API. It automatically tracks and connects outgoing requests with incoming responses, and returns promises that resolve/reject when a matching response is received. - -Refer to [V3/ws-api-trade-raw.ts](./V3/ws-api-trade-raw.ts) to see an example. - -Note: The WebsocketClient is built around this. For a more user friendly experience, it is recommended to use the WebsocketClient for WS API requests. It uses this method but has the convenience of behaving similar to a REST API (while all communication automatically happens over a persisted WebSocket connection). - -## V2 - -These examples are for Bitget's V2 APIs and WebSockets. They can be found in the examples/V2 folder. - -Refer to the V2 API documentation for more information on the V2 APIs: -https://www.bitget.com/api-doc/common/intro - -================ -File: src/types/request/v2/copytrading.ts -================ -/** - * - * - * Copy Trading | Future copy trading | Trader Api - * - * - */ +/* eslint-disable @typescript-eslint/no-unused-vars */ +import { + PlaceOrderRequestV3, + RestClientV3, + WebsocketClientV3, +} from '../../../src/index.js'; ⋮---- -export type CopyTradingProductTypeV2 = - | 'USDT-FUTURES' - | 'COIN-FUTURES' - | 'USDC-FUTURES'; +// or +// import { PlaceOrderRequestV3, RestClientV3, WebsocketClientV3 } from '../src'; ⋮---- -export interface GetFuturesTraderCurrentOrdersRequestV2 { - symbol?: string; - productType: CopyTradingProductTypeV2; - startTime?: string; - endTime?: string; - limit?: string; - idGreaterThan?: string; - idLessThan?: string; -} +// read from environmental variables ⋮---- -export interface GetFuturesTraderHistoryOrdersRequestV2 { - idLessThan?: string; - idGreaterThan?: string; - startTime?: string; - endTime?: string; - limit?: string; - order?: 'asc' | 'desc'; - symbol?: string; - productType: CopyTradingProductTypeV2; -} +// If running from CLI in unix, you can pass env vars as such: +// API_KEY_COM='lkm12n3-2ba3-1mxf-fn13-lkm12n3a' API_SECRET_COM='035B2B9637E1BDFFEE2646BFBDDB8CE4' API_PASSPHRASE_COM='ComplexPa$$!23$5^' ts-node examples/V3/rest-trade-futures.ts ⋮---- -export interface ModifyFuturesTraderOrderTPSLRequestV2 { - trackingNo: string; - productType: CopyTradingProductTypeV2; - stopSurplusPrice?: string; - stopLossPrice?: string; -} +// note the single quotes, preventing special characters such as $ from being incorrectly passed ⋮---- -export interface GetFuturesTraderProfitShareDetailRequestV2 { - coin?: string; - idLessThan?: string; - idGreaterThan?: string; - startTime?: string; - endTime?: string; - limit?: string; -} +// apiKey: 'apiKeyHere', +// apiSecret: 'apiSecretHere', +// apiPass: 'apiPassHere', ⋮---- -export interface FuturesTraderSymbolSettingRequestV2 { - symbol: string; - productType: CopyTradingProductTypeV2; - settingType: 'ADD' | 'DELETE' | 'UPDATE'; - stopSurplusRatio?: string; - stopLossRatio?: string; -} +function logWSEvent(type: string, data: any) ⋮---- -export interface GetFuturesTraderFollowersRequestV2 { - pageNo?: string; - pageSize?: string; - startTime?: string; - endTime?: string; -} +// simple sleep function +function promiseSleep(milliseconds: number) ⋮---- /** + * This is a simple script wrapped in a immediately invoked function expression (to execute the below workflow immediately). * - * - * Copy Trading | Future copy trading | Follower Api - * + * It is designed to: + * - open a private websocket channel to log account events + * - check for any available USDT balance in the account + * - immediately open a minimum sized long position on BTCUSDT + * - check active positions + * - immediately send closing orders for any active futures positions + * - check positions again * */ ⋮---- -export interface GetFollowerFuturesCurrentTrackingOrdersRequestV2 { - idLessThan?: string; - idGreaterThan?: string; - startTime?: string; - endTime?: string; - limit?: string; - symbol?: string; - productType: CopyTradingProductTypeV2; - traderId?: string; -} +// Add event listeners to log websocket events on account ⋮---- -export interface GetFollowerFuturesHistoryTrackingOrdersRequestV2 { - idLessThan?: string; - idGreaterThan?: string; - startTime?: string; - endTime?: string; - limit?: string; - symbol?: string; - productType: CopyTradingProductTypeV2; - traderId?: string; -} +// Subscribe to private topics for UTA account ⋮---- -export interface UpdateFuturesFollowerTPSLRequestV2 { - trackingNo: string; - symbol?: string; - productType: CopyTradingProductTypeV2; - stopSurplusPrice?: string; - stopLossPrice?: string; -} +// Subscribe to position updates ⋮---- -export type AutoCopyOption = 'on' | 'off'; -export type FollowMode = 'basic' | 'advanced'; -export type LeverageType = 'position' | 'specify' | 'trader'; -export type TraceType = 'percent' | 'amount' | 'count'; +// Subscribe to order updates ⋮---- -export interface FollowerCopyTradeSettingRequestV2 { - symbol: string; - productType: CopyTradingProductTypeV2; - marginType: 'trader' | 'specify'; - marginCoin?: string; - leverType: LeverageType; - longLeverage?: string; - shortLeverage?: string; - traceType: TraceType; - traceValue: string; - maxHoldSize?: string; - stopSurplusRatio?: string; - stopLossRatio?: string; -} +// wait briefly for ws to be ready (could also use the response or authenticated events, to make sure topics are subscribed to before starting) ⋮---- -export interface UpdateFuturesFollowerSettingsRequestV2 { - traderId: string; - autoCopy?: AutoCopyOption; - mode?: FollowMode; - settings: FollowerCopyTradeSettingRequestV2[]; -} -export interface CloseFuturesFollowerPositionsRequestV2 { - productType: CopyTradingProductTypeV2; - trackingNo?: string; - symbol?: string; - marginCoin?: string; - marginMode?: 'isolated' | 'cross'; - holdSide?: 'long' | 'short'; -} +// Loop through any active positions and send a closing market order on each position + +================ +File: examples/V3 - UTA/Rest/rest-trade-UTA-spot.ts +================ +/* eslint-disable @typescript-eslint/no-unused-vars */ +import { + PlaceOrderRequestV3, + RestClientV3, + WebsocketClientV3, +} from '../../../src/index.js'; ⋮---- -export interface GetFuturesFollowerTradersRequestV2 { - startTime?: string; - endTime?: string; - pageNo?: string; - pageSize?: string; -} +// import { RestClientV3, WebsocketClientV3 } from '../src/index'; ⋮---- -/** - * - * - * Copy Trading | Spot copy trading | Trader api - * - * - */ +// read from environmental variables ⋮---- -export interface GetSpotTraderHistoryProfitRequestV2 { - idLessThan?: string; - idGreaterThan?: string; - startTime?: string; - endTime?: string; - limit?: string; - coin?: string; -} +// If running from CLI in unix, you can pass env vars as such: +// API_KEY_COM='lkm12n3-2ba3-1mxf-fn13-lkm12n3a' API_SECRET_COM='035B2B9637E1BDFFEE2646BFBDDB8CE4' API_PASSPHRASE_COM='ComplexPa$$!23$5^' ts-node examples/V3/rest-trade-spot.ts ⋮---- -export interface GetSpotTraderHistoryOrdersRequestV2 { - idLessThan?: string; - idGreaterThan?: string; - startTime?: string; - endTime?: string; - limit?: string; - symbol?: string; -} +// note the single quotes, preventing special characters such as $ from being incorrectly passed ⋮---- -export interface GetSpotTraderCurrentOrdersRequestV2 { - symbol?: string; - idLessThan?: string; - idGreaterThan?: string; - startTime?: string; - endTime?: string; - limit?: string; -} +// apiKey: 'apiKeyHere', +// apiSecret: 'apiSecretHere', +// apiPass: 'apiPassHere', ⋮---- -export interface GetSpotTraderFollowersRequestV2 { - pageNo?: string; - pageSize?: string; - startTime?: string; - endTime?: string; -} +function logWSEvent(type: string, data: any) ⋮---- -/** - * - * - * Copy Trading | Spot copy trading | Follower api - * - * - */ +// simple sleep function +function promiseSleep(milliseconds: number) ⋮---- -export interface SpotFollowerCopyTradeSettingV2 { - symbol: string; - traceType: 'percent' | 'amount' | 'count'; - maxHoldSize: string; - traceValue: string; - stopLossRatio?: string; - stopSurplusRatio?: string; -} +/** This is a simple script wrapped in a immediately invoked function expression, designed to check for any available BTC balance and immediately sell the full amount for USDT */ ⋮---- -export interface GetSpotFollowerHistoryOrdersRequestV2 { - symbol?: string; - traderId?: string; - idLessThan?: string; - idGreaterThan?: string; - startTime?: string; - endTime?: string; - limit?: string; -} +// Add event listeners to log websocket events on account ⋮---- -export interface GetSpotFollowerOpenOrdersRequestV2 { - symbol?: string; - traderId?: string; - idLessThan?: string; - idGreaterThan?: string; - startTime?: string; - endTime?: string; - limit?: string; -} +// Subscribe to private account topics +// Account updates for UTA (unified trading account) +⋮---- +// Order updates for spot +⋮---- +// wait briefly for ws to be ready (could also use the response or authenticated events, to make sure topics are subscribed to before starting) ================ -File: src/types/request/v2/margin.ts +File: examples/V3 - UTA/Websocket/ws-private.ts ================ -/** - * - * * Margin | Cross/Isolated | Order Record - * - */ -⋮---- -export interface GetBorrowHistoryRequestV2 { - loanId?: string; - coin?: string; - startTime: string; - endTime?: string; - limit?: string; - idLessThan?: string; -} -⋮---- -export interface GetRepayHistoryRequestV2 { - repayId?: string; - coin?: string; - startTime: string; - endTime?: string; - limit?: string; - idLessThan?: string; -} -⋮---- -export interface GetInterestHistoryRequestV2 { - coin?: string; - startTime: string; - endTime?: string; - limit?: string; - idLessThan?: string; -} +import { + DefaultLogger, + WebsocketClientV3, + WS_KEY_MAP, +} from '../../../src/index.js'; ⋮---- -export interface GetLiquidationHistoryRequestV2 { - startTime: string; - endTime?: string; - limit?: string; - idLessThan?: string; -} +// or +// import { DefaultLogger, WS_KEY_MAP, WebsocketClientV2 } from 'bitget-api'; ⋮---- -export interface GetFinancialHistoryRequestV2 { - marginType?: string; - coin?: string; - startTime: string; - endTime?: string; - limit?: string; - idLessThan?: string; -} +// If running from CLI in unix, you can pass env vars as such: +// API_KEY_COM='lkm12n3-2ba3-1mxf-fn13-lkm12n3a' API_SECRET_COM='035B2B9637E1BDFFEE2646BFBDDB8CE4' API_PASSPHRASE_COM='ComplexPa$$!23$5^' ts-node examples/ws-private.ts ⋮---- -/** - * - * * Margin | Cross/Isolated | Account - * - */ +// console.log('WS raw message received ', JSON.stringify(data, null, 2)); ⋮---- -/** - * - * * Margin | Cross/Isolated | Trade - * - */ +// You can subscribe to one topic at a time ⋮---- -export type MarginOrderTypeV2 = 'limit' | 'market'; +instType: 'UTA', // Note: all account events go on the UTA instType ⋮---- -export type MarginLoanTypeV2 = - | 'normal' - | 'autoLoan' - | 'autoRepay' - | 'autoLoanAndRepay'; +WS_KEY_MAP.v3Private, // This parameter points to private or public ⋮---- -export type MarginTimeInForceV2 = 'gtc' | 'post_only' | 'fok' | 'ioc'; +// Note: all account events go on the UTA instType ⋮---- -export type MarginOrderSideV2 = 'buy' | 'sell'; +// Or multiple at once: ⋮---- -export type MarginSTPModeV2 = - | 'none' - | 'cancel_taker' - | 'cancel_maker' - | 'cancel_both'; +// Topics are tracked per websocket type +// The below example will pull a list of subscribed topics on that connection (e.g. all private topics), after a 5 second delay: + +================ +File: examples/V3 - UTA/Websocket/ws-public.ts +================ +import { + DefaultLogger, + WebsocketClientV3, + WS_KEY_MAP, +} from '../../../src/index.js'; ⋮---- -export interface MarginPlaceOrderRequestV2 { - symbol: string; - orderType: MarginOrderTypeV2; - price?: string; - loanType: MarginLoanTypeV2; - force: MarginTimeInForceV2; - baseSize?: string; - quoteSize?: string; - clientOid?: string; - side: MarginOrderSideV2; - stpMode?: MarginSTPModeV2; -} +// or +// import { DefaultLogger, WS_KEY_MAP, WebsocketClientV2 } from 'bitget-api'; ⋮---- -export interface MarginBatchOrderEntry { - orderType: MarginOrderTypeV2; - price?: string; - loanType: MarginLoanTypeV2; - force: MarginTimeInForceV2; - baseSize?: string; - quoteSize?: string; - clientOid?: string; - side: MarginOrderSideV2; - stpMode?: MarginSTPModeV2; -} +// console.log('WS raw message received ', JSON.stringify(data, null, 2)); ⋮---- -export interface MarginBatchOrdersRequestV2 { - symbol: string; - orderList: MarginBatchOrderEntry[]; -} +/** + * Public events + */ ⋮---- -export interface GetMarginCurrentOrdersRequestV2 { - symbol: string; - orderId?: string; - clientOid?: string; - startTime: string; - endTime?: string; - limit?: string; - idLessThan?: string; -} +// You can subscribe to one topic at a time ⋮---- -export interface GetHistoryOrdersRequestV2 { - symbol: string; - orderId?: string; - enterPointSource?: string; - clientOid?: string; - startTime: string; - endTime?: string; - limit?: string; - idLessThan?: string; -} +WS_KEY_MAP.v3Public, // This parameter points to private or public ⋮---- -export interface GetMarginOrderFillsRequestV2 { - symbol: string; - orderId?: string; - idLessThan?: string; - startTime: string; - endTime?: string; - limit?: string; -} +// Or multiple at once: ⋮---- -export interface GetMarginLiquidationOrdersRequestV2 { - type?: 'swap' | 'place_order'; - symbol?: string; - fromCoin?: string; - toCoin?: string; - startTime?: string; - endTime?: string; - limit?: string; - idLessThan?: string; -} +// Topics are tracked per websocket type +// The below example will pull a list of subscribed topics on that connection (e.g. all public topics), after a 5 second delay: ================ -File: src/types/request/shared.ts +File: examples/V3 - UTA/WS-API/ws-api-client-trade.ts ================ -/** Pagination */ -export interface Pagination { - /** Time after */ - after?: string; - /** Time before */ - before?: string; - /** Elements per page */ - limit?: string; -} +import { DefaultLogger, WebsocketAPIClient } from '../../../src/index.js'; ⋮---- -/** Time after */ +// or +// import { DefaultLogger, WS_KEY_MAP, WebsocketAPIClient } from 'bitget-api'; ⋮---- -/** Time before */ +// function attachEventHandlers( +// wsClient: TWSClient, +// ): void { +// wsClient.on('update', (data) => { +// console.log('raw message received ', JSON.stringify(data)); +// }); +// wsClient.on('open', (data) => { +// console.log('ws connected', data.wsKey); +// }); +// wsClient.on('reconnect', ({ wsKey }) => { +// console.log('ws automatically reconnecting.... ', wsKey); +// }); +// wsClient.on('reconnected', (data) => { +// console.log('ws has reconnected ', data?.wsKey); +// }); +// wsClient.on('authenticated', (data) => { +// console.log('ws has authenticated ', data?.wsKey); +// }); +// } ⋮---- -/** Elements per page */ +// If running from CLI in unix, you can pass env vars as such: +// API_KEY_COM='lkm12n3-2ba3-1mxf-fn13-lkm12n3a' API_SECRET_COM='035B2B9637E1BDFFEE2646BFBDDB8CE4' API_PASSPHRASE_COM='ComplexPa$$!23$5^' ts-node examples/ws-private.ts ⋮---- -export type OrderTimeInForce = 'normal' | 'post_only' | 'fok' | 'ioc'; +// Whether to use the demo trading wss connection +// demoTrading: true, ⋮---- -export interface GetHistoricTradesParams { - symbol: string; - limit?: string; - tradeId?: string; - startTime?: string; - endTime?: string; -} +// If you want your own event handlers instead of the default ones with logs, +// disable this setting and see the `attachEventHandlers` example below: +// attachEventListeners: false ⋮---- -/** - * The margin type, used directly in building the endpoint URL - */ -export type MarginType = 'crossed' | 'isolated'; +logger, // Optional: inject a custom logger ⋮---- -export type FuturesProductTypeV2 = - | 'USDT-FUTURES' - | 'COIN-FUTURES' - | 'USDC-FUTURES' - | 'SUSDT-FUTURES' - | 'SCOIN-FUTURES' - | 'SUSDC-FUTURES'; +// Optional, see above "attachEventListeners". Attach basic event handlers, so nothing is left unhandled +// attachEventHandlers(wsClient.getWSClient()); ⋮---- -export type FuturesPlanTypeV2 = - | 'profit_plan' - | 'loss_plan' - | 'moving_plan' - | 'pos_profit' - | 'pos_loss'; - -================ -File: src/types/response/v2/copy-trading.ts -================ -/** - * - * - * Copy Trading | Future copy trading | Trader Api - * - * - */ +// Optional: prepare the WebSocket API connection in advance. +// This happens automatically but you can do this early before making any API calls, to prevent delays from a cold start. ⋮---- -export interface CTFuturesTraderCurrentOrderV2 { - trackingNo: string; - openOrderId: string; - symbol: string; - posSide: string; - openLeverage: string; - openPriceAvg: string; - openTime: string; - openSize: string; - presetStopSurplusPrice: string; - presetStopLossPrice: string; - openFee: string; - followCount: string; -} +/** + * Bitget's WebSocket API be used like a REST API, through this SDK's WebsocketAPIClient. The WebsocketAPIClient is a utility class wrapped around WebsocketClientV3's sendWSAPIRequest() capabilities. + * + * Each request sent via the WebsocketAPIClient will automatically: + * - route via the active WS API connection + * - return a Promise, which automatically resolves/rejects when a matching response is received + * + * Note: this requires V3/UTA API keys! + */ ⋮---- -export interface CTFuturesTraderCurrentOrdersV2 { - trackingList: CTFuturesTraderCurrentOrderV2[]; - endId: string; -} +/** + * Place Order + * https://www.bitget.com/api-doc/uta/websocket/private/Place-Order-Channel#request-parameters + */ ⋮---- -export interface CTFuturesTraderHistoryOrderV2 { - trackingNo: string; - symbol: string; - openOrderId: string; - closeOrderId: string; - productType: string; - posSide: string; - openLeverage: string; - openPriceAvg: string; - openTime: string; - openSize: string; - closeSize: string; - closeTime: string; - closePriceAvg: string; - stopType: string; - achievedPL: string; - openFee: string; - closeFee: string; - cTime: string; -} +/** + const res = { + "event": "trade", + "id": "1750034396082", + "category": "spot", + "topic": "place-order", + "args": [ + { + "symbol": "BTCUSDT", + "orderId": "xxxxxxxx", + "clientOid": "xxxxxxxx", + "cTime": "1750034397008" + } + ], + "code": "0", + "msg": "success", + "ts": "1750034397076" + }; + */ ⋮---- -export interface CTFuturesTraderHistoryOrderV2 { - trackingList: CTFuturesTraderHistoryOrderV2[]; - endId: string; -} +/** + * Batch Place Order Channel + * https://www.bitget.com/api-doc/uta/websocket/private/Batch-Place-Order-Channel + */ ⋮---- -export interface CTRateCTimeV2 { - rate: string; - ctime: string; -} +/** + * Note: batch place will never reject the request, even if all orders were rejected. Check the "code" and "msg" properties for individual orders in the response, to detect batch place errors. + */ ⋮---- -export interface CTAmountCTimeV2 { - amount: string; - ctime: string; -} +/** + const res = { + "event": "trade", + "id": "1750035029506", + "category": "spot", + "topic": "batch-place", + "args": [ + { + "code": "0", + "msg": "Success", + "symbol": "BTCUSDT", + "orderId": "xxxxxxxx", + "clientOid": "xxxxxxxx" + }, + { + "code": "0", + "msg": "Success", + "symbol": "BTCUSDT", + "orderId": "xxxxxxxx", + "clientOid": "xxxxxxxx" + } + ], + "code": "0", + "msg": "Success", + "ts": "1750035029925" + } + */ ⋮---- -export interface CTFuturesTraderTotalOrderSummaryV2 { - roi: string; - tradingOrderNum: string; - totalFollowerNum: string; - currentFollowerNum: string; - totalpl: string; - gainNum: string; - lossNum: string; - winRate: string; - tradingPairsAvailableList: string[]; - lastWeekRoiList: CTRateCTimeV2[]; - lastWeekProfitList: CTAmountCTimeV2[]; - lastMonthRoiList: CTRateCTimeV2[]; - lastMonthProfitList: CTAmountCTimeV2[]; - totalEquity: string; -} +/** + * Cancel Order + * https://www.bitget.com/api-doc/uta/websocket/private/Cancel-Order-Channel + */ ⋮---- -export interface CTFuturesTraderProfitHistoryItemV2 { - coin: string; - profitCount: string; - lastProfitTime: string; -} +/** + const res = { + "event": "trade", + "id": "1750034870205", + "topic": "cancel-order", + "args": [ + { + "orderId": "xxxxxxxx", + "clientOid": "xxxxxxxx" + } + ], + "code": "0", + "msg": "Success", + "ts": "1750034870597" + } + */ ⋮---- -export interface CTFuturesTraderHistoryProfitSummaryV2 { - profitSummary: { - yesterdayProfit: string; - sumProfit: string; - waitProfit: string; - yesterdayTime: string; - }; - profitHistoryList: CTFuturesTraderProfitHistoryItemV2[]; -} +/** + * Batch Cancel Order + * https://www.bitget.com/api-doc/uta/websocket/private/Batch-Cancel-Order-Channel + */ ⋮---- -export interface CTFuturesTraderProfitShare { - profitId: string; - coin: string; - profit: string; - nickName: string; - profitTime: string; -} +/** + const res = { + "event": "trade", + "id": "bb553cc0-c1fa-454e-956d-c96c8d715760", + "topic": "batch-cancel", + "args": [ + { + "code": "0", + "msg": "Success", + "orderId": "xxxxxxxxxxxxx" + }, + { + "code": "25204", + "msg": "Order does not exist", + "orderId": "xxxxxxxxxxxxx" + } + ], + "code": "0", + "msg": "Success", + "ts": "1751980011084" + } + */ + +================ +File: examples/V3 - UTA/WS-API/ws-api-trade-raw.ts +================ +import { + DefaultLogger, + WebsocketClientV3, + WS_KEY_MAP, +} from '../../../src/index.js'; ⋮---- -export interface CTFuturesTraderProfitShareHistoryV2 { - profitList: CTFuturesTraderProfitShare[]; - endId: string; -} +// or +// import { DefaultLogger, WS_KEY_MAP, WebsocketClientV3 } from 'bitget-api'; ⋮---- -export interface CTFuturesTraderSymbolSettingsV2 { - symbol: string; - openTrader: string; - minOpenCount: string; - maxLeverage: string; - stopSurplusRatio: string; - stopLossRatio: string; -} +// If running from CLI in unix, you can pass env vars as such: +// API_KEY_COM='lkm12n3-2ba3-1mxf-fn13-lkm12n3a' API_SECRET_COM='035B2B9637E1BDFFEE2646BFBDDB8CE4' API_PASSPHRASE_COM='ComplexPa$$!23$5^' ts-node examples/ws-private.ts ⋮---- -export interface CTFuturesTraderMyFollowersV2 { - accountEquity: string; - isRemove: string; - followerHeadPic: string; - followerName: string; - followerUid: string; - followerTime: string; -} +// console.log('WS raw message received ', JSON.stringify(data, null, 2)); ⋮---- /** - * - * - * Copy Trading | Future copy trading | Follower Api - * - * - */ + * Bitget's WebSocket API can be used via the sendWSAPIRequest() method. + * + * Use the `WS_KEY_MAP.v3Private` connection key for any requests. + * + * Note: this requires V3/UTA API keys! + * Note: for a better user experience, it is recommended to use the WebsocketAPIClient. + */ ⋮---- -export interface CTFuturesFollowerCurrentOrdersV2 { - trackingNo: string; - traderName: string; - openOrderId: string; - closeOrderId: string; - traderId: string; - symbol: string; - posSide: string; - openLeverage: string; - openAvgPrice: string; - openTime: string; - openSize: string; - closeAvgPrice: string; - closeSize: string; - openMarginSz: string; - closeTime: string; -} +// Use the V3 private wss connection URL ⋮---- -export interface CTFuturesFollowerHistoryOrderV2 { - trackingNo: string; - posSide: string; - openLeverage: string; - openSize: string; - closeSize: string; - openPriceAvg: string; - closePriceAvg: string; - achievedPL: string; - openFee: string; - closeFee: string; - symbol: string; - profitRate: string; - netProfit: string; - openOrderId: string; - closeOrderId: string; - openTime: string; - closeTime: string; - traderId: string; - productType: string; -} +/** + * Place Order + * https://www.bitget.com/api-doc/uta/websocket/private/Place-Order-Channel#request-parameters + */ ⋮---- -export interface CTFuturesFollowerHistoryOrdersV2 { - trackingList: CTFuturesFollowerHistoryOrderV2[]; - endId: string; -} +/** + const res = { + "event": "trade", + "id": "1750034396082", + "category": "spot", + "topic": "place-order", + "args": [ + { + "symbol": "BTCUSDT", + "orderId": "xxxxxxxx", + "clientOid": "xxxxxxxx", + "cTime": "1750034397008" + } + ], + "code": "0", + "msg": "success", + "ts": "1750034397076" + }; + */ ⋮---- -export interface CTFuturesFollowerSettingV2 { - symbol: string; - productType: string; - marginType: string; - marginCoin: string; - leverType: string; - longLeverage: string; - shortLeverage: string; - traceType: string; -} +/** + * Batch Place Order Channel + * https://www.bitget.com/api-doc/uta/websocket/private/Batch-Place-Order-Channel + */ ⋮---- -export interface CTFuturesFollowerSettingsV2 { - followerEnable: string; - detailList: CTFuturesFollowerSettingV2[]; -} +/** + * Note: batch place will never reject the request, even if all orders were rejected. Check the "code" and "msg" properties for individual orders in the response, to detect batch place errors. + */ ⋮---- -export interface CTFuturesFollowerMyTradersV2 { - certificationType: string; - traderId: string; - traderName: string; - maxFollowLimit: string; - followCount: string; - traceTotalMarginAmount: string; - traceTotalNetProfit: string; - traceTotalProfit: string; - currentTradingPairs: string[]; - followerTime: string; - bgbMaxFollowLimit: string; - bgbFollowCount: string; -} +/** + const res = { + "event": "trade", + "id": "1750035029506", + "category": "spot", + "topic": "batch-place", + "args": [ + { + "code": "0", + "msg": "Success", + "symbol": "BTCUSDT", + "orderId": "xxxxxxxx", + "clientOid": "xxxxxxxx" + }, + { + "code": "0", + "msg": "Success", + "symbol": "BTCUSDT", + "orderId": "xxxxxxxx", + "clientOid": "xxxxxxxx" + } + ], + "code": "0", + "msg": "Success", + "ts": "1750035029925" + } + */ ⋮---- /** - * - * - * Copy Trading | Spot copy trading | Trader api - * - * - */ + * Cancel Order + * https://www.bitget.com/api-doc/uta/websocket/private/Cancel-Order-Channel + */ ⋮---- -export interface CTSpotTraderProfitSummaryV2 { - profitSummarys: { - yesterdayProfit: string; - yesterdayTime: string; - sumProfit: string; - waitProfit: string; - }; - profitHistoryList: { - coin: string; - profitCount: string; - lastProfitTime: string; - historysByDateList: { - profit: string; - profitTime: string; - }[]; - }[]; -} +/** + const res = { + "event": "trade", + "id": "1750034870205", + "topic": "cancel-order", + "args": [ + { + "orderId": "xxxxxxxx", + "clientOid": "xxxxxxxx" + } + ], + "code": "0", + "msg": "Success", + "ts": "1750034870597" + } + */ ⋮---- -export interface CTSpotTraderHistoryProfitShareItemV2 { - profitId: string; - coin: string; - distributeRatio: string; - profit: string; - followerName: string; - profitTime: string; -} +/** + * Batch Cancel Order + * https://www.bitget.com/api-doc/uta/websocket/private/Batch-Cancel-Order-Channel + */ ⋮---- -export interface CTSpotTraderHistoryProfitSharingV2 { - endId: string; - profitList: CTSpotTraderHistoryProfitShareItemV2[]; +/** + const res = { + "event": "trade", + "id": "bb553cc0-c1fa-454e-956d-c96c8d715760", + "topic": "batch-cancel", + "args": [ + { + "code": "0", + "msg": "Success", + "orderId": "xxxxxxxxxxxxx" + }, + { + "code": "25204", + "msg": "Order does not exist", + "orderId": "xxxxxxxxxxxxx" + } + ], + "code": "0", + "msg": "Success", + "ts": "1751980011084" + } + */ + +================ +File: examples/README.md +================ +# Examples + +These samples can be executed using `ts-node`: + +``` +ts-node ./examples/rest-spot-public.ts +``` + +Samples that require authentication can be edited directly but also support environmental variables. E.g. on mac/unix: + +``` +API_KEY_COM='yourkeyhere' API_SECRET_COM='yoursecrethere' API_PASS_COM='yourapipasshere' ts-node examples/rest-trade-futures.ts +``` + +They can also be converted to JavaScript by changing the imports to require & removing any type annotations. + +## V3 / Unified Trading Account (UTA) + +These newer examples are for Bitget's V3 APIs and WebSockets. They can be found in the examples/V3 folder. + +Refer to the V3 / UTA API documentation for more information on the V3 APIs: +https://www.bitget.com/api-doc/uta/intro + +These APIs require your account to be upgraded to the Unified Trading Account, if you plan on using the account-level REST APIs and WebSockets. Once upgraded, the V2 APIs are no longer available to you, unless you revert back to Classic Account mode. + +### WebSocket API (WS API) + +The V3/UTA API introduces order placement via a persisted WebSocket connection. This Bitget Node.js, JavaScript & TypeScript SDK supports Bitget's full V3 API offering, including the WebSocket API. + +There are two approaches to placing orders via the Bitget WebSocket APIs + +#### WebsocketAPIClient (recommended) + +This integration looks & feels like a REST API client, but uses WebSockets, via the WebsocketClient's sendWSAPIRequest method. It returns promises and has end to end types. + +This is the recommended approach to easily start sending orders via an automatically persisted WebSocket connection. A simple example is below, but for a more thorough example, check the example here: [./V3/ws-api-client-trade.ts](./V3/ws-api-client-trade.ts) + +```typescript +import { WebsocketAPIClient } from 'bitget-api'; +// or if you prefer require: +// const { WebsocketAPIClient } = require("bitget-api"); + +// Make an instance of the WS API Client class with your API keys +const wsClient = new WebsocketAPIClient({ + apiKey: API_KEY, + apiSecret: API_SECRET, + apiPass: API_PASS, + + // Whether to use the demo trading wss connection + // demoTrading: true, +}); + +async function start() { + // Start using it like a REST API. All actions are sent via a persisted WebSocket connection. + + /** + * Place Order + * https://www.bitget.com/api-doc/uta/websocket/private/Place-Order-Channel#request-parameters + */ + try { + const res = await wsClient.submitNewOrder('spot', { + orderType: 'limit', + price: '100', + qty: '0.1', + side: 'buy', + symbol: 'BTCUSDT', + timeInForce: 'gtc', + }); + + console.log(new Date(), 'WS API "submitNewOrder()" result: ', res); + } catch (e) { + console.error(new Date(), 'Exception with WS API "submitNewOrder()": ', e); + } } + +start().catch((e) => console.error('Exception in example: '.e)); +``` + +#### ws.sendWSAPIRequest(wsKey, command, category, operation) + +This is the "raw" integration within the existing WebSocket client. It uses an automatically persisted & authenticated connection to send events through Bitget's WebSocket API. It automatically tracks and connects outgoing requests with incoming responses, and returns promises that resolve/reject when a matching response is received. + +Refer to [V3/ws-api-trade-raw.ts](./V3/ws-api-trade-raw.ts) to see an example. + +Note: The WebsocketClient is built around this. For a more user friendly experience, it is recommended to use the WebsocketClient for WS API requests. It uses this method but has the convenience of behaving similar to a REST API (while all communication automatically happens over a persisted WebSocket connection). + +## V2 + +These examples are for Bitget's V2 APIs and WebSockets. They can be found in the examples/V2 folder. + +Refer to the V2 API documentation for more information on the V2 APIs: +https://www.bitget.com/api-doc/common/intro + +================ +File: src/types/request/v2/copytrading.ts +================ +/** + * + * + * Copy Trading | Future copy trading | Trader Api + * + * + */ ⋮---- -export interface CTSpotTraderUnrealizedProfitV2 { - distributeRatio: string; - coin: string; - profit: string; - followerName: string; +export type CopyTradingProductTypeV2 = + | 'USDT-FUTURES' + | 'COIN-FUTURES' + | 'USDC-FUTURES'; +⋮---- +export interface GetFuturesTraderCurrentOrdersRequestV2 { + symbol?: string; + productType: CopyTradingProductTypeV2; + startTime?: string; + endTime?: string; + limit?: string; + idGreaterThan?: string; + idLessThan?: string; } ⋮---- -export interface CTSpotTraderTotalOrderDetailV2 { - totalFollowerNum: string; - currentFollowerNum: string; - maxFollowerNum: string; - tradingOrderNum: string; - totalpl: string; - gainNum: string; - lossNum: string; - totalEquity: string; - winRate: string; - lastWeekRoiList: CTAmountCTimeV2[]; - lastMonthRoiList: CTRateCTimeV2[]; - lastWeekProfitList: CTAmountCTimeV2[]; - lastMonthProfitList: CTAmountCTimeV2[]; +export interface GetFuturesTraderHistoryOrdersRequestV2 { + idLessThan?: string; + idGreaterThan?: string; + startTime?: string; + endTime?: string; + limit?: string; + order?: 'asc' | 'desc'; + symbol?: string; + productType: CopyTradingProductTypeV2; } ⋮---- -export interface CTSpotTraderHistoryOrderV2 { +export interface ModifyFuturesTraderOrderTPSLRequestV2 { trackingNo: string; - fillSize: string; - buyPrice: string; - sellPrice: string; - achievedPL: string; - buyTime: string; - sellTime: string; - buyFee: string; - sellFee: string; - achievedPLR: string; - symbol: string; - netProfit: string; - followCount: string; -} -export interface CTSpotTraderHistoryOrdersV2 { - endId: string; - trackingList: CTSpotTraderHistoryOrderV2[]; + productType: CopyTradingProductTypeV2; + stopSurplusPrice?: string; + stopLossPrice?: string; } ⋮---- -export interface CTSpotTraderCurrentTrackingOrderV2 { - trackingNo: string; - orderId: string; - buyFillSize: string; - buyDelegateSize: string; - buyPrice: string; - unrealizedPL: string; - buyTime: string; - buyFee: string; - unrealizedPLR: string; - symbol: string; - stopLossPrice: string | null; - stopSurplusPrice: string | null; - followCount: string; +export interface GetFuturesTraderProfitShareDetailRequestV2 { + coin?: string; + idLessThan?: string; + idGreaterThan?: string; + startTime?: string; + endTime?: string; + limit?: string; } ⋮---- -export interface CTSpotTraderCurrentTrackingOrdersV2 { - endId: string; - trackingList: CTSpotTraderCurrentTrackingOrderV2[]; +export interface FuturesTraderSymbolSettingRequestV2 { + symbol: string; + productType: CopyTradingProductTypeV2; + settingType: 'ADD' | 'DELETE' | 'UPDATE'; + stopSurplusRatio?: string; + stopLossRatio?: string; } ⋮---- -export interface CTSpotTraderFollowerListV2 { - accountEquity: string; - isRemove: string; - followerHeadPic: string | null; - followerName: string; - followerUid: string; - followerTime: string; +export interface GetFuturesTraderFollowersRequestV2 { + pageNo?: string; + pageSize?: string; + startTime?: string; + endTime?: string; } ⋮---- /** * * - * Copy Trading | Spot copy trading | Follower api + * Copy Trading | Future copy trading | Follower Api * * */ ⋮---- -export interface CTSpotFollowerMyTraderV2 { - certificationType: string; - traceTotalAmount: string; - traceTotalNetProfit: string; - traceTotalProfit: string; - traderName: string; - traderId: string; - maxFollowLimit: string; - bgbMaxFollowLimit: string; - followCount: string; - bgbFollowCount: string; - followerTime: string; +export interface GetFollowerFuturesCurrentTrackingOrdersRequestV2 { + idLessThan?: string; + idGreaterThan?: string; + startTime?: string; + endTime?: string; + limit?: string; + symbol?: string; + productType: CopyTradingProductTypeV2; + traderId?: string; } ⋮---- -export interface CTSpotFollowerMyTradersV2 { - resultList: CTSpotFollowerMyTraderV2[]; +export interface GetFollowerFuturesHistoryTrackingOrdersRequestV2 { + idLessThan?: string; + idGreaterThan?: string; + startTime?: string; + endTime?: string; + limit?: string; + symbol?: string; + productType: CopyTradingProductTypeV2; + traderId?: string; } ⋮---- -export interface CTSpotFollowerTradeSettingV2 { - maxTraceAmount: string; - stopLossRation: string; - stopSurplusRation: string; - symbol: string; - traceType: string; +export interface UpdateFuturesFollowerTPSLRequestV2 { + trackingNo: string; + symbol?: string; + productType: CopyTradingProductTypeV2; + stopSurplusPrice?: string; + stopLossPrice?: string; } ⋮---- -export interface CTSpotFollowerTradeSymbolSettingV2 { - maxStopLossRation: string; - maxStopSurplusRation: string; - maxTraceAmount: string; - maxTraceAmountSystem: string; - maxTraceSize: string; - maxTraceRation: string; - minStopLossRation: string; - minStopSurplusRation: string; - minTraceAmount: string; - minTraceSize: string; - minTraceRation: string; - sliderMaxStopLossRatio: string; - sliderMaxStopSurplusRatio: string; - symbol: string; -} +export type AutoCopyOption = 'on' | 'off'; +export type FollowMode = 'basic' | 'advanced'; +export type LeverageType = 'position' | 'specify' | 'trader'; +export type TraceType = 'percent' | 'amount' | 'count'; ⋮---- -export interface CTSpotFollowerFollowConfigurationV2 { - enable: string; - profitRate: string; - settledInDays: string; - tradeSettingList: CTSpotFollowerTradeSettingV2[]; - tradeSymbolSettingList: CTSpotFollowerTradeSymbolSettingV2[]; - traderHeadPic: string; - traderName: string; +export interface FollowerCopyTradeSettingRequestV2 { + symbol: string; + productType: CopyTradingProductTypeV2; + marginType: 'trader' | 'specify'; + marginCoin?: string; + leverType: LeverageType; + longLeverage?: string; + shortLeverage?: string; + traceType: TraceType; + traceValue: string; + maxHoldSize?: string; + stopSurplusRatio?: string; + stopLossRatio?: string; } ⋮---- -export interface CTSpotFollowerHistoryOrderV2 { - trackingNo: string; +export interface UpdateFuturesFollowerSettingsRequestV2 { traderId: string; - fillSize: string; - buyPrice: string; - sellPrice: string; - buyFee: string; - sellFee: string; - achievedPL: string; - achievedPLR: string; - symbol: string; - buyTime: string; - sellTime: string; + autoCopy?: AutoCopyOption; + mode?: FollowMode; + settings: FollowerCopyTradeSettingRequestV2[]; } -export interface CTSpotFollowerHistoryOrdersV2 { - endId: string; - trackingList: CTSpotFollowerHistoryOrderV2[]; +export interface CloseFuturesFollowerPositionsRequestV2 { + productType: CopyTradingProductTypeV2; + trackingNo?: string; + symbol?: string; + marginCoin?: string; + marginMode?: 'isolated' | 'cross'; + holdSide?: 'long' | 'short'; } ⋮---- -export interface CTSpotFollowerCurrentOrderV2 { - trackingNo: string; - traderId: string; - buyFillSize: string; - buyDelegateSize: string; - buyPrice: string; - unrealizedPL: string; - buyTime: string; - buyFee: string; - unrealizedPLR: string; - symbol: string; - stopSurplusPrice: string | null; - stopLossPrice: string | null; +export interface GetFuturesFollowerTradersRequestV2 { + startTime?: string; + endTime?: string; + pageNo?: string; + pageSize?: string; } ⋮---- -export interface CTSpotFollowerCurrentOrdersV2 { - endId: string; - trackingList: CTSpotFollowerCurrentOrderV2[]; -} - -================ -File: src/types/response/v2/margin.ts -================ /** * - * * Margin | Common * - */ -⋮---- -export interface MarginCurrencyV2 { - symbol: string; - baseCoin: string; - quoteCoin: string; - maxCrossedLeverage: string; - maxIsolatedLeverage: string; - warningRiskRatio: string; - liquidationRiskRatio: string; - minTradeAmount: string; - maxTradeAmount: string; - takerFeeRate: string; - makerFeeRate: string; - pricePrecision: string; - quantityPrecision: string; - minTradeUSDT: string; - isBorrowable: boolean; - userMinBorrow: string; - status: string; - isIsolatedBaseBorrowable: boolean; - isIsolatedQuoteBorrowable: boolean; - isCrossBorrowable: boolean; -} -⋮---- -/** + * Copy Trading | Spot copy trading | Trader api * - * * Margin | Cross/Isolated | Order Record * */ ⋮---- -export interface MarginBorrowHistoryItemV2 { - loanId: string; - coin: string; - borrowAmount: string; - borrowType: string; - cTime: string; - uTime: string; -} -⋮---- -export interface MarginRepaymentHistoryItemV2 { - repayId: string; - coin: string; - repayAmount: string; - repayType: string; - repayInterest: string; - repayPrincipal: string; - symbol: string; - cTime: string; - uTime: string; +export interface GetSpotTraderHistoryProfitRequestV2 { + idLessThan?: string; + idGreaterThan?: string; + startTime?: string; + endTime?: string; + limit?: string; + coin?: string; } ⋮---- -export interface MarginInterestHistoryItemV2 { - interestId: string; - interestCoin: string; - dailyInterestRate: string; - loanCoin: string; - interestAmount: string; - interstType: string; - symbol: string; - cTime: string; - uTime: string; +export interface GetSpotTraderHistoryOrdersRequestV2 { + idLessThan?: string; + idGreaterThan?: string; + startTime?: string; + endTime?: string; + limit?: string; + symbol?: string; } ⋮---- -export interface MarginLiquidationHistoryItemV2 { - liqId: string; - symbol: string; - liqStartTime: string; - liqEndTime: string; - liqRiskRatio: string; - totalAssets: string; - totalDebt: string; - liqFee: string; - cTime: string; - uTime: string; +export interface GetSpotTraderCurrentOrdersRequestV2 { + symbol?: string; + idLessThan?: string; + idGreaterThan?: string; + startTime?: string; + endTime?: string; + limit?: string; } ⋮---- -export interface MarginFinancialHistoryItemV2 { - coin: string; - symbol: string; - marginId: string; - amount: string; - balance: string; - fee: string; - marginType: string; - cTime: string; - uTime: string; +export interface GetSpotTraderFollowersRequestV2 { + pageNo?: string; + pageSize?: string; + startTime?: string; + endTime?: string; } ⋮---- /** * - * * Margin | Cross/Isolated | Account + * + * Copy Trading | Spot copy trading | Follower api + * * */ ⋮---- -export interface MarginAccountAssetV2 { +export interface SpotFollowerCopyTradeSettingV2 { symbol: string; - coin: string; - totalAmount: string; - available: string; - frozen: string; - borrow: string; - interest: string; - net: string; - coupon: string; - cTime: string; - uTime: string; + traceType: 'percent' | 'amount' | 'count'; + maxHoldSize: string; + traceValue: string; + stopLossRatio?: string; + stopSurplusRatio?: string; } ⋮---- -export interface CrossMaxBorrowableResponseV2 { - coin: string; - maxBorrowableAmount: string; +export interface GetSpotFollowerHistoryOrdersRequestV2 { + symbol?: string; + traderId?: string; + idLessThan?: string; + idGreaterThan?: string; + startTime?: string; + endTime?: string; + limit?: string; } ⋮---- -export interface IsolatedMaxBorrowableResponseV2 { - symbol: string; - baseCoin: string; - baseCoinMaxBorrowAmount: string; - quoteCoin: string; - quoteCoinMaxBorrowAmount: string; +export interface GetSpotFollowerOpenOrdersRequestV2 { + symbol?: string; + traderId?: string; + idLessThan?: string; + idGreaterThan?: string; + startTime?: string; + endTime?: string; + limit?: string; } + +================ +File: src/types/request/v2/margin.ts +================ +/** + * + * * Margin | Cross/Isolated | Order Record + * + */ ⋮---- -export interface CrossMaxTransferableResponseV2 { - coin: string; - maxTransferOutAmount: string; +export interface GetBorrowHistoryRequestV2 { + loanId?: string; + coin?: string; + startTime: string; + endTime?: string; + limit?: string; + idLessThan?: string; } ⋮---- -export interface IsolatedMaxTransferableResponseV2 { - baseCoin: string; - symbol: string; - baseCoinMaxTransferOutAmount: string; - quoteCoin: string; - quoteCoinMaxTransferOutAmount: string; +export interface GetRepayHistoryRequestV2 { + repayId?: string; + coin?: string; + startTime: string; + endTime?: string; + limit?: string; + idLessThan?: string; } ⋮---- -export interface CrossInterestRateAndLimitResponseV2 { - transferable: boolean; - leverage: string; - coin: string; - borrowable: boolean; - dailyInterestRate: string; - annualInterestRate: string; - maxBorrowableAmount: string; - vipList: { - level: string; - limit: string; - dailyInterestRate: string; - annualInterestRate: string; - discountRate: string; - }[]; +export interface GetInterestHistoryRequestV2 { + coin?: string; + startTime: string; + endTime?: string; + limit?: string; + idLessThan?: string; } ⋮---- -export interface IsolatedInterestRateAndLimitResponseV2 { - symbol: string; - leverage: string; - baseCoin: string; - baseTransferable: boolean; - baseBorrowable: boolean; - baseDailyInterestRate: string; - baseAnnuallyInterestRate: string; - baseMaxBorrowableAmount: string; - baseVipList: { - level: string; - dailyInterestRate: string; - limit: string; - annuallyInterestRate: string; - discountRate: string; - }[]; - quoteCoin: string; - quoteTransferable: boolean; - quoteBorrowable: boolean; - quoteDailyInterestRate: string; - quoteAnnuallyInterestRate: string; - quoteMaxBorrowableAmount: string; - quoteList: { - level: string; - dailyInterestRate: string; - limit: string; - annuallyInterestRate: string; - discountRate: string; - }[]; +export interface GetLiquidationHistoryRequestV2 { + startTime: string; + endTime?: string; + limit?: string; + idLessThan?: string; } ⋮---- -export interface CrossTierConfigurationResponseV2 { - tier: string; - leverage: string; - coin: string; - maxBorrowableAmount: string; - maintainMarginRate: string; +export interface GetFinancialHistoryRequestV2 { + marginType?: string; + coin?: string; + startTime: string; + endTime?: string; + limit?: string; + idLessThan?: string; } ⋮---- -export interface IsolatedTierConfigurationResponseV2 { - tier: string; - symbol: string; - leverage: string; - baseCoin: string; - quoteCoin: string; - baseMaxBorrowableAmount: string; - quoteMaxBorrowableAmount: string; - maintainMarginRate: string; - initRate: string; -} +/** + * + * * Margin | Cross/Isolated | Account + * + */ ⋮---- /** * @@ -1646,1520 +1563,1603 @@ export interface IsolatedTierConfigurationResponseV2 { * */ ⋮---- -export interface MarginBatchOrdersResponseV2 { - successList: { - orderId: string; - clientOid: string; - }[]; - failureList: { - clientOid: string; - errorMsg: string; - }[]; +export type MarginOrderTypeV2 = 'limit' | 'market'; +⋮---- +export type MarginLoanTypeV2 = + | 'normal' + | 'autoLoan' + | 'autoRepay' + | 'autoLoanAndRepay'; +⋮---- +export type MarginTimeInForceV2 = 'gtc' | 'post_only' | 'fok' | 'ioc'; +⋮---- +export type MarginOrderSideV2 = 'buy' | 'sell'; +⋮---- +export type MarginSTPModeV2 = + | 'none' + | 'cancel_taker' + | 'cancel_maker' + | 'cancel_both'; +⋮---- +export interface MarginPlaceOrderRequestV2 { + symbol: string; + orderType: MarginOrderTypeV2; + price?: string; + loanType: MarginLoanTypeV2; + force: MarginTimeInForceV2; + baseSize?: string; + quoteSize?: string; + clientOid?: string; + side: MarginOrderSideV2; + stpMode?: MarginSTPModeV2; } ⋮---- -export interface MarginCurrentOrderV2 { - orderId: string; +export interface MarginBatchOrderEntry { + orderType: MarginOrderTypeV2; + price?: string; + loanType: MarginLoanTypeV2; + force: MarginTimeInForceV2; + baseSize?: string; + quoteSize?: string; + clientOid?: string; + side: MarginOrderSideV2; + stpMode?: MarginSTPModeV2; +} +⋮---- +export interface MarginBatchOrdersRequestV2 { symbol: string; - orderType: string; - enterPointSource: string; - clientOid: string; - loanType: string; - price: string; - side: string; - status: string; - baseSize: string; - quoteSize: string; - priceAvg: string; - size: string; - amount: string; - force: string; - cTime: string; - uTime: string; + orderList: MarginBatchOrderEntry[]; } ⋮---- -export interface MarginHistoryOrderV2 { - orderId: string; +export interface GetMarginCurrentOrdersRequestV2 { symbol: string; - orderType: string; - enterPointSource: string; - clientOid: string; - loanType: string; - price: string; - side: string; - status: string; - baseSize: string; - quoteSize: string; - priceAvg: string; - size: string; - amount: string; - force: string; - cTime: string; - uTime: string; + orderId?: string; + clientOid?: string; + startTime: string; + endTime?: string; + limit?: string; + idLessThan?: string; } ⋮---- -export interface MarginOrderFillV2 { - orderId: string; - tradeId: string; - orderType: string; - side: string; - priceAvg: string; - size: string; - amount: string; - tradeScope: string; - feeDetail: { - deduction: string; - feeCoin: string; - totalDeductionFee: string; - totalFee: string; - }; - cTime: string; - uTime: string; +export interface GetHistoryOrdersRequestV2 { + symbol: string; + orderId?: string; + enterPointSource?: string; + clientOid?: string; + startTime: string; + endTime?: string; + limit?: string; + idLessThan?: string; } ⋮---- -export interface MarginLiquidationOrderV2 { +export interface GetMarginOrderFillsRequestV2 { symbol: string; - orderType: string; - side: string; - priceAvg: string; - price: string; - fillSize: string; - size: string; - amount: string; - orderId: string; - fromCoin: string; - toCoin: string; - fromSize: string; - toSize: string; - cTime: string; - uTime: string; + orderId?: string; + idLessThan?: string; + startTime: string; + endTime?: string; + limit?: string; } - -================ -File: src/types/websockets/ws-api-response.ts -================ -export interface WSAPIPlaceOrderResponseV3 { - symbol: string; - orderId: string; - clientOid: string; - cTime: string; +⋮---- +export interface GetMarginLiquidationOrdersRequestV2 { + type?: 'swap' | 'place_order'; + symbol?: string; + fromCoin?: string; + toCoin?: string; + startTime?: string; + endTime?: string; + limit?: string; + idLessThan?: string; } ================ -File: src/types/shared.ts +File: src/types/request/shared.ts ================ -import { REST_CLIENT_TYPE_ENUM } from '../util/requestUtils.js'; +/** Pagination */ +export interface Pagination { + /** Time after */ + after?: string; + /** Time before */ + before?: string; + /** Elements per page */ + limit?: string; +} ⋮---- -export type numberInString = string; +/** Time after */ ⋮---- -export type OrderSide = 'Buy' | 'Sell'; +/** Time before */ +⋮---- +/** Elements per page */ +⋮---- +export type OrderTimeInForce = 'normal' | 'post_only' | 'fok' | 'ioc'; +⋮---- +export interface GetHistoricTradesParams { + symbol: string; + limit?: string; + tradeId?: string; + startTime?: string; + endTime?: string; +} ⋮---- /** - * @deprecated use SpotKlineInterval or FuturesKlineInterval, depending on which API group you're using + * The margin type, used directly in building the endpoint URL */ -export type KlineInterval = - | '1min' - | '5min' - | '15min' - | '30min' - | '1h' - | '4h' - | '6h' - | '12h' - | '1M' - | '1W' - | '1week' - | '6Hutc' - | '12Hutc' - | '1Dutc' - | '3Dutc' - | '1Wutc' - | '1Mutc'; +export type MarginType = 'crossed' | 'isolated'; ⋮---- -export type RestClientType = - (typeof REST_CLIENT_TYPE_ENUM)[keyof typeof REST_CLIENT_TYPE_ENUM]; +export type FuturesProductTypeV2 = + | 'USDT-FUTURES' + | 'COIN-FUTURES' + | 'USDC-FUTURES' + | 'SUSDT-FUTURES' + | 'SCOIN-FUTURES' + | 'SUSDC-FUTURES'; ⋮---- -export interface APIResponse { - code: string; - requestTime: number; - msg: 'success' | string; - data: T; -} +export type FuturesPlanTypeV2 = + | 'profit_plan' + | 'loss_plan' + | 'moving_plan' + | 'pos_profit' + | 'pos_loss'; ================ -File: src/websocket-client-v2.ts +File: src/types/response/v2/copy-trading.ts ================ -import { - WSOperation, - WSOperationLoginParams, - WsRequestOperationBitget, -} from './types/websockets/ws-api.js'; -import { MessageEventLike } from './types/websockets/ws-events.js'; -import { - BitgetInstTypeV2, - WsKey, - WsTopicV2, -} from './types/websockets/ws-general.js'; -import { - BaseWebsocketClient, - EmittableEvent, - MidflightWsRequestEvent, -} from './util/BaseWSClient.js'; -import { isWsPong } from './util/requestUtils.js'; -import { - SignAlgorithm, - SignEncodeMethod, - signMessage, -} from './util/webCryptoAPI.js'; -import { - getMaxTopicsPerSubscribeEvent, - getNormalisedTopicRequests, - getWsUrl, - isPrivateChannel, - WS_AUTH_ON_CONNECT_KEYS, - WS_KEY_MAP, - WsTopicRequest, -} from './util/websocket-util.js'; -import { WSConnectedResult } from './util/WsStore.types.js'; -⋮---- -export class WebsocketClientV2 extends BaseWebsocketClient< -⋮---- -WsRequestOperationBitget // subscribe requests have an "args" parameter with an object within -⋮---- /** - * Request connection of all dependent (public & private) websockets, instead of waiting for automatic connection by library - */ -public connectAll(): Promise[] + * + * + * Copy Trading | Future copy trading | Trader Api + * + * + */ ⋮---- -/** Some private channels use `coin` instead of `instId`. This method handles building the sub/unsub request */ -private getSubRequest( - instType: BitgetInstTypeV2, - topic: WsTopicV2, - coin: string = 'default', - ): WsTopicRequest +export interface CTFuturesTraderCurrentOrderV2 { + trackingNo: string; + openOrderId: string; + symbol: string; + posSide: string; + openLeverage: string; + openPriceAvg: string; + openTime: string; + openSize: string; + presetStopSurplusPrice: string; + presetStopLossPrice: string; + openFee: string; + followCount: string; +} ⋮---- -/** - * Subscribe to a topic - * @param instType instrument type (refer to API docs). - * @param topic topic name (e.g. "ticker"). - * @param instId instrument ID (e.g. "BTCUSDT"). Use "default" for private topics. - */ -public subscribeTopic( - instType: BitgetInstTypeV2, - topic: WsTopicV2, - coin: string = 'default', - ) +export interface CTFuturesTraderCurrentOrdersV2 { + trackingList: CTFuturesTraderCurrentOrderV2[]; + endId: string; +} ⋮---- -/** - * Unsubscribe from a topic - * @param instType instrument type (refer to API docs). - * @param topic topic name (e.g. "ticker"). - * @param instId instrument ID (e.g. "BTCUSDT"). Use "default" for private topics to get all symbols. - */ -public unsubscribeTopic( - instType: BitgetInstTypeV2, - topic: WsTopicV2, - coin: string = 'default', - ) +export interface CTFuturesTraderHistoryOrderV2 { + trackingNo: string; + symbol: string; + openOrderId: string; + closeOrderId: string; + productType: string; + posSide: string; + openLeverage: string; + openPriceAvg: string; + openTime: string; + openSize: string; + closeSize: string; + closeTime: string; + closePriceAvg: string; + stopType: string; + achievedPL: string; + openFee: string; + closeFee: string; + cTime: string; +} ⋮---- -/** - * 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, category: CategoryV5}. - * - * - Subscriptions are automatically routed to the correct websocket connection. - * - Authentication/connection is automatic. - * - Resubscribe after network issues is automatic. - * - * Call `unsubscribe(topics)` to remove topics - */ -public subscribe( - requests: - | (WsTopicRequest | WsTopicV2) - | (WsTopicRequest | WsTopicV2)[], - wsKey: WsKey, - ): Promise +export interface CTFuturesTraderHistoryOrderV2 { + trackingList: CTFuturesTraderHistoryOrderV2[]; + endId: string; +} ⋮---- -/** - * Unsubscribe from one or more topics. Similar to subscribe() but in reverse. - * - * - Requests are automatically routed to the correct websocket connection. - * - These topics will be removed from the topic cache, so they won't be subscribed to again. - */ -public unsubscribe( - requests: - | (WsTopicRequest | WsTopicV2) - | (WsTopicRequest | WsTopicV2)[], - wsKey: WsKey, - ) +export interface CTRateCTimeV2 { + rate: string; + ctime: string; +} ⋮---- -/** - * - * - * Internal methods required to integrate with the BaseWSClient - * - * - */ -⋮---- -protected sendPingEvent(wsKey: WsKey): void -⋮---- -protected sendPongEvent(wsKey: WsKey): void +export interface CTAmountCTimeV2 { + amount: string; + ctime: string; +} ⋮---- -protected isWsPing(data: any): boolean +export interface CTFuturesTraderTotalOrderSummaryV2 { + roi: string; + tradingOrderNum: string; + totalFollowerNum: string; + currentFollowerNum: string; + totalpl: string; + gainNum: string; + lossNum: string; + winRate: string; + tradingPairsAvailableList: string[]; + lastWeekRoiList: CTRateCTimeV2[]; + lastWeekProfitList: CTAmountCTimeV2[]; + lastMonthRoiList: CTRateCTimeV2[]; + lastMonthProfitList: CTAmountCTimeV2[]; + totalEquity: string; +} ⋮---- -protected isWsPong(data: any): boolean +export interface CTFuturesTraderProfitHistoryItemV2 { + coin: string; + profitCount: string; + lastProfitTime: string; +} ⋮---- -protected isPrivateTopicRequest( - _request: WsTopicRequest, - wsKey: WsKey, - ): boolean +export interface CTFuturesTraderHistoryProfitSummaryV2 { + profitSummary: { + yesterdayProfit: string; + sumProfit: string; + waitProfit: string; + yesterdayTime: string; + }; + profitHistoryList: CTFuturesTraderProfitHistoryItemV2[]; +} ⋮---- -protected getPrivateWSKeys(): WsKey[] +export interface CTFuturesTraderProfitShare { + profitId: string; + coin: string; + profit: string; + nickName: string; + profitTime: string; +} ⋮---- -protected isAuthOnConnectWsKey(wsKey: WsKey): boolean +export interface CTFuturesTraderProfitShareHistoryV2 { + profitList: CTFuturesTraderProfitShare[]; + endId: string; +} ⋮---- -protected async getWsUrl(wsKey: WsKey): Promise +export interface CTFuturesTraderSymbolSettingsV2 { + symbol: string; + openTrader: string; + minOpenCount: string; + maxLeverage: string; + stopSurplusRatio: string; + stopLossRatio: string; +} ⋮---- -protected getMaxTopicsPerSubscribeEvent(wsKey: WsKey): number | null +export interface CTFuturesTraderMyFollowersV2 { + accountEquity: string; + isRemove: string; + followerHeadPic: string; + followerName: string; + followerUid: string; + followerTime: string; +} ⋮---- /** - * @returns one or more correctly structured request events for performing a operations over WS. This can vary per exchange spec. - */ -protected async getWsRequestEvents( - operation: WSOperation, - requests: WsTopicRequest[], - ): Promise>[]> + * + * + * Copy Trading | Future copy trading | Follower Api + * + * + */ ⋮---- -// Previously used to track topics in a request. Keeping this for subscribe/unsubscribe requests, no need for incremental values +export interface CTFuturesFollowerCurrentOrdersV2 { + trackingNo: string; + traderName: string; + openOrderId: string; + closeOrderId: string; + traderId: string; + symbol: string; + posSide: string; + openLeverage: string; + openAvgPrice: string; + openTime: string; + openSize: string; + closeAvgPrice: string; + closeSize: string; + openMarginSz: string; + closeTime: string; +} ⋮---- -/** - { - "op":"subscribe", - "args":[ - { - "instType":"SPOT", - "channel":"ticker", - "instId":"BTCUSDT" - }, - { - "instType":"SPOT", - "channel":"candle5m", - "instId":"BTCUSDT" - } - ] - } - */ +export interface CTFuturesFollowerHistoryOrderV2 { + trackingNo: string; + posSide: string; + openLeverage: string; + openSize: string; + closeSize: string; + openPriceAvg: string; + closePriceAvg: string; + achievedPL: string; + openFee: string; + closeFee: string; + symbol: string; + profitRate: string; + netProfit: string; + openOrderId: string; + closeOrderId: string; + openTime: string; + closeTime: string; + traderId: string; + productType: string; +} ⋮---- -// const request = { -// topic: 'ticker', -// payload: { instType: 'SPOT', instId: 'BTCUSDT' }, -// }; -// becomes: -// const request = { -// channel: 'ticker', -// instType: 'SPOT', -// instId: 'BTCUSDT', -// }; +export interface CTFuturesFollowerHistoryOrdersV2 { + trackingList: CTFuturesFollowerHistoryOrderV2[]; + endId: string; +} ⋮---- -private async getWsAuthSignature( - wsKey: WsKey, - ): Promise<{ expiresAt: number; signature: string }> +export interface CTFuturesFollowerSettingV2 { + symbol: string; + productType: string; + marginType: string; + marginCoin: string; + leverType: string; + longLeverage: string; + shortLeverage: string; + traceType: string; +} ⋮---- -private async signMessage( - paramsStr: string, - secret: string, - method: SignEncodeMethod, - algorithm: SignAlgorithm, - ): Promise +export interface CTFuturesFollowerSettingsV2 { + followerEnable: string; + detailList: CTFuturesFollowerSettingV2[]; +} ⋮---- -protected async getWsAuthRequestEvent( - wsKey: WsKey, - ): Promise> +export interface CTFuturesFollowerMyTradersV2 { + certificationType: string; + traderId: string; + traderName: string; + maxFollowLimit: string; + followCount: string; + traceTotalMarginAmount: string; + traceTotalNetProfit: string; + traceTotalProfit: string; + currentTradingPairs: string[]; + followerTime: string; + bgbMaxFollowLimit: string; + bgbFollowCount: string; +} ⋮---- /** - * Abstraction called to sort ws events into emittable event types (response to a request, data update, etc) - */ -protected resolveEmittableEvents( - wsKey: WsKey, - event: MessageEventLike, - ): EmittableEvent[] -⋮---- -// v2 event processing + * + * + * Copy Trading | Spot copy trading | Trader api + * + * + */ ⋮---- -// v2 authentication event +export interface CTSpotTraderProfitSummaryV2 { + profitSummarys: { + yesterdayProfit: string; + yesterdayTime: string; + sumProfit: string; + waitProfit: string; + }; + profitHistoryList: { + coin: string; + profitCount: string; + lastProfitTime: string; + historysByDateList: { + profit: string; + profitTime: string; + }[]; + }[]; +} ⋮---- -// messageType: typeof msg, -// messageString: JSON.stringify(msg), +export interface CTSpotTraderHistoryProfitShareItemV2 { + profitId: string; + coin: string; + distributeRatio: string; + profit: string; + followerName: string; + profitTime: string; +} ⋮---- -// messageType: typeof msg, -// messageString: JSON.stringify(msg), +export interface CTSpotTraderHistoryProfitSharingV2 { + endId: string; + profitList: CTSpotTraderHistoryProfitShareItemV2[]; +} ⋮---- -// fallback emit anyway +export interface CTSpotTraderUnrealizedProfitV2 { + distributeRatio: string; + coin: string; + profit: string; + followerName: string; +} ⋮---- -/** - * @deprecrated not supported by Bitget's V2 API offering - */ -async sendWSAPIRequest(): Promise - -================ -File: .eslintrc.cjs -================ -// 'no-unused-vars': ['warn'], - -================ -File: .gitignore -================ -!.gitkeep -.DS_STORE -*.log -npm-debug.log* -yarn-debug.log* -yarn-error.log* -lerna-debug.log* -report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json -pids -*.pid -*.seed -*.pid.lock -node_modules/ -.npm -.eslintcache -.node_repl_history -*.tgz -.yarn-integrity -.env -.env.test -.cache -lib -bundleReport.html -.history/ -tiagoSpot.ts -restClientRegex.ts -localtest.sh -privaterepotracker -testfile.ts -dist -repomix.sh -coverage - -================ -File: .jshintrc -================ -{ - "esversion": 8, - "asi": true, - "laxbreak": true, - "predef": [ "-Promise" ] +export interface CTSpotTraderTotalOrderDetailV2 { + totalFollowerNum: string; + currentFollowerNum: string; + maxFollowerNum: string; + tradingOrderNum: string; + totalpl: string; + gainNum: string; + lossNum: string; + totalEquity: string; + winRate: string; + lastWeekRoiList: CTAmountCTimeV2[]; + lastMonthRoiList: CTRateCTimeV2[]; + lastWeekProfitList: CTAmountCTimeV2[]; + lastMonthProfitList: CTAmountCTimeV2[]; } - -================ -File: .prettierrc -================ -{ - "tabWidth": 2, - "singleQuote": true, - "trailingComma": "all" +⋮---- +export interface CTSpotTraderHistoryOrderV2 { + trackingNo: string; + fillSize: string; + buyPrice: string; + sellPrice: string; + achievedPL: string; + buyTime: string; + sellTime: string; + buyFee: string; + sellFee: string; + achievedPLR: string; + symbol: string; + netProfit: string; + followCount: string; +} +export interface CTSpotTraderHistoryOrdersV2 { + endId: string; + trackingList: CTSpotTraderHistoryOrderV2[]; } - -================ -File: jest.config.ts -================ -/** - * For a detailed explanation regarding each configuration property, visit: - * https://jestjs.io/docs/configuration - */ ⋮---- -import type { Config } from 'jest'; +export interface CTSpotTraderCurrentTrackingOrderV2 { + trackingNo: string; + orderId: string; + buyFillSize: string; + buyDelegateSize: string; + buyPrice: string; + unrealizedPL: string; + buyTime: string; + buyFee: string; + unrealizedPLR: string; + symbol: string; + stopLossPrice: string | null; + stopSurplusPrice: string | null; + followCount: string; +} ⋮---- -// All imported modules in your tests should be mocked automatically -// automock: false, +export interface CTSpotTraderCurrentTrackingOrdersV2 { + endId: string; + trackingList: CTSpotTraderCurrentTrackingOrderV2[]; +} ⋮---- -// Stop running tests after `n` failures -// bail: 0, -bail: false, // enable to stop test when an error occur, +export interface CTSpotTraderFollowerListV2 { + accountEquity: string; + isRemove: string; + followerHeadPic: string | null; + followerName: string; + followerUid: string; + followerTime: string; +} ⋮---- -// The directory where Jest should store its cached dependency information -// cacheDirectory: "/private/var/folders/kf/2k3sz4px6c9cbyzj1h_b192h0000gn/T/jest_dx", +/** + * + * + * Copy Trading | Spot copy trading | Follower api + * + * + */ ⋮---- -// Automatically clear mock calls, instances, contexts and results before every test +export interface CTSpotFollowerMyTraderV2 { + certificationType: string; + traceTotalAmount: string; + traceTotalNetProfit: string; + traceTotalProfit: string; + traderName: string; + traderId: string; + maxFollowLimit: string; + bgbMaxFollowLimit: string; + followCount: string; + bgbFollowCount: string; + followerTime: string; +} ⋮---- -// Indicates whether the coverage information should be collected while executing the test +export interface CTSpotFollowerMyTradersV2 { + resultList: CTSpotFollowerMyTraderV2[]; +} ⋮---- -// An array of glob patterns indicating a set of files for which coverage information should be collected +export interface CTSpotFollowerTradeSettingV2 { + maxTraceAmount: string; + stopLossRation: string; + stopSurplusRation: string; + symbol: string; + traceType: string; +} ⋮---- -// The directory where Jest should output its coverage files +export interface CTSpotFollowerTradeSymbolSettingV2 { + maxStopLossRation: string; + maxStopSurplusRation: string; + maxTraceAmount: string; + maxTraceAmountSystem: string; + maxTraceSize: string; + maxTraceRation: string; + minStopLossRation: string; + minStopSurplusRation: string; + minTraceAmount: string; + minTraceSize: string; + minTraceRation: string; + sliderMaxStopLossRatio: string; + sliderMaxStopSurplusRatio: string; + symbol: string; +} ⋮---- -// An array of regexp pattern strings used to skip coverage collection -// coveragePathIgnorePatterns: [ -// "/node_modules/" -// ], +export interface CTSpotFollowerFollowConfigurationV2 { + enable: string; + profitRate: string; + settledInDays: string; + tradeSettingList: CTSpotFollowerTradeSettingV2[]; + tradeSymbolSettingList: CTSpotFollowerTradeSymbolSettingV2[]; + traderHeadPic: string; + traderName: string; +} ⋮---- -// Indicates which provider should be used to instrument code for coverage +export interface CTSpotFollowerHistoryOrderV2 { + trackingNo: string; + traderId: string; + fillSize: string; + buyPrice: string; + sellPrice: string; + buyFee: string; + sellFee: string; + achievedPL: string; + achievedPLR: string; + symbol: string; + buyTime: string; + sellTime: string; +} +export interface CTSpotFollowerHistoryOrdersV2 { + endId: string; + trackingList: CTSpotFollowerHistoryOrderV2[]; +} ⋮---- -// A list of reporter names that Jest uses when writing coverage reports -// coverageReporters: [ -// "json", -// "text", -// "lcov", -// "clover" -// ], +export interface CTSpotFollowerCurrentOrderV2 { + trackingNo: string; + traderId: string; + buyFillSize: string; + buyDelegateSize: string; + buyPrice: string; + unrealizedPL: string; + buyTime: string; + buyFee: string; + unrealizedPLR: string; + symbol: string; + stopSurplusPrice: string | null; + stopLossPrice: string | null; +} ⋮---- -// An object that configures minimum threshold enforcement for coverage results -// coverageThreshold: undefined, +export interface CTSpotFollowerCurrentOrdersV2 { + endId: string; + trackingList: CTSpotFollowerCurrentOrderV2[]; +} + +================ +File: src/types/response/v2/margin.ts +================ +/** + * + * * Margin | Common + * + */ ⋮---- -// 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, +export interface MarginCurrencyV2 { + symbol: string; + baseCoin: string; + quoteCoin: string; + maxCrossedLeverage: string; + maxIsolatedLeverage: string; + warningRiskRatio: string; + liquidationRiskRatio: string; + minTradeAmount: string; + maxTradeAmount: string; + takerFeeRate: string; + makerFeeRate: string; + pricePrecision: string; + quantityPrecision: string; + minTradeUSDT: string; + isBorrowable: boolean; + userMinBorrow: string; + status: string; + isIsolatedBaseBorrowable: boolean; + isIsolatedQuoteBorrowable: boolean; + isCrossBorrowable: boolean; +} ⋮---- -// A set of global variables that need to be available in all test environments -// globals: {}, +/** + * + * * Margin | Cross/Isolated | Order Record + * + */ ⋮---- -// 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%", +export interface MarginBorrowHistoryItemV2 { + loanId: string; + coin: string; + borrowAmount: string; + borrowType: string; + cTime: string; + uTime: string; +} ⋮---- -// An array of directory names to be searched recursively up from the requiring module's location -// moduleDirectories: [ -// "node_modules" -// ], +export interface MarginRepaymentHistoryItemV2 { + repayId: string; + coin: string; + repayAmount: string; + repayType: string; + repayInterest: string; + repayPrincipal: string; + symbol: string; + cTime: string; + uTime: string; +} ⋮---- -// An array of file extensions your modules use +export interface MarginInterestHistoryItemV2 { + interestId: string; + interestCoin: string; + dailyInterestRate: string; + loanCoin: string; + interestAmount: string; + interstType: string; + symbol: string; + cTime: string; + uTime: string; +} ⋮---- -// modulePaths: ['src'], +export interface MarginLiquidationHistoryItemV2 { + liqId: string; + symbol: string; + liqStartTime: string; + liqEndTime: string; + liqRiskRatio: string; + totalAssets: string; + totalDebt: string; + liqFee: string; + cTime: string; + uTime: string; +} ⋮---- -// 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: {}, +export interface MarginFinancialHistoryItemV2 { + coin: string; + symbol: string; + marginId: string; + amount: string; + balance: string; + fee: string; + marginType: string; + cTime: string; + uTime: string; +} ⋮---- -// An array of regexp pattern strings, matched against all module paths before considered 'visible' to the module loader -// modulePathIgnorePatterns: [], +/** + * + * * Margin | Cross/Isolated | Account + * + */ ⋮---- -// Activates notifications for test results -// notify: false, +export interface MarginAccountAssetV2 { + symbol: string; + coin: string; + totalAmount: string; + available: string; + frozen: string; + borrow: string; + interest: string; + net: string; + coupon: string; + cTime: string; + uTime: string; +} ⋮---- -// An enum that specifies notification mode. Requires { notify: true } -// notifyMode: "failure-change", +export interface CrossMaxBorrowableResponseV2 { + coin: string; + maxBorrowableAmount: string; +} ⋮---- -// A preset that is used as a base for Jest's configuration -// preset: undefined, +export interface IsolatedMaxBorrowableResponseV2 { + symbol: string; + baseCoin: string; + baseCoinMaxBorrowAmount: string; + quoteCoin: string; + quoteCoinMaxBorrowAmount: string; +} ⋮---- -// Run tests from one or more projects -// projects: undefined, +export interface CrossMaxTransferableResponseV2 { + coin: string; + maxTransferOutAmount: string; +} ⋮---- -// Use this configuration option to add custom reporters to Jest -// reporters: undefined, +export interface IsolatedMaxTransferableResponseV2 { + baseCoin: string; + symbol: string; + baseCoinMaxTransferOutAmount: string; + quoteCoin: string; + quoteCoinMaxTransferOutAmount: string; +} ⋮---- -// Automatically reset mock state before every test -// resetMocks: false, +export interface CrossInterestRateAndLimitResponseV2 { + transferable: boolean; + leverage: string; + coin: string; + borrowable: boolean; + dailyInterestRate: string; + annualInterestRate: string; + maxBorrowableAmount: string; + vipList: { + level: string; + limit: string; + dailyInterestRate: string; + annualInterestRate: string; + discountRate: string; + }[]; +} ⋮---- -// Reset the module registry before running each individual test -// resetModules: false, +export interface IsolatedInterestRateAndLimitResponseV2 { + symbol: string; + leverage: string; + baseCoin: string; + baseTransferable: boolean; + baseBorrowable: boolean; + baseDailyInterestRate: string; + baseAnnuallyInterestRate: string; + baseMaxBorrowableAmount: string; + baseVipList: { + level: string; + dailyInterestRate: string; + limit: string; + annuallyInterestRate: string; + discountRate: string; + }[]; + quoteCoin: string; + quoteTransferable: boolean; + quoteBorrowable: boolean; + quoteDailyInterestRate: string; + quoteAnnuallyInterestRate: string; + quoteMaxBorrowableAmount: string; + quoteList: { + level: string; + dailyInterestRate: string; + limit: string; + annuallyInterestRate: string; + discountRate: string; + }[]; +} ⋮---- -// A path to a custom resolver -// resolver: undefined, +export interface CrossTierConfigurationResponseV2 { + tier: string; + leverage: string; + coin: string; + maxBorrowableAmount: string; + maintainMarginRate: string; +} ⋮---- -// Automatically restore mock state and implementation before every test -// restoreMocks: false, +export interface IsolatedTierConfigurationResponseV2 { + tier: string; + symbol: string; + leverage: string; + baseCoin: string; + quoteCoin: string; + baseMaxBorrowableAmount: string; + quoteMaxBorrowableAmount: string; + maintainMarginRate: string; + initRate: string; +} ⋮---- -// The root directory that Jest should scan for tests and modules within -// rootDir: undefined, +/** + * + * * Margin | Cross/Isolated | Trade + * + */ ⋮---- -// A list of paths to directories that Jest should use to search for files in -// roots: [ -// "" -// ], +export interface MarginBatchOrdersResponseV2 { + successList: { + orderId: string; + clientOid: string; + }[]; + failureList: { + clientOid: string; + errorMsg: string; + }[]; +} ⋮---- -// Allows you to use a custom runner instead of Jest's default test runner -// runner: "jest-runner", +export interface MarginCurrentOrderV2 { + orderId: string; + symbol: string; + orderType: string; + enterPointSource: string; + clientOid: string; + loanType: string; + price: string; + side: string; + status: string; + baseSize: string; + quoteSize: string; + priceAvg: string; + size: string; + amount: string; + force: string; + cTime: string; + uTime: string; +} ⋮---- -// The paths to modules that run some code to configure or set up the testing environment before each test -// setupFiles: [], +export interface MarginHistoryOrderV2 { + orderId: string; + symbol: string; + orderType: string; + enterPointSource: string; + clientOid: string; + loanType: string; + price: string; + side: string; + status: string; + baseSize: string; + quoteSize: string; + priceAvg: string; + size: string; + amount: string; + force: string; + cTime: string; + uTime: string; +} ⋮---- -// A list of paths to modules that run some code to configure or set up the testing framework before each test -// setupFilesAfterEnv: [], +export interface MarginOrderFillV2 { + orderId: string; + tradeId: string; + orderType: string; + side: string; + priceAvg: string; + size: string; + amount: string; + tradeScope: string; + feeDetail: { + deduction: string; + feeCoin: string; + totalDeductionFee: string; + totalFee: string; + }; + cTime: string; + uTime: string; +} ⋮---- -// The number of seconds after which a test is considered as slow and reported as such in the results. -// slowTestThreshold: 5, +export interface MarginLiquidationOrderV2 { + symbol: string; + orderType: string; + side: string; + priceAvg: string; + price: string; + fillSize: string; + size: string; + amount: string; + orderId: string; + fromCoin: string; + toCoin: string; + fromSize: string; + toSize: string; + cTime: string; + uTime: string; +} + +================ +File: src/types/websockets/ws-api-response.ts +================ +export interface WSAPIPlaceOrderResponseV3 { + symbol: string; + orderId: string; + clientOid: string; + cTime: string; +} + +================ +File: src/types/shared.ts +================ +import { REST_CLIENT_TYPE_ENUM } from '../util/requestUtils.js'; ⋮---- -// A list of paths to snapshot serializer modules Jest should use for snapshot testing -// snapshotSerializers: [], +export type numberInString = string; ⋮---- -// The test environment that will be used for testing -// testEnvironment: "jest-environment-node", +export type OrderSide = 'Buy' | 'Sell'; ⋮---- -// Options that will be passed to the testEnvironment -// testEnvironmentOptions: {}, +/** + * @deprecated use SpotKlineInterval or FuturesKlineInterval, depending on which API group you're using + */ +export type KlineInterval = + | '1min' + | '5min' + | '15min' + | '30min' + | '1h' + | '4h' + | '6h' + | '12h' + | '1M' + | '1W' + | '1week' + | '6Hutc' + | '12Hutc' + | '1Dutc' + | '3Dutc' + | '1Wutc' + | '1Mutc'; ⋮---- -// Adds a location field to test results -// testLocationInResults: false, +export type RestClientType = + (typeof REST_CLIENT_TYPE_ENUM)[keyof typeof REST_CLIENT_TYPE_ENUM]; ⋮---- -// The glob patterns Jest uses to detect test files +export interface APIResponse { + code: string; + requestTime: number; + msg: 'success' | string; + data: T; +} + +================ +File: src/websocket-client-v2.ts +================ +import { + WSOperation, + WSOperationLoginParams, + WsRequestOperationBitget, +} from './types/websockets/ws-api.js'; +import { MessageEventLike } from './types/websockets/ws-events.js'; +import { + BitgetInstTypeV2, + WsKey, + WsTopicV2, +} from './types/websockets/ws-general.js'; +import { + BaseWebsocketClient, + EmittableEvent, + MidflightWsRequestEvent, +} from './util/BaseWSClient.js'; +import { isWsPong } from './util/requestUtils.js'; +import { + SignAlgorithm, + SignEncodeMethod, + signMessage, +} from './util/webCryptoAPI.js'; +import { + getMaxTopicsPerSubscribeEvent, + getNormalisedTopicRequests, + getWsUrl, + isPrivateChannel, + WS_AUTH_ON_CONNECT_KEYS, + WS_KEY_MAP, + WsTopicRequest, +} from './util/websocket-util.js'; +import { WSConnectedResult } from './util/WsStore.types.js'; ⋮---- -// "**/__tests__/**/*.[jt]s?(x)", +export class WebsocketClientV2 extends BaseWebsocketClient< ⋮---- -// An array of regexp pattern strings that are matched against all test paths, matched tests are skipped -// testPathIgnorePatterns: [ -// "/node_modules/" -// ], +WsRequestOperationBitget // subscribe requests have an "args" parameter with an object within ⋮---- -// The regexp pattern or array of patterns that Jest uses to detect test files -// testRegex: [], +/** + * Request connection of all dependent (public & private) websockets, instead of waiting for automatic connection by library + */ +public connectAll(): Promise[] ⋮---- -// This option allows the use of a custom results processor -// testResultsProcessor: undefined, +/** Some private channels use `coin` instead of `instId`. This method handles building the sub/unsub request */ +private getSubRequest( + instType: BitgetInstTypeV2, + topic: WsTopicV2, + coin: string = 'default', + ): WsTopicRequest ⋮---- -// This option allows use of a custom test runner -// testRunner: "jest-circus/runner", +/** + * Subscribe to a topic + * @param instType instrument type (refer to API docs). + * @param topic topic name (e.g. "ticker"). + * @param instId instrument ID (e.g. "BTCUSDT"). Use "default" for private topics. + */ +public subscribeTopic( + instType: BitgetInstTypeV2, + topic: WsTopicV2, + coin: string = 'default', + ) ⋮---- -// A map from regular expressions to paths to transformers -// transform: undefined, +/** + * Unsubscribe from a topic + * @param instType instrument type (refer to API docs). + * @param topic topic name (e.g. "ticker"). + * @param instId instrument ID (e.g. "BTCUSDT"). Use "default" for private topics to get all symbols. + */ +public unsubscribeTopic( + instType: BitgetInstTypeV2, + topic: WsTopicV2, + coin: string = 'default', + ) ⋮---- -// An array of regexp pattern strings that are matched against all source file paths, matched files will skip transformation -// transformIgnorePatterns: [ -// "/node_modules/", -// "\\.pnp\\.[^\\/]+$" -// ], +/** + * 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, category: CategoryV5}. + * + * - Subscriptions are automatically routed to the correct websocket connection. + * - Authentication/connection is automatic. + * - Resubscribe after network issues is automatic. + * + * Call `unsubscribe(topics)` to remove topics + */ +public subscribe( + requests: + | (WsTopicRequest | WsTopicV2) + | (WsTopicRequest | WsTopicV2)[], + wsKey: WsKey, + ): Promise ⋮---- -// Prevents import esm module error from v1 axios release, issue #5026 +/** + * Unsubscribe from one or more topics. Similar to subscribe() but in reverse. + * + * - Requests are automatically routed to the correct websocket connection. + * - These topics will be removed from the topic cache, so they won't be subscribed to again. + */ +public unsubscribe( + requests: + | (WsTopicRequest | WsTopicV2) + | (WsTopicRequest | WsTopicV2)[], + wsKey: WsKey, + ) ⋮---- -// 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 +/** + * + * + * Internal methods required to integrate with the BaseWSClient + * + * + */ ⋮---- -// An array of regexp patterns that are matched against all source file paths before re-running tests in watch mode -// watchPathIgnorePatterns: [], +protected sendPingEvent(wsKey: WsKey): void ⋮---- -// Whether to use watchman for file crawling -// watchman: true, - -================ -File: LICENSE.md -================ -Copyright 2022 Tiago Siebler - -Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - -================ -File: postBuild.sh -================ -#!/bin/bash -# -# Add package.json files to cjs/mjs subtrees -# - -cat >dist/cjs/package.json <dist/mjs/package.json <, + wsKey: WsKey, + ): boolean ⋮---- -// note the single quotes, preventing special characters such as $ from being incorrectly passed +protected getPrivateWSKeys(): WsKey[] ⋮---- -// apiKey: 'apiKeyHere', -// apiSecret: 'apiSecretHere', -// apiPass: 'apiPassHere', +protected isAuthOnConnectWsKey(wsKey: WsKey): boolean ⋮---- -function logWSEvent(type: string, data: any) +protected async getWsUrl(wsKey: WsKey): Promise ⋮---- -// simple sleep function -function promiseSleep(milliseconds: number) +protected getMaxTopicsPerSubscribeEvent(wsKey: WsKey): number | null ⋮---- /** - * This is a simple script wrapped in a immediately invoked function expression (to execute the below workflow immediately). - * - * It is designed to: - * - open a private websocket channel to log account events - * - check for any available USDT balance in the futures account - * - immediately open a minimum sized long position on BTCUSDT - * - check active positions - * - immediately send closing orders for any active futures positions - * - check positions again - * - */ -⋮---- -// Add event listeners to log websocket events on account + * @returns one or more correctly structured request events for performing a operations over WS. This can vary per exchange spec. + */ +protected async getWsRequestEvents( + operation: WSOperation, + requests: WsTopicRequest[], + ): Promise>[]> ⋮---- -// futures private -// : account updates +// Previously used to track topics in a request. Keeping this for subscribe/unsubscribe requests, no need for incremental values ⋮---- -// : position updates +/** + { + "op":"subscribe", + "args":[ + { + "instType":"SPOT", + "channel":"ticker", + "instId":"BTCUSDT" + }, + { + "instType":"SPOT", + "channel":"candle5m", + "instId":"BTCUSDT" + } + ] + } + */ ⋮---- -// : order updates +// const request = { +// topic: 'ticker', +// payload: { instType: 'SPOT', instId: 'BTCUSDT' }, +// }; +// becomes: +// const request = { +// channel: 'ticker', +// instType: 'SPOT', +// instId: 'BTCUSDT', +// }; ⋮---- -// wait briefly for ws to be ready (could also use the response or authenticated events, to make sure topics are subscribed to before starting) +private async getWsAuthSignature( + wsKey: WsKey, + ): Promise<{ expiresAt: number; signature: string }> ⋮---- -// const balances = allBalances.filter((bal) => Number(bal.available) != 0); +private async signMessage( + paramsStr: string, + secret: string, + method: SignEncodeMethod, + algorithm: SignAlgorithm, + ): Promise ⋮---- -// Loop through any active positions and send a closing market order on each position - -================ -File: examples/V2 - Classic/Rest/rest-trade-spot.ts -================ -import { - RestClientV2, - SpotOrderRequestV2, - WebsocketClientV2, -} from '../../../src/index.js'; +protected async getWsAuthRequestEvent( + wsKey: WsKey, + ): Promise> ⋮---- -// import { RestClientV2, WebsocketClient } from '../src/index'; +/** + * Abstraction called to sort ws events into emittable event types (response to a request, data update, etc) + */ +protected resolveEmittableEvents( + wsKey: WsKey, + event: MessageEventLike, + ): EmittableEvent[] ⋮---- -// read from environmental variables +// v2 event processing ⋮---- -// If running from CLI in unix, you can pass env vars as such: -// API_KEY_COM='lkm12n3-2ba3-1mxf-fn13-lkm12n3a' API_SECRET_COM='035B2B9637E1BDFFEE2646BFBDDB8CE4' API_PASSPHRASE_COM='ComplexPa$$!23$5^' ts-node examples/rest-trade-spot.ts +// v2 authentication event ⋮---- -// note the single quotes, preventing special characters such as $ from being incorrectly passed +// messageType: typeof msg, +// messageString: JSON.stringify(msg), ⋮---- -// apiKey: 'apiKeyHere', -// apiSecret: 'apiSecretHere', -// apiPass: 'apiPassHere', -⋮---- -function logWSEvent(type: string, data: any) -⋮---- -// simple sleep function -function promiseSleep(milliseconds: number) -⋮---- -/** This is a simple script wrapped in a immediately invoked function expression, designed to check for any available BTC balance and immediately sell the full amount for USDT */ -⋮---- -// Add event listeners to log websocket events on account -⋮---- -// Subscribe to private account topics -// spot private -// : account updates -⋮---- -// : order updates (note: symbol is required) +// messageType: typeof msg, +// messageString: JSON.stringify(msg), ⋮---- -// wait briefly for ws to be ready (could also use the response or authenticated events, to make sure topics are subscribed to before starting) +// fallback emit anyway ⋮---- -// console.log('balance: ', JSON.stringify(balances, null, 2)); +/** + * @deprecrated not supported by Bitget's V2 API offering + */ +async sendWSAPIRequest(): Promise ================ -File: examples/V2 - Classic/Websocket/ws-demo-trading.ts +File: .eslintrc.cjs ================ -import { DefaultLogger, WebsocketClientV2 } from '../../../src/index.js'; +// 'no-unused-vars': ['warn'], + +================ +File: .gitignore +================ +!.gitkeep +.DS_STORE +*.log +npm-debug.log* +yarn-debug.log* +yarn-error.log* +lerna-debug.log* +report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json +pids +*.pid +*.seed +*.pid.lock +node_modules/ +.npm +.eslintcache +.node_repl_history +*.tgz +.yarn-integrity +.env +.env.test +.cache +lib +bundleReport.html +.history/ +tiagoSpot.ts +restClientRegex.ts +localtest.sh +privaterepotracker +testfile.ts +dist +repomix.sh +coverage + +================ +File: .jshintrc +================ +{ + "esversion": 8, + "asi": true, + "laxbreak": true, + "predef": [ "-Promise" ] +} + +================ +File: .prettierrc +================ +{ + "tabWidth": 2, + "singleQuote": true, + "trailingComma": "all" +} + +================ +File: jest.config.ts +================ +/** + * For a detailed explanation regarding each configuration property, visit: + * https://jestjs.io/docs/configuration + */ ⋮---- -// or -// import { DefaultLogger, WS_KEY_MAP, WebsocketClientV2 } from 'bitget-api'; +import type { Config } from 'jest'; ⋮---- -// If running from CLI in unix, you can pass env vars as such: -// API_KEY_COM='lkm12n3-2ba3-1mxf-fn13-lkm12n3a' API_SECRET_COM='035B2B9637E1BDFFEE2646BFBDDB8CE4' API_PASSPHRASE_COM='ComplexPa$$!23$5^' ts-node examples/ws-private.ts +// All imported modules in your tests should be mocked automatically +// automock: false, ⋮---- -// restOptions: { -// optionally provide rest options, e.g. to pass through a proxy -// }, +// Stop running tests after `n` failures +// bail: 0, +bail: false, // enable to stop test when an error occur, ⋮---- -// Set demoTrading to true, to route all connections to the demo trading wss URLs: +// The directory where Jest should store its cached dependency information +// cacheDirectory: "/private/var/folders/kf/2k3sz4px6c9cbyzj1h_b192h0000gn/T/jest_dx", ⋮---- -// If using private topics, make sure to include API keys +// Automatically clear mock calls, instances, contexts and results before every test ⋮---- -// console.log('WS raw message received ', JSON.stringify(data, null, 2)); +// Indicates whether the coverage information should be collected while executing the test ⋮---- -/** - * Public events - */ - -================ -File: examples/V2 - Classic/Websocket/ws-private.ts -================ -import { DefaultLogger, WebsocketClientV2 } from '../../../src/index.js'; +// An array of glob patterns indicating a set of files for which coverage information should be collected ⋮---- -// or -// import { DefaultLogger, WS_KEY_MAP, WebsocketClientV2 } from 'bitget-api'; +// The directory where Jest should output its coverage files ⋮---- -// If running from CLI in unix, you can pass env vars as such: -// API_KEY_COM='lkm12n3-2ba3-1mxf-fn13-lkm12n3a' API_SECRET_COM='035B2B9637E1BDFFEE2646BFBDDB8CE4' API_PASSPHRASE_COM='ComplexPa$$!23$5^' ts-node examples/ws-private.ts +// An array of regexp pattern strings used to skip coverage collection +// coveragePathIgnorePatterns: [ +// "/node_modules/" +// ], ⋮---- -// note the single quotes, preventing special characters such as $ from being incorrectly passed +// Indicates which provider should be used to instrument code for coverage ⋮---- -// restOptions: { -// optionally provide rest options, e.g. to pass through a proxy -// }, +// A list of reporter names that Jest uses when writing coverage reports +// coverageReporters: [ +// "json", +// "text", +// "lcov", +// "clover" +// ], ⋮---- -// console.log('WS raw message received ', JSON.stringify(data, null, 2)); +// An object that configures minimum threshold enforcement for coverage results +// coverageThreshold: undefined, ⋮---- -// auth happens async after the ws connection opens +// A path to a custom dependency extractor +// dependencyExtractor: undefined, ⋮---- -// wsClient.subscribePublicSpotTickers(['BTCUSDT', 'LTCUSDT']); +// Make calling deprecated APIs throw helpful error messages +// errorOnDeprecated: false, ⋮---- -/** - * Private account updates - */ +// The default configuration for fake timers +// fakeTimers: { +// "enableGlobally": false +// }, ⋮---- -// spot private -// : account updates +// Force coverage collection from ignored files using an array of glob patterns +// forceCoverageMatch: [], ⋮---- -// : order updates (note: symbol is required) -// wsClient.subscribeTopic('SPOT', 'orders', 'BTCUSDT'); +// A path to a module which exports an async function that is triggered once before all test suites +// globalSetup: undefined, ⋮---- -// futures private -// : account updates +// A path to a module which exports an async function that is triggered once after all test suites +// globalTeardown: undefined, ⋮---- -// : position updates -// wsClient.subscribeTopic('USDT-FUTURES', 'positions'); +// A set of global variables that need to be available in all test environments +// globals: {}, ⋮---- -// : order updates -// wsClient.subscribeTopic('USDT-FUTURES', 'orders'); +// 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%", ⋮---- -// : plan order updates -// wsClient.subscribeTopic('USDT-FUTURES', 'orders-algo'); +// An array of directory names to be searched recursively up from the requiring module's location +// moduleDirectories: [ +// "node_modules" +// ], ⋮---- -// wsClient -// .getWsStore() -// .getKeys() -// .forEach((wsKey) => { -// const state = wsClient.getWsStore().get(wsKey); -// console.log(`${wsKey} state: `, state.subscribedTopics.values()); -// }); +// An array of file extensions your modules use ⋮---- -// setTimeout(() => { -// wsClient.unsubscribeTopic('USDT-FUTURES', 'account'); -// }, 1000 * 2); +// modulePaths: ['src'], ⋮---- -// setTimeout(() => { -// wsClient -// .getWsStore() -// .getKeys() -// .forEach((wsKey) => { -// const state = wsClient.getWsStore().get(wsKey); -// console.log(`${wsKey} state: `, state.subscribedTopics.values()); -// }); -// }, 1000 * 5); - -================ -File: examples/V2 - Classic/Websocket/ws-public.ts -================ -import { - DefaultLogger, - WebsocketClientV2, - WS_KEY_MAP, -} from '../../../src/index.js'; +// 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: {}, ⋮---- -// or -// import { DefaultLogger, WS_KEY_MAP, WebsocketClientV2 } from 'bitget-api'; +// An array of regexp pattern strings, matched against all module paths before considered 'visible' to the module loader +// modulePathIgnorePatterns: [], ⋮---- -// restOptions: { -// optionally provide rest options, e.g. to pass through a proxy -// }, +// Activates notifications for test results +// notify: false, ⋮---- -// console.log('WS raw message received ', JSON.stringify(data, null, 2)); +// An enum that specifies notification mode. Requires { notify: true } +// notifyMode: "failure-change", ⋮---- -/** - * Public events - */ +// A preset that is used as a base for Jest's configuration +// preset: undefined, ⋮---- -// Spot public +// Run tests from one or more projects +// projects: undefined, ⋮---- -// tickers +// Use this configuration option to add custom reporters to Jest +// reporters: undefined, ⋮---- -// candles -// wsClient.subscribeTopic('SPOT', 'candle1m', symbol); +// Automatically reset mock state before every test +// resetMocks: false, ⋮---- -// orderbook updates -// wsClient.subscribeTopic('SPOT', 'books', symbol); +// Reset the module registry before running each individual test +// resetModules: false, ⋮---- -// trades -// wsClient.subscribeTopic('SPOT', 'trade', symbol); +// A path to a custom resolver +// resolver: undefined, ⋮---- -// Futures public +// Automatically restore mock state and implementation before every test +// restoreMocks: false, ⋮---- -// tickers -// wsClient.subscribeTopic('USDT-FUTURES', 'ticker', symbol); -⋮---- -// candles -// wsClient.subscribeTopic('USDT-FUTURES', 'candle1m', symbol); -⋮---- -// orderbook updates -// wsClient.subscribeTopic('USDT-FUTURES', 'books', symbol); -⋮---- -// trades -// wsClient.subscribeTopic('USDT-FUTURES', 'trade', symbol); -⋮---- -// Topics are tracked per websocket type -// Get a list of subscribed topics (e.g. all public topics) (after a 5 second delay) - -================ -File: examples/V3 - UTA/Rest/rest-trade-UTA-futures.ts -================ -/* eslint-disable @typescript-eslint/no-unused-vars */ -import { - PlaceOrderRequestV3, - RestClientV3, - WebsocketClientV3, -} from '../../../src/index.js'; -⋮---- -// or -// import { PlaceOrderRequestV3, RestClientV3, WebsocketClientV3 } from '../src'; -⋮---- -// read from environmental variables -⋮---- -// If running from CLI in unix, you can pass env vars as such: -// API_KEY_COM='lkm12n3-2ba3-1mxf-fn13-lkm12n3a' API_SECRET_COM='035B2B9637E1BDFFEE2646BFBDDB8CE4' API_PASSPHRASE_COM='ComplexPa$$!23$5^' ts-node examples/V3/rest-trade-futures.ts -⋮---- -// note the single quotes, preventing special characters such as $ from being incorrectly passed +// The root directory that Jest should scan for tests and modules within +// rootDir: undefined, ⋮---- -// apiKey: 'apiKeyHere', -// apiSecret: 'apiSecretHere', -// apiPass: 'apiPassHere', +// A list of paths to directories that Jest should use to search for files in +// roots: [ +// "" +// ], ⋮---- -function logWSEvent(type: string, data: any) +// Allows you to use a custom runner instead of Jest's default test runner +// runner: "jest-runner", ⋮---- -// simple sleep function -function promiseSleep(milliseconds: number) +// The paths to modules that run some code to configure or set up the testing environment before each test +// setupFiles: [], ⋮---- -/** - * This is a simple script wrapped in a immediately invoked function expression (to execute the below workflow immediately). - * - * It is designed to: - * - open a private websocket channel to log account events - * - check for any available USDT balance in the account - * - immediately open a minimum sized long position on BTCUSDT - * - check active positions - * - immediately send closing orders for any active futures positions - * - check positions again - * - */ +// A list of paths to modules that run some code to configure or set up the testing framework before each test +// setupFilesAfterEnv: [], ⋮---- -// Add event listeners to log websocket events on account +// The number of seconds after which a test is considered as slow and reported as such in the results. +// slowTestThreshold: 5, ⋮---- -// Subscribe to private topics for UTA account +// A list of paths to snapshot serializer modules Jest should use for snapshot testing +// snapshotSerializers: [], ⋮---- -// Subscribe to position updates +// The test environment that will be used for testing +// testEnvironment: "jest-environment-node", ⋮---- -// Subscribe to order updates +// Options that will be passed to the testEnvironment +// testEnvironmentOptions: {}, ⋮---- -// wait briefly for ws to be ready (could also use the response or authenticated events, to make sure topics are subscribed to before starting) +// Adds a location field to test results +// testLocationInResults: false, ⋮---- -// Loop through any active positions and send a closing market order on each position - -================ -File: examples/V3 - UTA/Rest/rest-trade-UTA-spot.ts -================ -/* eslint-disable @typescript-eslint/no-unused-vars */ -import { - PlaceOrderRequestV3, - RestClientV3, - WebsocketClientV3, -} from '../../../src/index.js'; +// The glob patterns Jest uses to detect test files ⋮---- -// import { RestClientV3, WebsocketClientV3 } from '../src/index'; +// "**/__tests__/**/*.[jt]s?(x)", ⋮---- -// read from environmental variables +// An array of regexp pattern strings that are matched against all test paths, matched tests are skipped +// testPathIgnorePatterns: [ +// "/node_modules/" +// ], ⋮---- -// If running from CLI in unix, you can pass env vars as such: -// API_KEY_COM='lkm12n3-2ba3-1mxf-fn13-lkm12n3a' API_SECRET_COM='035B2B9637E1BDFFEE2646BFBDDB8CE4' API_PASSPHRASE_COM='ComplexPa$$!23$5^' ts-node examples/V3/rest-trade-spot.ts +// The regexp pattern or array of patterns that Jest uses to detect test files +// testRegex: [], ⋮---- -// note the single quotes, preventing special characters such as $ from being incorrectly passed +// This option allows the use of a custom results processor +// testResultsProcessor: undefined, ⋮---- -// apiKey: 'apiKeyHere', -// apiSecret: 'apiSecretHere', -// apiPass: 'apiPassHere', +// This option allows use of a custom test runner +// testRunner: "jest-circus/runner", ⋮---- -function logWSEvent(type: string, data: any) +// A map from regular expressions to paths to transformers +// transform: undefined, ⋮---- -// simple sleep function -function promiseSleep(milliseconds: number) +// An array of regexp pattern strings that are matched against all source file paths, matched files will skip transformation +// transformIgnorePatterns: [ +// "/node_modules/", +// "\\.pnp\\.[^\\/]+$" +// ], ⋮---- -/** This is a simple script wrapped in a immediately invoked function expression, designed to check for any available BTC balance and immediately sell the full amount for USDT */ +// Prevents import esm module error from v1 axios release, issue #5026 ⋮---- -// Add event listeners to log websocket events on account +// 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, ⋮---- -// Subscribe to private account topics -// Account updates for UTA (unified trading account) +// Indicates whether each individual test should be reported during the run +// verbose: undefined, +verbose: true, // report individual test ⋮---- -// Order updates for spot +// An array of regexp patterns that are matched against all source file paths before re-running tests in watch mode +// watchPathIgnorePatterns: [], ⋮---- -// wait briefly for ws to be ready (could also use the response or authenticated events, to make sure topics are subscribed to before starting) +// Whether to use watchman for file crawling +// watchman: true, ================ -File: examples/V3 - UTA/Websocket/ws-private.ts +File: LICENSE.md ================ -import { - DefaultLogger, - WebsocketClientV3, - WS_KEY_MAP, -} from '../../../src/index.js'; -⋮---- -// or -// import { DefaultLogger, WS_KEY_MAP, WebsocketClientV2 } from 'bitget-api'; -⋮---- -// If running from CLI in unix, you can pass env vars as such: -// API_KEY_COM='lkm12n3-2ba3-1mxf-fn13-lkm12n3a' API_SECRET_COM='035B2B9637E1BDFFEE2646BFBDDB8CE4' API_PASSPHRASE_COM='ComplexPa$$!23$5^' ts-node examples/ws-private.ts -⋮---- -// console.log('WS raw message received ', JSON.stringify(data, null, 2)); -⋮---- -// You can subscribe to one topic at a time -⋮---- -instType: 'UTA', // Note: all account events go on the UTA instType -⋮---- -WS_KEY_MAP.v3Private, // This parameter points to private or public -⋮---- -// Note: all account events go on the UTA instType -⋮---- -// Or multiple at once: -⋮---- -// Topics are tracked per websocket type -// The below example will pull a list of subscribed topics on that connection (e.g. all private topics), after a 5 second delay: +Copyright 2022 Tiago Siebler + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ================ -File: examples/V3 - UTA/Websocket/ws-public.ts +File: postBuild.sh ================ -import { - DefaultLogger, - WebsocketClientV3, - WS_KEY_MAP, -} from '../../../src/index.js'; -⋮---- -// or -// import { DefaultLogger, WS_KEY_MAP, WebsocketClientV2 } from 'bitget-api'; -⋮---- -// console.log('WS raw message received ', JSON.stringify(data, null, 2)); -⋮---- -/** - * Public events - */ -⋮---- -// You can subscribe to one topic at a time -⋮---- -WS_KEY_MAP.v3Public, // This parameter points to private or public -⋮---- -// Or multiple at once: -⋮---- -// Topics are tracked per websocket type -// The below example will pull a list of subscribed topics on that connection (e.g. all public topics), after a 5 second delay: +#!/bin/bash +# +# Add package.json files to cjs/mjs subtrees +# + +cat >dist/cjs/package.json <dist/mjs/package.json <( -// wsClient: TWSClient, -// ): void { -// wsClient.on('update', (data) => { -// console.log('raw message received ', JSON.stringify(data)); -// }); -// wsClient.on('open', (data) => { -// console.log('ws connected', data.wsKey); -// }); -// wsClient.on('reconnect', ({ wsKey }) => { -// console.log('ws automatically reconnecting.... ', wsKey); -// }); -// wsClient.on('reconnected', (data) => { -// console.log('ws has reconnected ', data?.wsKey); -// }); -// wsClient.on('authenticated', (data) => { -// console.log('ws has authenticated ', data?.wsKey); -// }); -// } -⋮---- -// If running from CLI in unix, you can pass env vars as such: -// API_KEY_COM='lkm12n3-2ba3-1mxf-fn13-lkm12n3a' API_SECRET_COM='035B2B9637E1BDFFEE2646BFBDDB8CE4' API_PASSPHRASE_COM='ComplexPa$$!23$5^' ts-node examples/ws-private.ts -⋮---- -// Whether to use the demo trading wss connection -// demoTrading: true, -⋮---- -// If you want your own event handlers instead of the default ones with logs, -// disable this setting and see the `attachEventHandlers` example below: -// attachEventListeners: false -⋮---- -logger, // Optional: inject a custom logger -⋮---- -// Optional, see above "attachEventListeners". Attach basic event handlers, so nothing is left unhandled -// attachEventHandlers(wsClient.getWSClient()); +{ + "extends": "./tsconfig.json", + "compilerOptions": { + "module": "commonjs", + "outDir": "dist/cjs", + "target": "esnext" + }, + "include": ["src/**/*.*"] +} + +================ +File: tsconfig.esm.json +================ +{ + "extends": "./tsconfig.json", + "compilerOptions": { + "module": "esnext", + "outDir": "dist/mjs", + "target": "esnext" + }, + "include": ["src/**/*.*"] +} + +================ +File: tsconfig.json +================ +{ + "compilerOptions": { + "allowSyntheticDefaultImports": true, + "baseUrl": ".", + "noEmitOnError": true, + "declaration": true, + "esModuleInterop": true, + "forceConsistentCasingInFileNames": false, + "inlineSourceMap": false, + "lib": ["esnext", "DOM"], + "listEmittedFiles": false, + "listFiles": false, + "moduleResolution": "node", + "noFallthroughCasesInSwitch": true, + "noImplicitAny": true, + "noUnusedParameters": true, + "pretty": true, + "removeComments": false, + "resolveJsonModule": true, + "skipLibCheck": false, + "sourceMap": true, + "strict": true, + "strictNullChecks": true, + "types": ["node", "jest"], + "module": "commonjs", + "outDir": "dist/cjs", + "target": "esnext" + }, + "compileOnSave": true, + "exclude": ["node_modules", "dist"], + "include": ["src/**/*.*", "test/**/*.*", ".eslintrc.cjs"] +} + +================ +File: tsconfig.linting.json +================ +{ + "extends": "./tsconfig.json", + "compilerOptions": { + "module": "commonjs", + "target": "esnext", + "rootDir": "../", + "allowJs": true + }, + "include": [ + "src/**/*.*", + "test/**/*.*", + "examples/**/*.*", + ".eslintrc.cjs", + "jest.config.ts", + "webpack/webpack.config.ts" + ] +} + +================ +File: src/constants/enum.ts +================ +/** Parameter verification exception margin mode == FIXED */ + +================ +File: src/types/request/v2/earn.ts +================ +/** + * + * + * Earn | Savings + * + * + */ ⋮---- -// Optional: prepare the WebSocket API connection in advance. -// This happens automatically but you can do this early before making any API calls, to prevent delays from a cold start. +export interface GetEarnSavingsAssetsRequestV2 { + periodType: string; + startTime?: string; + endTime?: string; + limit?: string; + idLessThan?: string; +} ⋮---- -/** - * Bitget's WebSocket API be used like a REST API, through this SDK's WebsocketAPIClient. The WebsocketAPIClient is a utility class wrapped around WebsocketClientV3's sendWSAPIRequest() capabilities. - * - * Each request sent via the WebsocketAPIClient will automatically: - * - route via the active WS API connection - * - return a Promise, which automatically resolves/rejects when a matching response is received - * - * Note: this requires V3/UTA API keys! - */ +export interface GetEarnSavingsRecordsRequestV2 { + coin?: string; + periodType: string; + orderType?: string; + startTime?: string; + endTime?: string; + limit?: string; + idLessThan?: string; +} ⋮---- -/** - * Place Order - * https://www.bitget.com/api-doc/uta/websocket/private/Place-Order-Channel#request-parameters - */ +export interface RedeemSavingsRequestV2 { + productId: string; + orderId?: string; + periodType: string; + amount: string; +} ⋮---- /** - const res = { - "event": "trade", - "id": "1750034396082", - "category": "spot", - "topic": "place-order", - "args": [ - { - "symbol": "BTCUSDT", - "orderId": "xxxxxxxx", - "clientOid": "xxxxxxxx", - "cTime": "1750034397008" - } - ], - "code": "0", - "msg": "success", - "ts": "1750034397076" - }; - */ + * + * + * Earn | Shark Fin + * + * + */ ⋮---- -/** - * Batch Place Order Channel - * https://www.bitget.com/api-doc/uta/websocket/private/Batch-Place-Order-Channel - */ +export interface GetSharkfinAssetsRequestV2 { + status: string; + startTime?: string; + endTime?: string; + limit?: string; + idLessThan?: string; +} ⋮---- -/** - * Note: batch place will never reject the request, even if all orders were rejected. Check the "code" and "msg" properties for individual orders in the response, to detect batch place errors. - */ +export interface GetSharkfinRecordsRequestV2 { + coin?: string; + type: string; + startTime?: string; + endTime?: string; + limit?: string; + idLessThan?: string; +} ⋮---- /** - const res = { - "event": "trade", - "id": "1750035029506", - "category": "spot", - "topic": "batch-place", - "args": [ - { - "code": "0", - "msg": "Success", - "symbol": "BTCUSDT", - "orderId": "xxxxxxxx", - "clientOid": "xxxxxxxx" - }, - { - "code": "0", - "msg": "Success", - "symbol": "BTCUSDT", - "orderId": "xxxxxxxx", - "clientOid": "xxxxxxxx" - } - ], - "code": "0", - "msg": "Success", - "ts": "1750035029925" - } - */ + * + * + * Earn | Loan + * + * + */ ⋮---- -/** - * Cancel Order - * https://www.bitget.com/api-doc/uta/websocket/private/Cancel-Order-Channel - */ +export interface GetLoanEstInterestAndBorrowableRequestV2 { + loanCoin: string; + pledgeCoin: string; + daily: 'SEVEN' | 'THIRTY'; + pledgeAmount?: string; +} ⋮---- -/** - const res = { - "event": "trade", - "id": "1750034870205", - "topic": "cancel-order", - "args": [ - { - "orderId": "xxxxxxxx", - "clientOid": "xxxxxxxx" - } - ], - "code": "0", - "msg": "Success", - "ts": "1750034870597" - } - */ +export interface BorrowLoanRequestV2 { + loanCoin: string; + pledgeCoin: string; + daily: 'SEVEN' | 'THIRTY'; + pledgeAmount?: string; + loanAmount?: string; +} ⋮---- -/** - * Batch Cancel Order - * https://www.bitget.com/api-doc/uta/websocket/private/Batch-Cancel-Order-Channel - */ -⋮---- -/** - const res = { - "event": "trade", - "id": "bb553cc0-c1fa-454e-956d-c96c8d715760", - "topic": "batch-cancel", - "args": [ - { - "code": "0", - "msg": "Success", - "orderId": "xxxxxxxxxxxxx" - }, - { - "code": "25204", - "msg": "Order does not exist", - "orderId": "xxxxxxxxxxxxx" - } - ], - "code": "0", - "msg": "Success", - "ts": "1751980011084" - } - */ - -================ -File: examples/V3 - UTA/WS-API/ws-api-trade-raw.ts -================ -import { - DefaultLogger, - WebsocketClientV3, - WS_KEY_MAP, -} from '../../../src/index.js'; -⋮---- -// or -// import { DefaultLogger, WS_KEY_MAP, WebsocketClientV3 } from 'bitget-api'; -⋮---- -// If running from CLI in unix, you can pass env vars as such: -// API_KEY_COM='lkm12n3-2ba3-1mxf-fn13-lkm12n3a' API_SECRET_COM='035B2B9637E1BDFFEE2646BFBDDB8CE4' API_PASSPHRASE_COM='ComplexPa$$!23$5^' ts-node examples/ws-private.ts -⋮---- -// console.log('WS raw message received ', JSON.stringify(data, null, 2)); -⋮---- -/** - * Bitget's WebSocket API can be used via the sendWSAPIRequest() method. - * - * Use the `WS_KEY_MAP.v3Private` connection key for any requests. - * - * Note: this requires V3/UTA API keys! - * Note: for a better user experience, it is recommended to use the WebsocketAPIClient. - */ -⋮---- -// Use the V3 private wss connection URL -⋮---- -/** - * Place Order - * https://www.bitget.com/api-doc/uta/websocket/private/Place-Order-Channel#request-parameters - */ -⋮---- -/** - const res = { - "event": "trade", - "id": "1750034396082", - "category": "spot", - "topic": "place-order", - "args": [ - { - "symbol": "BTCUSDT", - "orderId": "xxxxxxxx", - "clientOid": "xxxxxxxx", - "cTime": "1750034397008" - } - ], - "code": "0", - "msg": "success", - "ts": "1750034397076" - }; - */ -⋮---- -/** - * Batch Place Order Channel - * https://www.bitget.com/api-doc/uta/websocket/private/Batch-Place-Order-Channel - */ -⋮---- -/** - * Note: batch place will never reject the request, even if all orders were rejected. Check the "code" and "msg" properties for individual orders in the response, to detect batch place errors. - */ -⋮---- -/** - const res = { - "event": "trade", - "id": "1750035029506", - "category": "spot", - "topic": "batch-place", - "args": [ - { - "code": "0", - "msg": "Success", - "symbol": "BTCUSDT", - "orderId": "xxxxxxxx", - "clientOid": "xxxxxxxx" - }, - { - "code": "0", - "msg": "Success", - "symbol": "BTCUSDT", - "orderId": "xxxxxxxx", - "clientOid": "xxxxxxxx" - } - ], - "code": "0", - "msg": "Success", - "ts": "1750035029925" - } - */ -⋮---- -/** - * Cancel Order - * https://www.bitget.com/api-doc/uta/websocket/private/Cancel-Order-Channel - */ -⋮---- -/** - const res = { - "event": "trade", - "id": "1750034870205", - "topic": "cancel-order", - "args": [ - { - "orderId": "xxxxxxxx", - "clientOid": "xxxxxxxx" - } - ], - "code": "0", - "msg": "Success", - "ts": "1750034870597" - } - */ -⋮---- -/** - * Batch Cancel Order - * https://www.bitget.com/api-doc/uta/websocket/private/Batch-Cancel-Order-Channel - */ -⋮---- -/** - const res = { - "event": "trade", - "id": "bb553cc0-c1fa-454e-956d-c96c8d715760", - "topic": "batch-cancel", - "args": [ - { - "code": "0", - "msg": "Success", - "orderId": "xxxxxxxxxxxxx" - }, - { - "code": "25204", - "msg": "Order does not exist", - "orderId": "xxxxxxxxxxxxx" - } - ], - "code": "0", - "msg": "Success", - "ts": "1751980011084" - } - */ - -================ -File: src/constants/enum.ts -================ -/** Parameter verification exception margin mode == FIXED */ - -================ -File: src/types/request/v2/earn.ts -================ -/** - * - * - * Earn | Savings - * - * - */ -⋮---- -export interface GetEarnSavingsAssetsRequestV2 { - periodType: string; - startTime?: string; - endTime?: string; - limit?: string; - idLessThan?: string; -} -⋮---- -export interface GetEarnSavingsRecordsRequestV2 { - coin?: string; - periodType: string; - orderType?: string; - startTime?: string; - endTime?: string; - limit?: string; - idLessThan?: string; -} -⋮---- -export interface RedeemSavingsRequestV2 { - productId: string; - orderId?: string; - periodType: string; - amount: string; -} -⋮---- -/** - * - * - * Earn | Shark Fin - * - * - */ -⋮---- -export interface GetSharkfinAssetsRequestV2 { - status: string; - startTime?: string; - endTime?: string; - limit?: string; - idLessThan?: string; -} -⋮---- -export interface GetSharkfinRecordsRequestV2 { - coin?: string; - type: string; - startTime?: string; - endTime?: string; - limit?: string; - idLessThan?: string; -} -⋮---- -/** - * - * - * Earn | Loan - * - * - */ -⋮---- -export interface GetLoanEstInterestAndBorrowableRequestV2 { - loanCoin: string; - pledgeCoin: string; - daily: 'SEVEN' | 'THIRTY'; - pledgeAmount?: string; -} -⋮---- -export interface BorrowLoanRequestV2 { - loanCoin: string; - pledgeCoin: string; - daily: 'SEVEN' | 'THIRTY'; - pledgeAmount?: string; - loanAmount?: string; -} -⋮---- -export interface RepayLoanRequestV2 { - orderId: string; - amount?: string; - repayUnlock?: string; - repayAll: string; -} +export interface RepayLoanRequestV2 { + orderId: string; + amount?: string; + repayUnlock?: string; + repayAll: string; +} ⋮---- export interface GetLoanRepayHistoryRequestV2 { orderId?: string; @@ -3905,132 +3905,6 @@ export interface GetNeutralGridBotOrderDetailsRequestV3 { botId: string; } -================ -File: src/types/request/v3/loan.ts -================ -export interface GetTransferedRequestV3 { - userId?: string; - coin: string; -} -⋮---- -export interface GetSymbolsRequestV3 { - productId: string; -} -⋮---- -export interface GetRepaidHistoryRequestV3 { - startTime?: string; - endTime?: string; - limit?: string; -} -⋮---- -export interface GetProductInfosRequestV3 { - productId: string; -} -⋮---- -export interface GetLoanOrderRequestV3 { - orderId?: string; - startTime?: string; - endTime?: string; -} -⋮---- -export interface GetEnsureCoinsRequestV3 { - productId: string; -} -⋮---- -export interface BindUidRequestV3 { - riskUnitId?: string; - uid: string; - operate: 'bind' | 'unbind'; -} -⋮---- -export interface GetLTVConvertRequestV3 { - riskUnitId?: string; -} -⋮---- -/* Unified Account Staking & Lending (Crypto Loans) - /api/v3/loan/* */ -⋮---- -export interface GetLoanCoinsRequestV3 { - coin?: string; -} -⋮---- -export interface GetLoanInterestRequestV3 { - loanCoin: string; - pledgeCoin: string; - daily: 'SEVEN' | 'THIRTY' | 'FLEXIBLE'; - pledgeAmount: string; -} -⋮---- -export interface LoanBorrowRequestV3 { - loanCoin: string; - pledgeCoin: string; - daily: 'SEVEN' | 'THIRTY' | 'FLEXIBLE'; - pledgeAmount?: string; - loanAmount?: string; -} -⋮---- -export interface GetLoanBorrowOngoingRequestV3 { - orderId?: string; - loanCoin?: string; - pledgeCoin?: string; -} -⋮---- -export interface GetLoanBorrowHistoryRequestV3 { - orderId?: string; - loanCoin?: string; - pledgeCoin?: string; - status?: 'ROLLBACK' | 'FORCE' | 'REPAY'; - startTime: string; - endTime: string; - pageNum?: string; - pageSize?: string; -} -⋮---- -export interface LoanRepayRequestV3 { - orderId: string; - method: 'borrowed_coin' | 'collateral'; - repayAll: 'yes' | 'no'; - amount?: string; - repayUnlock?: 'yes' | 'no'; -} -⋮---- -export interface GetLoanRepayHistoryRequestV3 { - orderId?: string; - loanCoin?: string; - pledgeCoin?: string; - startTime: string; - endTime: string; - pageNum?: string; - pageSize?: string; -} -⋮---- -export interface LoanRevisePledgeRequestV3 { - orderId: string; - amount: string; - pledgeCoin: string; - reviseType?: 'OUT' | 'IN'; -} -⋮---- -export interface GetLoanPledgeRateHistoryRequestV3 { - orderId?: string; - reviseSide?: 'down' | 'up'; - pledgeCoin?: string; - startTime: string; - endTime: string; - pageNum?: string; - pageSize?: string; -} -⋮---- -export interface GetLoanReducesRequestV3 { - orderId?: string; - loanCoin?: string; - pledgeCoin?: string; - status?: 'COMPLETE' | 'WAIT'; - startTime: string; - endTime: string; - pageNum?: string; - pageSize?: string; -} - ================ File: src/types/request/v3/p2p.ts ================ @@ -5423,325 +5297,86 @@ export interface NeutralGridBotDetailV3 { } ================ -File: src/types/response/v3/loan.ts +File: src/types/response/v3/p2p.ts ================ -export interface LoanTransfersV3 { - coin: string; - transfered: string; - userId: string; -} +import type { + P2pAdStatusV3, + P2pMarketTypeV3, + P2pOrderStatusV3, + P2pPriceTypeV3, + P2pSideV3, +} from '../../request/v3/p2p.js'; ⋮---- -export interface LoanSymbolSettingV3 { - symbol: string; - leverage: string; +export interface P2pPayMethodInfoFieldV3 { + name: string; + type: 'file' | 'number' | 'txt'; + value: string; } ⋮---- -export interface LoanSymbolsV3 { - productId: string; - spotSymbols: string[]; - marginLeverage: string; - usdtContractLeverage: string; - coinContractLeverage: string; - usdcContractLeverage: string; - usdtContractSymbols: LoanSymbolSettingV3[]; - coinContractSymbols: LoanSymbolSettingV3[]; - usdcContractSymbols: LoanSymbolSettingV3[]; +export interface P2pPayMethodV3 { + payMethodId: string; + payMethodName: string; + payMethodUserName: string; + userPayMethodId: string; + payMethodInfo: P2pPayMethodInfoFieldV3[]; } ⋮---- -export interface RepaidHistoryItemV3 { - repayOrderId: string; - businessType: 'normal' | 'liquidation'; - repayType: 'all' | 'part'; - repaidTime: string; - coin: string; - repayAmount: string; - repayInterest: string; +export interface P2pTokenDetailV3 { + token: string; + precision: string; } ⋮---- -export interface LoanProductInfoV3 { - productId: string; - leverage: string; - supportUsdtContract: 'YES' | 'NO'; - supportCoinContract: 'YES' | 'NO'; - supportUsdcContract: 'YES' | 'NO'; - transferLine: string; - spotBuyLine: string; - usdtContractOpenLine: string; - coinContractOpenLine: string; - usdcContractOpenLine: string; - liquidationLine: string; - stopLiquidationLine: string; +export interface P2pFiatPayMethodV3 { + payMethodName: string; + iconUrl: string; + payMethodId: string; } ⋮---- -export interface LoanOrderV3 { - orderId: string; - orderProductId: string; - uid: string; - loanTime: string; - loanCoin: string; - loanAmount: string; - unpaidAmount: string; - unpaidInterest: string; - repaidAmount: string; - repaidInterest: string; - reserve: string; - status: 'not_paid_off' | 'paid_off'; +export interface P2pWithdrawalLimitV3 { + withdrawLimitKey: string; + withdrawLimitValue: string; } ⋮---- -/** Tiered conversion rate item (when Tiered Discount Rate Model is enabled) */ -export interface ConvertRatioListItemV3 { - ladder: string; - convertRatio: string; +export interface P2pFiatDetailV3 { + fiat: string; + precision: string; + floatRateMin: string; + floatRateMax: string; + fixedRateMin: string; + fixedRateMax: string; + adMinLimit: string; + adMaxLimit: string; + payMethods: P2pFiatPayMethodV3; + withdrawalLimit: P2pWithdrawalLimitV3; + payTimeLimit: number[]; } ⋮---- -export interface CoinInfoV3 { - coin: string; - convertRatio: string; - maxConvertValue: string; - /** Tiered conversion rate (when margin mode is Tiered Discount Rate Model) */ - convertRatioList?: ConvertRatioListItemV3[]; +export interface P2pCurrenciesV3 { + tokenDetailList: P2pTokenDetailV3[]; + fiatDetailList: P2pFiatDetailV3[]; } ⋮---- -/** Tiered conversion rate (when margin mode is Tiered Discount Rate Model) */ +export interface P2pUserEquityDetailV3 { + maxAdvSellNum: string; + maxAdvSellLimit: string; + maxAdvBuyNum: string; + maxAdvBuyLimit: string; + totalMaxPendingOrder: string; + advMaxPendingOrder: string; +} ⋮---- -export interface BindUidResponseV3 { - riskUnitId: string; +export interface P2pUserInfoV3 { uid: string; - operate: 'bind' | 'unbind'; -} -⋮---- -export interface UnpaidInfoV3 { - coin: string; - unpaidQty: string; - unpaidInterest: string; -} -⋮---- -export interface BalanceInfoV3 { - coin: string; - price: string; - amount: string; - convertedUsdtAmount: string; -} -⋮---- -export interface LTVConvertResponseV3 { - ltv: string; - subAccountUids: string[]; - unpaidUsdtAmount: string; - usdtBalance: string; - unpaidInfo: UnpaidInfoV3[]; - balanceInfo: BalanceInfoV3[]; -} -⋮---- -/* Unified Account Staking & Lending (Crypto Loans) - /api/v3/loan/* */ -⋮---- -export interface LoanCoinInfoV3 { - coin: string; - hourRateFlexible: string; - rateFlexible: string; - hourRate7D: string; - rate7D: string; - hourRate30D: string; - rate30D: string; - minBorrowAmount: string; - maxBorrowAmount: string; - minBorrowLimit: string; - maxBorrowLimit: string; -} -⋮---- -export interface LoanPledgeInfoV3 { - coin: string; - initRate: string; - supRate: string; - forceRate: string; - minPledgeAmount: string; - maxPledgeAmount: string; -} -⋮---- -export interface GetLoanCoinsResponseV3 { - loanInfos: LoanCoinInfoV3[]; - pledgeInfos: LoanPledgeInfoV3[]; -} -⋮---- -export interface GetLoanInterestResponseV3 { - hourInterest: string; - loanAmount: string; -} -⋮---- -export interface LoanBorrowResponseV3 { - orderId: string; -} -⋮---- -export interface LoanBorrowOngoingItemV3 { - orderId: string; - loanCoin: string; - loanAmount: string; - interestAmount: string; - hourInterestRate: string; - pledgeCoin: string; - pledgeAmount: string; - pledgeRate: string; - supRate: string; - forceRate: string; - borrowTime: string; - expireTime: string; -} -⋮---- -export interface LoanBorrowHistoryItemV3 { - orderId: string; - loanCoin: string; - pledgeCoin: string; - initPledgeAmount: string; - initLoanAmount: string; - hourRate: string; - daily: string; - borrowTime: string; - status: string; -} -⋮---- -export interface LoanRepayResponseV3 { - loanCoin: string; - pledgeCoin: string; - repayAmount: string; - payInterest: string; - repayLoanAmount: string; - repayUnlockAmount: string; -} -⋮---- -export interface LoanRepayHistoryItemV3 { - orderId: string; - loanCoin: string; - pledgeCoin: string; - repayAmount: string; - payInterest: string; - repayLoanAmount: string; - repayUnlockAmount: string; - repayTime: string; -} -⋮---- -export interface LoanRevisePledgeResponseV3 { - loanCoin: string; - pledgeCoin: string; - afterPledgeRate: string; -} -⋮---- -export interface LoanPledgeRateHistoryItemV3 { - loanCoin: string; - pledgeCoin: string; - orderId: string; - reviseTime: string; - reviseSide: string; - reviseAmount: string; - afterPledgeRate: string; - beforePledgeRate: string; -} -⋮---- -export interface LoanDebtInfoV3 { - coin: string; - amount: string; - amountUsdt: string; -} -⋮---- -export interface GetLoanDebtsResponseV3 { - pledgeInfos: LoanDebtInfoV3[]; - loanInfos: LoanDebtInfoV3[]; -} -⋮---- -export interface LoanReduceItemV3 { - orderId: string; - loanCoin: string; - pledgeCoin: string; - reduceTime: string; - pledgeRate: string; - pledgePrice: string; - status: string; - pledgeAmount: string; - reduceFee: string; - residueAmount: string; - runlockAmount: string; - repayLoanAmount: string; -} - -================ -File: src/types/response/v3/p2p.ts -================ -import type { - P2pAdStatusV3, - P2pMarketTypeV3, - P2pOrderStatusV3, - P2pPriceTypeV3, - P2pSideV3, -} from '../../request/v3/p2p.js'; -⋮---- -export interface P2pPayMethodInfoFieldV3 { - name: string; - type: 'file' | 'number' | 'txt'; - value: string; -} -⋮---- -export interface P2pPayMethodV3 { - payMethodId: string; - payMethodName: string; - payMethodUserName: string; - userPayMethodId: string; - payMethodInfo: P2pPayMethodInfoFieldV3[]; -} -⋮---- -export interface P2pTokenDetailV3 { - token: string; - precision: string; -} -⋮---- -export interface P2pFiatPayMethodV3 { - payMethodName: string; - iconUrl: string; - payMethodId: string; -} -⋮---- -export interface P2pWithdrawalLimitV3 { - withdrawLimitKey: string; - withdrawLimitValue: string; -} -⋮---- -export interface P2pFiatDetailV3 { - fiat: string; - precision: string; - floatRateMin: string; - floatRateMax: string; - fixedRateMin: string; - fixedRateMax: string; - adMinLimit: string; - adMaxLimit: string; - payMethods: P2pFiatPayMethodV3; - withdrawalLimit: P2pWithdrawalLimitV3; - payTimeLimit: number[]; -} -⋮---- -export interface P2pCurrenciesV3 { - tokenDetailList: P2pTokenDetailV3[]; - fiatDetailList: P2pFiatDetailV3[]; -} -⋮---- -export interface P2pUserEquityDetailV3 { - maxAdvSellNum: string; - maxAdvSellLimit: string; - maxAdvBuyNum: string; - maxAdvBuyLimit: string; - totalMaxPendingOrder: string; - advMaxPendingOrder: string; -} -⋮---- -export interface P2pUserInfoV3 { - uid: string; - nickName: string; - accountLevel: 'starter' | 'advanced' | 'master'; - completedOrderNum: string; - positiveRate: string; - completedOrderNum30D: string; - completedRate30D: string; - avgPayTime30D: string; - avgReleaseTime30D: string; - equityDetail: P2pUserEquityDetailV3; - registerTime: string; + nickName: string; + accountLevel: 'starter' | 'advanced' | 'master'; + completedOrderNum: string; + positiveRate: string; + completedOrderNum30D: string; + completedRate30D: string; + avgPayTime30D: string; + avgReleaseTime30D: string; + equityDetail: P2pUserEquityDetailV3; + registerTime: string; } ⋮---- export interface P2pBalanceV3 { @@ -6081,11 +5716,6 @@ File: .npmrc min-release-age=30 save-exact=true -================ -File: .nvmrc -================ -v24.18.0 - ================ File: src/types/request/v2/common.ts ================ @@ -7102,22 +6732,149 @@ export interface GetCfdInstrumentsRequestV3 { } ================ -File: src/types/request/v3/stockplus.ts +File: src/types/request/v3/loan.ts ================ -/** - * - * - * Stock+ (UTA) - * - * - */ +export interface GetTransferedRequestV3 { + userId?: string; + coin: string; +} ⋮---- -export interface GetStockPlusOptionQuoteRequestV3 { - symbol: string; +export interface GetSymbolsRequestV3 { + productId: string; } ⋮---- -export interface GetStockPlusOptionChainInfoRequestV3 { - symbol: string; +export interface GetRepaidHistoryRequestV3 { + startTime?: string; + endTime?: string; + limit?: string; +} +⋮---- +export interface GetProductInfosRequestV3 { + productId: string; + clientType?: 'Hedge' | 'HFT'; +} +⋮---- +export interface GetLoanOrderRequestV3 { + orderId?: string; + startTime?: string; + endTime?: string; +} +⋮---- +export interface GetEnsureCoinsRequestV3 { + productId: string; +} +⋮---- +export interface BindUidRequestV3 { + riskUnitId?: string; + uid: string; + operate: 'bind' | 'unbind'; +} +⋮---- +export interface GetLTVConvertRequestV3 { + riskUnitId?: string; +} +⋮---- +/* Unified Account Staking & Lending (Crypto Loans) - /api/v3/loan/* */ +⋮---- +export interface GetLoanCoinsRequestV3 { + coin?: string; +} +⋮---- +export interface GetLoanInterestRequestV3 { + loanCoin: string; + pledgeCoin: string; + daily: 'SEVEN' | 'THIRTY' | 'FLEXIBLE'; + pledgeAmount: string; +} +⋮---- +export interface LoanBorrowRequestV3 { + loanCoin: string; + pledgeCoin: string; + daily: 'SEVEN' | 'THIRTY' | 'FLEXIBLE'; + pledgeAmount?: string; + loanAmount?: string; +} +⋮---- +export interface GetLoanBorrowOngoingRequestV3 { + orderId?: string; + loanCoin?: string; + pledgeCoin?: string; +} +⋮---- +export interface GetLoanBorrowHistoryRequestV3 { + orderId?: string; + loanCoin?: string; + pledgeCoin?: string; + status?: 'ROLLBACK' | 'FORCE' | 'REPAY'; + startTime: string; + endTime: string; + pageNum?: string; + pageSize?: string; +} +⋮---- +export interface LoanRepayRequestV3 { + orderId: string; + method: 'borrowed_coin' | 'collateral'; + repayAll: 'yes' | 'no'; + amount?: string; + repayUnlock?: 'yes' | 'no'; +} +⋮---- +export interface GetLoanRepayHistoryRequestV3 { + orderId?: string; + loanCoin?: string; + pledgeCoin?: string; + startTime: string; + endTime: string; + pageNum?: string; + pageSize?: string; +} +⋮---- +export interface LoanRevisePledgeRequestV3 { + orderId: string; + amount: string; + pledgeCoin: string; + reviseType?: 'OUT' | 'IN'; +} +⋮---- +export interface GetLoanPledgeRateHistoryRequestV3 { + orderId?: string; + reviseSide?: 'down' | 'up'; + pledgeCoin?: string; + startTime: string; + endTime: string; + pageNum?: string; + pageSize?: string; +} +⋮---- +export interface GetLoanReducesRequestV3 { + orderId?: string; + loanCoin?: string; + pledgeCoin?: string; + status?: 'COMPLETE' | 'WAIT'; + startTime: string; + endTime: string; + pageNum?: string; + pageSize?: string; +} + +================ +File: src/types/request/v3/stockplus.ts +================ +/** + * + * + * Stock+ (UTA) + * + * + */ +⋮---- +export interface GetStockPlusOptionQuoteRequestV3 { + symbol: string; +} +⋮---- +export interface GetStockPlusOptionChainInfoRequestV3 { + symbol: string; expiryDate: string; } ⋮---- @@ -9002,86 +8759,341 @@ export interface BrokerRebateInfoV3 { } ================ -File: src/types/response/v3/stockplus.ts +File: src/types/response/v3/loan.ts ================ -/** - * - * - * Stock+ (UTA) - * - * - */ +export interface LoanTransfersV3 { + coin: string; + transfered: string; + userId: string; +} ⋮---- -export interface StockPlusOptionQuoteItemV3 { +export interface LoanSymbolSettingV3 { symbol: string; - lastDone: string; - prevClose: string; - open: string; - high: string; - low: string; - timestamp: string; - volume: string; - turnover: string; - tradeStatus: string; - impliedVolatility: string; - openInterest: string; - expiryDate: string; - strikePrice: string; - contractMultipier: string; - contractType: string; - contractSize: string; - direction: string; - historicalVolatility: string; - underlyingSymbol: string; + leverage: string; } ⋮---- -export interface StockPlusOptionQuoteV3 { - secuQuote: StockPlusOptionQuoteItemV3[]; +export interface LoanSymbolsV3 { + productId: string; + spotSymbols: string[]; + marginLeverage: string; + usdtContractLeverage: string; + coinContractLeverage: string; + usdcContractLeverage: string; + usdtContractSymbols: LoanSymbolSettingV3[]; + coinContractSymbols: LoanSymbolSettingV3[]; + usdcContractSymbols: LoanSymbolSettingV3[]; } ⋮---- -export interface StockPlusOptionStrikePriceInfoV3 { - price: string; - callSymbol: string; - putSymbol: string; - standard: boolean; +export interface RepaidHistoryItemV3 { + repayOrderId: string; + businessType: 'normal' | 'liquidation'; + repayType: 'all' | 'part'; + repaidTime: string; + coin: string; + repayAmount: string; + repayInterest: string; } ⋮---- -export interface StockPlusOptionChainInfoV3 { - strikePriceInfo: StockPlusOptionStrikePriceInfoV3[]; +export interface LoanProductInfoV3 { + productId: string; + leverage: string; + supportUsdtContract: 'YES' | 'NO'; + supportCoinContract: 'YES' | 'NO'; + supportUsdcContract: 'YES' | 'NO'; + transferLine: string; + spotBuyLine: string; + usdtContractOpenLine: string; + coinContractOpenLine: string; + usdcContractOpenLine: string; + liquidationLine: string; + stopLiquidationLine: string; + /** Delta exceed threshold. Hedge only */ + deltaThreshold?: string; + /** Position leverage ratio threshold. Hedge only */ + leverageThreshold?: string; } ⋮---- -export interface StockPlusOptionExpiryDateV3 { - expiryDate: string[]; -} +/** Delta exceed threshold. Hedge only */ ⋮---- -export interface StockPlusOptionVolumeV3 { - c: string; - p: string; +/** Position leverage ratio threshold. Hedge only */ +⋮---- +export interface LoanOrderV3 { + orderId: string; + orderProductId: string; + uid: string; + loanTime: string; + loanCoin: string; + loanAmount: string; + unpaidAmount: string; + unpaidInterest: string; + repaidAmount: string; + repaidInterest: string; + reserve: string; + status: 'not_paid_off' | 'paid_off'; } ⋮---- -export interface StockPlusStaticInfoItemV3 { - symbol: string; - nameCn: string; - nameEn: string; - exchange: string; - currency: string; - lotSize: number | string; - totalShares: string | number; - circulatingShares: string | number; - eps: string | number; - epsTtm: string | number; - bps: string | number; - dividendYield: string | number; - stockDerivatives: string[]; - board: string; +/** Tiered conversion rate item (when Tiered Discount Rate Model is enabled) */ +export interface ConvertRatioListItemV3 { + ladder: string; + convertRatio: string; } ⋮---- -export interface StockPlusStaticInfoV3 { - list: StockPlusStaticInfoItemV3[]; +export interface CoinInfoV3 { + coin: string; + convertRatio: string; + maxConvertValue: string; + /** Tiered conversion rate (when margin mode is Tiered Discount Rate Model) */ + convertRatioList?: ConvertRatioListItemV3[]; } ⋮---- -export interface StockPlusSessionQuoteV3 { - lastDone: string | number; +/** Tiered conversion rate (when margin mode is Tiered Discount Rate Model) */ +⋮---- +export interface BindUidResponseV3 { + riskUnitId: string; + uid: string; + operate: 'bind' | 'unbind'; +} +⋮---- +export interface UnpaidInfoV3 { + coin: string; + unpaidQty: string; + unpaidInterest: string; +} +⋮---- +export interface BalanceInfoV3 { + coin: string; + price: string; + amount: string; + convertedUsdtAmount: string; +} +⋮---- +export interface LTVConvertResponseV3 { + ltv: string; + /** Current risk unit delta. Hedge only; empty for HFT */ + delta: string; + /** Current position leverage ratio. Hedge only; empty for HFT */ + leverageRatio: string; + subAccountUids: string[]; + unpaidUsdtAmount: string; + usdtBalance: string; + unpaidInfo: UnpaidInfoV3[]; + balanceInfo: BalanceInfoV3[]; +} +⋮---- +/** Current risk unit delta. Hedge only; empty for HFT */ +⋮---- +/** Current position leverage ratio. Hedge only; empty for HFT */ +⋮---- +/* Unified Account Staking & Lending (Crypto Loans) - /api/v3/loan/* */ +⋮---- +export interface LoanCoinInfoV3 { + coin: string; + hourRateFlexible: string; + rateFlexible: string; + hourRate7D: string; + rate7D: string; + hourRate30D: string; + rate30D: string; + minBorrowAmount: string; + maxBorrowAmount: string; + minBorrowLimit: string; + maxBorrowLimit: string; +} +⋮---- +export interface LoanPledgeInfoV3 { + coin: string; + initRate: string; + supRate: string; + forceRate: string; + minPledgeAmount: string; + maxPledgeAmount: string; +} +⋮---- +export interface GetLoanCoinsResponseV3 { + loanInfos: LoanCoinInfoV3[]; + pledgeInfos: LoanPledgeInfoV3[]; +} +⋮---- +export interface GetLoanInterestResponseV3 { + hourInterest: string; + loanAmount: string; +} +⋮---- +export interface LoanBorrowResponseV3 { + orderId: string; +} +⋮---- +export interface LoanBorrowOngoingItemV3 { + orderId: string; + loanCoin: string; + loanAmount: string; + interestAmount: string; + hourInterestRate: string; + pledgeCoin: string; + pledgeAmount: string; + pledgeRate: string; + supRate: string; + forceRate: string; + borrowTime: string; + expireTime: string; +} +⋮---- +export interface LoanBorrowHistoryItemV3 { + orderId: string; + loanCoin: string; + pledgeCoin: string; + initPledgeAmount: string; + initLoanAmount: string; + hourRate: string; + daily: string; + borrowTime: string; + status: string; +} +⋮---- +export interface LoanRepayResponseV3 { + loanCoin: string; + pledgeCoin: string; + repayAmount: string; + payInterest: string; + repayLoanAmount: string; + repayUnlockAmount: string; +} +⋮---- +export interface LoanRepayHistoryItemV3 { + orderId: string; + loanCoin: string; + pledgeCoin: string; + repayAmount: string; + payInterest: string; + repayLoanAmount: string; + repayUnlockAmount: string; + repayTime: string; +} +⋮---- +export interface LoanRevisePledgeResponseV3 { + loanCoin: string; + pledgeCoin: string; + afterPledgeRate: string; +} +⋮---- +export interface LoanPledgeRateHistoryItemV3 { + loanCoin: string; + pledgeCoin: string; + orderId: string; + reviseTime: string; + reviseSide: string; + reviseAmount: string; + afterPledgeRate: string; + beforePledgeRate: string; +} +⋮---- +export interface LoanDebtInfoV3 { + coin: string; + amount: string; + amountUsdt: string; +} +⋮---- +export interface GetLoanDebtsResponseV3 { + pledgeInfos: LoanDebtInfoV3[]; + loanInfos: LoanDebtInfoV3[]; +} +⋮---- +export interface LoanReduceItemV3 { + orderId: string; + loanCoin: string; + pledgeCoin: string; + reduceTime: string; + pledgeRate: string; + pledgePrice: string; + status: string; + pledgeAmount: string; + reduceFee: string; + residueAmount: string; + runlockAmount: string; + repayLoanAmount: string; +} + +================ +File: src/types/response/v3/stockplus.ts +================ +/** + * + * + * Stock+ (UTA) + * + * + */ +⋮---- +export interface StockPlusOptionQuoteItemV3 { + symbol: string; + lastDone: string; + prevClose: string; + open: string; + high: string; + low: string; + timestamp: string; + volume: string; + turnover: string; + tradeStatus: string; + impliedVolatility: string; + openInterest: string; + expiryDate: string; + strikePrice: string; + contractMultipier: string; + contractType: string; + contractSize: string; + direction: string; + historicalVolatility: string; + underlyingSymbol: string; +} +⋮---- +export interface StockPlusOptionQuoteV3 { + secuQuote: StockPlusOptionQuoteItemV3[]; +} +⋮---- +export interface StockPlusOptionStrikePriceInfoV3 { + price: string; + callSymbol: string; + putSymbol: string; + standard: boolean; +} +⋮---- +export interface StockPlusOptionChainInfoV3 { + strikePriceInfo: StockPlusOptionStrikePriceInfoV3[]; +} +⋮---- +export interface StockPlusOptionExpiryDateV3 { + expiryDate: string[]; +} +⋮---- +export interface StockPlusOptionVolumeV3 { + c: string; + p: string; +} +⋮---- +export interface StockPlusStaticInfoItemV3 { + symbol: string; + nameCn: string; + nameEn: string; + exchange: string; + currency: string; + lotSize: number | string; + totalShares: string | number; + circulatingShares: string | number; + eps: string | number; + epsTtm: string | number; + bps: string | number; + dividendYield: string | number; + stockDerivatives: string[]; + board: string; +} +⋮---- +export interface StockPlusStaticInfoV3 { + list: StockPlusStaticInfoItemV3[]; +} +⋮---- +export interface StockPlusSessionQuoteV3 { + lastDone: string | number; timestamp: string; volume: string | number; turnover: string | number; @@ -9356,6 +9368,11 @@ export interface StockPlusTransferRecordsV3 { cursor: string; } +================ +File: .nvmrc +================ +v24.22.3 + ================ File: src/types/request/v2/broker.ts ================ @@ -11482,1892 +11499,1287 @@ Yes. The SDK works in JavaScript and TypeScript. TypeScript users also get reque Yes. Pass your RSA private key as `apiSecret`; the SDK auto-detects RSA vs HMAC signing. See the [GitHub repository](https://github.com/sieblyio/bitget-api). -### What should I do after a WebSocket reconnect? - -Normal - let the SDK reconnect and resubscribe. Then reconcile balances, orders, and fills over REST before acting on cached state. - -### Where can I find more examples? - -More in the repo: - -- [V3/UTA examples](../examples/V3%20-%20UTA) -- [V2/Classic examples](../examples/V2%20-%20Classic) -- [Auth examples](../examples/Auth) -- [Bitget JavaScript Endpoint Reference](./endpointFunctionList.md) - ---- - - -## Next steps - -- [Bitget JavaScript SDK page](https://siebly.io/sdk/bitget/javascript) -- [`bitget-api` on npm](https://www.npmjs.com/package/bitget-api) -- [GitHub repo](https://github.com/sieblyio/bitget-api) -- [Endpoint reference](./endpointFunctionList.md) -- Bitget docs: [UTA](https://www.bitget.com/api-doc/uta/intro) · [Classic](https://www.bitget.com/api-doc/classic/quickStart/intro) -- [More exchange SDKs on Siebly.io](https://siebly.io) - -================ -File: src/types/request/v3/copytrading.ts -================ -export interface GetCopyFuturesMaxTransferableRequestV3 { - coin: string; -} -⋮---- -export interface GetCopyFuturesCopyMaxTransferableRequestV3 { - projectId: string; - /** e.g. USDT */ - coin: string; -} -⋮---- -/** e.g. USDT */ -⋮---- -export interface CopyFuturesTransferRequestV3 { - type: 'in' | 'out'; - coin: string; - amount: string; - /** Source account type(s) for transfer-in. Comma-separated: funding, uta, otc */ - inAccountType?: string; -} -⋮---- -/** Source account type(s) for transfer-in. Comma-separated: funding, uta, otc */ -⋮---- -export interface GetCopyFuturesTransferRecordRequestV3 { - startTime?: string; - endTime?: string; - limit?: string; - /** Pass transferId from the previous page to paginate forward */ - cursor?: string; -} -⋮---- -/** Pass transferId from the previous page to paginate forward */ -⋮---- -export interface GetCopyFuturesFollowersRequestV3 { - limit?: string; - cursor?: string; -} -⋮---- -export interface GetCopyFuturesProfitDetailsRequestV3 { - startTime?: string; - endTime?: string; - limit?: string; - cursor?: string; -} -⋮---- -export type CopyFuturesCopyTypeV3 = 'fixed_ratio' | 'fixed_margin'; -⋮---- -export interface GetCopyFuturesPortfolioOverviewRequestV3 { - period: '7D' | '30D' | '90D' | '180D'; -} -⋮---- -export interface CreateCopyFuturesRequestV3 { - projectId: string; - type: CopyFuturesCopyTypeV3; - amount: string; - /** Comma-separated: funding, uta, otc */ - accountType?: string; - /** Comma-separated symbols. Omit to copy every pair */ - tradingPairList?: string; - /** Required when type is fixed_margin */ - marginPerOrder?: string; - autoCopy?: 'on' | 'off'; - leverage?: string; - maxEntrySlippage?: string; - maxMarginRatio?: string; - /** API field name (Bitget spelling). */ - maxPostionValue?: string; -} -⋮---- -/** Comma-separated: funding, uta, otc */ -⋮---- -/** Comma-separated symbols. Omit to copy every pair */ -⋮---- -/** Required when type is fixed_margin */ -⋮---- -/** API field name (Bitget spelling). */ -⋮---- -export interface ModifyCopyFuturesFollowerSettingsRequestV3 { - projectId: string; - /** Pass all to follow every pair */ - tradingPairList?: string; - marginPerOrder?: string; - autoCopy?: 'on' | 'off'; - leverage?: string; - maxEntrySlippage?: string; - maxMarginRatio?: string; - /** API field name (Bitget spelling). */ - maxPostionValue?: string; -} -⋮---- -/** Pass all to follow every pair */ -⋮---- -/** API field name (Bitget spelling). */ -⋮---- -export interface UnfollowCopyFuturesRequestV3 { - projectId: string; - closeType?: 'follow_close' | 'instant_close'; -} -⋮---- -export interface GetCopyFuturesCopySettingsRequestV3 { - projectId: string; -} -⋮---- -export interface CopyFuturesFollowerTransferRequestV3 { - projectId: string; - type: 'in' | 'out'; - coin: string; - amount: string; - /** Comma-separated: funding, uta, otc */ - inAccountType?: string; -} -⋮---- -/** Comma-separated: funding, uta, otc */ -⋮---- -export interface GetCopyFuturesFollowerTransferRecordRequestV3 { - projectId: string; - limit?: string; - cursor?: string; -} -⋮---- -export interface GetCopyFuturesCurrentCopyRequestV3 { - projectId: string; -} -⋮---- -export interface GetCopyFuturesCopyProfitDetailsRequestV3 { - projectId: string; - startTime?: string; - endTime?: string; - limit?: string; - cursor?: string; -} -⋮---- -export interface CloseCopyFuturesPositionsRequestV3 { - projectId: string; - symbol: string; - qty: string; - holdSide: 'long' | 'short'; -} -⋮---- -export interface CloseAllCopyFuturesRequestV3 { - projectId: string; -} -⋮---- -export interface GetCopyFuturesCurrentPositionsRequestV3 { - projectId: string; - symbol?: string; - posSide?: 'long' | 'short'; -} -⋮---- -export interface PlaceCopyFuturesTpSlRequestV3 { - projectId: string; - positionId: string; - tpTriggerBy: 'market' | 'mark'; - slTriggerBy: 'market' | 'mark'; - takeProfit: string; - stopLoss: string; -} -⋮---- -export interface ModifyCopyFuturesTpSlRequestV3 { - projectId: string; - strategyId: string; - tpTriggerBy: 'market' | 'mark'; - slTriggerBy: 'market' | 'mark'; - takeProfit: string; - stopLoss: string; -} -⋮---- -export interface CancelCopyFuturesTpSlRequestV3 { - projectId: string; - strategyId: string; -} -⋮---- -export interface GetCopyFuturesCurrentTpSlOrdersRequestV3 { - projectId: string; -} -⋮---- -export interface GetCopyFuturesTpSlOrderHistoryRequestV3 { - projectId: string; - startTime?: string; - endTime?: string; - limit?: string; - cursor?: string; -} - -================ -File: src/types/websockets/ws-events.ts -================ -export interface MessageEventLike { - target: WebSocket; - type: 'message'; - data: string; -} -⋮---- -export function isMessageEvent(msg: unknown): msg is MessageEventLike -⋮---- -export interface WsBaseEvent { - action: TAction; - arg: unknown; - data: TData[]; -} -⋮---- -export interface WsSnapshotChannelEvent extends WsBaseEvent<'snapshot'> { - arg: { - instType: string; - channel: string; - instId: string; - }; -} -⋮---- -export interface WsSnapshotAccountEvent extends WsBaseEvent<'snapshot'> { - arg: { - instType: string; - channel: 'account'; - instId: string; - }; -} -⋮---- -export interface WsSnapshotPositionsEvent extends WsBaseEvent<'snapshot'> { - arg: { - instType: string; - channel: 'positions'; - instId: string; - }; -} -⋮---- -export interface WsAccountSnapshotDataUMCBL { - marginCoin: string; - locked: string; - available: string; - maxOpenPosAvailable: string; - maxTransferOut: string; - equity: string; - usdtEquity: string; -} -⋮---- -export interface WsAccountSnapshotUMCBL extends WsBaseEvent<'snapshot'> { - arg: { - instType: 'umcbl'; - channel: 'account'; - instId: string; - }; - data: WsAccountSnapshotDataUMCBL[]; -} -⋮---- -export interface WsPositionSnapshotDataUMCBL { - posId: string; - instId: string; - instName: string; - marginCoin: string; - margin: string; - marginMode: string; - holdSide: string; - holdMode: string; - total: string; - available: string; - locked: string; - averageOpenPrice: string; - leverage: number; - achievedProfits: string; - upl: string; - uplRate: string; - liqPx: string; - keepMarginRate: string; - marginRate: string; - cTime: string; - uTime: string; - markPrice: string; - /** Cash dividend, USDT (Classic V2 positions channel) */ - cashDividend?: string; -} -⋮---- -/** Cash dividend, USDT (Classic V2 positions channel) */ -⋮---- -/** UTA reality-orderbook push (ts/seq/pseq removed July 2026). Every push is a full snapshot. */ -export interface WsRealityOrderBookDataV3 { - a: [string, string][]; - b: [string, string][]; -} -⋮---- -/** - * UTA reality-orderbook-segmented push. - * Each level is [price, onshoreQty, offshoreQty]. - * Every push is a full snapshot. Whitelist required. - * Go-live 20 Oct 2026. Pairs that have not finished the matching-engine upgrade do not push. - * A crossed book after the upgrade is expected. - */ -export interface WsRealityOrderBookSegmentedDataV3 { - a: [string, string, string][]; - b: [string, string, string][]; -} -⋮---- -export interface WSPositionSnapshotUMCBL extends WsBaseEvent<'snapshot'> { - arg: { - instType: 'umcbl'; - channel: 'positions'; - instId: string; - }; - data: WsPositionSnapshotDataUMCBL[]; -} -⋮---- -/** Classic V2 depth channel push data. checksum removed May 2026 - use seq instead */ -export interface WsDepthBookDataV2 { - asks: [string, string][]; - bids: [string, string][]; - ts: string; - seq: string; - /** Futures books channel only - previous push serial number */ - pseq?: string; -} -⋮---- -/** Futures books channel only - previous push serial number */ -⋮---- -/** UTA account channel coin row */ -export interface WsAccountCoinV3 { - coin: string; - balance: string; - /** Coin balance before borrowing-related amounts are deducted */ - balanceOriginal?: string; - available: string; - locked: string; - equity: string; - usdValue: string; - borrow: string; - debts: string; - bonus?: string; -} -⋮---- -/** Coin balance before borrowing-related amounts are deducted */ -⋮---- -/** UTA account channel push. action is snapshot or update */ -export interface WsAccountDataV3 { - totalEquity: string; - effEquity: string; - mmr: string; - imr: string; - mgnRatio: string; - positionMgnRatio: string; - unrealisedPnL: string; - coin: WsAccountCoinV3[]; -} -⋮---- -/** - * UTA depth push. - * books1 and books5: every message is a full snapshot. - * books and books50: the first message is a snapshot, later messages are incremental updates. - * Do not replace the local book with a books or books50 update. - * pseq is set on books and books50. - * rToken: books1 pushes at all times. books5, books50, and books push only outside US market hours. - */ -export interface WsOrderBookDataV3 { - a: [string, string][]; - b: [string, string][]; - seq: string | number; - pseq?: string | number; - /** Present on the books topic */ - maxDepth?: string; - ts: string; -} -⋮---- -/** Present on the books topic */ - -================ -File: src/types/response/v3/copytrading.ts -================ -/** - * - * - * Copy Trading | Futures (UTA) - * - * - */ -⋮---- -export interface CopyFuturesMarginDetailV3 { - marginCoin: string; - maxLongCount: string; - remainingLongCount: string; - maxShortCount: string; - remainingShortCount: string; -} -⋮---- -export interface CopyFuturesTradingPairV3 { - symbol: string; - leverage: string; - marginDetails: CopyFuturesMarginDetailV3[]; -} -⋮---- -export interface CopyFuturesPositionSummaryV3 { - unrealizedPnl: string; - realizedPnl: string; - holdSize: string; - avgPrice: string; - symbol: string; - leverage: string; - marginMode: string; - liqPrice: string; - margin: string; - holdSide: string; - roi: string; - markPrice: string; - positionValue: string; -} -⋮---- -export interface CopyFuturesMaxTransferableV3 { - maxTransferable: string; - available: string; -} -⋮---- -/** Follower copy account. Lead accounts use CopyFuturesMaxTransferableV3. */ -export interface CopyFuturesCopyMaxTransferableV3 { - maxTransferable: string; -} -⋮---- -export interface CopyFuturesTransferResponseV3 { - transferId: string; -} -⋮---- -/** May be a single value or comma-separated values */ -export type CopyFuturesTransferAccountTypeV3 = - | 'spot' - | 'uta' - | 'lead' - | 'otc' - | string; -⋮---- -export interface CopyFuturesTransferRecordV3 { - transferId: string; - fromType: CopyFuturesTransferAccountTypeV3; - toType: CopyFuturesTransferAccountTypeV3; - amount: string; - coin: string; - status: 'Successful' | 'Failed' | 'Processing'; - createdTime: string; -} -⋮---- -export interface CopyFuturesTransferRecordListV3 { - list: CopyFuturesTransferRecordV3[]; -} -⋮---- -export interface CopyFuturesCurrentFollowerV3 { - followerName: string; - estimateAssets: string; - totalProfit: string; - totalShareProfit: string; - totalInvestment: string; - canRemove: 'yes' | 'no'; - followDays: string; - totalAssets: string; - startTime: string; -} -⋮---- -export interface CopyFuturesCurrentFollowersV3 { - list: CopyFuturesCurrentFollowerV3[]; -} -⋮---- -export interface CopyFuturesHistoryFollowerV3 { - followerName: string; - totalProfit: string; - totalShareProfit: string; - totalInvestment: string; - startTime: string; - endTime: string; -} -⋮---- -export interface CopyFuturesHistoryFollowersV3 { - list: CopyFuturesHistoryFollowerV3[]; -} -⋮---- -export interface CopyFuturesProfitSummaryV3 { - totalProfit: string; - totalAllocatedProfit: string; - totalPendingProfit: string; -} -⋮---- -export interface CopyFuturesProfitDetailV3 { - followerName: string; - profit: string; - allocatedPnl: string; - pendingPnl: string; - shareRatio: string; - shareProfit: string; - reason: 'period' | 'unfollow' | string; - settleTime: string; -} -⋮---- -export interface CopyFuturesProfitDetailsV3 { - list: CopyFuturesProfitDetailV3[]; - nextCursor: string; +### What should I do after a WebSocket reconnect? + +Normal - let the SDK reconnect and resubscribe. Then reconcile balances, orders, and fills over REST before acting on cached state. + +### Where can I find more examples? + +More in the repo: + +- [V3/UTA examples](../examples/V3%20-%20UTA) +- [V2/Classic examples](../examples/V2%20-%20Classic) +- [Auth examples](../examples/Auth) +- [Bitget JavaScript Endpoint Reference](./endpointFunctionList.md) + +--- + + +## Next steps + +- [Bitget JavaScript SDK page](https://siebly.io/sdk/bitget/javascript) +- [`bitget-api` on npm](https://www.npmjs.com/package/bitget-api) +- [GitHub repo](https://github.com/sieblyio/bitget-api) +- [Endpoint reference](./endpointFunctionList.md) +- Bitget docs: [UTA](https://www.bitget.com/api-doc/uta/intro) · [Classic](https://www.bitget.com/api-doc/classic/quickStart/intro) +- [More exchange SDKs on Siebly.io](https://siebly.io) + +================ +File: src/types/request/v3/copytrading.ts +================ +export interface GetCopyFuturesMaxTransferableRequestV3 { + coin: string; } ⋮---- -export interface CopyFuturesPortfolioOverviewV3 { +export interface GetCopyFuturesCopyMaxTransferableRequestV3 { projectId: string; - asset: string; - roi: string; - totalProfit: string; - followerProfit: string; - maxDrawdown: string; -} -⋮---- -export interface CopyFuturesCopySettingsV3 { - type: 'fixed_ratio' | 'fixed_margin' | string; - amount: string; - tradingPairList: string[]; - marginPerOrder: string; - autoCopy: 'on' | 'off' | string; - leverage: string; - maxEntrySlippage: string; - maxMarginRatio: string; - /** API field name (Bitget spelling). */ - maxPostionValue: string; -} -⋮---- -/** API field name (Bitget spelling). */ -⋮---- -export interface CopyFuturesFollowerTransferRecordV3 { - fromType: string; - toType: string; - amount: string; + /** e.g. USDT */ coin: string; - status: string; - createdTime: string; -} -⋮---- -export interface CopyFuturesFollowerTransferRecordListV3 { - list: CopyFuturesFollowerTransferRecordV3[]; - nextCursor?: string; -} -⋮---- -export interface CopyFuturesCurrentCopyV3 { - eliteTrader: string; - estNetProfit: string; - profitShare: string; - estValue: string; - available: string; - currentInvestment: string; -} -⋮---- -export interface CopyFuturesCopyProfitDetailItemV3 { - settleTime: string; - profit: string; - allocatedPnl: string; - pendingPnl: string; - shareRatio: string; - shareProfit: string; -} -⋮---- -export interface CopyFuturesCopyProfitDetailsV3 { - list: CopyFuturesCopyProfitDetailItemV3[]; - nextCursor?: string; -} -⋮---- -export interface CopyFuturesFollowerPositionV3 { - symbol: string; - marginCoin: string; - posSide: 'long' | 'short' | string; - total: string; - leverage: string; - avgPrice: string; - marginMode: string; - holdMode: string; - createdTime: string; - positionId: string; -} -⋮---- -export interface CopyFuturesFollowerPositionsV3 { - list: CopyFuturesFollowerPositionV3[]; } ⋮---- -export interface CopyFuturesTpSlOrderV3 { - strategyId: string; - category: string; - symbol: string; - qty: string; - posSide: string; - status: string; - tpTriggerBy: string; - slTriggerBy: string; - takeProfit: string; - stopLoss: string; - tpOrderType: string; - slOrderType: string; -} +/** e.g. USDT */ ⋮---- -export interface CopyFuturesTpSlResponseV3 { - strategyId: string; +export interface CopyFuturesTransferRequestV3 { + type: 'in' | 'out'; + coin: string; + amount: string; + /** Source account type(s) for transfer-in. Comma-separated: funding, uta, otc */ + inAccountType?: string; } ⋮---- -export interface CopyFuturesCurrentTpSlOrdersV3 { - list: CopyFuturesTpSlOrderV3[]; -} +/** Source account type(s) for transfer-in. Comma-separated: funding, uta, otc */ ⋮---- -export interface CopyFuturesTpSlOrderHistoryV3 { - list: CopyFuturesTpSlOrderV3[]; +export interface GetCopyFuturesTransferRecordRequestV3 { + startTime?: string; + endTime?: string; + limit?: string; + /** Pass transferId from the previous page to paginate forward */ cursor?: string; } - -================ -File: src/types/response/v3/earn.ts -================ -/** - * - * - * Earn | On-Chain Elite (UTA) - * - * - */ ⋮---- -export interface EarnEliteSubscriptionCoinV3 { - subscriptionCoin: string; - precision: string; - feeRate: string; - exchangeRate: string; - remainQuota?: string; - minAmount?: string; -} +/** Pass transferId from the previous page to paginate forward */ ⋮---- -export interface EarnEliteProductV3 { - productId: string; - coin: string; - minApr: string; - maxApr: string; - subscriptionCoinList: EarnEliteSubscriptionCoinV3[]; - sellOut: 'YES' | 'NO' | string; +export interface GetCopyFuturesFollowersRequestV3 { + limit?: string; + cursor?: string; } ⋮---- -export interface EarnEliteAssetProjectV3 { - projectName: string; +export interface GetCopyFuturesProfitDetailsRequestV3 { + startTime?: string; + endTime?: string; + limit?: string; + cursor?: string; } ⋮---- -export interface EarnEliteAssetV3 { - productId: string; - productCoin: string; - holdingAmount: string; - usdtHoldingAmount: string; - exchangeRate: string; - apr: string; - minApy?: string; - maxApy?: string; - subscriptionCoin: string; - exchangeAmount: string; - projectList?: EarnEliteAssetProjectV3[]; - unsettledBGPoints: string; - interestCoin: string; - totalProfit: string; -} +export type CopyFuturesCopyTypeV3 = 'fixed_ratio' | 'fixed_margin'; ⋮---- -export interface EarnEliteAssetsV3 { - resultList: EarnEliteAssetV3[]; +export interface GetCopyFuturesPortfolioOverviewRequestV3 { + period: '7D' | '30D' | '90D' | '180D'; } ⋮---- -export interface EarnEliteRecordV3 { - recordId: string; - productId: string; - coin: string; - status: string; - exchangeRate: string; - receivedCoin: string; - receivedAmount: string; - investAmount: string; - feeRate: string; - redeemType?: string | string[]; - receivingAccount: string; - actualReceivingAccount: string; - paymentAccount?: string[]; - settlePoints: string; - fee: string; - /** Business time, Unix ms */ - bizTime?: string; +export interface CreateCopyFuturesRequestV3 { + projectId: string; + type: CopyFuturesCopyTypeV3; + amount: string; + /** Comma-separated: funding, uta, otc */ + accountType?: string; + /** Comma-separated symbols. Omit to copy every pair */ + tradingPairList?: string; + /** Required when type is fixed_margin */ + marginPerOrder?: string; + autoCopy?: 'on' | 'off'; + leverage?: string; + maxEntrySlippage?: string; + maxMarginRatio?: string; + /** API field name (Bitget spelling). */ + maxPostionValue?: string; } ⋮---- -/** Business time, Unix ms */ -⋮---- -export interface EarnEliteRecordsV3 { - recordList: EarnEliteRecordV3[]; - endId: string; -} +/** Comma-separated: funding, uta, otc */ ⋮---- -export interface EarnEliteSubscribeInfoV3 { - productSubId: string; - minAmount: string; - remainQuota: string; - exchangeRate: string; - productCoin: string; - interestTime: string; - settleTime: string; - precision: string; - feeRate: string; - subscriptionCoinList?: EarnEliteSubscriptionCoinV3[]; -} +/** Comma-separated symbols. Omit to copy every pair */ ⋮---- -export interface EarnEliteSubscribeResultV3 { - orderId: string; -} +/** Required when type is fixed_margin */ ⋮---- -export interface EarnEliteSubscribeStatusV3 { - result: 'settled' | 'pending' | 'rejected' | string; -} +/** API field name (Bitget spelling). */ ⋮---- -export interface EarnEliteRedeemInfoBgusdReceiveCoinV3 { - bgusdReceiveCoin: string; - bgusdExchangeRate: string; +export interface ModifyCopyFuturesFollowerSettingsRequestV3 { + projectId: string; + /** Pass all to follow every pair */ + tradingPairList?: string; + marginPerOrder?: string; + autoCopy?: 'on' | 'off'; + leverage?: string; + maxEntrySlippage?: string; + maxMarginRatio?: string; + /** API field name (Bitget spelling). */ + maxPostionValue?: string; } ⋮---- -export interface EarnEliteRedeemModeV3 { - redeemFeeRate: string; - remainQuota: string; - redeemType: 'fast' | 'standard' | string; - redeemScale: string; - redeemDelayDate: string; - minRedeemAmount: string; - redeemTime: string; -} +/** Pass all to follow every pair */ ⋮---- -export interface EarnEliteRedeemInfoV3 { - productId: string; - productSubId: string; - productCoin: string; - subscriptionCoin: string; - profitCoin: string; - exchangeRate: string; - totalUnPayInterestAmount: string; - preSettleApr: string; - receivedCoin: string; - unsettledPoints: string; - bgusdReceiveCoinList: EarnEliteRedeemInfoBgusdReceiveCoinV3[]; - redeemModeList: EarnEliteRedeemModeV3[]; -} +/** API field name (Bitget spelling). */ ⋮---- -export interface RedeemEarnEliteResultV3 { - orderId: string; +export interface UnfollowCopyFuturesRequestV3 { + projectId: string; + closeType?: 'follow_close' | 'instant_close'; } ⋮---- -/** - * - * - * Earn | Cash+ (UTA) - * - * - */ +export interface GetCopyFuturesCopySettingsRequestV3 { + projectId: string; +} ⋮---- -export interface EarnCashPlusSubscribeCoinV3 { - /** Used for subscribe and redeem */ - productSubId: string; +export interface CopyFuturesFollowerTransferRequestV3 { + projectId: string; + type: 'in' | 'out'; coin: string; - /** Minimum subscription amount, in this coin */ - minAmount: string; - /** How much Cash+ 1 unit of this coin converts into. Default 1 */ - conversionRate: string; - /** Decimal places for the subscription amount */ - subscribeScale: string; - /** Decimal places for profit */ - profitScale: string; - soldOut: 'yes' | 'no'; + amount: string; + /** Comma-separated: funding, uta, otc */ + inAccountType?: string; } ⋮---- -/** Used for subscribe and redeem */ +/** Comma-separated: funding, uta, otc */ ⋮---- -/** Minimum subscription amount, in this coin */ +export interface GetCopyFuturesFollowerTransferRecordRequestV3 { + projectId: string; + limit?: string; + cursor?: string; +} ⋮---- -/** How much Cash+ 1 unit of this coin converts into. Default 1 */ +export interface GetCopyFuturesCurrentCopyRequestV3 { + projectId: string; +} ⋮---- -/** Decimal places for the subscription amount */ +export interface GetCopyFuturesCopyProfitDetailsRequestV3 { + projectId: string; + startTime?: string; + endTime?: string; + limit?: string; + cursor?: string; +} ⋮---- -/** Decimal places for profit */ +export interface CloseCopyFuturesPositionsRequestV3 { + projectId: string; + symbol: string; + qty: string; + holdSide: 'long' | 'short'; +} ⋮---- -export interface EarnCashPlusSubscribeInfoV3 { - /** Profit source coin. Currently USDGO */ - profitSourceCoin: string; - /** Decimal APR. 0.04 means 4% */ - cashPlusApr: string; - subscribeCoinList: EarnCashPlusSubscribeCoinV3[]; - /** Unix ms */ - interestTime: string; - /** Unix ms */ - payInterestTime: string; - /** Unix ms */ - subscribeTime: string; +export interface CloseAllCopyFuturesRequestV3 { + projectId: string; } ⋮---- -/** Profit source coin. Currently USDGO */ +export interface GetCopyFuturesCurrentPositionsRequestV3 { + projectId: string; + symbol?: string; + posSide?: 'long' | 'short'; +} ⋮---- -/** Decimal APR. 0.04 means 4% */ +export interface PlaceCopyFuturesTpSlRequestV3 { + projectId: string; + positionId: string; + tpTriggerBy: 'market' | 'mark'; + slTriggerBy: 'market' | 'mark'; + takeProfit: string; + stopLoss: string; +} ⋮---- -/** Unix ms */ +export interface ModifyCopyFuturesTpSlRequestV3 { + projectId: string; + strategyId: string; + tpTriggerBy: 'market' | 'mark'; + slTriggerBy: 'market' | 'mark'; + takeProfit: string; + stopLoss: string; +} ⋮---- -/** Unix ms */ +export interface CancelCopyFuturesTpSlRequestV3 { + projectId: string; + strategyId: string; +} ⋮---- -/** Unix ms */ +export interface GetCopyFuturesCurrentTpSlOrdersRequestV3 { + projectId: string; +} ⋮---- -export interface EarnCashPlusSubscribeResultV3 { - orderId: string; +export interface GetCopyFuturesTpSlOrderHistoryRequestV3 { + projectId: string; + startTime?: string; + endTime?: string; + limit?: string; + cursor?: string; +} + +================ +File: src/types/websockets/ws-events.ts +================ +export interface MessageEventLike { + target: WebSocket; + type: 'message'; + data: string; } ⋮---- -export type EarnCashPlusOrderStatusV3 = 'processing' | 'success' | 'failed'; +export function isMessageEvent(msg: unknown): msg is MessageEventLike ⋮---- -export type EarnCashPlusAccountTypeV3 = 'funding' | 'uta' | 'otc'; +export interface WsBaseEvent { + action: TAction; + arg: unknown; + data: TData[]; +} ⋮---- -export interface EarnCashPlusPaymentAccountV3 { - accountType: EarnCashPlusAccountTypeV3; - payAmount: string; +export interface WsSnapshotChannelEvent extends WsBaseEvent<'snapshot'> { + arg: { + instType: string; + channel: string; + instId: string; + }; } ⋮---- -export interface EarnCashPlusSubscribeStatusV3 { - orderId: string; - status: EarnCashPlusOrderStatusV3; - coin: string; - amount: string; - /** Unix ms */ - subscribeTime: string; - /** Unix ms */ - interestTime: string; - /** First interest distribution, Unix ms */ - dividendTime: string; - paymentAccountList: EarnCashPlusPaymentAccountV3[]; +export interface WsSnapshotAccountEvent extends WsBaseEvent<'snapshot'> { + arg: { + instType: string; + channel: 'account'; + instId: string; + }; } ⋮---- -/** Unix ms */ +export interface WsSnapshotPositionsEvent extends WsBaseEvent<'snapshot'> { + arg: { + instType: string; + channel: 'positions'; + instId: string; + }; +} ⋮---- -/** Unix ms */ +export interface WsAccountSnapshotDataUMCBL { + marginCoin: string; + locked: string; + available: string; + maxOpenPosAvailable: string; + maxTransferOut: string; + equity: string; + usdtEquity: string; +} ⋮---- -/** First interest distribution, Unix ms */ +export interface WsAccountSnapshotUMCBL extends WsBaseEvent<'snapshot'> { + arg: { + instType: 'umcbl'; + channel: 'account'; + instId: string; + }; + data: WsAccountSnapshotDataUMCBL[]; +} ⋮---- -export interface EarnCashPlusRedeemCoinV3 { - productSubId: string; - coin: string; - /** How much of this coin 1 unit of Cash+ equals */ - conversionRate: string; - /** Redeemable Cash+ position */ - redeemAvailable: string; - redeemMinAmount: string; - /** Decimal places for the redemption amount */ - redeemScale: string; - /** Unlock request time, Unix ms */ - redeemTime: string; - /** Estimated arrival, Unix ms */ - receivedTime: string; +export interface WsPositionSnapshotDataUMCBL { + posId: string; + instId: string; + instName: string; + marginCoin: string; + margin: string; + marginMode: string; + holdSide: string; + holdMode: string; + total: string; + available: string; + locked: string; + averageOpenPrice: string; + leverage: number; + achievedProfits: string; + upl: string; + uplRate: string; + liqPx: string; + keepMarginRate: string; + marginRate: string; + cTime: string; + uTime: string; + markPrice: string; + /** Cash dividend, USDT (Classic V2 positions channel) */ + cashDividend?: string; } ⋮---- -/** How much of this coin 1 unit of Cash+ equals */ -⋮---- -/** Redeemable Cash+ position */ -⋮---- -/** Decimal places for the redemption amount */ -⋮---- -/** Unlock request time, Unix ms */ -⋮---- -/** Estimated arrival, Unix ms */ +/** Cash dividend, USDT (Classic V2 positions channel) */ ⋮---- -export interface EarnCashPlusRedeemInfoV3 { - redeemCoinList: EarnCashPlusRedeemCoinV3[]; - /** Remaining redemption quota for today */ - userRemainingQuota: string; +/** UTA reality-orderbook push (ts/seq/pseq removed July 2026). Every push is a full snapshot. */ +export interface WsRealityOrderBookDataV3 { + a: [string, string][]; + b: [string, string][]; } ⋮---- -/** Remaining redemption quota for today */ -⋮---- -export interface EarnCashPlusRedeemResultV3 { - orderId: string; - /** Unix ms */ - redeemTime: number; - /** Estimated arrival, Unix ms */ - receiveTime: number; +/** + * UTA reality-orderbook-segmented push. + * Each level is [price, onshoreQty, offshoreQty]. + * Every push is a full snapshot. Whitelist required. + * Go-live 20 Oct 2026. Pairs that have not finished the matching-engine upgrade do not push. + * A crossed book after the upgrade is expected. + */ +export interface WsRealityOrderBookSegmentedDataV3 { + a: [string, string, string][]; + b: [string, string, string][]; } ⋮---- -/** Unix ms */ -⋮---- -/** Estimated arrival, Unix ms */ -⋮---- -export interface EarnCashPlusRedeemStatusV3 { - orderId: string; - status: EarnCashPlusOrderStatusV3; - /** Unix ms */ - redeemTime: string; - /** Estimated arrival, Unix ms */ - receiveTime: string; +export interface WSPositionSnapshotUMCBL extends WsBaseEvent<'snapshot'> { + arg: { + instType: 'umcbl'; + channel: 'positions'; + instId: string; + }; + data: WsPositionSnapshotDataUMCBL[]; } ⋮---- -/** Unix ms */ +/** Classic V2 depth channel push data. checksum removed May 2026 - use seq instead */ +export interface WsDepthBookDataV2 { + asks: [string, string][]; + bids: [string, string][]; + ts: string; + seq: string; + /** Futures books channel only - previous push serial number */ + pseq?: string; +} ⋮---- -/** Estimated arrival, Unix ms */ +/** Futures books channel only - previous push serial number */ ⋮---- -export interface EarnCashPlusPositionV3 { - /** Holding, converted to USD */ +/** UTA account channel coin row */ +export interface WsAccountCoinV3 { + coin: string; balance: string; - /** Cumulative profit, converted to USD */ - totalProfit: string; - /** Yesterday's profit, converted to USD */ - yesterdayProfit: string; - /** Compound annual rate, for reference */ - apr: string; + /** Coin balance before borrowing-related amounts are deducted */ + balanceOriginal?: string; + available: string; + locked: string; + equity: string; + usdValue: string; + borrow: string; + debts: string; + bonus?: string; } ⋮---- -/** Holding, converted to USD */ -⋮---- -/** Cumulative profit, converted to USD */ -⋮---- -/** Yesterday's profit, converted to USD */ -⋮---- -/** Compound annual rate, for reference */ +/** Coin balance before borrowing-related amounts are deducted */ ⋮---- -export interface EarnCashPlusHistoryOrderV3 { - recordId: string; - recordType: - | 'subscribe' - | 'redeem' - | 'compound_interest' - | 'liquidation_redeem'; - status: EarnCashPlusOrderStatusV3; - amount: string; - coin: string; - /** Unix ms */ - createdTime: number; - /** - * Debit account on a subscription. - * Credit account on interest or redemption. - */ - accountType: EarnCashPlusAccountTypeV3; +/** UTA account channel push. action is snapshot or update */ +export interface WsAccountDataV3 { + totalEquity: string; + effEquity: string; + mmr: string; + imr: string; + mgnRatio: string; + positionMgnRatio: string; + unrealisedPnL: string; + coin: WsAccountCoinV3[]; } ⋮---- -/** Unix ms */ -⋮---- /** - * Debit account on a subscription. - * Credit account on interest or redemption. - */ -⋮---- -export interface EarnCashPlusHistoryOrdersV3 { - items: EarnCashPlusHistoryOrderV3[]; - /** Pass back as cursor. Absent on the last page */ - nextCursor?: string; + * UTA depth push. + * books1 and books5: every message is a full snapshot. + * books and books50: the first message is a snapshot, later messages are incremental updates. + * Do not replace the local book with a books or books50 update. + * pseq is set on books and books50. + * rToken: books1 pushes at all times. books5, books50, and books push only outside US market hours. + */ +export interface WsOrderBookDataV3 { + a: [string, string][]; + b: [string, string][]; + seq: string | number; + pseq?: string | number; + /** Present on the books topic */ + maxDepth?: string; + ts: string; } ⋮---- -/** Pass back as cursor. Absent on the last page */ -⋮---- +/** Present on the books topic */ + +================ +File: src/types/response/v3/copytrading.ts +================ /** * * - * Earn | Savings (UTA) + * Copy Trading | Futures (UTA) * * */ ⋮---- -export interface EarnSavingsApyV3 { - rateLevel: string; - minStepVal: string; - maxStepVal: string; - currentApy: string; -} -⋮---- -export interface EarnSavingsProductV3 { - productId: string; - coin: string; - periodType: 'flexible' | 'fixed'; - /** Only returned for fixed-term savings */ - period?: string; - apyType: string; - advanceRedeem: string; - settleMethod: string; - apyList: EarnSavingsApyV3[]; - status: string; - productLevel: string; -} -⋮---- -/** Only returned for fixed-term savings */ -⋮---- -export interface EarnSavingsAccountV3 { - btcAmount: string; - usdtAmount: string; - btc24hEarning: string; - usdt24hEarning: string; - btcTotalEarning: string; - usdtTotalEarning: string; -} -⋮---- -export interface EarnSavingsAssetApyV3 { - rateLevel: string; - minApy: string; - maxApy: string; - currentApy: string; -} -⋮---- -export interface EarnSavingsAssetV3 { - productId: string; - /** Only returned for fixed-term savings */ - orderId?: string; - productCoin: string; - interestCoin: string; - periodType: 'flexible' | 'fixed'; - /** Only returned for fixed-term savings */ - period?: string; - holdAmount: string; - lastProfit: string; - totalProfit: string; - holdDays: string; - status: string; - allowRedemption: string; - productLevel: string; - apy: EarnSavingsAssetApyV3[]; +export interface CopyFuturesMarginDetailV3 { + marginCoin: string; + maxLongCount: string; + remainingLongCount: string; + maxShortCount: string; + remainingShortCount: string; } ⋮---- -/** Only returned for fixed-term savings */ -⋮---- -/** Only returned for fixed-term savings */ -⋮---- -export interface EarnSavingsAssetsV3 { - resultList: EarnSavingsAssetV3[]; - endId: string; +export interface CopyFuturesTradingPairV3 { + symbol: string; + leverage: string; + marginDetails: CopyFuturesMarginDetailV3[]; } ⋮---- -export interface EarnSavingsRecordV3 { - orderId: string; - coinName: string; - settleCoinName: string; - productType: 'flexible' | 'fixed'; - /** Only returned for fixed-term savings */ - period?: string; - productLevel: string; - amount: string; - ts: string; - orderType: string; +export interface CopyFuturesPositionSummaryV3 { + unrealizedPnl: string; + realizedPnl: string; + holdSize: string; + avgPrice: string; + symbol: string; + leverage: string; + marginMode: string; + liqPrice: string; + margin: string; + holdSide: string; + roi: string; + markPrice: string; + positionValue: string; } ⋮---- -/** Only returned for fixed-term savings */ -⋮---- -export interface EarnSavingsRecordsV3 { - resultList: EarnSavingsRecordV3[]; - endId: string; +export interface CopyFuturesMaxTransferableV3 { + maxTransferable: string; + available: string; } ⋮---- -export interface EarnSavingsSubscriptionDetailV3 { - singleMinAmount: string; - singleMaxAmount: string; - remainingAmount: string; - subscribePrecision: string; - profitPrecision: string; - subscribeTime: string; - interestTime: string; - settleTime: string; - expireTime: string; - redeemTime: string; - settleMethod: string; - apyList: EarnSavingsApyV3[]; - redeemDelay: string; +/** Follower copy account. Lead accounts use CopyFuturesMaxTransferableV3. */ +export interface CopyFuturesCopyMaxTransferableV3 { + maxTransferable: string; } ⋮---- -export interface SubscribeSavingsResponseV3 { - orderId: string; +export interface CopyFuturesTransferResponseV3 { + transferId: string; } ⋮---- -export interface EarnSavingsSubscriptionResultV3 { - result: 'success' | 'fail'; - msg: string; +/** May be a single value or comma-separated values */ +export type CopyFuturesTransferAccountTypeV3 = + | 'spot' + | 'uta' + | 'lead' + | 'otc' + | string; +⋮---- +export interface CopyFuturesTransferRecordV3 { + transferId: string; + fromType: CopyFuturesTransferAccountTypeV3; + toType: CopyFuturesTransferAccountTypeV3; + amount: string; + coin: string; + status: 'Successful' | 'Failed' | 'Processing'; + createdTime: string; } ⋮---- -export interface RedeemSavingsResponseV3 { - orderId: string; - status: string; +export interface CopyFuturesTransferRecordListV3 { + list: CopyFuturesTransferRecordV3[]; } ⋮---- -export interface EarnSavingsRedemptionResultV3 { - result: 'success' | 'fail'; - msg: string; +export interface CopyFuturesCurrentFollowerV3 { + followerName: string; + estimateAssets: string; + totalProfit: string; + totalShareProfit: string; + totalInvestment: string; + canRemove: 'yes' | 'no'; + followDays: string; + totalAssets: string; + startTime: string; } ⋮---- -/** - * - * - * Earn | SharkFin (UTA) - * - * - */ +export interface CopyFuturesCurrentFollowersV3 { + list: CopyFuturesCurrentFollowerV3[]; +} ⋮---- -export interface EarnSharkfinProductV3 { - productId: string; - productName: string; - productCoin: string; - subscribeCoin: string; - farmingStartTime: string; - farmingEndTime: string; - lowerRate: string; - defaultRate: string; - upperRate: string; - period: string; - interestStartTime: string; - status: string; - minAmount: string; - limitAmount: string; - soldAmount: string; +export interface CopyFuturesHistoryFollowerV3 { + followerName: string; + totalProfit: string; + totalShareProfit: string; + totalInvestment: string; startTime: string; endTime: string; } ⋮---- -export interface EarnSharkfinProductsV3 { - resultList: EarnSharkfinProductV3[]; - endId: string; +export interface CopyFuturesHistoryFollowersV3 { + list: CopyFuturesHistoryFollowerV3[]; } ⋮---- -export interface EarnSharkfinAccountV3 { - btcSubscribeAmount: string; - usdtSubscribeAmount: string; - btcHistoricalAmount: string; - usdtHistoricalAmount: string; - btcTotalEarning: string; - usdtTotalEarning: string; +export interface CopyFuturesProfitSummaryV3 { + totalProfit: string; + totalAllocatedProfit: string; + totalPendingProfit: string; } ⋮---- -export interface EarnSharkfinAssetV3 { - productId: string; - interestStartTime: string; - interestEndTime: string; - productCoin: string; - subscribeCoin: string; - trend: string; +export interface CopyFuturesProfitDetailV3 { + followerName: string; + profit: string; + allocatedPnl: string; + pendingPnl: string; + shareRatio: string; + shareProfit: string; + reason: 'period' | 'unfollow' | string; settleTime: string; - interestAmount: string; - productStatus: string; } ⋮---- -export interface EarnSharkfinAssetsV3 { - resultList: EarnSharkfinAssetV3[]; - endId: string; +export interface CopyFuturesProfitDetailsV3 { + list: CopyFuturesProfitDetailV3[]; + nextCursor: string; } ⋮---- -export interface EarnSharkfinRecordV3 { - orderId: string; - product: string; - period: string; +export interface CopyFuturesPortfolioOverviewV3 { + projectId: string; + asset: string; + roi: string; + totalProfit: string; + followerProfit: string; + maxDrawdown: string; +} +⋮---- +export interface CopyFuturesCopySettingsV3 { + type: 'fixed_ratio' | 'fixed_margin' | string; amount: string; - ts: string; - type: string; + tradingPairList: string[]; + marginPerOrder: string; + autoCopy: 'on' | 'off' | string; + leverage: string; + maxEntrySlippage: string; + maxMarginRatio: string; + /** API field name (Bitget spelling). */ + maxPostionValue: string; } ⋮---- -export interface EarnSharkfinRecordsV3 { - resultList: EarnSharkfinRecordV3[]; - endId: string; +/** API field name (Bitget spelling). */ +⋮---- +export interface CopyFuturesFollowerTransferRecordV3 { + fromType: string; + toType: string; + amount: string; + coin: string; + status: string; + createdTime: string; } ⋮---- -export interface EarnSharkfinSubscriptionDetailV3 { - productCoin: string; - subscribeCoin: string; - interestTime: string; - expirationTime: string; - minPrice: string; - currentPrice: string; - maxPrice: string; - minRate: string; - defaultRate: string; - maxRate: string; - period: string; - productMinAmount: string; - availableBalance: string; - userAmount: string; - remainingAmount: string; - profitPrecision: string; - subscribePrecision: string; +export interface CopyFuturesFollowerTransferRecordListV3 { + list: CopyFuturesFollowerTransferRecordV3[]; + nextCursor?: string; } ⋮---- -export interface SubscribeSharkfinResponseV3 { - orderId: string; - status: string; +export interface CopyFuturesCurrentCopyV3 { + eliteTrader: string; + estNetProfit: string; + profitShare: string; + estValue: string; + available: string; + currentInvestment: string; } ⋮---- -export interface EarnSharkfinSubscriptionResultV3 { - result: 'success' | 'fail'; - msg: string; +export interface CopyFuturesCopyProfitDetailItemV3 { + settleTime: string; + profit: string; + allocatedPnl: string; + pendingPnl: string; + shareRatio: string; + shareProfit: string; } - -================ -File: src/types/response/v3/strategy.ts -================ -import type { - StrategyIcebergParamsV3, - StrategyOcoParamsV3, - StrategyOrderStatusV3, - StrategyOrderTypeV3, - StrategyTrailingStopParamsV3, - StrategyTriggerByV3, - StrategyTriggerOrderTypeV3, - StrategyTwapParamsV3, -} from '../../request/v3/strategy.js'; ⋮---- -export interface PlaceStrategyOrderResponseV3 { - orderId: string; - clientOid: string; +export interface CopyFuturesCopyProfitDetailsV3 { + list: CopyFuturesCopyProfitDetailItemV3[]; + nextCursor?: string; +} +⋮---- +export interface CopyFuturesFollowerPositionV3 { + symbol: string; + marginCoin: string; + posSide: 'long' | 'short' | string; + total: string; + leverage: string; + avgPrice: string; + marginMode: string; + holdMode: string; + createdTime: string; + positionId: string; } ⋮---- -export interface ModifyStrategyOrderResponseV3 { - orderId: string; - clientOid: string; +export interface CopyFuturesFollowerPositionsV3 { + list: CopyFuturesFollowerPositionV3[]; } ⋮---- -export interface StrategyOrderV3 { - orderId: string; - clientOid: string; - category: 'USDT-FUTURES' | 'COIN-FUTURES' | 'USDC-FUTURES' | string; +export interface CopyFuturesTpSlOrderV3 { + strategyId: string; + category: string; symbol: string; qty: string; - /** buy / sell. Same field as the WS order push. */ - side?: 'buy' | 'sell'; - /** Can be null (seen live on unfilled trigger orders; user report t.me/bitgetOpenapi/153322, staff checking) */ - posSide: 'long' | 'short' | null; - status: StrategyOrderStatusV3; - type?: StrategyOrderTypeV3 | string; - triggerType?: 'takeProfit' | 'stopLoss'; - tpTriggerBy?: StrategyTriggerByV3; - slTriggerBy?: StrategyTriggerByV3; - takeProfit?: string; - stopLoss?: string; - tpOrderType?: StrategyTriggerOrderTypeV3; - slOrderType?: StrategyTriggerOrderTypeV3; - tpLimitPrice?: string; - slLimitPrice?: string; - triggerBy?: StrategyTriggerByV3; - triggerPrice?: string; - triggerOrderType?: StrategyTriggerOrderTypeV3; - triggerOrderPrice?: string; - ocoParams?: StrategyOcoParamsV3; - trailingStopParams?: StrategyTrailingStopParamsV3; - icebergParams?: StrategyIcebergParamsV3; - twapParams?: StrategyTwapParamsV3; - createdTime: string; - updatedTime: string; - /** crossed or isolated. Returned by unfilled and history strategy orders */ - marginMode?: 'crossed' | 'isolated'; + posSide: string; + status: string; + tpTriggerBy: string; + slTriggerBy: string; + takeProfit: string; + stopLoss: string; + tpOrderType: string; + slOrderType: string; } ⋮---- -/** buy / sell. Same field as the WS order push. */ -⋮---- -/** Can be null (seen live on unfilled trigger orders; user report t.me/bitgetOpenapi/153322, staff checking) */ +export interface CopyFuturesTpSlResponseV3 { + strategyId: string; +} ⋮---- -/** crossed or isolated. Returned by unfilled and history strategy orders */ +export interface CopyFuturesCurrentTpSlOrdersV3 { + list: CopyFuturesTpSlOrderV3[]; +} ⋮---- -export interface StrategySubOrderV3 { - subOrderId: string; - subClientOid?: string; - orderId?: string; - clientOid?: string; - category?: string; - symbol?: string; - side?: string; - posSide?: string; - orderType?: string; - price?: string; - qty?: string; - cumExecQty?: string; - avgPrice?: string; - status?: string; - createdTime?: string; - updatedTime?: string; +export interface CopyFuturesTpSlOrderHistoryV3 { + list: CopyFuturesTpSlOrderV3[]; + cursor?: string; } ================ -File: src/types/websockets/ws-api.ts +File: src/types/response/v3/earn.ts ================ -import { WS_KEY_MAP } from '../../util/websocket-util.js'; -import { - CancelOrderRequestV3, - ModifyOrderRequestV3, -} from '../request/v3/trade.js'; -import { - CancelOrderResponseV3, - ModifyOrderResponseV3, -} from '../response/v3/trade.js'; -import { WSAPIPlaceOrderRequestV3 } from './ws-api-request.js'; -import { WSAPIPlaceOrderResponseV3 } from './ws-api-response.js'; -import { BitgetInstTypeV3, WsKey } from './ws-general.js'; -⋮---- -export type WSOperation = 'subscribe' | 'unsubscribe' | 'login'; -⋮---- -// When new WS API operations are added, make sure to also update WS_API_Operations[] below -export type WSAPIOperation = - | 'place-order' - | 'batch-place' - | 'cancel-order' - | 'batch-cancel' - | 'modify-order' - | 'batch-modify'; +/** + * + * + * Earn | On-Chain Elite (UTA) + * + * + */ ⋮---- -export interface WSOperationLoginParams { - apiKey: string; - passphrase: string; - timestamp: number; - sign: string; +export interface EarnEliteSubscriptionCoinV3 { + subscriptionCoin: string; + precision: string; + feeRate: string; + exchangeRate: string; + remainQuota?: string; + minAmount?: string; } ⋮---- -export interface WSAPIRequestBitgetV3 { - op: 'trade'; - id: string; - category: BitgetInstTypeV3; - topic: WSAPIOperation; - args: TWSParams | TWSParams[]; - /** - * Broker rebate code. Top-level, not inside args. - * Place-order docs name this field. Sent on place-order and batch-place. - */ - apiCode?: string; - /** Client-side request timestamp; required for receiveWindow on place-order */ - requestTime?: string; +export interface EarnEliteProductV3 { + productId: string; + coin: string; + minApr: string; + maxApr: string; + subscriptionCoinList: EarnEliteSubscriptionCoinV3[]; + sellOut: 'YES' | 'NO' | string; } ⋮---- -/** - * Broker rebate code. Top-level, not inside args. - * Place-order docs name this field. Sent on place-order and batch-place. - */ -⋮---- -/** Client-side request timestamp; required for receiveWindow on place-order */ +export interface EarnEliteAssetProjectV3 { + projectName: string; +} ⋮---- -export interface WSAPIRequestFlags { - /** If true, will skip auth requirement for WS API connection */ - authIsOptional?: boolean | undefined; +export interface EarnEliteAssetV3 { + productId: string; + productCoin: string; + holdingAmount: string; + usdtHoldingAmount: string; + exchangeRate: string; + apr: string; + minApy?: string; + maxApy?: string; + subscriptionCoin: string; + exchangeAmount: string; + projectList?: EarnEliteAssetProjectV3[]; + unsettledBGPoints: string; + interestCoin: string; + totalProfit: string; } ⋮---- -/** If true, will skip auth requirement for WS API connection */ +export interface EarnEliteAssetsV3 { + resultList: EarnEliteAssetV3[]; +} ⋮---- -export type Exact = { - // This part says: if there's any key that's not in T, it's an error - [K: string]: never; -} & { - [K in keyof T]: T[K]; -}; +export interface EarnEliteRecordV3 { + recordId: string; + productId: string; + coin: string; + status: string; + exchangeRate: string; + receivedCoin: string; + receivedAmount: string; + investAmount: string; + feeRate: string; + redeemType?: string | string[]; + receivingAccount: string; + actualReceivingAccount: string; + paymentAccount?: string[]; + settlePoints: string; + fee: string; + /** Business time, Unix ms */ + bizTime?: string; +} ⋮---- -// This part says: if there's any key that's not in T, it's an error +/** Business time, Unix ms */ ⋮---- -/** - -/** - * V2 request looks like this: -{ - "op":"subscribe", - "args":[ - { - "instType":"SPOT", - "channel":"ticker", - "instId":"BTCUSDT" - }, - { - "instType":"SPOT", - "channel":"candle5m", - "instId":"BTCUSDT" - } - ] -} - */ -export interface WsRequestOperationBitget { - op: WSOperation; - args?: (TWSRequestArg | string | number)[]; -} -export interface WSAPIRateLimitV3 { - limit: string; - remaining: string; +export interface EarnEliteRecordsV3 { + recordList: EarnEliteRecordV3[]; + endId: string; } ⋮---- -export interface WSAPIResponse< - TResponseData extends object = object, - TOperation extends WSAPIOperation = WSAPIOperation, -> { - wsKey: WsKey; - /** Auto-generated */ - id: string; - event: 'trade'; - category: BitgetInstTypeV3; - topic: TOperation; - args: TResponseData; - code: '0' | string; - msg: 'success' | string; - ts: string; - /** Connection ID (trade operation responses, May 2026+) */ - connId?: string; - /** Gateway receive time, Unix microseconds */ - receiveTime?: string; - /** Gateway push time, Unix microseconds */ - pushTime?: string; - rateLimit?: WSAPIRateLimitV3[]; +export interface EarnEliteSubscribeInfoV3 { + productSubId: string; + minAmount: string; + remainQuota: string; + exchangeRate: string; + productCoin: string; + interestTime: string; + settleTime: string; + precision: string; + feeRate: string; + subscriptionCoinList?: EarnEliteSubscriptionCoinV3[]; } ⋮---- -/** Auto-generated */ +export interface EarnEliteSubscribeResultV3 { + orderId: string; +} ⋮---- -/** Connection ID (trade operation responses, May 2026+) */ +export interface EarnEliteSubscribeStatusV3 { + result: 'settled' | 'pending' | 'rejected' | string; +} ⋮---- -/** Gateway receive time, Unix microseconds */ +export interface EarnEliteRedeemInfoBgusdReceiveCoinV3 { + bgusdReceiveCoin: string; + bgusdExchangeRate: string; +} ⋮---- -/** Gateway push time, Unix microseconds */ +export interface EarnEliteRedeemModeV3 { + redeemFeeRate: string; + remainQuota: string; + redeemType: 'fast' | 'standard' | string; + redeemScale: string; + redeemDelayDate: string; + minRedeemAmount: string; + redeemTime: string; +} ⋮---- -/** - * List of operations supported for this WsKey (connection) - */ -export interface WsAPIWsKeyTopicMap { - [WS_KEY_MAP.v3Private]: WSAPIOperation; +export interface EarnEliteRedeemInfoV3 { + productId: string; + productSubId: string; + productCoin: string; + subscriptionCoin: string; + profitCoin: string; + exchangeRate: string; + totalUnPayInterestAmount: string; + preSettleApr: string; + receivedCoin: string; + unsettledPoints: string; + bgusdReceiveCoinList: EarnEliteRedeemInfoBgusdReceiveCoinV3[]; + redeemModeList: EarnEliteRedeemModeV3[]; +} +⋮---- +export interface RedeemEarnEliteResultV3 { + orderId: string; } ⋮---- /** - * Request parameters expected per operation + * + * + * Earn | Cash+ (UTA) + * + * */ -export interface WsAPITopicRequestParamMap { - // https://www.bitget.com/api-doc/uta/websocket/private/Place-Order-Channel#request-parameters - 'place-order': WSAPIPlaceOrderRequestV3; - // https://www.bitget.com/api-doc/uta/websocket/private/Batch-Place-Order-Channel - 'batch-place': WSAPIPlaceOrderRequestV3[]; - // https://www.bitget.com/api-doc/uta/websocket/private/Cancel-Order-Channel - 'cancel-order': CancelOrderRequestV3; - // https://www.bitget.com/docs/uta/websocket/private/Batch-Cancel-Order-Channel - 'batch-cancel': CancelOrderRequestV3[]; - 'modify-order': ModifyOrderRequestV3; - 'batch-modify': ModifyOrderRequestV3[]; +⋮---- +export interface EarnCashPlusSubscribeCoinV3 { + /** Used for subscribe and redeem */ + productSubId: string; + coin: string; + /** Minimum subscription amount, in this coin */ + minAmount: string; + /** How much Cash+ 1 unit of this coin converts into. Default 1 */ + conversionRate: string; + /** Decimal places for the subscription amount */ + subscribeScale: string; + /** Decimal places for profit */ + profitScale: string; + soldOut: 'yes' | 'no'; } ⋮---- -// https://www.bitget.com/api-doc/uta/websocket/private/Place-Order-Channel#request-parameters +/** Used for subscribe and redeem */ ⋮---- -// https://www.bitget.com/api-doc/uta/websocket/private/Batch-Place-Order-Channel +/** Minimum subscription amount, in this coin */ ⋮---- -// https://www.bitget.com/api-doc/uta/websocket/private/Cancel-Order-Channel +/** How much Cash+ 1 unit of this coin converts into. Default 1 */ ⋮---- -// https://www.bitget.com/docs/uta/websocket/private/Batch-Cancel-Order-Channel +/** Decimal places for the subscription amount */ ⋮---- -/** - * Response structure expected for each operation - */ -export interface WsAPIOperationResponseMap { - // https://www.bitget.com/api-doc/uta/websocket/private/Place-Order-Channel#request-parameters - 'place-order': WSAPIResponse<[WSAPIPlaceOrderResponseV3], 'place-order'>; - // https://www.bitget.com/api-doc/uta/websocket/private/Batch-Place-Order-Channel - 'batch-place': WSAPIResponse; - // https://www.bitget.com/api-doc/uta/websocket/private/Cancel-Order-Channel - 'cancel-order': WSAPIResponse<[CancelOrderResponseV3], 'cancel-order'>; - // https://www.bitget.com/docs/uta/websocket/private/Batch-Cancel-Order-Channel - 'batch-cancel': WSAPIResponse; - 'modify-order': WSAPIResponse<[ModifyOrderResponseV3], 'modify-order'>; - 'batch-modify': WSAPIResponse; +/** Decimal places for profit */ +⋮---- +export interface EarnCashPlusSubscribeInfoV3 { + /** Profit source coin. Currently USDGO */ + profitSourceCoin: string; + /** Decimal APR. 0.04 means 4% */ + cashPlusApr: string; + subscribeCoinList: EarnCashPlusSubscribeCoinV3[]; + /** Unix ms */ + interestTime: string; + /** Unix ms */ + payInterestTime: string; + /** Unix ms */ + subscribeTime: string; } ⋮---- -// https://www.bitget.com/api-doc/uta/websocket/private/Place-Order-Channel#request-parameters +/** Profit source coin. Currently USDGO */ ⋮---- -// https://www.bitget.com/api-doc/uta/websocket/private/Batch-Place-Order-Channel +/** Decimal APR. 0.04 means 4% */ ⋮---- -// https://www.bitget.com/api-doc/uta/websocket/private/Cancel-Order-Channel +/** Unix ms */ ⋮---- -// https://www.bitget.com/docs/uta/websocket/private/Batch-Cancel-Order-Channel - -================ -File: src/index.ts -================ - - -================ -File: src/websocket-api-client.ts -================ -import { - CancelOrderRequestV3, - ModifyOrderRequestV3, -} from './types/request/v3/trade.js'; -import { - CancelOrderResponseV3, - ModifyOrderResponseV3, -} from './types/response/v3/trade.js'; -import { WSAPIResponse } from './types/websockets/ws-api.js'; -import { WSAPIPlaceOrderRequestV3 } from './types/websockets/ws-api-request.js'; -import { WSAPIPlaceOrderResponseV3 } from './types/websockets/ws-api-response.js'; -import { - BitgetInstTypeV3, - WSClientConfigurableOptions, -} from './types/websockets/ws-general.js'; -import { DefaultLogger } from './util/logger.js'; -import { WS_KEY_MAP } from './util/websocket-util.js'; -import { WebsocketClientV3 } from './websocket-client-v3.js'; +/** Unix ms */ ⋮---- -/** - * Configurable options specific to only the REST-like WebsocketAPIClient - */ -export interface WSAPIClientConfigurableOptions { - /** - * Default: true - * - * Attach default event listeners, which will console log any high level - * events (opened/reconnecting/reconnected/etc). - * - * If you disable this, you should set your own event listeners - * on the embedded WS Client `wsApiClient.getWSClient().on(....)`. - */ - attachEventListeners: boolean; +/** Unix ms */ +⋮---- +export interface EarnCashPlusSubscribeResultV3 { + orderId: string; } ⋮---- -/** - * Default: true - * - * Attach default event listeners, which will console log any high level - * events (opened/reconnecting/reconnected/etc). - * - * If you disable this, you should set your own event listeners - * on the embedded WS Client `wsApiClient.getWSClient().on(....)`. - */ +export type EarnCashPlusOrderStatusV3 = 'processing' | 'success' | 'failed'; ⋮---- -/** - * This is a minimal Websocket API wrapper around the WebsocketClient. - * - * Note: You can also directly use the sendWSAPIRequest() method to make WS API calls, but some - * may find the below methods slightly more intuitive. - * - * Refer to the WS API promises example for a more detailed example on using sendWSAPIRequest() directly: - * https://github.com/tiagosiebler/bitget-api/blob/master/examples/V3/ws-api-trade-raw.ts - */ -export class WebsocketAPIClient +export type EarnCashPlusAccountTypeV3 = 'funding' | 'uta' | 'otc'; ⋮---- -constructor( - options?: WSClientConfigurableOptions & - Partial, - logger?: DefaultLogger, - ) +export interface EarnCashPlusPaymentAccountV3 { + accountType: EarnCashPlusAccountTypeV3; + payAmount: string; +} ⋮---- -public getWSClient(): WebsocketClientV3 +export interface EarnCashPlusSubscribeStatusV3 { + orderId: string; + status: EarnCashPlusOrderStatusV3; + coin: string; + amount: string; + /** Unix ms */ + subscribeTime: string; + /** Unix ms */ + interestTime: string; + /** First interest distribution, Unix ms */ + dividendTime: string; + paymentAccountList: EarnCashPlusPaymentAccountV3[]; +} ⋮---- -public setTimeOffsetMs(newOffset: number): void +/** Unix ms */ ⋮---- -/* - * Bitget WebSocket API Methods - * https://www.bitget.com/api-doc/uta/websocket/private/Place-Order-Channel - */ +/** Unix ms */ ⋮---- -/** - * Submit a new order - * - * https://www.bitget.com/api-doc/uta/websocket/private/Place-Order-Channel - * - * @returns - */ -submitNewOrder( - category: BitgetInstTypeV3, - params: WSAPIPlaceOrderRequestV3, - ): Promise> +/** First interest distribution, Unix ms */ ⋮---- -/** - * Submit a batch of orders - * - * https://www.bitget.com/api-doc/uta/websocket/private/Batch-Place-Order-Channel - * - * @returns - */ -placeBatchOrders( - category: BitgetInstTypeV3, - params: WSAPIPlaceOrderRequestV3[], - ): Promise> +export interface EarnCashPlusRedeemCoinV3 { + productSubId: string; + coin: string; + /** How much of this coin 1 unit of Cash+ equals */ + conversionRate: string; + /** Redeemable Cash+ position */ + redeemAvailable: string; + redeemMinAmount: string; + /** Decimal places for the redemption amount */ + redeemScale: string; + /** Unlock request time, Unix ms */ + redeemTime: string; + /** Estimated arrival, Unix ms */ + receivedTime: string; +} ⋮---- -/* - * Bitget WebSocket API Methods - * https://www.bitget.com/api-doc/uta/websocket/private/Place-Order-Channel - */ +/** How much of this coin 1 unit of Cash+ equals */ ⋮---- -/** - * Cancel Order - * - * https://www.bitget.com/api-doc/uta/websocket/private/Cancel-Order-Channel - * - * @returns - */ -cancelOrder( - category: BitgetInstTypeV3, - params: CancelOrderRequestV3, - ): Promise> +/** Redeemable Cash+ position */ ⋮---- -/** - * Batch Cancel Order - * - * https://www.bitget.com/api-doc/uta/websocket/private/Batch-Cancel-Order-Channel - * - * @returns - */ -cancelBatchOrders( - category: BitgetInstTypeV3, - params: CancelOrderRequestV3[], - ): Promise> +/** Decimal places for the redemption amount */ ⋮---- -updateOrder( - category: BitgetInstTypeV3, - params: ModifyOrderRequestV3, - ): Promise> +/** Unlock request time, Unix ms */ ⋮---- -batchUpdateOrders( - category: BitgetInstTypeV3, - params: ModifyOrderRequestV3[], - ): Promise> +/** Estimated arrival, Unix ms */ ⋮---- -/** - * - * - * - * - * - * - * - * Private methods for handling some of the convenience/automation provided by the WS API Client - * - * - * - * - * - * - * - */ +export interface EarnCashPlusRedeemInfoV3 { + redeemCoinList: EarnCashPlusRedeemCoinV3[]; + /** Remaining redemption quota for today */ + userRemainingQuota: string; +} ⋮---- -private setupDefaultEventListeners() +/** Remaining redemption quota for today */ ⋮---- -/** - * General event handlers for monitoring the WebsocketClient - */ +export interface EarnCashPlusRedeemResultV3 { + orderId: string; + /** Unix ms */ + redeemTime: number; + /** Estimated arrival, Unix ms */ + receiveTime: number; +} ⋮---- -// Blind JSON.stringify can fail on circular references +/** Unix ms */ ⋮---- -// JSON.stringify({ ...data, target: 'WebSocket' }), - -================ -File: src/websocket-client-v3.ts -================ -import { - WsAPIOperationResponseMap, - WSAPIRequestBitgetV3, - WSAPIRequestFlags, - WsAPITopicRequestParamMap, - WsAPIWsKeyTopicMap, - WSOperation, - WSOperationLoginParams, - WsRequestOperationBitget, -} from './types/websockets/ws-api.js'; -import { MessageEventLike } from './types/websockets/ws-events.js'; -import { - BitgetInstTypeV3, - WsKey, - WsTopicV3, -} from './types/websockets/ws-general.js'; -import { - BaseWebsocketClient, - EmittableEvent, - MidflightWsRequestEvent, -} from './util/BaseWSClient.js'; -import { CHANNEL_API_CODE, isWsPong } from './util/requestUtils.js'; -import { isWSAPIResponse } from './util/type-guards.js'; -import { SignAlgorithm, signMessage } from './util/webCryptoAPI.js'; -import { - getMaxTopicsPerSubscribeEvent, - getNormalisedTopicRequests, - getPromiseRefForWSAPIRequest, - getWsUrl, - WS_AUTH_ON_CONNECT_KEYS, - WS_KEY_MAP, - WS_LOGGER_CATEGORY, - WsTopicRequest, -} from './util/websocket-util.js'; -import { WSConnectedResult } from './util/WsStore.types.js'; +/** Estimated arrival, Unix ms */ ⋮---- -/** - * WebSocket client dedicated to the unified account (V3) WebSockets. - * - * Your Bitget account needs to be upgraded to unified account mode, to use the account-level WebSocket topics. - */ -export class WebsocketClientV3 extends BaseWebsocketClient< +export interface EarnCashPlusRedeemStatusV3 { + orderId: string; + status: EarnCashPlusOrderStatusV3; + /** Unix ms */ + redeemTime: string; + /** Estimated arrival, Unix ms */ + receiveTime: string; +} ⋮---- -WsRequestOperationBitget // subscribe requests have an "args" parameter with an object within +/** Unix ms */ ⋮---- -/** - * Request connection of all dependent (public & private) websockets, instead of waiting for automatic connection by library - */ -public connectAll(): Promise[] +/** Estimated arrival, Unix ms */ ⋮---- -/** - * Ensures the WS API connection is active and ready. - * - * You do not need to call this, but if you call this before making any WS API requests, - * it can accelerate the first request (by preparing the connection in advance). - */ -public connectWSAPI(): Promise +export interface EarnCashPlusPositionV3 { + /** Holding, converted to USD */ + balance: string; + /** Cumulative profit, converted to USD */ + totalProfit: string; + /** Yesterday's profit, converted to USD */ + yesterdayProfit: string; + /** Compound annual rate, for reference */ + apr: string; +} ⋮---- -/** This call automatically ensures the connection is active AND authenticated before resolving */ +/** Holding, converted to USD */ ⋮---- -/** - * 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, category: CategoryV5}. - * - * - Subscriptions are automatically routed to the correct websocket connection. - * - Authentication/connection is automatic. - * - Resubscribe after network issues is automatic. - * - * Call `unsubscribe(topics)` to remove topics - */ -public subscribe( - requests: - | (WsTopicRequest | WsTopicV3) - | (WsTopicRequest | WsTopicV3)[], - wsKey: WsKey, - ): Promise +/** Cumulative profit, converted to USD */ ⋮---- -/** - * 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. +/** Yesterday's profit, converted to USD */ +⋮---- +/** Compound annual rate, for reference */ +⋮---- +export interface EarnCashPlusHistoryOrderV3 { + recordId: string; + recordType: + | 'subscribe' + | 'redeem' + | 'compound_interest' + | 'liquidation_redeem'; + status: EarnCashPlusOrderStatusV3; + amount: string; + coin: string; + /** Unix ms */ + createdTime: number; + /** + * Debit account on a subscription. + * Credit account on interest or redemption. */ -public unsubscribe( - requests: - | (WsTopicRequest | WsTopicV3) - | (WsTopicRequest | WsTopicV3)[], - wsKey: WsKey, - ) + accountType: EarnCashPlusAccountTypeV3; +} +⋮---- +/** Unix ms */ ⋮---- /** - * - * - * Internal methods required to integrate with the BaseWSClient - * - * + * Debit account on a subscription. + * Credit account on interest or redemption. */ ⋮---- -protected sendPingEvent(wsKey: WsKey): void +export interface EarnCashPlusHistoryOrdersV3 { + items: EarnCashPlusHistoryOrderV3[]; + /** Pass back as cursor. Absent on the last page */ + nextCursor?: string; +} ⋮---- -protected sendPongEvent(wsKey: WsKey): void +/** Pass back as cursor. Absent on the last page */ ⋮---- -protected isWsPing(data: any): boolean +/** + * + * + * Earn | Savings (UTA) + * + * + */ ⋮---- -protected isWsPong(data: any): boolean +export interface EarnSavingsApyV3 { + rateLevel: string; + minStepVal: string; + maxStepVal: string; + currentApy: string; +} ⋮---- -protected isPrivateTopicRequest( - _request: WsTopicRequest, - wsKey: WsKey, - ): boolean +export interface EarnSavingsProductV3 { + productId: string; + coin: string; + periodType: 'flexible' | 'fixed'; + /** Only returned for fixed-term savings */ + period?: string; + apyType: string; + advanceRedeem: string; + settleMethod: string; + apyList: EarnSavingsApyV3[]; + status: string; + productLevel: string; +} ⋮---- -protected getPrivateWSKeys(): WsKey[] +/** Only returned for fixed-term savings */ ⋮---- -protected isAuthOnConnectWsKey(wsKey: WsKey): boolean +export interface EarnSavingsAccountV3 { + btcAmount: string; + usdtAmount: string; + btc24hEarning: string; + usdt24hEarning: string; + btcTotalEarning: string; + usdtTotalEarning: string; +} ⋮---- -protected async getWsUrl(wsKey: WsKey): Promise +export interface EarnSavingsAssetApyV3 { + rateLevel: string; + minApy: string; + maxApy: string; + currentApy: string; +} ⋮---- -protected getMaxTopicsPerSubscribeEvent(wsKey: WsKey): number | null +export interface EarnSavingsAssetV3 { + productId: string; + /** Only returned for fixed-term savings */ + orderId?: string; + productCoin: string; + interestCoin: string; + periodType: 'flexible' | 'fixed'; + /** Only returned for fixed-term savings */ + period?: string; + holdAmount: string; + lastProfit: string; + totalProfit: string; + holdDays: string; + status: string; + allowRedemption: string; + productLevel: string; + apy: EarnSavingsAssetApyV3[]; +} ⋮---- -/** - * @returns one or more correctly structured request events for performing a operations over WS. This can vary per exchange spec. - */ -protected async getWsRequestEvents( - operation: WSOperation, - requests: WsTopicRequest[], - ): Promise>[]> +/** Only returned for fixed-term savings */ ⋮---- -// Previously used to track topics in a request. Keeping this for subscribe/unsubscribe requests, no need for incremental values +/** Only returned for fixed-term savings */ ⋮---- -/** - { - "op":"subscribe", - "args":[ - { - "instType":"spot", - "topic":"ticker", - "symbol":"BTCUSDT" - }, - { - "instType":"spot", - "topic":"candle5m", - "symbol":"BTCUSDT" - } - ] - } - */ +export interface EarnSavingsAssetsV3 { + resultList: EarnSavingsAssetV3[]; + endId: string; +} ⋮---- -// const request = { -// topic: 'ticker', -// payload: { instType: 'spot', symbol: 'BTCUSDT' }, -// }; -// becomes: -// const request = { -// topic: 'ticker', -// instType: 'spot', -// symbol: 'BTCUSDT', -// }; +export interface EarnSavingsRecordV3 { + orderId: string; + coinName: string; + settleCoinName: string; + productType: 'flexible' | 'fixed'; + /** Only returned for fixed-term savings */ + period?: string; + productLevel: string; + amount: string; + ts: string; + orderType: string; +} ⋮---- -private async getWsAuthSignature( - wsKey: WsKey, - ): Promise<{ expiresAt: number; signature: string }> +/** Only returned for fixed-term savings */ ⋮---- -private async signMessage( - paramsStr: string, - secret: string, - method: 'hex' | 'base64', - algorithm: SignAlgorithm, - ): Promise +export interface EarnSavingsRecordsV3 { + resultList: EarnSavingsRecordV3[]; + endId: string; +} ⋮---- -protected async getWsAuthRequestEvent( - wsKey: WsKey, - ): Promise> +export interface EarnSavingsSubscriptionDetailV3 { + singleMinAmount: string; + singleMaxAmount: string; + remainingAmount: string; + subscribePrecision: string; + profitPrecision: string; + subscribeTime: string; + interestTime: string; + settleTime: string; + expireTime: string; + redeemTime: string; + settleMethod: string; + apyList: EarnSavingsApyV3[]; + redeemDelay: string; +} ⋮---- -/** - * Abstraction called to sort ws events into emittable event types (response to a request, data update, etc) - */ -protected resolveEmittableEvents( - wsKey: WsKey, - event: MessageEventLike, - ): EmittableEvent[] +export interface SubscribeSavingsResponseV3 { + orderId: string; +} ⋮---- -/** - * WS API response handling - */ +export interface EarnSavingsSubscriptionResultV3 { + result: 'success' | 'fail'; + msg: string; +} ⋮---- -// const eg1 = { -// event: 'error', -// id: '1', -// code: '43012', -// msg: 'Insufficient balance', -// }; +export interface RedeemSavingsResponseV3 { + orderId: string; + status: string; +} ⋮---- -// WS API Success +export interface EarnSavingsRedemptionResultV3 { + result: 'success' | 'fail'; + msg: string; +} ⋮---- /** - * V3 event handling for consumers - behaves the same as V2 - */ + * + * + * Earn | SharkFin (UTA) + * + * + */ ⋮---- -// v2 authentication event +export interface EarnSharkfinProductV3 { + productId: string; + productName: string; + productCoin: string; + subscribeCoin: string; + farmingStartTime: string; + farmingEndTime: string; + lowerRate: string; + defaultRate: string; + upperRate: string; + period: string; + interestStartTime: string; + status: string; + minAmount: string; + limitAmount: string; + soldAmount: string; + startTime: string; + endTime: string; +} ⋮---- -// messageType: typeof msg, -// messageString: JSON.stringify(msg), +export interface EarnSharkfinProductsV3 { + resultList: EarnSharkfinProductV3[]; + endId: string; +} ⋮---- -// Service upgrade (30033): Bitget sends this ~60s before disconnect. Log and let automatic reconnect handle when connection drops. +export interface EarnSharkfinAccountV3 { + btcSubscribeAmount: string; + usdtSubscribeAmount: string; + btcHistoricalAmount: string; + usdtHistoricalAmount: string; + btcTotalEarning: string; + usdtTotalEarning: string; +} ⋮---- -// messageType: typeof msg, -// messageString: JSON.stringify(msg), +export interface EarnSharkfinAssetV3 { + productId: string; + interestStartTime: string; + interestEndTime: string; + productCoin: string; + subscribeCoin: string; + trend: string; + settleTime: string; + interestAmount: string; + productStatus: string; +} ⋮---- -// fallback emit anyway +export interface EarnSharkfinAssetsV3 { + resultList: EarnSharkfinAssetV3[]; + endId: string; +} ⋮---- -/** - * V3/UTA supports order placement via WebSockets. This is the WS API: - * https://www.bitget.com/api-doc/uta/websocket/private/Place-Order-Channel - * - * @returns a promise that resolves/rejects when a matching response arrives - */ -async sendWSAPIRequest< - TWSKey extends keyof WsAPIWsKeyTopicMap, - TWSOperation extends WsAPIWsKeyTopicMap[TWSKey], - TWSParams extends WsAPITopicRequestParamMap[TWSOperation], - TWSAPIResponse extends - WsAPIOperationResponseMap[TWSOperation] = WsAPIOperationResponseMap[TWSOperation], - >( - wsKey: WsKey, - operation: TWSOperation, - category: BitgetInstTypeV3, - params: TWSParams & { signRequest?: boolean }, - requestFlags?: WSAPIRequestFlags, - ): Promise +export interface EarnSharkfinRecordV3 { + orderId: string; + product: string; + period: string; + amount: string; + ts: string; + type: string; +} +⋮---- +export interface EarnSharkfinRecordsV3 { + resultList: EarnSharkfinRecordV3[]; + endId: string; +} +⋮---- +export interface EarnSharkfinSubscriptionDetailV3 { + productCoin: string; + subscribeCoin: string; + interestTime: string; + expirationTime: string; + minPrice: string; + currentPrice: string; + maxPrice: string; + minRate: string; + defaultRate: string; + maxRate: string; + period: string; + productMinAmount: string; + availableBalance: string; + userAmount: string; + remainingAmount: string; + profitPrecision: string; + subscribePrecision: string; +} ⋮---- -// this.logger.trace('sendWSAPIRequest(): assertIsAuthenticated(${wsKey})...'); +export interface SubscribeSharkfinResponseV3 { + orderId: string; + status: string; +} ⋮---- -// this.logger.trace('sendWSAPIRequest(): assertIsAuthenticated(${wsKey}) ok'); +export interface EarnSharkfinSubscriptionResultV3 { + result: 'success' | 'fail'; + msg: string; +} + +================ +File: src/types/response/v3/strategy.ts +================ +import type { + StrategyIcebergParamsV3, + StrategyOcoParamsV3, + StrategyOrderStatusV3, + StrategyOrderTypeV3, + StrategyTrailingStopParamsV3, + StrategyTriggerByV3, + StrategyTriggerOrderTypeV3, + StrategyTwapParamsV3, +} from '../../request/v3/strategy.js'; ⋮---- -// Ensure "args" is always wrapped as array +export interface PlaceStrategyOrderResponseV3 { + orderId: string; + clientOid: string; +} ⋮---- -// Store deferred promise, resolved within the "resolveEmittableEvents" method while parsing incoming events +export interface ModifyStrategyOrderResponseV3 { + orderId: string; + clientOid: string; +} ⋮---- -// eslint-disable-next-line @typescript-eslint/no-explicit-any +export interface StrategyOrderV3 { + orderId: string; + clientOid: string; + category: 'USDT-FUTURES' | 'COIN-FUTURES' | 'USDC-FUTURES' | string; + symbol: string; + qty: string; + /** buy / sell. Same field as the WS order push. */ + side?: 'buy' | 'sell'; + /** Can be null (seen live on unfilled trigger orders; user report t.me/bitgetOpenapi/153322, staff checking) */ + posSide: 'long' | 'short' | null; + status: StrategyOrderStatusV3; + type?: StrategyOrderTypeV3 | string; + triggerType?: 'takeProfit' | 'stopLoss'; + tpTriggerBy?: StrategyTriggerByV3; + slTriggerBy?: StrategyTriggerByV3; + takeProfit?: string; + stopLoss?: string; + tpOrderType?: StrategyTriggerOrderTypeV3; + slOrderType?: StrategyTriggerOrderTypeV3; + tpLimitPrice?: string; + slLimitPrice?: string; + triggerBy?: StrategyTriggerByV3; + triggerPrice?: string; + triggerOrderType?: StrategyTriggerOrderTypeV3; + triggerOrderPrice?: string; + ocoParams?: StrategyOcoParamsV3; + trailingStopParams?: StrategyTrailingStopParamsV3; + icebergParams?: StrategyIcebergParamsV3; + twapParams?: StrategyTwapParamsV3; + createdTime: string; + updatedTime: string; + /** crossed or isolated. Returned by unfilled and history strategy orders */ + marginMode?: 'crossed' | 'isolated'; +} ⋮---- -// Enrich returned promise with request context for easier debugging +/** buy / sell. Same field as the WS order push. */ ⋮---- -// throw e; +/** Can be null (seen live on unfilled trigger orders; user report t.me/bitgetOpenapi/153322, staff checking) */ ⋮---- -// Send event +/** crossed or isolated. Returned by unfilled and history strategy orders */ ⋮---- -// Return deferred promise, so caller can await this call +export interface StrategySubOrderV3 { + subOrderId: string; + subClientOid?: string; + orderId?: string; + clientOid?: string; + category?: string; + symbol?: string; + side?: string; + posSide?: string; + orderType?: string; + price?: string; + qty?: string; + cumExecQty?: string; + avgPrice?: string; + status?: string; + createdTime?: string; + updatedTime?: string; +} + +================ +File: src/index.ts +================ + ================ File: src/types/request/v3/public.ts @@ -14077,44 +13489,235 @@ export interface CurrentPositionV3 { updatedTime: string; } ⋮---- -/** Cash dividend, USDT */ +/** Cash dividend, USDT */ +⋮---- +export interface LoanDataDebtCoinV3 { + coin: string; + debt: string; + interestFreeAmount: string; + interestRateNextHour: string; +} +⋮---- +export interface LoanDataV3 { + currentLoans: string; + interestPaymentTime: string; + debtCoinList: LoanDataDebtCoinV3[]; +} +⋮---- +export interface ModifyOrderResponseV3 { + orderId: string; + clientOid: string; +} +⋮---- +export interface PlaceBatchOrdersResponseV3 { + orderId: string; + clientOid: string; + code?: string; + msg?: string; +} +⋮---- +export interface PlaceOrderResponseV3 { + orderId: string; + clientOid: string; +} +⋮---- +export interface PositionAdlRankV3 { + symbol: string; + marginCoin: string; + adlRank: string; + holdSide: 'long' | 'short'; +} + +================ +File: src/types/websockets/ws-api.ts +================ +import { WS_KEY_MAP } from '../../util/websocket-util.js'; +import { + CancelOrderRequestV3, + ModifyOrderRequestV3, +} from '../request/v3/trade.js'; +import { + CancelOrderResponseV3, + ModifyOrderResponseV3, +} from '../response/v3/trade.js'; +import { WSAPIPlaceOrderRequestV3 } from './ws-api-request.js'; +import { WSAPIPlaceOrderResponseV3 } from './ws-api-response.js'; +import { BitgetInstTypeV3, WsKey } from './ws-general.js'; +⋮---- +export type WSOperation = 'subscribe' | 'unsubscribe' | 'login'; +⋮---- +// When new WS API operations are added, make sure to also update WS_API_Operations[] below +export type WSAPIOperation = + | 'place-order' + | 'batch-place' + | 'cancel-order' + | 'batch-cancel' + | 'modify-order' + | 'batch-modify'; +⋮---- +export interface WSOperationLoginParams { + apiKey: string; + passphrase: string; + timestamp: number; + sign: string; +} +⋮---- +export interface WSAPIRequestBitgetV3 { + op: 'trade'; + id: string; + category: BitgetInstTypeV3; + topic: WSAPIOperation; + args: TWSParams | TWSParams[]; + /** + * Broker rebate code. Top-level, not inside args. + * Place-order docs name this field. Sent on place-order and batch-place. + */ + apiCode?: string; + /** Client-side request timestamp; required for receiveWindow on place-order */ + requestTime?: string; +} +⋮---- +/** + * Broker rebate code. Top-level, not inside args. + * Place-order docs name this field. Sent on place-order and batch-place. + */ +⋮---- +/** Client-side request timestamp; required for receiveWindow on place-order */ +⋮---- +export interface WSAPIRequestFlags { + /** If true, will skip auth requirement for WS API connection */ + authIsOptional?: boolean | undefined; + /** Client-side timestamp in ms. Overrides the envelope timestamp, which defaults to String(Date.now()) when any order has receiveWindow */ + requestTime?: string; +} +⋮---- +/** If true, will skip auth requirement for WS API connection */ +⋮---- +/** Client-side timestamp in ms. Overrides the envelope timestamp, which defaults to String(Date.now()) when any order has receiveWindow */ +⋮---- +export type Exact = { + // This part says: if there's any key that's not in T, it's an error + [K: string]: never; +} & { + [K in keyof T]: T[K]; +}; +⋮---- +// This part says: if there's any key that's not in T, it's an error +⋮---- +/** + +/** + * V2 request looks like this: +{ + "op":"subscribe", + "args":[ + { + "instType":"SPOT", + "channel":"ticker", + "instId":"BTCUSDT" + }, + { + "instType":"SPOT", + "channel":"candle5m", + "instId":"BTCUSDT" + } + ] +} + */ +export interface WsRequestOperationBitget { + op: WSOperation; + args?: (TWSRequestArg | string | number)[]; +} +export interface WSAPIRateLimitV3 { + limit: string; + remaining: string; +} +⋮---- +export interface WSAPIResponse< + TResponseData extends object = object, + TOperation extends WSAPIOperation = WSAPIOperation, +> { + wsKey: WsKey; + /** Auto-generated */ + id: string; + event: 'trade'; + category: BitgetInstTypeV3; + topic: TOperation; + args: TResponseData; + code: '0' | string; + msg: 'success' | string; + ts: string; + /** Connection ID (trade operation responses, May 2026+) */ + connId?: string; + /** Gateway receive time, Unix microseconds */ + receiveTime?: string; + /** Gateway push time, Unix microseconds */ + pushTime?: string; + rateLimit?: WSAPIRateLimitV3[]; +} +⋮---- +/** Auto-generated */ ⋮---- -export interface LoanDataDebtCoinV3 { - coin: string; - debt: string; - interestFreeAmount: string; - interestRateNextHour: string; -} +/** Connection ID (trade operation responses, May 2026+) */ ⋮---- -export interface LoanDataV3 { - currentLoans: string; - interestPaymentTime: string; - debtCoinList: LoanDataDebtCoinV3[]; -} +/** Gateway receive time, Unix microseconds */ ⋮---- -export interface ModifyOrderResponseV3 { - orderId: string; - clientOid: string; -} +/** Gateway push time, Unix microseconds */ ⋮---- -export interface PlaceBatchOrdersResponseV3 { - orderId: string; - clientOid: string; - code?: string; - msg?: string; +/** + * List of operations supported for this WsKey (connection) + */ +export interface WsAPIWsKeyTopicMap { + [WS_KEY_MAP.v3Private]: WSAPIOperation; } ⋮---- -export interface PlaceOrderResponseV3 { - orderId: string; - clientOid: string; +/** + * Request parameters expected per operation + */ +export interface WsAPITopicRequestParamMap { + // https://www.bitget.com/api-doc/uta/websocket/private/Place-Order-Channel#request-parameters + 'place-order': WSAPIPlaceOrderRequestV3; + // https://www.bitget.com/api-doc/uta/websocket/private/Batch-Place-Order-Channel + 'batch-place': WSAPIPlaceOrderRequestV3[]; + // https://www.bitget.com/api-doc/uta/websocket/private/Cancel-Order-Channel + 'cancel-order': CancelOrderRequestV3; + // https://www.bitget.com/docs/uta/websocket/private/Batch-Cancel-Order-Channel + 'batch-cancel': CancelOrderRequestV3[]; + 'modify-order': ModifyOrderRequestV3; + 'batch-modify': ModifyOrderRequestV3[]; } ⋮---- -export interface PositionAdlRankV3 { - symbol: string; - marginCoin: string; - adlRank: string; - holdSide: 'long' | 'short'; +// https://www.bitget.com/api-doc/uta/websocket/private/Place-Order-Channel#request-parameters +⋮---- +// https://www.bitget.com/api-doc/uta/websocket/private/Batch-Place-Order-Channel +⋮---- +// https://www.bitget.com/api-doc/uta/websocket/private/Cancel-Order-Channel +⋮---- +// https://www.bitget.com/docs/uta/websocket/private/Batch-Cancel-Order-Channel +⋮---- +/** + * Response structure expected for each operation + */ +export interface WsAPIOperationResponseMap { + // https://www.bitget.com/api-doc/uta/websocket/private/Place-Order-Channel#request-parameters + 'place-order': WSAPIResponse<[WSAPIPlaceOrderResponseV3], 'place-order'>; + // https://www.bitget.com/api-doc/uta/websocket/private/Batch-Place-Order-Channel + 'batch-place': WSAPIResponse; + // https://www.bitget.com/api-doc/uta/websocket/private/Cancel-Order-Channel + 'cancel-order': WSAPIResponse<[CancelOrderResponseV3], 'cancel-order'>; + // https://www.bitget.com/docs/uta/websocket/private/Batch-Cancel-Order-Channel + 'batch-cancel': WSAPIResponse; + 'modify-order': WSAPIResponse<[ModifyOrderResponseV3], 'modify-order'>; + 'batch-modify': WSAPIResponse; } +⋮---- +// https://www.bitget.com/api-doc/uta/websocket/private/Place-Order-Channel#request-parameters +⋮---- +// https://www.bitget.com/api-doc/uta/websocket/private/Batch-Place-Order-Channel +⋮---- +// https://www.bitget.com/api-doc/uta/websocket/private/Cancel-Order-Channel +⋮---- +// https://www.bitget.com/docs/uta/websocket/private/Batch-Cancel-Order-Channel ================ File: src/rest-client-v2.ts @@ -15879,859 +15482,1279 @@ getAgentCustomerKycResult( params?: GetAgentCustomerKycResultRequestV2, ): Promise> ⋮---- -getAgentCustomerDeposits( - params?: AgentCustomerDepositRequestV2, - ): Promise> +getAgentCustomerDeposits( + params?: AgentCustomerDepositRequestV2, + ): Promise> +⋮---- +getAgentCustomerAssets( + params?: AgentCustomerAssetRequestV2, + ): Promise> +⋮---- +getAgentCommissionDetail( + params?: GetAgentCommissionDetailRequestV2, + ): Promise> +⋮---- +/** + * + * + * Margin + * + * + */ +⋮---- +/** + * + * * Margin | Common + * + */ +⋮---- +getMarginCurrencies(): Promise> +⋮---- +/** + * + * * Margin | Cross/Isolated | Order Record + * + */ +⋮---- +getMarginBorrowHistory( + marginType: MarginType, + params: GetBorrowHistoryRequestV2, + ): Promise< + APIResponse<{ + resultList: MarginBorrowHistoryItemV2[]; + maxId: string; + minId: string; + }> + > +⋮---- +getMarginRepayHistory( + marginType: MarginType, + params: GetRepayHistoryRequestV2, + ): Promise< + APIResponse<{ + resultList: MarginRepaymentHistoryItemV2[]; + maxId: string; + minId: string; + }> + > +⋮---- +getMarginInterestHistory( + marginType: MarginType, + params: GetInterestHistoryRequestV2, + ): Promise< + APIResponse<{ + resultList: MarginInterestHistoryItemV2[]; + maxId: string; + minId: string; + }> + > +⋮---- +getMarginLiquidationHistory( + marginType: MarginType, + params: GetLiquidationHistoryRequestV2, + ): Promise< + APIResponse<{ + resultList: MarginLiquidationHistoryItemV2[]; + maxId: string; + minId: string; + }> + > +⋮---- +getMarginFinancialHistory( + marginType: MarginType, + params: GetFinancialHistoryRequestV2, + ): Promise< + APIResponse<{ + resultList: MarginFinancialHistoryItemV2[]; + maxId: string; + minId: string; + }> + > +⋮---- +/** + * + * * Margin | Cross/Isolated | Account + * + */ +⋮---- +getMarginAccountAssets( + marginType: MarginType, + params?: { coin?: string }, + ): Promise> +⋮---- +marginBorrow( + marginType: MarginType, + params: { + loanId: string; + symbol: string; + coin: string; + borrowAmount: string; + }, + ): Promise< + APIResponse<{ + loanId: string; + symbol: string; + coin: string; + borrowAmount: string; + }> + > +⋮---- +marginRepay( + marginType: MarginType, + params: { + remainDebtAmount: string; + symbol: string; + repayId: string; + coin: string; + repayAmount: string; + }, + ): Promise< + APIResponse<{ + symbol: string; + coin: string; + repayId: string; + remainDebtAmount: string; + repayAmount: string; + }> + > +⋮---- +getMarginRiskRate(marginType: MarginType): Promise< + APIResponse< + { + symbol: string; + riskRateRatio: string; + }[] + > + > +⋮---- +getMarginMaxBorrowable( + marginType: MarginType, + params: { coin: string }, + ): Promise< + APIResponse + > +⋮---- +getMarginMaxTransferable( + marginType: MarginType, + params: { coin: string }, + ): Promise< + APIResponse< + CrossMaxTransferableResponseV2 | IsolatedMaxTransferableResponseV2 + > + > +⋮---- +getMarginInterestRateAndMaxBorrowable( + marginType: MarginType, + params: { coin: string }, + ): Promise< + APIResponse< + | IsolatedInterestRateAndLimitResponseV2[] + | CrossInterestRateAndLimitResponseV2[] + > + > ⋮---- -getAgentCustomerAssets( - params?: AgentCustomerAssetRequestV2, - ): Promise> +getMarginTierConfiguration( + marginType: MarginType, + params: { coin: string }, + ): Promise< + APIResponse< + CrossTierConfigurationResponseV2[] | IsolatedTierConfigurationResponseV2[] + > + > ⋮---- -getAgentCommissionDetail( - params?: GetAgentCommissionDetailRequestV2, - ): Promise> +marginFlashRepay( + marginType: MarginType, + params: { coin: string }, + ): Promise< + APIResponse<{ + repayId: string; + coin?: string; + symbol?: string; + result?: string; + }> + > ⋮---- -/** - * - * - * Margin - * - * - */ +getMarginFlashRepayResult( + marginType: MarginType, + params: { idList: string }, + ): Promise< + APIResponse< + { + repayId: string; + status: string; + }[] + > + > ⋮---- /** * - * * Margin | Common + * * Margin | Cross/Isolated | Trade * */ ⋮---- -getMarginCurrencies(): Promise> +marginSubmitOrder( + marginType: MarginType, + params: MarginPlaceOrderRequestV2, + ): Promise< + APIResponse<{ + orderId: string; + clientOid: string; + }> + > ⋮---- -/** - * - * * Margin | Cross/Isolated | Order Record - * - */ +marginBatchSubmitOrders( + marginType: MarginType, + params: MarginBatchOrdersRequestV2, + ): Promise> ⋮---- -getMarginBorrowHistory( +marginCancelOrder( marginType: MarginType, - params: GetBorrowHistoryRequestV2, + params: { + symbol: string; + orderId?: string; + clientOid?: string; + }, ): Promise< APIResponse<{ - resultList: MarginBorrowHistoryItemV2[]; - maxId: string; - minId: string; + orderId: string; + clientOid: string; }> > ⋮---- -getMarginRepayHistory( +marginBatchCancelOrders( marginType: MarginType, - params: GetRepayHistoryRequestV2, + params: { + symbol: string; + orderIdList: string[]; + }, + ): Promise> +⋮---- +getMarginOpenOrders( + marginType: MarginType, + params: GetMarginCurrentOrdersRequestV2, ): Promise< APIResponse<{ - resultList: MarginRepaymentHistoryItemV2[]; + orderList: MarginCurrentOrderV2[]; maxId: string; minId: string; }> > ⋮---- -getMarginInterestHistory( +getMarginHistoricOrders( marginType: MarginType, - params: GetInterestHistoryRequestV2, + params: GetHistoryOrdersRequestV2, ): Promise< APIResponse<{ - resultList: MarginInterestHistoryItemV2[]; + orderList: MarginHistoryOrderV2[]; maxId: string; minId: string; }> > ⋮---- -getMarginLiquidationHistory( +getMarginHistoricOrderFills( marginType: MarginType, - params: GetLiquidationHistoryRequestV2, + params: GetMarginOrderFillsRequestV2, ): Promise< APIResponse<{ - resultList: MarginLiquidationHistoryItemV2[]; - maxId: string; + fills: MarginOrderFillV2[]; minId: string; + maxId: string; }> > ⋮---- -getMarginFinancialHistory( +getMarginLiquidationOrders( marginType: MarginType, - params: GetFinancialHistoryRequestV2, + params: GetMarginLiquidationOrdersRequestV2, ): Promise< APIResponse<{ - resultList: MarginFinancialHistoryItemV2[]; - maxId: string; - minId: string; + resultList: MarginLiquidationOrderV2[]; + idLessThan: string; }> > ⋮---- /** * - * * Margin | Cross/Isolated | Account + * + * Copy Trading + * + * + */ +⋮---- +/** + * + * + * Copy Trading | Future copy trading | Trader Api + * + * + */ +⋮---- +getFuturesTraderCurrentOrder( + params: GetFuturesTraderCurrentOrdersRequestV2, + ): Promise> +⋮---- +getFuturesTraderHistoryOrders( + params: GetFuturesTraderHistoryOrdersRequestV2, + ): Promise> +⋮---- +modifyFuturesTraderOrderTPSL( + params: ModifyFuturesTraderOrderTPSLRequestV2, + ): Promise> +⋮---- +getFuturesTraderOrder(): Promise< + APIResponse + > +⋮---- +getFuturesTraderProfitHistory(): Promise< + APIResponse + > +⋮---- +getFuturesTraderProfitShareHistory( + params: GetFuturesTraderProfitShareDetailRequestV2, + ): Promise> +⋮---- +closeFuturesTraderOrder(params: { + trackingNo: string; + symbol: string; + productType: CopyTradingProductTypeV2; + }): Promise< + APIResponse< + { + trackingNo: string; + symbol: string; + productType: string; + }[] + > + > +⋮---- +getFuturesTraderProfitShare(params?: { + coin?: string; + pageSize?: string; + pageNo?: string; + }): Promise< + APIResponse< + { + coin: string; + profit: string; + nickName: string; + }[] + > + > +⋮---- +getFuturesTraderProfitShareGroup(params?: { + pageSize?: string; + pageNo?: string; + }): Promise< + APIResponse< + { + coin: string; + profit: string; + profitTime: string; + }[] + > + > +⋮---- +getFuturesTraderSymbolSettings(params: { + productType: CopyTradingProductTypeV2; + }): Promise> +⋮---- +updateFuturesTraderSymbolSettings(params: { + settingList: FuturesTraderSymbolSettingRequestV2[]; + }): Promise> +⋮---- +updateFuturesTraderGlobalSettings(params?: { + enable?: 'YES' | 'NO'; + showTotalEquity?: 'YES' | 'NO'; + showTpsl?: 'YES' | 'NO'; + }): Promise> +⋮---- +getFuturesTraderFollowers( + params?: GetFuturesTraderFollowersRequestV2, + ): Promise> +⋮---- +removeFuturesTraderFollower(params: { + followerUid: string; + }): Promise> +⋮---- +/** + * + * + * Copy Trading | Future copy trading | Follower Api + * * */ ⋮---- -getMarginAccountAssets( - marginType: MarginType, - params?: { coin?: string }, - ): Promise> +getFuturesFollowerCurrentOrders( + params: GetFollowerFuturesCurrentTrackingOrdersRequestV2, + ): Promise> +⋮---- +getFuturesFollowerHistoryOrders( + params: GetFollowerFuturesHistoryTrackingOrdersRequestV2, + ): Promise> +⋮---- +updateFuturesFollowerTPSL( + params: UpdateFuturesFollowerTPSLRequestV2, + ): Promise> +⋮---- +updateFuturesFollowerSettings( + params: UpdateFuturesFollowerSettingsRequestV2, + ): Promise> +⋮---- +getFuturesFollowerSettings(params: { + traderId: string; + }): Promise> ⋮---- -marginBorrow( - marginType: MarginType, - params: { - loanId: string; - symbol: string; - coin: string; - borrowAmount: string; - }, +closeFuturesFollowerPositions( + params: CloseFuturesFollowerPositionsRequestV2, ): Promise< APIResponse<{ - loanId: string; - symbol: string; - coin: string; - borrowAmount: string; + orderIdList: string[]; }> > ⋮---- -marginRepay( - marginType: MarginType, - params: { - remainDebtAmount: string; - symbol: string; - repayId: string; - coin: string; - repayAmount: string; - }, - ): Promise< - APIResponse<{ - symbol: string; - coin: string; - repayId: string; - remainDebtAmount: string; - repayAmount: string; - }> - > +getFuturesFollowerTraders( + params: GetFuturesFollowerTradersRequestV2, + ): Promise> ⋮---- -getMarginRiskRate(marginType: MarginType): Promise< +getFuturesFollowerFollowLimit(params: { + symbol: string; + productType: CopyTradingProductTypeV2; + }): Promise< APIResponse< { + maxFollowSize: string; + minFollowSize: string; symbol: string; - riskRateRatio: string; }[] > > ⋮---- -getMarginMaxBorrowable( - marginType: MarginType, - params: { coin: string }, - ): Promise< - APIResponse - > +unfollowFuturesTrader(params: { + traderId: string; + }): Promise> ⋮---- -getMarginMaxTransferable( - marginType: MarginType, - params: { coin: string }, - ): Promise< - APIResponse< - CrossMaxTransferableResponseV2 | IsolatedMaxTransferableResponseV2 - > - > +/** + * + * + * Copy Trading | Future copy trading | Broker api + * + * + */ ⋮---- -getMarginInterestRateAndMaxBorrowable( - marginType: MarginType, - params: { coin: string }, - ): Promise< - APIResponse< - | IsolatedInterestRateAndLimitResponseV2[] - | CrossInterestRateAndLimitResponseV2[] - > - > +getBrokerTraders(params: object): Promise> ⋮---- -getMarginTierConfiguration( - marginType: MarginType, - params: { coin: string }, - ): Promise< - APIResponse< - CrossTierConfigurationResponseV2[] | IsolatedTierConfigurationResponseV2[] - > - > +getBrokerTradersHistoricalOrders(params: object): Promise> ⋮---- -marginFlashRepay( - marginType: MarginType, - params: { coin: string }, - ): Promise< - APIResponse<{ - repayId: string; - coin?: string; - symbol?: string; - result?: string; - }> - > +getBrokerTradersPendingOrders(params: object): Promise> ⋮---- -getMarginFlashRepayResult( - marginType: MarginType, - params: { idList: string }, - ): Promise< - APIResponse< - { - repayId: string; - status: string; - }[] - > - > +/** + * + * + * Copy Trading | Spot copy trading | Trader api + * + * + */ +⋮---- +getSpotTraderProfit(): Promise> +⋮---- +getSpotTraderHistoryProfit( + params: GetSpotTraderHistoryProfitRequestV2, + ): Promise> +⋮---- +getSpotTraderUnrealizedProfit(params?: { + coin?: string; + pageNo?: string; + pageSize?: string; + }): Promise> +⋮---- +getSpotTraderOrder(): Promise> +⋮---- +modifySpotTraderOrderTPSL(params: { + trackingNo: string; + stopSurplusPrice?: string; + stopLossPrice?: string; + }): Promise> +⋮---- +getSpotTraderHistoryOrders( + params: GetSpotTraderHistoryOrdersRequestV2, + ): Promise> +⋮---- +getSpotTraderCurrentOrders( + params: GetSpotTraderCurrentOrdersRequestV2, + ): Promise> +⋮---- +sellSpotTrader(params: { + trackingNoList: string[]; + symbol: string; + }): Promise> +⋮---- +getSpotTraderSymbolSettings(params: { + symbolList: string[]; + settingType: 'add' | 'delete'; + }): Promise> +⋮---- +removeSpotTraderFollowers(params: { + followerUid: string; + }): Promise> +⋮---- +getSpotTraderConfiguration(): Promise> +⋮---- +getSpotTraderFollowers( + params: GetSpotTraderFollowersRequestV2, + ): Promise> ⋮---- /** * - * * Margin | Cross/Isolated | Trade + * + * Copy Trading | Spot copy trading | Follower api + * * */ ⋮---- -marginSubmitOrder( - marginType: MarginType, - params: MarginPlaceOrderRequestV2, - ): Promise< +cancelSpotFollowerOrder(params: { + trackingNoList: string[]; + }): Promise> +⋮---- +updateSpotFollowerSettings(params: { + traderId: string; + autoCopy?: 'on' | 'off'; + mode?: 'basic' | 'advanced'; + settings: SpotFollowerCopyTradeSettingV2[]; + }): Promise> +⋮---- +updateSpotFollowerTPSL(params: { + trackingNo: string; + stopSurplusPrice?: string; + stopLossPrice?: string; + }): Promise> +⋮---- +getSpotFollowerTraders(params?: { + pageNo?: string; + pageSize?: string; + startTime?: string; + endTime?: string; + }): Promise> +⋮---- +getSpotFollowerCurrentTraderSymbols(params: { traderId: string }): Promise< APIResponse<{ - orderId: string; - clientOid: string; + currentTradingList: string[]; }> > ⋮---- -marginBatchSubmitOrders( - marginType: MarginType, - params: MarginBatchOrdersRequestV2, - ): Promise> +getSpotFollowerSettings(params: { + traderId: string; + }): Promise> +⋮---- +getSpotFollowerHistoryOrders( + params: GetSpotFollowerHistoryOrdersRequestV2, + ): Promise> +⋮---- +getSpotFollowerOpenOrders( + params: GetSpotFollowerOpenOrdersRequestV2, + ): Promise> +⋮---- +sellSpotFollower(params: { + trackingNoList: string[]; + symbol: string; + }): Promise> +⋮---- +unfollowSpotTrader(params: { + traderId: string; + }): Promise> +⋮---- +/** + * + * + * Earn | Savings + * + * + */ +⋮---- +getEarnSavingsProducts(params?: { + coin?: string; + filter?: string; + }): Promise> +⋮---- +getEarnSavingsAccount(): Promise> +⋮---- +getEarnSavingsAssets( + params: GetEarnSavingsAssetsRequestV2, + ): Promise> +⋮---- +getEarnSavingsRecords( + params: GetEarnSavingsRecordsRequestV2, + ): Promise> ⋮---- -marginCancelOrder( - marginType: MarginType, - params: { - symbol: string; - orderId?: string; - clientOid?: string; - }, - ): Promise< +getEarnSavingsSubscription(params: { + productId: string; + periodType: string; + }): Promise> +⋮---- +earnSubscribeSavings(params: { + productId: string; + periodType: string; + amount: string; + }): Promise< APIResponse<{ orderId: string; - clientOid: string; + status: string; }> > ⋮---- -marginBatchCancelOrders( - marginType: MarginType, - params: { - symbol: string; - orderIdList: string[]; - }, - ): Promise> -⋮---- -getMarginOpenOrders( - marginType: MarginType, - params: GetMarginCurrentOrdersRequestV2, - ): Promise< +getEarnSavingsSubscriptionResult(params: { + productId: string; + periodType: string; + }): Promise< APIResponse<{ - orderList: MarginCurrentOrderV2[]; - maxId: string; - minId: string; + result: 'success' | 'fail'; + msg: string; }> > ⋮---- -getMarginHistoricOrders( - marginType: MarginType, - params: GetHistoryOrdersRequestV2, - ): Promise< +earnRedeemSavings(params: RedeemSavingsRequestV2): Promise< APIResponse<{ - orderList: MarginHistoryOrderV2[]; - maxId: string; - minId: string; + orderId: string; + status: string; }> > ⋮---- -getMarginHistoricOrderFills( - marginType: MarginType, - params: GetMarginOrderFillsRequestV2, - ): Promise< +getEarnSavingsRedemptionResult(params: { + orderId: string; + periodType: string; + }): Promise< APIResponse<{ - fills: MarginOrderFillV2[]; - minId: string; - maxId: string; + result: 'success' | 'fail'; + msg: string; }> > ⋮---- -getMarginLiquidationOrders( - marginType: MarginType, - params: GetMarginLiquidationOrdersRequestV2, - ): Promise< - APIResponse<{ - resultList: MarginLiquidationOrderV2[]; - idLessThan: string; - }> +/** + * + * + * Earn | Earn Account + * + * + */ +⋮---- +getEarnAccount(params?: { coin?: string }): Promise< + APIResponse< + { + coin: string; + amount: string; + }[] + > > ⋮---- /** * * - * Copy Trading + * Earn | On-Chain Elite * * */ ⋮---- +getEarnEliteProducts(): Promise> +⋮---- +getEarnEliteAssets(): Promise> +⋮---- +getEarnEliteRecords( + params: GetEarnEliteRecordsRequestV2, + ): Promise> +⋮---- +getEarnEliteSubscribeInfo( + params: GetEarnEliteSubscribeInfoRequestV2, + ): Promise> +⋮---- +subscribeEarnElite( + params: EarnEliteSubscribeRequestV2, + ): Promise> +⋮---- +getEarnEliteSubscribeResult( + params: GetEarnEliteSubscribeResultRequestV2, + ): Promise> +⋮---- +getEarnEliteRedeemInfo( + params: GetEarnEliteRedeemInfoRequestV2, + ): Promise> +⋮---- +redeemEarnElite( + params: RedeemEarnEliteRequestV2, + ): Promise> +⋮---- /** * * - * Copy Trading | Future copy trading | Trader Api + * Earn | Shark Fin * * */ ⋮---- -getFuturesTraderCurrentOrder( - params: GetFuturesTraderCurrentOrdersRequestV2, - ): Promise> +getSharkfinProducts(params: { + coin: string; + limit?: string; + idLessThan?: string; + }): Promise> ⋮---- -getFuturesTraderHistoryOrders( - params: GetFuturesTraderHistoryOrdersRequestV2, - ): Promise> +getSharkfinAccount(): Promise> ⋮---- -modifyFuturesTraderOrderTPSL( - params: ModifyFuturesTraderOrderTPSLRequestV2, - ): Promise> +getSharkfinAssets( + params: GetSharkfinAssetsRequestV2, + ): Promise> ⋮---- -getFuturesTraderOrder(): Promise< - APIResponse - > +getSharkfinRecords( + params: GetSharkfinRecordsRequestV2, + ): Promise> ⋮---- -getFuturesTraderProfitHistory(): Promise< - APIResponse - > +getSharkfinSubscription(params: { + productId: string; + }): Promise> ⋮---- -getFuturesTraderProfitShareHistory( - params: GetFuturesTraderProfitShareDetailRequestV2, - ): Promise> +subscribeSharkfin(params: { productId: string; amount: string }): Promise< + APIResponse<{ + orderId: string; + status: string; + }> + > ⋮---- -closeFuturesTraderOrder(params: { - trackingNo: string; - symbol: string; - productType: CopyTradingProductTypeV2; - }): Promise< - APIResponse< - { - trackingNo: string; - symbol: string; - productType: string; - }[] - > +getSharkfinSubscriptionResult(params: { orderId: string }): Promise< + APIResponse<{ + result: 'success' | 'fail'; + msg: string; + }> > ⋮---- -getFuturesTraderProfitShare(params?: { +/** + * + * + * Earn | Loan + * + * + */ +⋮---- +getLoanCurrencies(params?: { coin?: string; - pageSize?: string; - pageNo?: string; - }): Promise< - APIResponse< - { - coin: string; - profit: string; - nickName: string; - }[] - > + }): Promise> +⋮---- +getLoanEstInterestAndBorrowable( + params: GetLoanEstInterestAndBorrowableRequestV2, + ): Promise< + APIResponse<{ + hourInterest: string; + loanAmount: string; + }> > ⋮---- -getFuturesTraderProfitShareGroup(params?: { - pageSize?: string; - pageNo?: string; - }): Promise< - APIResponse< - { - coin: string; - profit: string; - profitTime: string; - }[] - > +borrowLoan(params: BorrowLoanRequestV2): Promise< + APIResponse<{ + orderId: string; + }> > ⋮---- -getFuturesTraderSymbolSettings(params: { - productType: CopyTradingProductTypeV2; - }): Promise> +getOngoingLoanOrders(params?: { + orderId?: string; + loanCoin?: string; + pledgeCoin?: string; + }): Promise> ⋮---- -updateFuturesTraderSymbolSettings(params: { - settingList: FuturesTraderSymbolSettingRequestV2[]; - }): Promise> +repayLoan( + params: RepayLoanRequestV2, + ): Promise> ⋮---- -updateFuturesTraderGlobalSettings(params?: { - enable?: 'YES' | 'NO'; - showTotalEquity?: 'YES' | 'NO'; - showTpsl?: 'YES' | 'NO'; - }): Promise> +getRepayHistory( + params: GetLoanRepayHistoryRequestV2, + ): Promise> +⋮---- +updateLoanPledgeRate(params: ModifyLoanPledgeRateRequestV2): Promise< + APIResponse<{ + loanCoin: string; + pledgeCoin: string; + afterPledgeRate: string; + }> + > +⋮---- +getLoanPledgeRateHistory( + params: GetLoanPledgeRateHistoryRequestV2, + ): Promise> +⋮---- +getLoanHistory( + params: GetLoanHistoryRequestV2, + ): Promise> ⋮---- -getFuturesTraderFollowers( - params?: GetFuturesTraderFollowersRequestV2, - ): Promise> +getLoanDebts(): Promise> ⋮---- -removeFuturesTraderFollower(params: { - followerUid: string; - }): Promise> +getLoanLiquidationRecords( + params: GetLiquidationRecordsRequestV2, + ): Promise> ⋮---- /** * - * - * Copy Trading | Future copy trading | Follower Api - * + * * Inst Loan | Product Info * */ ⋮---- -getFuturesFollowerCurrentOrders( - params: GetFollowerFuturesCurrentTrackingOrdersRequestV2, - ): Promise> -⋮---- -getFuturesFollowerHistoryOrders( - params: GetFollowerFuturesHistoryTrackingOrdersRequestV2, - ): Promise> -⋮---- -updateFuturesFollowerTPSL( - params: UpdateFuturesFollowerTPSLRequestV2, - ): Promise> -⋮---- -updateFuturesFollowerSettings( - params: UpdateFuturesFollowerSettingsRequestV2, - ): Promise> +getLoanProductInfo( + params: GetInstLoanProductInfoRequestV2, + ): Promise> ⋮---- -getFuturesFollowerSettings(params: { - traderId: string; - }): Promise> +getLoanSymbols( + params: GetInstLoanSymbolsRequestV2, + ): Promise> ⋮---- -closeFuturesFollowerPositions( - params: CloseFuturesFollowerPositionsRequestV2, - ): Promise< +getLoanMarginCoinInfo(params: GetInstLoanMarginCoinInfoRequestV2): Promise< APIResponse<{ - orderIdList: string[]; + productId: string; + coinInfo: InstLoanCoinInfoV2[]; }> > ⋮---- -getFuturesFollowerTraders( - params: GetFuturesFollowerTradersRequestV2, - ): Promise> +/** + * + * * Inst Loan | Account + * + */ ⋮---- -getFuturesFollowerFollowLimit(params: { - symbol: string; - productType: CopyTradingProductTypeV2; - }): Promise< - APIResponse< - { - maxFollowSize: string; - minFollowSize: string; - symbol: string; - }[] - > +getLoanRiskUnit(): Promise< + APIResponse<{ + riskUnitId: string[]; + }> > ⋮---- -unfollowFuturesTrader(params: { - traderId: string; - }): Promise> +getLoanLTVConvert( + params?: GetInstLoanLTVConvertRequestV2, + ): Promise> ⋮---- /** * - * - * Copy Trading | Future copy trading | Broker api - * + * * Inst Loan | Orders * */ ⋮---- -getBrokerTraders(params: object): Promise> -⋮---- -getBrokerTradersHistoricalOrders(params: object): Promise> +getLoanRepaidHistory( + params?: GetInstLoanRepaidHistoryRequestV2, + ): Promise> ⋮---- -getBrokerTradersPendingOrders(params: object): Promise> +getLoanOrder( + params?: GetInstLoanOrderRequestV2, + ): Promise> + +================ +File: src/websocket-api-client.ts +================ +import { + CancelOrderRequestV3, + ModifyOrderRequestV3, +} from './types/request/v3/trade.js'; +import { + CancelOrderResponseV3, + ModifyOrderResponseV3, +} from './types/response/v3/trade.js'; +import { WSAPIRequestFlags, WSAPIResponse } from './types/websockets/ws-api.js'; +import { WSAPIPlaceOrderRequestV3 } from './types/websockets/ws-api-request.js'; +import { WSAPIPlaceOrderResponseV3 } from './types/websockets/ws-api-response.js'; +import { + BitgetInstTypeV3, + WSClientConfigurableOptions, +} from './types/websockets/ws-general.js'; +import { DefaultLogger } from './util/logger.js'; +import { WS_KEY_MAP } from './util/websocket-util.js'; +import { WebsocketClientV3 } from './websocket-client-v3.js'; ⋮---- /** + * Configurable options specific to only the REST-like WebsocketAPIClient + */ +export interface WSAPIClientConfigurableOptions { + /** + * Default: true * + * Attach default event listeners, which will console log any high level + * events (opened/reconnecting/reconnected/etc). * - * Copy Trading | Spot copy trading | Trader api + * If you disable this, you should set your own event listeners + * on the embedded WS Client `wsApiClient.getWSClient().on(....)`. + */ + attachEventListeners: boolean; +} +⋮---- +/** + * Default: true * + * Attach default event listeners, which will console log any high level + * events (opened/reconnecting/reconnected/etc). * + * If you disable this, you should set your own event listeners + * on the embedded WS Client `wsApiClient.getWSClient().on(....)`. */ ⋮---- -getSpotTraderProfit(): Promise> -⋮---- -getSpotTraderHistoryProfit( - params: GetSpotTraderHistoryProfitRequestV2, - ): Promise> -⋮---- -getSpotTraderUnrealizedProfit(params?: { - coin?: string; - pageNo?: string; - pageSize?: string; - }): Promise> -⋮---- -getSpotTraderOrder(): Promise> -⋮---- -modifySpotTraderOrderTPSL(params: { - trackingNo: string; - stopSurplusPrice?: string; - stopLossPrice?: string; - }): Promise> -⋮---- -getSpotTraderHistoryOrders( - params: GetSpotTraderHistoryOrdersRequestV2, - ): Promise> -⋮---- -getSpotTraderCurrentOrders( - params: GetSpotTraderCurrentOrdersRequestV2, - ): Promise> -⋮---- -sellSpotTrader(params: { - trackingNoList: string[]; - symbol: string; - }): Promise> +/** + * This is a minimal Websocket API wrapper around the WebsocketClient. + * + * Note: You can also directly use the sendWSAPIRequest() method to make WS API calls, but some + * may find the below methods slightly more intuitive. + * + * Refer to the WS API promises example for a more detailed example on using sendWSAPIRequest() directly: + * https://github.com/tiagosiebler/bitget-api/blob/master/examples/V3/ws-api-trade-raw.ts + */ +export class WebsocketAPIClient ⋮---- -getSpotTraderSymbolSettings(params: { - symbolList: string[]; - settingType: 'add' | 'delete'; - }): Promise> +constructor( + options?: WSClientConfigurableOptions & + Partial, + logger?: DefaultLogger, + ) ⋮---- -removeSpotTraderFollowers(params: { - followerUid: string; - }): Promise> +public getWSClient(): WebsocketClientV3 ⋮---- -getSpotTraderConfiguration(): Promise> +public setTimeOffsetMs(newOffset: number): void ⋮---- -getSpotTraderFollowers( - params: GetSpotTraderFollowersRequestV2, - ): Promise> +/* + * Bitget WebSocket API Methods + * https://www.bitget.com/api-doc/uta/websocket/private/Place-Order-Channel + */ ⋮---- /** + * Submit a new order * + * https://www.bitget.com/api-doc/uta/websocket/private/Place-Order-Channel * - * Copy Trading | Spot copy trading | Follower api + * @returns + */ +submitNewOrder( + category: BitgetInstTypeV3, + params: WSAPIPlaceOrderRequestV3, + requestFlags?: WSAPIRequestFlags, + ): Promise> +⋮---- +/** + * Submit a batch of orders * + * https://www.bitget.com/api-doc/uta/websocket/private/Batch-Place-Order-Channel * + * @returns */ +placeBatchOrders( + category: BitgetInstTypeV3, + params: WSAPIPlaceOrderRequestV3[], + requestFlags?: WSAPIRequestFlags, + ): Promise> ⋮---- -cancelSpotFollowerOrder(params: { - trackingNoList: string[]; - }): Promise> -⋮---- -updateSpotFollowerSettings(params: { - traderId: string; - autoCopy?: 'on' | 'off'; - mode?: 'basic' | 'advanced'; - settings: SpotFollowerCopyTradeSettingV2[]; - }): Promise> -⋮---- -updateSpotFollowerTPSL(params: { - trackingNo: string; - stopSurplusPrice?: string; - stopLossPrice?: string; - }): Promise> -⋮---- -getSpotFollowerTraders(params?: { - pageNo?: string; - pageSize?: string; - startTime?: string; - endTime?: string; - }): Promise> -⋮---- -getSpotFollowerCurrentTraderSymbols(params: { traderId: string }): Promise< - APIResponse<{ - currentTradingList: string[]; - }> - > -⋮---- -getSpotFollowerSettings(params: { - traderId: string; - }): Promise> -⋮---- -getSpotFollowerHistoryOrders( - params: GetSpotFollowerHistoryOrdersRequestV2, - ): Promise> -⋮---- -getSpotFollowerOpenOrders( - params: GetSpotFollowerOpenOrdersRequestV2, - ): Promise> -⋮---- -sellSpotFollower(params: { - trackingNoList: string[]; - symbol: string; - }): Promise> -⋮---- -unfollowSpotTrader(params: { - traderId: string; - }): Promise> +/* + * Bitget WebSocket API Methods + * https://www.bitget.com/api-doc/uta/websocket/private/Place-Order-Channel + */ ⋮---- /** + * Cancel Order * + * https://www.bitget.com/api-doc/uta/websocket/private/Cancel-Order-Channel * - * Earn | Savings + * @returns + */ +cancelOrder( + category: BitgetInstTypeV3, + params: CancelOrderRequestV3, + ): Promise> +⋮---- +/** + * Batch Cancel Order * + * https://www.bitget.com/api-doc/uta/websocket/private/Batch-Cancel-Order-Channel * + * @returns */ +cancelBatchOrders( + category: BitgetInstTypeV3, + params: CancelOrderRequestV3[], + ): Promise> ⋮---- -getEarnSavingsProducts(params?: { - coin?: string; - filter?: string; - }): Promise> -⋮---- -getEarnSavingsAccount(): Promise> -⋮---- -getEarnSavingsAssets( - params: GetEarnSavingsAssetsRequestV2, - ): Promise> -⋮---- -getEarnSavingsRecords( - params: GetEarnSavingsRecordsRequestV2, - ): Promise> -⋮---- -getEarnSavingsSubscription(params: { - productId: string; - periodType: string; - }): Promise> -⋮---- -earnSubscribeSavings(params: { - productId: string; - periodType: string; - amount: string; - }): Promise< - APIResponse<{ - orderId: string; - status: string; - }> - > -⋮---- -getEarnSavingsSubscriptionResult(params: { - productId: string; - periodType: string; - }): Promise< - APIResponse<{ - result: 'success' | 'fail'; - msg: string; - }> - > -⋮---- -earnRedeemSavings(params: RedeemSavingsRequestV2): Promise< - APIResponse<{ - orderId: string; - status: string; - }> - > +updateOrder( + category: BitgetInstTypeV3, + params: ModifyOrderRequestV3, + ): Promise> ⋮---- -getEarnSavingsRedemptionResult(params: { - orderId: string; - periodType: string; - }): Promise< - APIResponse<{ - result: 'success' | 'fail'; - msg: string; - }> - > +batchUpdateOrders( + category: BitgetInstTypeV3, + params: ModifyOrderRequestV3[], + ): Promise> ⋮---- /** * * - * Earn | Earn Account * * - */ -⋮---- -getEarnAccount(params?: { coin?: string }): Promise< - APIResponse< - { - coin: string; - amount: string; - }[] - > - > -⋮---- -/** * * - * Earn | On-Chain Elite + * + * Private methods for handling some of the convenience/automation provided by the WS API Client + * + * + * + * + * * * */ ⋮---- -getEarnEliteProducts(): Promise> -⋮---- -getEarnEliteAssets(): Promise> +private setupDefaultEventListeners() ⋮---- -getEarnEliteRecords( - params: GetEarnEliteRecordsRequestV2, - ): Promise> +/** + * General event handlers for monitoring the WebsocketClient + */ ⋮---- -getEarnEliteSubscribeInfo( - params: GetEarnEliteSubscribeInfoRequestV2, - ): Promise> +// Blind JSON.stringify can fail on circular references ⋮---- -subscribeEarnElite( - params: EarnEliteSubscribeRequestV2, - ): Promise> +// JSON.stringify({ ...data, target: 'WebSocket' }), + +================ +File: src/websocket-client-v3.ts +================ +import { + WsAPIOperationResponseMap, + WSAPIRequestBitgetV3, + WSAPIRequestFlags, + WsAPITopicRequestParamMap, + WsAPIWsKeyTopicMap, + WSOperation, + WSOperationLoginParams, + WsRequestOperationBitget, +} from './types/websockets/ws-api.js'; +import { MessageEventLike } from './types/websockets/ws-events.js'; +import { + BitgetInstTypeV3, + WsKey, + WsTopicV3, +} from './types/websockets/ws-general.js'; +import { + BaseWebsocketClient, + EmittableEvent, + MidflightWsRequestEvent, +} from './util/BaseWSClient.js'; +import { CHANNEL_API_CODE, isWsPong } from './util/requestUtils.js'; +import { isWSAPIResponse } from './util/type-guards.js'; +import { SignAlgorithm, signMessage } from './util/webCryptoAPI.js'; +import { + getMaxTopicsPerSubscribeEvent, + getNormalisedTopicRequests, + getPromiseRefForWSAPIRequest, + getWsUrl, + WS_AUTH_ON_CONNECT_KEYS, + WS_KEY_MAP, + WS_LOGGER_CATEGORY, + WsTopicRequest, +} from './util/websocket-util.js'; +import { WSConnectedResult } from './util/WsStore.types.js'; ⋮---- -getEarnEliteSubscribeResult( - params: GetEarnEliteSubscribeResultRequestV2, - ): Promise> +/** + * WebSocket client dedicated to the unified account (V3) WebSockets. + * + * Your Bitget account needs to be upgraded to unified account mode, to use the account-level WebSocket topics. + */ +export class WebsocketClientV3 extends BaseWebsocketClient< ⋮---- -getEarnEliteRedeemInfo( - params: GetEarnEliteRedeemInfoRequestV2, - ): Promise> +WsRequestOperationBitget // subscribe requests have an "args" parameter with an object within ⋮---- -redeemEarnElite( - params: RedeemEarnEliteRequestV2, - ): Promise> +/** + * Request connection of all dependent (public & private) websockets, instead of waiting for automatic connection by library + */ +public connectAll(): Promise[] ⋮---- /** + * Ensures the WS API connection is active and ready. * + * You do not need to call this, but if you call this before making any WS API requests, + * it can accelerate the first request (by preparing the connection in advance). + */ +public connectWSAPI(): Promise +⋮---- +/** This call automatically ensures the connection is active AND authenticated before resolving */ +⋮---- +/** + * Request subscription to one or more topics. Pass topics as either an array of strings, + * or array of objects (if the topic has parameters). * - * Earn | Shark Fin + * Objects should be formatted as {topic: string, params: object, category: CategoryV5}. * + * - Subscriptions are automatically routed to the correct websocket connection. + * - Authentication/connection is automatic. + * - Resubscribe after network issues is automatic. * + * Call `unsubscribe(topics)` to remove topics */ +public subscribe( + requests: + | (WsTopicRequest | WsTopicV3) + | (WsTopicRequest | WsTopicV3)[], + wsKey: WsKey, + ): Promise ⋮---- -getSharkfinProducts(params: { - coin: string; - limit?: string; - idLessThan?: string; - }): Promise> -⋮---- -getSharkfinAccount(): Promise> -⋮---- -getSharkfinAssets( - params: GetSharkfinAssetsRequestV2, - ): Promise> -⋮---- -getSharkfinRecords( - params: GetSharkfinRecordsRequestV2, - ): Promise> -⋮---- -getSharkfinSubscription(params: { - productId: string; - }): Promise> -⋮---- -subscribeSharkfin(params: { productId: string; amount: string }): Promise< - APIResponse<{ - orderId: string; - status: string; - }> - > -⋮---- -getSharkfinSubscriptionResult(params: { orderId: string }): Promise< - APIResponse<{ - result: 'success' | 'fail'; - msg: string; - }> - > +/** + * Unsubscribe from one or more topics. Similar to subscribe() but in reverse. + * + * - Requests are automatically routed to the correct websocket connection. + * - These topics will be removed from the topic cache, so they won't be subscribed to again. + */ +public unsubscribe( + requests: + | (WsTopicRequest | WsTopicV3) + | (WsTopicRequest | WsTopicV3)[], + wsKey: WsKey, + ) ⋮---- /** * * - * Earn | Loan + * Internal methods required to integrate with the BaseWSClient * * */ ⋮---- -getLoanCurrencies(params?: { - coin?: string; - }): Promise> +protected sendPingEvent(wsKey: WsKey): void ⋮---- -getLoanEstInterestAndBorrowable( - params: GetLoanEstInterestAndBorrowableRequestV2, - ): Promise< - APIResponse<{ - hourInterest: string; - loanAmount: string; - }> - > +protected sendPongEvent(wsKey: WsKey): void ⋮---- -borrowLoan(params: BorrowLoanRequestV2): Promise< - APIResponse<{ - orderId: string; - }> - > +protected isWsPing(data: any): boolean ⋮---- -getOngoingLoanOrders(params?: { - orderId?: string; - loanCoin?: string; - pledgeCoin?: string; - }): Promise> +protected isWsPong(data: any): boolean ⋮---- -repayLoan( - params: RepayLoanRequestV2, - ): Promise> +protected isPrivateTopicRequest( + _request: WsTopicRequest, + wsKey: WsKey, + ): boolean ⋮---- -getRepayHistory( - params: GetLoanRepayHistoryRequestV2, - ): Promise> +protected getPrivateWSKeys(): WsKey[] ⋮---- -updateLoanPledgeRate(params: ModifyLoanPledgeRateRequestV2): Promise< - APIResponse<{ - loanCoin: string; - pledgeCoin: string; - afterPledgeRate: string; - }> - > +protected isAuthOnConnectWsKey(wsKey: WsKey): boolean ⋮---- -getLoanPledgeRateHistory( - params: GetLoanPledgeRateHistoryRequestV2, - ): Promise> +protected async getWsUrl(wsKey: WsKey): Promise ⋮---- -getLoanHistory( - params: GetLoanHistoryRequestV2, - ): Promise> +protected getMaxTopicsPerSubscribeEvent(wsKey: WsKey): number | null ⋮---- -getLoanDebts(): Promise> +/** + * @returns one or more correctly structured request events for performing a operations over WS. This can vary per exchange spec. + */ +protected async getWsRequestEvents( + operation: WSOperation, + requests: WsTopicRequest[], + ): Promise>[]> ⋮---- -getLoanLiquidationRecords( - params: GetLiquidationRecordsRequestV2, - ): Promise> +// Previously used to track topics in a request. Keeping this for subscribe/unsubscribe requests, no need for incremental values ⋮---- /** - * - * * Inst Loan | Product Info - * - */ + { + "op":"subscribe", + "args":[ + { + "instType":"spot", + "topic":"ticker", + "symbol":"BTCUSDT" + }, + { + "instType":"spot", + "topic":"candle5m", + "symbol":"BTCUSDT" + } + ] + } + */ ⋮---- -getLoanProductInfo( - params: GetInstLoanProductInfoRequestV2, - ): Promise> +// const request = { +// topic: 'ticker', +// payload: { instType: 'spot', symbol: 'BTCUSDT' }, +// }; +// becomes: +// const request = { +// topic: 'ticker', +// instType: 'spot', +// symbol: 'BTCUSDT', +// }; ⋮---- -getLoanSymbols( - params: GetInstLoanSymbolsRequestV2, - ): Promise> +private async getWsAuthSignature( + wsKey: WsKey, + ): Promise<{ expiresAt: number; signature: string }> ⋮---- -getLoanMarginCoinInfo(params: GetInstLoanMarginCoinInfoRequestV2): Promise< - APIResponse<{ - productId: string; - coinInfo: InstLoanCoinInfoV2[]; - }> - > +private async signMessage( + paramsStr: string, + secret: string, + method: 'hex' | 'base64', + algorithm: SignAlgorithm, + ): Promise +⋮---- +protected async getWsAuthRequestEvent( + wsKey: WsKey, + ): Promise> ⋮---- /** - * - * * Inst Loan | Account - * + * Abstraction called to sort ws events into emittable event types (response to a request, data update, etc) */ +protected resolveEmittableEvents( + wsKey: WsKey, + event: MessageEventLike, + ): EmittableEvent[] ⋮---- -getLoanRiskUnit(): Promise< - APIResponse<{ - riskUnitId: string[]; - }> - > +/** + * WS API response handling + */ ⋮---- -getLoanLTVConvert( - params?: GetInstLoanLTVConvertRequestV2, - ): Promise> +// const eg1 = { +// event: 'error', +// id: '1', +// code: '43012', +// msg: 'Insufficient balance', +// }; +⋮---- +// WS API Success ⋮---- /** + * V3 event handling for consumers - behaves the same as V2 + */ +⋮---- +// v2 authentication event +⋮---- +// messageType: typeof msg, +// messageString: JSON.stringify(msg), +⋮---- +// Service upgrade (30033): Bitget sends this ~60s before disconnect. Log and let automatic reconnect handle when connection drops. +⋮---- +// messageType: typeof msg, +// messageString: JSON.stringify(msg), +⋮---- +// fallback emit anyway +⋮---- +/** + * V3/UTA supports order placement via WebSockets. This is the WS API: + * https://www.bitget.com/api-doc/uta/websocket/private/Place-Order-Channel * - * * Inst Loan | Orders - * + * @returns a promise that resolves/rejects when a matching response arrives */ +async sendWSAPIRequest< + TWSKey extends keyof WsAPIWsKeyTopicMap, + TWSOperation extends WsAPIWsKeyTopicMap[TWSKey], + TWSParams extends WsAPITopicRequestParamMap[TWSOperation], + TWSAPIResponse extends + WsAPIOperationResponseMap[TWSOperation] = WsAPIOperationResponseMap[TWSOperation], + >( + wsKey: WsKey, + operation: TWSOperation, + category: BitgetInstTypeV3, + params: TWSParams & { signRequest?: boolean }, + requestFlags?: WSAPIRequestFlags, + ): Promise ⋮---- -getLoanRepaidHistory( - params?: GetInstLoanRepaidHistoryRequestV2, - ): Promise> +// this.logger.trace('sendWSAPIRequest(): assertIsAuthenticated(${wsKey})...'); ⋮---- -getLoanOrder( - params?: GetInstLoanOrderRequestV2, - ): Promise> +// this.logger.trace('sendWSAPIRequest(): assertIsAuthenticated(${wsKey}) ok'); +⋮---- +// Ensure "args" is always wrapped as array +⋮---- +// Store deferred promise, resolved within the "resolveEmittableEvents" method while parsing incoming events +⋮---- +// eslint-disable-next-line @typescript-eslint/no-explicit-any +⋮---- +// Enrich returned promise with request context for easier debugging +⋮---- +// throw e; +⋮---- +// Send event +⋮---- +// Return deferred promise, so caller can await this call ================ File: src/types/websockets/ws-general.ts @@ -18284,1469 +18307,1369 @@ old ones: Contributions are encouraged, I will review any incoming pull requests. See the issues tab for todo items. - -## Star History - -[![Star History Chart](https://api.star-history.com/svg?repos=sieblyio/bybit-api,sieblyio/okx-api,sieblyio/binance,sieblyio/bitget-api,sieblyio/bitmart-api,sieblyio/gateio-api,sieblyio/kucoin-api,sieblyio/coinbase-api,sieblyio/orderbooks,sieblyio/accountstate,sieblyio/awesome-crypto-examples&type=Date)](https://star-history.com/#sieblyio/bybit-api&sieblyio/okx-api&sieblyio/binance&sieblyio/bitget-api&sieblyio/bitmart-api&sieblyio/gateio-api&sieblyio/kucoin-api&sieblyio/coinbase-api&sieblyio/orderbooks&sieblyio/accountstate&sieblyio/awesome-crypto-examples&Date) - - - -================ -File: src/types/request/v3/trade.ts -================ -export interface BatchModifyOrderRequestV3 { - orderId?: string; - clientOid?: string; - qty?: string; - price?: string; - /** Custom request ID. Numbers within 18 digits. */ - requestId?: number; - autoCancel?: 'yes' | 'no'; - /** Required since 30 Sep 2026 */ - symbol: string; - /** Required since 30 Sep 2026 */ - category: - | 'SPOT' - | 'MARGIN' - | 'USDT-FUTURES' - | 'COIN-FUTURES' - | 'USDC-FUTURES'; - /** Limit orders only. no rejects a price outside the band (default). yes clamps it */ - pxAmendType?: 'yes' | 'no'; -} -⋮---- -/** Custom request ID. Numbers within 18 digits. */ -⋮---- -/** Required since 30 Sep 2026 */ -⋮---- -/** Required since 30 Sep 2026 */ -⋮---- -/** Limit orders only. no rejects a price outside the band (default). yes clamps it */ -⋮---- -export interface CancelAllOrdersRequestV3 { - category: - | 'SPOT' - | 'MARGIN' - | 'USDT-FUTURES' - | 'COIN-FUTURES' - | 'USDC-FUTURES'; - symbol?: string; -} + +## Star History + +[![Star History Chart](https://api.star-history.com/svg?repos=sieblyio/bybit-api,sieblyio/okx-api,sieblyio/binance,sieblyio/bitget-api,sieblyio/bitmart-api,sieblyio/gateio-api,sieblyio/kucoin-api,sieblyio/coinbase-api,sieblyio/orderbooks,sieblyio/accountstate,sieblyio/awesome-crypto-examples&type=Date)](https://star-history.com/#sieblyio/bybit-api&sieblyio/okx-api&sieblyio/binance&sieblyio/bitget-api&sieblyio/bitmart-api&sieblyio/gateio-api&sieblyio/kucoin-api&sieblyio/coinbase-api&sieblyio/orderbooks&sieblyio/accountstate&sieblyio/awesome-crypto-examples&Date) + + + +================ +File: src/types/response/v3/account.ts +================ +// Account Management Response Types +import type { + CollateralTypeV3, + FinancialRecordTypeV3, +} from '../../request/v3/account.js'; ⋮---- -export interface CancelBatchOrdersRequestV3 { - orderId?: string; - clientOid?: string; - category: - | 'SPOT' - | 'MARGIN' - | 'USDT-FUTURES' - | 'COIN-FUTURES' - | 'USDC-FUTURES'; +export interface AccountSymbolConfigV3 { + category: string; symbol: string; + marginMode: string; + leverage: string; } ⋮---- -export interface CloseAllPositionsRequestV3 { - category: 'USDT-FUTURES' | 'COIN-FUTURES' | 'USDC-FUTURES'; - symbol?: string; - posSide?: 'long' | 'short'; -} -⋮---- -export interface CancelOrderRequestV3 { - orderId?: string; - clientOid?: string; - category?: - | 'SPOT' - | 'MARGIN' - | 'USDT-FUTURES' - | 'COIN-FUTURES' - | 'USDC-FUTURES'; +export interface AccountCoinConfigV3 { + coin: string; + leverage: string; } ⋮---- -export type FuturesMarginModeV3 = 'crossed' | 'isolated'; +export type AccountPermissionV3 = + | 'uta_mgt' + | 'uta_trade' + | 'withdraw' + | 'copy_futures_position' + | 'copy_futures_order'; ⋮---- -export interface GetMaxOpenAvailableRequestV3 { - category: - | 'SPOT' - | 'MARGIN' - | 'USDT-FUTURES' - | 'COIN-FUTURES' - | 'USDC-FUTURES'; - symbol: string; - orderType: 'limit' | 'market'; - side: 'buy' | 'sell'; - price?: string; - size?: string; - /** Spot only. Default: no */ - autoBorrow?: 'yes' | 'no'; +export interface AccountInfoV3 { + userId: string; + inviterId: string; /** - * crossed (default) or isolated. - * Under isolated margin, available excludes futures trial funds. + * Only set when the calling account is a sub-account. + * Confirmed by Bitget devs but not yet in their docs: the API returns + * parentId as an integer, not only the string shown in the docs. */ - marginMode?: FuturesMarginModeV3; + parentId: string | number; + channelCode: string; + channel: string; + ips: string; + /** + * Confirmed by Bitget devs but not yet in their docs: permType uses + * underscores (read_and_write). readonly is also possible on demo keys. + */ + permType: + | 'read-only' + | 'read-and-write' + | 'read_only' + | 'read_and_write' + | 'readonly'; + permissions: AccountPermissionV3[]; + regisTime: string; + traderType?: 'trader' | 'not_trader'; } ⋮---- -/** Spot only. Default: no */ -⋮---- /** - * crossed (default) or isolated. - * Under isolated margin, available excludes futures trial funds. + * Only set when the calling account is a sub-account. + * Confirmed by Bitget devs but not yet in their docs: the API returns + * parentId as an integer, not only the string shown in the docs. */ ⋮---- -export interface GetOrderInfoRequestV3 { - orderId?: string; - clientOid?: string; -} -⋮---- -export interface GetFillsRequestV3 { - category?: - | 'SPOT' - | 'MARGIN' - | 'USDT-FUTURES' - | 'COIN-FUTURES' - | 'USDC-FUTURES'; - orderId?: string; - startTime?: string; - endTime?: string; - limit?: string; - cursor?: string; -} -⋮---- -export interface GetUnfilledOrdersRequestV3 { - category?: - | 'SPOT' - | 'MARGIN' - | 'USDT-FUTURES' - | 'COIN-FUTURES' - | 'USDC-FUTURES'; - symbol?: string; - startTime?: string; - endTime?: string; - limit?: string; - cursor?: string; -} +/** + * Confirmed by Bitget devs but not yet in their docs: permType uses + * underscores (read_and_write). readonly is also possible on demo keys. + */ ⋮---- -export interface GetHistoryOrdersRequestV3 { - category: - | 'SPOT' - | 'MARGIN' - | 'USDT-FUTURES' - | 'COIN-FUTURES' - | 'USDC-FUTURES'; - symbol?: string; - startTime?: string; - endTime?: string; - limit?: string; - cursor?: string; -} +export type AccountLevelV3 = 'basic' | 'advanced' | 'isolated' | 'delta'; ⋮---- -export interface GetPositionHistoryRequestV3 { - category: 'USDT-FUTURES' | 'COIN-FUTURES' | 'USDC-FUTURES'; - symbol?: string; - startTime?: string; - endTime?: string; - limit?: string; - cursor?: string; +export interface AccountSettingsV3 { + uid: string; + accountMode: 'unified' | 'hybrid' | 'upgrading' | 'switching'; + assetMode: string; + accountLevel: AccountLevelV3; + holdMode: string; + stpMode: 'none' | 'cancel_taker' | 'cancel_maker' | 'cancel_both'; + deltaSwitch?: 'yes' | 'no'; + repayMode?: 'auto' | 'manual'; + symbolConfigList: AccountSymbolConfigV3[]; + coinConfigList: AccountCoinConfigV3[]; } ⋮---- -export interface GetCurrentPositionRequestV3 { - category: 'USDT-FUTURES' | 'COIN-FUTURES' | 'USDC-FUTURES'; - symbol?: string; - posSide?: 'long' | 'short'; +export interface AccountDeltaCoinPositionV3 { + coin: string; + positionRatio: string; } ⋮---- -export interface ModifyOrderRequestV3 { - orderId?: string; - clientOid?: string; - qty?: string; - price?: string; - /** Custom request ID. Numbers within 18 digits. */ - requestId?: number; - autoCancel?: 'yes' | 'no'; - /** Required since 30 Sep 2026 */ - symbol: string; - /** Required since 30 Sep 2026 */ - category: - | 'SPOT' - | 'MARGIN' - | 'USDT-FUTURES' - | 'COIN-FUTURES' - | 'USDC-FUTURES'; - tpTriggerBy?: 'market' | 'mark'; - slTriggerBy?: 'market' | 'mark'; - takeProfit?: string; - stopLoss?: string; - tpOrderType?: 'limit' | 'market'; - slOrderType?: 'limit' | 'market'; - tpLimitPrice?: string; - slLimitPrice?: string; - /** Limit orders only. no rejects a price outside the band (default). yes clamps it */ - pxAmendType?: 'yes' | 'no'; +/** Delta-neutral mode metrics. Available when deltaSwitch is enabled. */ +export interface AccountDeltaInfoV3 { + /** Deprecated, no longer used as a hedge-eligibility criterion */ + deltaEquityRatio: string; + /** Deprecated, no longer used as a hedge-eligibility criterion */ + deltaThreshold: string; + positionThreshold: string; + list: AccountDeltaCoinPositionV3[]; } ⋮---- -/** Custom request ID. Numbers within 18 digits. */ -⋮---- -/** Required since 30 Sep 2026 */ -⋮---- -/** Required since 30 Sep 2026 */ +/** Deprecated, no longer used as a hedge-eligibility criterion */ ⋮---- -/** Limit orders only. no rejects a price outside the band (default). yes clamps it */ +/** Deprecated, no longer used as a hedge-eligibility criterion */ ⋮---- -export interface PlaceRealityOrderRequestV3 { - category?: 'SPOT' | 'MARGIN'; - symbol: string; - side: 'buy' | 'sell'; - orderType: 'limit' | 'market'; - qty: string; - price?: string; - clientOid?: string; - /** - * rToken routing. Accepted: internal_market | lit_market. Omit for default. - * internal_market = on-exchange only (not submitted to the U.S. stock broker). - * lit_market = broker only (not matched on-exchange). - * Omit / default = internal first at best price, then unfilled to broker. - * Live since 5 Nov 2026 (internalization renamed; old lit_market meaning is now default). - */ - venue?: 'internal_market' | 'lit_market'; - /** - * rToken time in force. gtd (default) = current session. - * gtc = 90 days. Same changelog note as venue. - */ - rTokenTimeInForce?: 'gtd' | 'gtc'; +export interface AccountAssetV3 { + coin: string; + equity: string; + usdValue: string; + balance: string; + /** Coin balance before borrowing-related amounts are deducted */ + balanceOriginal?: string; + available: string; + debt: string; + locked: string; + /** Position value in USD */ + positionValue?: string; + /** Account leverage (non-negative) */ + leverage?: string; + /** USDT bonus amount */ + bonus?: string; + /** Interest calculation base */ + interestBase?: string; } ⋮---- -/** - * rToken routing. Accepted: internal_market | lit_market. Omit for default. - * internal_market = on-exchange only (not submitted to the U.S. stock broker). - * lit_market = broker only (not matched on-exchange). - * Omit / default = internal first at best price, then unfilled to broker. - * Live since 5 Nov 2026 (internalization renamed; old lit_market meaning is now default). - */ +/** Coin balance before borrowing-related amounts are deducted */ ⋮---- -/** - * rToken time in force. gtd (default) = current session. - * gtc = 90 days. Same changelog note as venue. - */ +/** Position value in USD */ ⋮---- -export interface CancelRealityOrderRequestV3 { - category?: 'SPOT' | 'MARGIN'; - symbol: string; - orderId?: string; - clientOid?: string; -} +/** Account leverage (non-negative) */ ⋮---- -export interface PlaceBatchOrdersRequestV3 { - category: - | 'SPOT' - | 'MARGIN' - | 'USDT-FUTURES' - | 'COIN-FUTURES' - | 'USDC-FUTURES'; - symbol: string; - qty: string; - price?: string; - side: 'buy' | 'sell'; - orderType: 'limit' | 'market'; - timeInForce?: 'ioc' | 'fok' | 'gtc' | 'post_only'; - posSide?: 'long' | 'short'; +/** USDT bonus amount */ +⋮---- +/** Interest calculation base */ +⋮---- +export interface BorrowResponseV3 { + orderId: string; clientOid?: string; - reduceOnly?: 'yes' | 'no'; - /** Limit orders only. no rejects a price outside the band (default). yes clamps it */ - pxAmendType?: 'yes' | 'no'; - /** - * Unix ms. Used with receiveWindow. - * If omitted, receiveWindow has no effect. - * An order that reaches the matching engine after requestTime + receiveWindow is canceled. - */ - requestTime?: string; - /** Validity window in ms. Range [10, 60000]. Requires requestTime. */ - receiveWindow?: string; } ⋮---- -/** Limit orders only. no rejects a price outside the band (default). yes clamps it */ +export interface MaxBorrowableV3 { + maxBorrowable: string; +} ⋮---- -/** - * Unix ms. Used with receiveWindow. - * If omitted, receiveWindow has no effect. - * An order that reaches the matching engine after requestTime + receiveWindow is canceled. - */ +export interface AccountAssetsV3 { + accountEquity: string; + usdtEquity: string; + btcEquity: string; + unrealisedPnl: string; + usdtUnrealisedPnl: string; + btcUnrealizedPnl: string; + effEquity: string; + mmr: string; + imr: string; + mgnRatio: string; + positionMgnRatio: string; + positionValue?: string; + leverage?: string; + assets: AccountAssetV3[]; +} ⋮---- -/** Validity window in ms. Range [10, 60000]. Requires requestTime. */ +export interface ConvertRecordV3 { + fromCoin: string; + fromCoinSize: string; + toCoin: string; + toCoinSize: string; + price: string; + ts: string; +} ⋮---- -export interface PlaceOrderRequestV3 { - category: - | 'SPOT' - | 'MARGIN' - | 'USDT-FUTURES' - | 'COIN-FUTURES' - | 'USDC-FUTURES'; +export interface FinancialRecordV3 { + category: string; + id: string; symbol: string; - /** - * Futures qty must be a multiple of quantityMultiplier - * and have at most quantityPrecision decimal places. - * Both come from /api/v3/market/instruments. Futures only. - */ - qty: string; - price?: string; - side: 'buy' | 'sell'; - /** - * Market orders always run as IOC. - * Staff-confirmed: t.me/bitgetOpenapi/153169. - * timeInForce does not change that. - */ - orderType: 'limit' | 'market'; - timeInForce?: 'ioc' | 'fok' | 'gtc' | 'post_only' | 'rpi'; - posSide?: 'long' | 'short'; - clientOid?: string; - reduceOnly?: 'yes' | 'no'; - /** Futures only. Defaults to crossed */ - marginMode?: FuturesMarginModeV3; - stpMode?: 'none' | 'cancel_taker' | 'cancel_maker' | 'cancel_both'; - tpTriggerBy?: 'market' | 'mark'; - slTriggerBy?: 'market' | 'mark'; - takeProfit?: string; - stopLoss?: string; - tpOrderType?: 'limit' | 'market'; - slOrderType?: 'limit' | 'market'; - tpLimitPrice?: string; - slLimitPrice?: string; - /** Spot only. Default: no */ - autoBorrow?: 'yes' | 'no'; - /** Limit orders only. no rejects a price outside the band (default). yes clamps it */ - pxAmendType?: 'yes' | 'no'; - /** Limit orders only. queue1, queue5, counterparty1, or counterparty5 */ - bboLevel?: 'queue1' | 'queue5' | 'counterparty1' | 'counterparty5'; - /** Market orders only. Decimal, default 0.02, range 0.01-0.05 */ - slippageTolerance?: string; - /** - * rToken routing. Accepted: internal_market | lit_market. Omit for default. - * internal_market = on-exchange only (not submitted to the U.S. stock broker). - * lit_market = broker only (not matched on-exchange). - * Omit / default = internal first at best price, then unfilled to broker. - * Ignored for non-rToken symbols. timeInForce is also ignored for rToken. - * Live since 5 Nov 2026 (internalization renamed; old lit_market meaning is now default). - */ - venue?: 'internal_market' | 'lit_market'; - /** - * rToken time in force. gtd (default) lasts the current session. - * gtc lasts 90 days. Ignored for non-rToken symbols. - */ - rTokenTimeInForce?: 'gtd' | 'gtc'; - /** - * Unix ms. Used with receiveWindow. - * If omitted, receiveWindow has no effect. - * An order that reaches the matching engine after requestTime + receiveWindow is canceled. - */ - requestTime?: string; - /** Validity window in ms. Range [10, 60000]. Requires requestTime. */ - receiveWindow?: string; + coin: string; + type: FinancialRecordTypeV3; + amount: string; + fee: string; + balance: string; + ts: string; + /** crossed | isolated */ + positionType?: string; + positionAmount?: string; + positionBalance?: string; } ⋮---- -/** - * Futures qty must be a multiple of quantityMultiplier - * and have at most quantityPrecision decimal places. - * Both come from /api/v3/market/instruments. Futures only. - */ +/** crossed | isolated */ ⋮---- -/** - * Market orders always run as IOC. - * Staff-confirmed: t.me/bitgetOpenapi/153169. - * timeInForce does not change that. - */ +export interface PaymentCoinV3 { + coin: string; + size: string; + amount: string; +} ⋮---- -/** Futures only. Defaults to crossed */ +export interface RepayableCoinV3 { + coin: string; + size: string; + amount: string; +} ⋮---- -/** Spot only. Default: no */ +export interface RepayResponseV3 { + result: string; + repayAmount: string; +} ⋮---- -/** Limit orders only. no rejects a price outside the band (default). yes clamps it */ +// Sub-account Management Response Types ⋮---- -/** Limit orders only. queue1, queue5, counterparty1, or counterparty5 */ +export interface CreateSubAccountApiKeyResponseV3 { + note: string; + apiKey: string; + secret: string; + type: string; + permissions: string[]; + ips: string[]; +} +export interface SubAccountApiKeyV3 { + apiKey: string; + note: string; + type: string; + permissions: string[]; + ips: string[]; + ts?: string; +} ⋮---- -/** Market orders only. Decimal, default 0.02, range 0.01-0.05 */ +export interface UpdateSubAccountApiKeyResponseV3 { + note: string; + apiKey: string; + type: string; + permissions: string[]; + ips: string[]; +} ⋮---- -/** - * rToken routing. Accepted: internal_market | lit_market. Omit for default. - * internal_market = on-exchange only (not submitted to the U.S. stock broker). - * lit_market = broker only (not matched on-exchange). - * Omit / default = internal first at best price, then unfilled to broker. - * Ignored for non-rToken symbols. timeInForce is also ignored for rToken. - * Live since 5 Nov 2026 (internalization renamed; old lit_market meaning is now default). - */ +export interface CreateSubAccountResponseV3 { + username: string; + subUid: string; + status: string; + note: string; + createdTime: string; + updatedTime: string; +} ⋮---- -/** - * rToken time in force. gtd (default) lasts the current session. - * gtc lasts 90 days. Ignored for non-rToken symbols. - */ +export interface CreateAgentSubAccountResponseV3 { + username: string; + subUid: string; + apiKey: string; + secret: string; + note: string; + createdTime: string; +} ⋮---- -/** - * Unix ms. Used with receiveWindow. - * If omitted, receiveWindow has no effect. - * An order that reaches the matching engine after requestTime + receiveWindow is canceled. - */ +export interface SubAccountV3 { + subUid: string; + username: string; + status: string; + accountMode: string; + type: 'normal' | 'virtual' | 'custodian' | 'fund_management'; + note: string; + createdTime: string; + updatedTime: string; +} ⋮---- -/** Validity window in ms. Range [10, 60000]. Requires requestTime. */ +export interface WithdrawAddressBookEntryV3 { + coin: string; + chain: string; + address: string; + countryCode: string; + label: string; + memo: string; + type: 'regular' | 'EVM' | 'universal' | 'internal'; + internalType: '' | 'uid' | 'mobile' | 'email'; + createdTime: string; +} ⋮---- -export interface CountdownCancelAllRequestV3 { - countdown: string; // seconds until auto-cancel (5-60, or 0 to disable) +export interface WithdrawAddressBookV3 { + addressList: WithdrawAddressBookEntryV3[]; + cursor?: string; } ⋮---- -countdown: string; // seconds until auto-cancel (5-60, or 0 to disable) - -================ -File: src/types/response/v3/account.ts -================ -// Account Management Response Types -import type { - CollateralTypeV3, - FinancialRecordTypeV3, -} from '../../request/v3/account.js'; +// Transfer Response Types ⋮---- -export interface AccountSymbolConfigV3 { - category: string; +export interface AllSymbolFeeRateV3 { symbol: string; - marginMode: string; - leverage: string; + makerFeeRate: string; + takerFeeRate: string; } ⋮---- -export interface AccountCoinConfigV3 { +export interface TransferResponseV3 { + transferId: string; + clientOid?: string; +} +⋮---- +export interface SubTransferRecordV3 { + transferId: string; + oldTransferId?: string; + fromType: string; + toType: string; + amount: string; coin: string; - leverage: string; + fromUserId: string; + toUserId: string; + status: string; + clientOid: string; + createdTime: string; + updatedTime: string; } ⋮---- -export type AccountPermissionV3 = - | 'uta_mgt' - | 'uta_trade' - | 'withdraw' - | 'copy_futures_position' - | 'copy_futures_order'; +export interface SubUnifiedAssetV3 { + coin: string; + equity: string; + usdValue: string; + balance: string; + available: string; + debt: string; + locked: string; +} ⋮---- -export interface AccountInfoV3 { - userId: string; - inviterId: string; - /** - * Only set when the calling account is a sub-account. - * Confirmed by Bitget devs but not yet in their docs: the API returns - * parentId as an integer, not only the string shown in the docs. - */ - parentId: string | number; - channelCode: string; - channel: string; - ips: string; - /** - * Confirmed by Bitget devs but not yet in their docs: permType uses - * underscores (read_and_write). readonly is also possible on demo keys. - */ - permType: - | 'read-only' - | 'read-and-write' - | 'read_only' - | 'read_and_write' - | 'readonly'; - permissions: AccountPermissionV3[]; - regisTime: string; - traderType?: 'trader' | 'not_trader'; +export interface SubUnifiedAssetV3 { + subUid: string; + cursor: string; + assets: SubUnifiedAssetV3[]; } ⋮---- -/** - * Only set when the calling account is a sub-account. - * Confirmed by Bitget devs but not yet in their docs: the API returns - * parentId as an integer, not only the string shown in the docs. - */ +export interface GetFeeRateResponseV3 { + makerFeeRate: string; + takerFeeRate: string; +} ⋮---- -/** - * Confirmed by Bitget devs but not yet in their docs: permType uses - * underscores (read_and_write). readonly is also possible on demo keys. - */ +export interface FundingAssetV3 { + coin: string; + available: string; + frozen: string; + balance: string; +} ⋮---- -export type AccountLevelV3 = 'basic' | 'advanced' | 'isolated' | 'delta'; +// Deposit Response Types ⋮---- -export interface AccountSettingsV3 { - uid: string; - accountMode: 'unified' | 'hybrid' | 'upgrading' | 'switching'; - assetMode: string; - accountLevel: AccountLevelV3; - holdMode: string; - stpMode: 'none' | 'cancel_taker' | 'cancel_maker' | 'cancel_both'; - deltaSwitch?: 'yes' | 'no'; - repayMode?: 'auto' | 'manual'; - symbolConfigList: AccountSymbolConfigV3[]; - coinConfigList: AccountCoinConfigV3[]; +export interface DepositAddressV3 { + address: string; + chain: string; + coin: string; + tag: string; + url: string; } ⋮---- -export interface AccountDeltaCoinPositionV3 { +export interface DepositRecordV3 { + orderId: string; + recordId: string; coin: string; - positionRatio: string; + type: 'deposit'; + dest: 'on_chain' | 'internal_transfer'; + size: string; + status: 'pending' | 'success' | 'fail'; + fromAddress: string; + toAddress: string; + chain: string; + createdTime: string; + updatedTime: string; } ⋮---- -/** Delta-neutral mode metrics. Available when deltaSwitch is enabled. */ -export interface AccountDeltaInfoV3 { - /** Deprecated, no longer used as a hedge-eligibility criterion */ - deltaEquityRatio: string; - /** Deprecated, no longer used as a hedge-eligibility criterion */ - deltaThreshold: string; - positionThreshold: string; - list: AccountDeltaCoinPositionV3[]; +// Withdraw Response Types +⋮---- +export interface WithdrawResponseV3 { + orderId: string; + clientOid: string; } ⋮---- -/** Deprecated, no longer used as a hedge-eligibility criterion */ +export interface WithdrawRecordV3 { + orderId: string; + clientOid: string; + recordId: string; + coin: string; + type: 'withdraw'; + dest: 'on_chain' | 'internal_transfer'; + size: string; + status: 'pending' | 'success' | 'fail'; + fromAddress: string; + toAddress: string; + chain: string; + fee: string; + confirm: string; + tag: string; + createdTime: string; + updatedTime: string; +} ⋮---- -/** Deprecated, no longer used as a hedge-eligibility criterion */ +export interface MaxTransferableV3 { + coin: string; + maxTransfer: string; + borrowMaxTransfer: string; +} ⋮---- -export interface AccountAssetV3 { +export interface OpenInterestLimitV3 { + symbol: string; + singleUserLimit: string; + masterSubLimit: string; + marketMakerLimit: string; +} +⋮---- +export interface TaxRecordV3 { + id: string; coin: string; - equity: string; - usdValue: string; + type: string; + amount: string; + fee: string; balance: string; - /** Coin balance before borrowing-related amounts are deducted */ - balanceOriginal?: string; - available: string; - debt: string; - locked: string; - /** Position value in USD */ - positionValue?: string; - /** Account leverage (non-negative) */ - leverage?: string; - /** USDT bonus amount */ - bonus?: string; - /** Interest calculation base */ - interestBase?: string; + ts: string; } ⋮---- -/** Coin balance before borrowing-related amounts are deducted */ -⋮---- -/** Position value in USD */ +export interface CollateralTypeConfigV3 { + collateralType: CollateralTypeV3; + /** Returned when collateralType=custom */ + collateralCoins?: string; +} ⋮---- -/** Account leverage (non-negative) */ +/** Returned when collateralType=custom */ ⋮---- -/** USDT bonus amount */ +export interface CustomCollateralCoinV3 { + collateralCoin: string; +} ⋮---- -/** Interest calculation base */ +export interface PreSetLeverageV3 { + estMaxOpen?: string; + estMaxBorrowable?: string; + requiredMargin: string; + marginChange: string; +} ⋮---- -export interface BorrowResponseV3 { - orderId: string; - clientOid?: string; +export interface MaxWithdrawalV3 { + coin: string; + otcMaxWithdrawal: string; + spotMaxWithdrawal: string; + utaMaxWithdrawal: string; + totalMaxWithdrawal: string; } ⋮---- -export interface MaxBorrowableV3 { - maxBorrowable: string; +export interface MovePositionOrderResultV3 { + orderId: string; + clientOid: string; + code: string; + msg: string; } ⋮---- -export interface AccountAssetsV3 { - accountEquity: string; - usdtEquity: string; - btcEquity: string; - unrealisedPnl: string; - usdtUnrealisedPnl: string; - btcUnrealizedPnl: string; - effEquity: string; - mmr: string; - imr: string; - mgnRatio: string; - positionMgnRatio: string; - positionValue?: string; - leverage?: string; - assets: AccountAssetV3[]; +export interface MovePositionsResponseV3 { + closePosition: MovePositionOrderResultV3[]; + openPosition: MovePositionOrderResultV3[]; } ⋮---- -export interface ConvertRecordV3 { - fromCoin: string; - fromCoinSize: string; - toCoin: string; - toCoinSize: string; +export interface MovePositionHistoryV3 { + category: string; + fromUid: string; + toUid: string; + orderId: string; + openExecId: string; + closeExecId: string; + symbol: string; + posSide: 'long' | 'short'; + qty: string; price: string; - ts: string; + status: 'processing' | 'completed' | 'failed'; + createdTime: string; + updatedTime: string; } ⋮---- -export interface FinancialRecordV3 { - category: string; - id: string; +export interface EligibleSymbolV3 { symbol: string; - coin: string; - type: FinancialRecordTypeV3; - amount: string; - fee: string; - balance: string; - ts: string; - /** crossed | isolated */ - positionType?: string; - positionAmount?: string; - positionBalance?: string; + category: string; + baseCoin: string; + quoteCoin: string; + symbolType?: string; + buyLimitPriceRatio: string; + sellLimitPriceRatio: string; + minOrderQty: string; + maxOrderQty: string; + pricePrecision: string; + quantityPrecision: string; + quotePrecision: string; + minOrderAmount: string; + maxSymbolOrderNum: string; + maxProductOrderNum: string; + status: string; + maintainTime: string; + areaSymbol?: string; + maxPositionNum?: string; + isReality?: string; + launchTime?: string; } ⋮---- -/** crossed | isolated */ -⋮---- -export interface PaymentCoinV3 { - coin: string; - size: string; - amount: string; +export interface EligibleMarginTierItemV3 { + tier: string; + minTierValue: string; + maxTierValue: string; + leverage: string; + mmr: string; } ⋮---- -export interface RepayableCoinV3 { +export interface EligibleMarginTierV3 { coin: string; - size: string; - amount: string; + tiers: EligibleMarginTierItemV3[]; } ⋮---- -export interface RepayResponseV3 { - result: string; - repayAmount: string; +export interface EligibleLoanInfoV3 { + limit: string; + masterSubLimit: string; + /** Bitget spelling */ + platformRemaingQuota: string; } ⋮---- -// Sub-account Management Response Types +/** Bitget spelling */ ⋮---- -export interface CreateSubAccountApiKeyResponseV3 { - note: string; - apiKey: string; - secret: string; - type: string; - permissions: string[]; - ips: string[]; +export interface EligibleDiscountRateTierV3 { + tierStartValue: string; + discountRate: string; } -export interface SubAccountApiKeyV3 { - apiKey: string; - note: string; - type: string; - permissions: string[]; - ips: string[]; - ts?: string; +⋮---- +export interface EligibleDiscountRateV3 { + coin: string; + list: EligibleDiscountRateTierV3[]; } ⋮---- -export interface UpdateSubAccountApiKeyResponseV3 { - note: string; - apiKey: string; +export interface FundingFinancialRecordV3 { + id: string; + coin: string; + groupType: string; type: string; - permissions: string[]; - ips: string[]; + amount: string; + balance: string; + ts: string; } ⋮---- -export interface CreateSubAccountResponseV3 { - username: string; - subUid: string; - status: string; - note: string; - createdTime: string; - updatedTime: string; +export interface SmallAssetFeeDetailV3 { + feeRate?: string; + fee?: string; + feeCoin?: string; } ⋮---- -export interface CreateAgentSubAccountResponseV3 { - username: string; - subUid: string; - apiKey: string; - secret: string; - note: string; - createdTime: string; +export interface SmallAssetV3 { + coin: string; + available?: string; + estimatedCoin?: string; + estimatedAmount?: string; + feeDetail?: SmallAssetFeeDetailV3; + cTime?: string; + size?: string; + usdtValue?: string; } ⋮---- -export interface SubAccountV3 { - subUid: string; - username: string; - status: string; - accountMode: string; - type: 'normal' | 'virtual' | 'custodian' | 'fund_management'; - note: string; - createdTime: string; - updatedTime: string; +export interface SmallAssetsTradeResponseV3 { + fromCoin?: string; + toCoin?: string; + orderId?: string; + result?: string; } ⋮---- -export interface WithdrawAddressBookEntryV3 { - coin: string; - chain: string; - address: string; - countryCode: string; - label: string; - memo: string; - type: 'regular' | 'EVM' | 'universal' | 'internal'; - internalType: '' | 'uid' | 'mobile' | 'email'; - createdTime: string; +export interface SmallAssetsHistoryItemV3 { + orderId?: string; + fromCoin?: string; + fromAmount?: string; + fromCoinPrice?: string; + fromCoinSize?: string; + toCoin?: string; + toAmount?: string; + toCoinPrice?: string; + toCoinSize?: string; + feeDetail?: SmallAssetFeeDetailV3; + status?: string; + createdTime?: string; + ts?: string; } ⋮---- -export interface WithdrawAddressBookV3 { - addressList: WithdrawAddressBookEntryV3[]; - cursor?: string; +export interface RateLimitQuotaItemV3 { + uid: string; + quota: string; } ⋮---- -// Transfer Response Types -⋮---- -export interface AllSymbolFeeRateV3 { - symbol: string; - makerFeeRate: string; - takerFeeRate: string; +export interface RateLimitQuotaV3 { + category: 'spot' | 'futures' | string; + quotaList: RateLimitQuotaItemV3[]; + masterSubQuota: string; + masterSubCap: string; + cursor: string; } ⋮---- -export interface TransferResponseV3 { - transferId: string; - clientOid?: string; +export interface StpGroupMemberV3 { + uid: string; + joinedTime: string; } ⋮---- -export interface SubTransferRecordV3 { - transferId: string; - oldTransferId?: string; - fromType: string; - toType: string; - amount: string; - coin: string; - fromUserId: string; - toUserId: string; - status: string; - clientOid: string; +export interface StpGroupV3 { + groupId: string; + groupName: string; createdTime: string; - updatedTime: string; + members?: StpGroupMemberV3[]; } ⋮---- -export interface SubUnifiedAssetV3 { - coin: string; - equity: string; - usdValue: string; - balance: string; - available: string; - debt: string; - locked: string; +export interface StpGroupListV3 { + groups: StpGroupV3[]; } ⋮---- -export interface SubUnifiedAssetV3 { - subUid: string; - cursor: string; - assets: SubUnifiedAssetV3[]; +export interface CreateStpGroupResponseV3 { + groupId: string; + groupName: string; + createdTime: string; } ⋮---- -export interface GetFeeRateResponseV3 { - makerFeeRate: string; - takerFeeRate: string; +export interface StpGroupUidResultV3 { + uid: string; } ⋮---- -export interface FundingAssetV3 { - coin: string; - available: string; - frozen: string; - balance: string; +export interface StpGroupMembersResponseV3 { + createdTime: string; + successUids: StpGroupUidResultV3[]; + failedUids: StpGroupUidResultV3[]; } + +================ +File: src/types/request/v3/account.ts +================ +// Account Management Request Types ⋮---- -// Deposit Response Types +export type AccountAdjustModeV3 = 'basic' | 'advanced' | 'delta' | 'isolated'; ⋮---- -export interface DepositAddressV3 { - address: string; - chain: string; - coin: string; - tag: string; - url: string; +export interface AdjustAccountModeRequestV3 { + mode: AccountAdjustModeV3; + /** Enable/disable delta-neutral mode when mode is advanced. `delta` mode is deprecated. */ + deltaSwitch?: 'yes' | 'no'; + /** Sub-account UID when the master account switches mode for a sub-account */ + targetUid?: string; } ⋮---- -export interface DepositRecordV3 { - orderId: string; - recordId: string; - coin: string; - type: 'deposit'; - dest: 'on_chain' | 'internal_transfer'; - size: string; - status: 'pending' | 'success' | 'fail'; - fromAddress: string; - toAddress: string; - chain: string; - createdTime: string; - updatedTime: string; +/** Enable/disable delta-neutral mode when mode is advanced. `delta` mode is deprecated. */ +⋮---- +/** Sub-account UID when the master account switches mode for a sub-account */ +⋮---- +export interface SetLeverageRequestV3 { + category: 'MARGIN' | 'USDT-FUTURES' | 'COIN-FUTURES' | 'USDC-FUTURES'; + symbol?: string; + /** + * Error 25159 means a low-liquidity period capped leverage at 5x. + * There is no pre-check API for that cap. + */ + leverage: string; + coin?: string; + posSide?: 'long' | 'short'; + /** Futures only. Defaults to crossed */ + marginMode?: 'crossed' | 'isolated'; + /** Isolated two-way mode: long leverage. Takes priority over leverage when both set */ + longLeverage?: string; + /** Isolated two-way mode: short leverage. Takes priority over leverage when both set */ + shortLeverage?: string; } ⋮---- -// Withdraw Response Types +/** + * Error 25159 means a low-liquidity period capped leverage at 5x. + * There is no pre-check API for that cap. + */ ⋮---- -export interface WithdrawResponseV3 { - orderId: string; - clientOid: string; +/** Futures only. Defaults to crossed */ +⋮---- +/** Isolated two-way mode: long leverage. Takes priority over leverage when both set */ +⋮---- +/** Isolated two-way mode: short leverage. Takes priority over leverage when both set */ +⋮---- +export interface GetAllFeeRatesRequestV3 { + category: + | 'SPOT' + | 'MARGIN' + | 'USDT-FUTURES' + | 'COIN-FUTURES' + | 'USDC-FUTURES'; + symbol?: string; } ⋮---- -export interface WithdrawRecordV3 { - orderId: string; - clientOid: string; - recordId: string; - coin: string; - type: 'withdraw'; - dest: 'on_chain' | 'internal_transfer'; - size: string; - status: 'pending' | 'success' | 'fail'; - fromAddress: string; - toAddress: string; - chain: string; - fee: string; - confirm: string; - tag: string; - createdTime: string; - updatedTime: string; +export interface GetConvertRecordsRequestV3 { + fromCoin?: string; + toCoin?: string; + startTime?: string; + endTime?: string; + limit?: string; + cursor?: string; } ⋮---- -export interface MaxTransferableV3 { - coin: string; - maxTransfer: string; - borrowMaxTransfer: string; +/** + * UTA account financial-record type. + * https://www.bitget.com/docs/uta/enum + * MARIN_BUY_DEAL and MARIN_SELL_DEAL keep Bitget's spelling. + */ +export type FinancialRecordTypeV3 = + | 'TRANSFER_IN' + | 'TRANSFER_OUT' + | 'CONVERSION_UPON_DELISTING' + | 'ORDER_DEALT_FROZEN_OUT' + | 'ORDER_DEALT_IN' + | 'ORDER_PLF_FEE_OUT' + | 'EXCHANGE_SOURCE_TOKEN_USER_OUT' + | 'EXCHANGE_TARGET_TOKEN_USER_IN' + | 'OPEN_LONG' + | 'OPEN_SHORT' + | 'BUY_DEAL' + | 'SELL_DEAL' + | 'CLOSE_LONG' + | 'CLOSE_SHORT' + | 'FORCE_CLOSE_LONG' + | 'FORCE_CLOSE_SHORT' + | 'BURST_CLOSE_LONG' + | 'BURST_CLOSE_SHORT' + | 'OFFSET_REDUCE_CLOSE_LONG' + | 'OFFSET_REDUCE_CLOSE_SHORT' + | 'FORCE_BUY_SSM' + | 'FORCE_SELL_SSM' + | 'BURST_BUY_SSM' + | 'BURST_SELL_SSM' + | 'RISK_LIQ_USER_IN' + | 'INTEREST_SETTLEMENT_OUT' + | 'CONTRACT_MAIN_SETTLE_FEE_USER_IN' + | 'CONTRACT_MAIN_SETTLE_FEE_USER_OUT' + | 'RISK_LIQ_USER_OUT' + | 'BORROW' + | 'RESERVE_TRANSFER_IN' + | 'RESERVE_TRANSFER_OUT' + | 'REPAYMENT' + | 'INTEREST_REPAYMENT' + | 'LIQ_FUND_OUT' + | 'LIQ_CONVERT_USER_OUT' + | 'LIQ_CONVERT_SYS_IN' + | 'LIQ_CONVERT_SYS_OUT' + | 'LIQ_CONVERT_USER_IN' + | 'LIQ_TRANSFER_IN' + | 'LIQ_TRANSFER_OUT' + | 'LIQ_FUND_IN' + | 'LIQ_FEE' + | 'LIQ_REPAYMENT' + | 'DELIST_MARGIN_TOKEN_SOURCE_USER_OUT' + | 'DELIST_MARGIN_TOKEN_SOURCE_SYS_IN' + | 'DELIST_MARGIN_TOKEN_TARGET_SYS_OUT' + | 'DELIST_MARGIN_TOKEN_TARGET_USER_IN' + | 'CONFISCATE_TOKEN_USER_OUT' + | 'CONFISCATE_TOKEN_SYS_IN' + | 'DELIST_SMALL_BALANCE_USER_OUT' + | 'DELIST_SMALL_BALANCE_SYS_IN' + | 'DELIST_SMALL_LIABILITY_SYS_OUT' + | 'DELIST_SMALL_LIABILITY_USER_IN' + | 'SMALL_ASSET_SOURCE_TOKEN_USER_OUT' + | 'SMALL_ASSET_SOURCE_TOKEN_SYS_IN' + | 'SMALL_ASSET_TARGET_TOKEN_SYS_OUT' + | 'SMALL_ASSET_TARGET_TOKEN_USER_IN' + | 'SMALL_ASSET_FEE_SYS_IN' + | 'TRACE_SHARE_BENEFIT_USER_OUT' + | 'TRACE_SHARE_BENEFIT_SYSTEM_IN' + | 'TRACE_SHARE_BENEFIT_SYSTEM_OUT' + | 'TRACE_SHARE_BENEFIT_USER_IN' + | 'MARGIN_OPEN_LONG' + | 'MARGIN_OPEN_SHORT' + | 'MARIN_BUY_DEAL' + | 'MARIN_SELL_DEAL' + | 'MARGIN_BACK' + | 'INCREASE_MARGIN' + | 'REDUCE_MARGIN' + | 'MARGIN_SETTLE_FEE_USER_IN' + | 'MARGIN_SETTLE_FEE_USER_OUT' + | 'MARGIN_LEVER_ORDER_REFROZEN' + | 'MARGIN_LEVER_ORDER_FROZEN' + | 'MARGIN_LEVER_POS_IN' + | 'MARGIN_OFFSET_IN_SSM_LONG' + | 'MARGIN_OFFSET_IN_SSM_SHORT' + | 'FIXED_OFFSET_IN_SSM_LONG' + | 'FIXED_OFFSET_IN_SSM_SHORT' + | 'FIXED_CLOSE_LONG' + | 'FIXED_CLOSE_SHORT' + | 'FIXED_FORCE_CLOSE_LONG' + | 'FIXED_FORCE_CLOSE_SHORT' + | 'FIXED_BURST_CLOSE_LONG' + | 'FIXED_BURST_CLOSE_SHORT' + | 'FIXED_ADL_CLOSE_LONG' + | 'FIXED_ADL_CLOSE_SHORT' + | 'FIXED_RISK_LIQ_USER_IN' + | 'FIXED_RISK_LIQ_USER_OUT' + | 'FIXED_FORCE_BUY_SSM' + | 'FIXED_FORCE_SELL_SSM' + | 'FIXED_BURST_BUY_SSM' + | 'FIXED_BURST_SELL_SSM' + | 'ON_CHAIN_TRANSFER_REFUND' + | 'ON_CHAIN_TRANSFER_OUT' + | 'MT5_TRANSFER_IN' + | 'MT5_REFUND_IN' + | 'MT5_TRANSFER_OUT' + | 'TRACE_LOCK_USER_OUT' + | 'TRACE_LOCK_USER_IN' + | 'TRACE_TRANSFER_USER_OUT' + | 'TRACE_TRANSFER_USER_IN' + | 'TRACE_TRANSFER_REFUND_IN' + | 'FINANCIAL_TRANSFER_OUT' + | 'FINANCIAL_TRANSFER_IN' + | 'CONVERT_TRANSFER_IN' + | 'CONVERT_TRANSFER_OUT' + | 'BGPAY_TRANSFER_OUT' + | 'BGPAY_REFUND_IN' + | 'RWA_FIXED_SETTLE_FEE_USER_IN' + | 'RWA_FIXED_SETTLE_FEE_USER_OUT' + | 'RWA_CONTRACT_MAIN_SETTLE_FEE_SYSTEM_IN' + | 'RWA_CONTRACT_MAIN_SETTLE_FEE_SYSTEM_OUT' + | 'RWA_CONTRACT_MAIN_SETTLE_FEE_SYSTEM_KEEP_IN' + | 'RWA_CONTRACT_MAIN_SETTLE_FEE_SYSTEM_KEEP_OUT' + | 'RWA_CONTRACT_MAIN_SETTLE_FEE_USER_IN' + | 'RWA_CONTRACT_MAIN_SETTLE_FEE_USER_OUT' + | 'RWA_CONTRACT_REBASE_USER_OPEN_LONG' + | 'RWA_CONTRACT_REBASE_USER_OPEN_SHORT' + | 'RWA_CONTRACT_REBASE_USER_CLOSE_LONG' + | 'RWA_CONTRACT_REBASE_USER_CLOSE_SHORT' + | 'RWA_CONTRACT_REBASE_USER_BUY_IN_SSM' + | 'RWA_CONTRACT_REBASE_USER_SELL_IN_SSM' + | 'RISK_LIQ_DEFAULT_USER_IN' + | 'FIXED_RISK_LIQ_DEFAULT_USER_IN' + | 'BONUS_GRANT_USER_IN' + | 'BONUS_EXPIRE_USER_OUT' + | 'BONUS_TRANSFER_USER_OUT' + | 'WITHDRAW_TRANSFER_OUT' + | 'WITHDRAW_TRANSFER_IN' + | 'DELIVERY_LONG' + | 'DELIVERY_SHORT' + | 'FIXED_DELIVERY_LONG' + | 'FIXED_DELIVERY_SHORT' + | 'REBASE_COIN_SPLIT_OUT' + | 'REBASE_COIN_SPLIT_IN' + | 'REBASE_COIN_MERGE_OUT' + | 'REBASE_COIN_MERGE_IN'; +⋮---- +export interface GetFinancialRecordsRequestV3 { + category: + | 'SPOT' + | 'MARGIN' + | 'USDT-FUTURES' + | 'COIN-FUTURES' + | 'USDC-FUTURES'; + coin?: string; + type?: FinancialRecordTypeV3; + startTime?: string; + endTime?: string; + limit?: string; + cursor?: string; } ⋮---- -export interface OpenInterestLimitV3 { - symbol: string; - singleUserLimit: string; - masterSubLimit: string; - marketMakerLimit: string; +export interface RepayRequestV3 { + repayableCoinList: string[]; + paymentCoinList: string[]; } ⋮---- -export interface TaxRecordV3 { - id: string; - coin: string; - type: string; - amount: string; - fee: string; - balance: string; - ts: string; -} +// Sub-account Management Request Types ⋮---- -export interface CollateralTypeConfigV3 { - collateralType: CollateralTypeV3; - /** Returned when collateralType=custom */ - collateralCoins?: string; +export interface CreateSubAccountApiKeyRequestV3 { + subUid: string; + note: string; + type: 'read_write' | 'read_only'; + passphrase: string; + permissions: string[]; + ips: string[]; } ⋮---- -/** Returned when collateralType=custom */ +export interface DeleteSubAccountApiKeyRequestV3 { + apiKey: string; +} ⋮---- -export interface CustomCollateralCoinV3 { - collateralCoin: string; +export interface GetSubAccountApiKeysRequestV3 { + subUid: string; + limit?: string; + cursor?: string; } ⋮---- -export interface PreSetLeverageV3 { - estMaxOpen?: string; - estMaxBorrowable?: string; - requiredMargin: string; - marginChange: string; +export interface UpdateSubAccountApiKeyRequestV3 { + apiKey: string; + passphrase: string; + type?: 'read_write' | 'read_only'; + permissions?: string[]; + ips?: string[]; } ⋮---- -export interface MaxWithdrawalV3 { - coin: string; - otcMaxWithdrawal: string; - spotMaxWithdrawal: string; - utaMaxWithdrawal: string; - totalMaxWithdrawal: string; +export interface CreateSubAccountRequestV3 { + username: string; + accountMode?: 'classic' | 'unified'; + note?: string; } ⋮---- -export interface MovePositionOrderResultV3 { - orderId: string; - clientOid: string; - code: string; - msg: string; +export interface FreezeSubAccountRequestV3 { + subUid: string; + operation: 'freeze' | 'unfreeze'; } ⋮---- -export interface MovePositionsResponseV3 { - closePosition: MovePositionOrderResultV3[]; - openPosition: MovePositionOrderResultV3[]; +export interface GetSubAccountListRequestV3 { + limit?: string; + cursor?: string; } ⋮---- -export interface MovePositionHistoryV3 { - category: string; - fromUid: string; - toUid: string; - orderId: string; - openExecId: string; - closeExecId: string; - symbol: string; - posSide: 'long' | 'short'; - qty: string; - price: string; - status: 'processing' | 'completed' | 'failed'; - createdTime: string; - updatedTime: string; +// Transfer Request Types +⋮---- +export interface TransferRequestV3 { + clientOid?: string; + fromType: + | 'spot' + | 'p2p' + | 'coin_futures' + | 'usdt_futures' + | 'usdc_futures' + | 'crossed_margin' + | 'isolated_margin' + | 'uta'; + toType: + | 'spot' + | 'p2p' + | 'coin_futures' + | 'usdt_futures' + | 'usdc_futures' + | 'crossed_margin' + | 'isolated_margin' + | 'uta'; + amount: string; + coin: string; + symbol?: string; + /** Enable automatic margin borrowing when balance insufficient. yes | no */ + allowBorrow?: 'yes' | 'no'; } ⋮---- -export interface EligibleSymbolV3 { - symbol: string; - category: string; - baseCoin: string; - quoteCoin: string; - symbolType?: string; - buyLimitPriceRatio: string; - sellLimitPriceRatio: string; - minOrderQty: string; - maxOrderQty: string; - pricePrecision: string; - quantityPrecision: string; - quotePrecision: string; - minOrderAmount: string; - maxSymbolOrderNum: string; - maxProductOrderNum: string; - status: string; - maintainTime: string; - areaSymbol?: string; - maxPositionNum?: string; - isReality?: string; - launchTime?: string; +/** Enable automatic margin borrowing when balance insufficient. yes | no */ +⋮---- +export interface GetTransferableCoinsRequestV3 { + fromType: + | 'spot' + | 'p2p' + | 'coin_futures' + | 'usdt_futures' + | 'usdc_futures' + | 'crossed_margin' + | 'isolated_margin' + | 'uta'; + toType: + | 'spot' + | 'p2p' + | 'coin_futures' + | 'usdt_futures' + | 'usdc_futures' + | 'crossed_margin' + | 'isolated_margin' + | 'uta'; } ⋮---- -export interface EligibleMarginTierItemV3 { - tier: string; - minTierValue: string; - maxTierValue: string; - leverage: string; - mmr: string; +export interface GetSubTransferRecordsRequestV3 { + subUid?: string; + role?: 'initiator' | 'receiver'; + coin?: string; + startTime?: string; + endTime?: string; + clientOid?: string; + limit?: string; + cursor?: string; } ⋮---- -export interface EligibleMarginTierV3 { +export interface SubAccountTransferRequestV3 { + fromType: + | 'spot' + | 'p2p' + | 'usdt_futures' + | 'coin_futures' + | 'usdc_futures' + | 'crossed_margin' + | 'uta'; + toType: + | 'spot' + | 'p2p' + | 'usdt_futures' + | 'coin_futures' + | 'usdc_futures' + | 'crossed_margin' + | 'uta'; + amount: string; coin: string; - tiers: EligibleMarginTierItemV3[]; + fromUserId: string; + toUserId: string; + /** Custom order ID, max 50 characters */ + clientOid: string; + /** Enable automatic margin borrowing when balance insufficient. yes | no */ + allowBorrow?: 'yes' | 'no'; } ⋮---- -export interface EligibleLoanInfoV3 { - limit: string; - masterSubLimit: string; - /** Bitget spelling */ - platformRemaingQuota: string; -} +/** Custom order ID, max 50 characters */ ⋮---- -/** Bitget spelling */ +/** Enable automatic margin borrowing when balance insufficient. yes | no */ ⋮---- -export interface EligibleDiscountRateTierV3 { - tierStartValue: string; - discountRate: string; +export interface GetSubUnifiedAssetsRequestV3 { + subUid?: string; + cursor?: string; + limit?: string; } ⋮---- -export interface EligibleDiscountRateV3 { - coin: string; - list: EligibleDiscountRateTierV3[]; +export interface GetFeeRateRequestV3 { + category: + | 'SPOT' + | 'MARGIN' + | 'USDT-FUTURES' + | 'COIN-FUTURES' + | 'USDC-FUTURES'; + symbol: string; + /** RPI fee rate flag for market maker users. Default: no */ + rpiFlag?: 'yes' | 'no'; } ⋮---- -export interface FundingFinancialRecordV3 { - id: string; - coin: string; - groupType: string; - type: string; - amount: string; - balance: string; - ts: string; +/** RPI fee rate flag for market maker users. Default: no */ +⋮---- +export interface GetFundingAssetsRequestV3 { + coin?: string; } ⋮---- -export interface SmallAssetFeeDetailV3 { - feeRate?: string; - fee?: string; - feeCoin?: string; +export interface SwitchDeductRequestV3 { + deduct: 'on' | 'off'; } ⋮---- -export interface SmallAssetV3 { +// Deposit Request Types +⋮---- +export interface GetDepositAddressRequestV3 { coin: string; - available?: string; - estimatedCoin?: string; - estimatedAmount?: string; - feeDetail?: SmallAssetFeeDetailV3; - cTime?: string; + chain?: string; size?: string; - usdtValue?: string; } ⋮---- -export interface SmallAssetsTradeResponseV3 { - fromCoin?: string; - toCoin?: string; - orderId?: string; - result?: string; +export interface GetSubDepositAddressRequestV3 { + subUid: string; + coin: string; + chain?: string; + size?: string; } ⋮---- -export interface SmallAssetsHistoryItemV3 { +export interface GetDepositRecordsRequestV3 { + coin?: string; orderId?: string; - fromCoin?: string; - fromAmount?: string; - fromCoinPrice?: string; - fromCoinSize?: string; - toCoin?: string; - toAmount?: string; - toCoinPrice?: string; - toCoinSize?: string; - feeDetail?: SmallAssetFeeDetailV3; - status?: string; - createdTime?: string; - ts?: string; + startTime: string; + endTime: string; + limit?: string; + cursor?: string; } ⋮---- -export interface RateLimitQuotaItemV3 { - uid: string; - quota: string; +export interface GetSubDepositRecordsRequestV3 { + coin?: string; + subUid: string; + startTime: string; + endTime: string; + limit?: string; + cursor?: string; } ⋮---- -export interface RateLimitQuotaV3 { - category: 'spot' | 'futures' | string; - quotaList: RateLimitQuotaItemV3[]; - masterSubQuota: string; - masterSubCap: string; - cursor: string; -} +// Withdraw Request Types ⋮---- -export interface StpGroupMemberV3 { - uid: string; - joinedTime: string; +export interface WithdrawRequestV3 { + coin: string; + chain?: string; + /** Deduct from funding, uta, and/or otc accounts (comma-separated). Order: funding -> otc -> uta */ + accountType?: string; + transferType: 'on_chain' | 'internal_transfer'; + address: string; + innerToType?: 'uid' | 'email' | 'mobile'; + areaCode?: string; + tag?: string; + size: string; + remark?: string; + clientOid?: string; + memberCode?: 'bithumb' | 'korbit' | 'coinone'; + identityType?: 'company' | 'user'; + companyName?: string; + firstName?: string; + lastName?: string; } ⋮---- -export interface StpGroupV3 { - groupId: string; - groupName: string; - createdTime: string; - members?: StpGroupMemberV3[]; +/** Deduct from funding, uta, and/or otc accounts (comma-separated). Order: funding -> otc -> uta */ +⋮---- +export interface GetWithdrawRecordsRequestV3 { + coin?: string; + orderId?: string; + clientOid?: string; + startTime: string; + endTime: string; + limit?: string; + cursor?: string; } ⋮---- -export interface StpGroupListV3 { - groups: StpGroupV3[]; +export interface GetWithdrawAddressBookRequestV3 { + coin?: string; + type?: 'EVM' | 'regular' | 'universal' | 'internal'; + limit?: string; + cursor?: string; } ⋮---- -export interface CreateStpGroupResponseV3 { - groupId: string; - groupName: string; - createdTime: string; +export interface CancelWithdrawalRequestV3 { + orderId?: string; + clientOid?: string; } ⋮---- -export interface StpGroupUidResultV3 { - uid: string; +export interface SetDepositAccountRequestV3 { + coin: string; + accountType: 'funding' | 'unified' | 'otc'; } ⋮---- -export interface StpGroupMembersResponseV3 { - createdTime: string; - successUids: StpGroupUidResultV3[]; - failedUids: StpGroupUidResultV3[]; +export interface GetMaxTransferableRequestV3 { + coin: string; } - -================ -File: src/types/websockets/ws-api-request.ts -================ -import type { FuturesMarginModeV3 } from '../request/v3/trade.js'; ⋮---- -export interface WSAPIPlaceOrderRequestV3 { +export interface GetOpenInterestLimitRequestV3 { symbol: string; - orderType: 'limit' | 'market'; - qty: string; - price?: string; - side: 'buy' | 'sell'; - posSide?: 'long' | 'short'; - timeInForce?: 'gtc' | 'ioc' | 'fok' | 'post_only' | 'rpi'; - reduceOnly?: 'YES' | 'NO'; // Note: reduceOnly is not supported for batch place WS API. Might be supported starting late Q4 2025, but not supported yet. - /** Futures only. Defaults to crossed */ - marginMode?: FuturesMarginModeV3; - clientOid?: string; - stpMode?: 'none' | 'cancel_taker' | 'cancel_maker' | 'cancel_both'; - tpTriggerBy?: 'market' | 'mark'; - slTriggerBy?: 'market' | 'mark'; - takeProfit?: string; - stopLoss?: string; - tpOrderType?: 'limit' | 'market'; - slOrderType?: 'limit' | 'market'; - tpLimitPrice?: string; - slLimitPrice?: string; - /** Order TTL in ms [10, 60000]. Only effective when requestTime is also set on the envelope */ - receiveWindow?: string; - /** Spot only. Default: no */ - autoBorrow?: 'yes' | 'no'; - /** Limit orders only. no rejects a price outside the band (default). yes clamps it */ - pxAmendType?: 'yes' | 'no'; - /** Limit orders only. queue1, queue5, counterparty1, or counterparty5. Ignored for market orders */ - bboLevel?: 'queue1' | 'queue5' | 'counterparty1' | 'counterparty5'; - /** Market orders only. Decimal, default 0.02, range 0.01-0.05 */ - slippageTolerance?: string; - /** - * rToken routing. Accepted: internal_market | lit_market. Omit for default. - * internal_market = on-exchange only; lit_market = broker only. - * Omit / default = internal first, then broker. Ignored for non-rToken symbols. - * Live since 5 Nov 2026. - */ - venue?: 'internal_market' | 'lit_market'; - /** rToken time in force. gtd (default) or gtc (90 days). */ - rTokenTimeInForce?: 'gtd' | 'gtc'; + category: 'USDT-FUTURES' | 'COIN-FUTURES' | 'USDC-FUTURES'; } ⋮---- -reduceOnly?: 'YES' | 'NO'; // Note: reduceOnly is not supported for batch place WS API. Might be supported starting late Q4 2025, but not supported yet. -/** Futures only. Defaults to crossed */ -⋮---- -/** Order TTL in ms [10, 60000]. Only effective when requestTime is also set on the envelope */ -⋮---- -/** Spot only. Default: no */ +export interface GetTaxRecordsRequestV3 { + bizType: + | 'SPOT' + | 'MARGIN' + | 'USDT-FUTURES' + | 'COIN-FUTURES' + | 'USDC-FUTURES' + | 'OTHER'; + marginType?: 'isolated' | 'crossed'; + coin?: string; + startTime: string; + endTime: string; + limit?: string; + cursor?: string; +} ⋮---- -/** Limit orders only. no rejects a price outside the band (default). yes clamps it */ +export type CollateralTypeV3 = 'mainstream' | 'all' | 'custom'; ⋮---- -/** Limit orders only. queue1, queue5, counterparty1, or counterparty5. Ignored for market orders */ +export interface SetCollateralTypeRequestV3 { + collateralType: CollateralTypeV3; + /** Required when collateralType=custom. Comma-separated coin names */ + collateralCoins?: string; + /** Enable Cash+ as collateral. Official field name is allowCashPlus */ + allowCashPlus?: 'yes' | 'no'; +} ⋮---- -/** Market orders only. Decimal, default 0.02, range 0.01-0.05 */ +/** Required when collateralType=custom. Comma-separated coin names */ ⋮---- -/** - * rToken routing. Accepted: internal_market | lit_market. Omit for default. - * internal_market = on-exchange only; lit_market = broker only. - * Omit / default = internal first, then broker. Ignored for non-rToken symbols. - * Live since 5 Nov 2026. - */ +/** Enable Cash+ as collateral. Official field name is allowCashPlus */ ⋮---- -/** rToken time in force. gtd (default) or gtc (90 days). */ - -================ -File: src/types/request/v3/account.ts -================ -// Account Management Request Types +export interface BorrowRequestV3 { + coin: string; + amount: string; + clientOid?: string; +} ⋮---- -export type AccountAdjustModeV3 = 'basic' | 'advanced' | 'delta' | 'isolated'; +export interface GetMaxBorrowableRequestV3 { + coin: string; +} ⋮---- -export interface AdjustAccountModeRequestV3 { - mode: AccountAdjustModeV3; - /** Enable/disable delta-neutral mode when mode is advanced. `delta` mode is deprecated. */ - deltaSwitch?: 'yes' | 'no'; - /** Sub-account UID when the master account switches mode for a sub-account */ - targetUid?: string; +export interface SetRepayModeRequestV3 { + /** Account-level. Master and each sub-account keep their own setting */ + repayMode: 'auto' | 'manual'; } ⋮---- -/** Enable/disable delta-neutral mode when mode is advanced. `delta` mode is deprecated. */ +/** Account-level. Master and each sub-account keep their own setting */ ⋮---- -/** Sub-account UID when the master account switches mode for a sub-account */ +export interface DeleteSubAccountRequestV3 { + subUid: string; +} ⋮---- -export interface SetLeverageRequestV3 { +export interface PreSetLeverageRequestV3 { category: 'MARGIN' | 'USDT-FUTURES' | 'COIN-FUTURES' | 'USDC-FUTURES'; - symbol?: string; - /** - * Error 25159 means a low-liquidity period capped leverage at 5x. - * There is no pre-check API for that cap. - */ - leverage: string; - coin?: string; - posSide?: 'long' | 'short'; - /** Futures only. Defaults to crossed */ - marginMode?: 'crossed' | 'isolated'; - /** Isolated two-way mode: long leverage. Takes priority over leverage when both set */ + symbol?: string; + coin?: string; + marginMode: 'isolated' | 'cross'; + leverage?: string; longLeverage?: string; - /** Isolated two-way mode: short leverage. Takes priority over leverage when both set */ shortLeverage?: string; } ⋮---- -/** - * Error 25159 means a low-liquidity period capped leverage at 5x. - * There is no pre-check API for that cap. - */ -⋮---- -/** Futures only. Defaults to crossed */ +export interface SetMarginRequestV3 { + category: 'USDT-FUTURES' | 'COIN-FUTURES' | 'USDC-FUTURES'; + symbol: string; + posSide: 'long' | 'short'; + operation: 'add' | 'remove'; + amount: string; +} ⋮---- -/** Isolated two-way mode: long leverage. Takes priority over leverage when both set */ +export interface GetMaxWithdrawalRequestV3 { + coin: string; +} ⋮---- -/** Isolated two-way mode: short leverage. Takes priority over leverage when both set */ +export interface GetRealityOrderBookRequestV3 { + symbol: string; +} ⋮---- -export interface GetAllFeeRatesRequestV3 { - category: - | 'SPOT' - | 'MARGIN' - | 'USDT-FUTURES' - | 'COIN-FUTURES' - | 'USDC-FUTURES'; - symbol?: string; +export interface GetRealityOrderBookSegmentedRequestV3 { + symbol: string; } ⋮---- -export interface GetConvertRecordsRequestV3 { - fromCoin?: string; - toCoin?: string; - startTime?: string; - endTime?: string; +export interface GetRealityFillsRequestV3 { + symbol: string; limit?: string; - cursor?: string; } ⋮---- -/** - * UTA account financial-record type. - * https://www.bitget.com/docs/uta/enum - * MARIN_BUY_DEAL and MARIN_SELL_DEAL keep Bitget's spelling. - */ -export type FinancialRecordTypeV3 = - | 'TRANSFER_IN' - | 'TRANSFER_OUT' - | 'CONVERSION_UPON_DELISTING' - | 'ORDER_DEALT_FROZEN_OUT' - | 'ORDER_DEALT_IN' - | 'ORDER_PLF_FEE_OUT' - | 'EXCHANGE_SOURCE_TOKEN_USER_OUT' - | 'EXCHANGE_TARGET_TOKEN_USER_IN' - | 'OPEN_LONG' - | 'OPEN_SHORT' - | 'BUY_DEAL' - | 'SELL_DEAL' - | 'CLOSE_LONG' - | 'CLOSE_SHORT' - | 'FORCE_CLOSE_LONG' - | 'FORCE_CLOSE_SHORT' - | 'BURST_CLOSE_LONG' - | 'BURST_CLOSE_SHORT' - | 'OFFSET_REDUCE_CLOSE_LONG' - | 'OFFSET_REDUCE_CLOSE_SHORT' - | 'FORCE_BUY_SSM' - | 'FORCE_SELL_SSM' - | 'BURST_BUY_SSM' - | 'BURST_SELL_SSM' - | 'RISK_LIQ_USER_IN' - | 'INTEREST_SETTLEMENT_OUT' - | 'CONTRACT_MAIN_SETTLE_FEE_USER_IN' - | 'CONTRACT_MAIN_SETTLE_FEE_USER_OUT' - | 'RISK_LIQ_USER_OUT' - | 'BORROW' - | 'RESERVE_TRANSFER_IN' - | 'RESERVE_TRANSFER_OUT' - | 'REPAYMENT' - | 'INTEREST_REPAYMENT' - | 'LIQ_FUND_OUT' - | 'LIQ_CONVERT_USER_OUT' - | 'LIQ_CONVERT_SYS_IN' - | 'LIQ_CONVERT_SYS_OUT' - | 'LIQ_CONVERT_USER_IN' - | 'LIQ_TRANSFER_IN' - | 'LIQ_TRANSFER_OUT' - | 'LIQ_FUND_IN' - | 'LIQ_FEE' - | 'LIQ_REPAYMENT' - | 'DELIST_MARGIN_TOKEN_SOURCE_USER_OUT' - | 'DELIST_MARGIN_TOKEN_SOURCE_SYS_IN' - | 'DELIST_MARGIN_TOKEN_TARGET_SYS_OUT' - | 'DELIST_MARGIN_TOKEN_TARGET_USER_IN' - | 'CONFISCATE_TOKEN_USER_OUT' - | 'CONFISCATE_TOKEN_SYS_IN' - | 'DELIST_SMALL_BALANCE_USER_OUT' - | 'DELIST_SMALL_BALANCE_SYS_IN' - | 'DELIST_SMALL_LIABILITY_SYS_OUT' - | 'DELIST_SMALL_LIABILITY_USER_IN' - | 'SMALL_ASSET_SOURCE_TOKEN_USER_OUT' - | 'SMALL_ASSET_SOURCE_TOKEN_SYS_IN' - | 'SMALL_ASSET_TARGET_TOKEN_SYS_OUT' - | 'SMALL_ASSET_TARGET_TOKEN_USER_IN' - | 'SMALL_ASSET_FEE_SYS_IN' - | 'TRACE_SHARE_BENEFIT_USER_OUT' - | 'TRACE_SHARE_BENEFIT_SYSTEM_IN' - | 'TRACE_SHARE_BENEFIT_SYSTEM_OUT' - | 'TRACE_SHARE_BENEFIT_USER_IN' - | 'MARGIN_OPEN_LONG' - | 'MARGIN_OPEN_SHORT' - | 'MARIN_BUY_DEAL' - | 'MARIN_SELL_DEAL' - | 'MARGIN_BACK' - | 'INCREASE_MARGIN' - | 'REDUCE_MARGIN' - | 'MARGIN_SETTLE_FEE_USER_IN' - | 'MARGIN_SETTLE_FEE_USER_OUT' - | 'MARGIN_LEVER_ORDER_REFROZEN' - | 'MARGIN_LEVER_ORDER_FROZEN' - | 'MARGIN_LEVER_POS_IN' - | 'MARGIN_OFFSET_IN_SSM_LONG' - | 'MARGIN_OFFSET_IN_SSM_SHORT' - | 'FIXED_OFFSET_IN_SSM_LONG' - | 'FIXED_OFFSET_IN_SSM_SHORT' - | 'FIXED_CLOSE_LONG' - | 'FIXED_CLOSE_SHORT' - | 'FIXED_FORCE_CLOSE_LONG' - | 'FIXED_FORCE_CLOSE_SHORT' - | 'FIXED_BURST_CLOSE_LONG' - | 'FIXED_BURST_CLOSE_SHORT' - | 'FIXED_ADL_CLOSE_LONG' - | 'FIXED_ADL_CLOSE_SHORT' - | 'FIXED_RISK_LIQ_USER_IN' - | 'FIXED_RISK_LIQ_USER_OUT' - | 'FIXED_FORCE_BUY_SSM' - | 'FIXED_FORCE_SELL_SSM' - | 'FIXED_BURST_BUY_SSM' - | 'FIXED_BURST_SELL_SSM' - | 'ON_CHAIN_TRANSFER_REFUND' - | 'ON_CHAIN_TRANSFER_OUT' - | 'MT5_TRANSFER_IN' - | 'MT5_REFUND_IN' - | 'MT5_TRANSFER_OUT' - | 'TRACE_LOCK_USER_OUT' - | 'TRACE_LOCK_USER_IN' - | 'TRACE_TRANSFER_USER_OUT' - | 'TRACE_TRANSFER_USER_IN' - | 'TRACE_TRANSFER_REFUND_IN' - | 'FINANCIAL_TRANSFER_OUT' - | 'FINANCIAL_TRANSFER_IN' - | 'CONVERT_TRANSFER_IN' - | 'CONVERT_TRANSFER_OUT' - | 'BGPAY_TRANSFER_OUT' - | 'BGPAY_REFUND_IN' - | 'RWA_FIXED_SETTLE_FEE_USER_IN' - | 'RWA_FIXED_SETTLE_FEE_USER_OUT' - | 'RWA_CONTRACT_MAIN_SETTLE_FEE_SYSTEM_IN' - | 'RWA_CONTRACT_MAIN_SETTLE_FEE_SYSTEM_OUT' - | 'RWA_CONTRACT_MAIN_SETTLE_FEE_SYSTEM_KEEP_IN' - | 'RWA_CONTRACT_MAIN_SETTLE_FEE_SYSTEM_KEEP_OUT' - | 'RWA_CONTRACT_MAIN_SETTLE_FEE_USER_IN' - | 'RWA_CONTRACT_MAIN_SETTLE_FEE_USER_OUT' - | 'RWA_CONTRACT_REBASE_USER_OPEN_LONG' - | 'RWA_CONTRACT_REBASE_USER_OPEN_SHORT' - | 'RWA_CONTRACT_REBASE_USER_CLOSE_LONG' - | 'RWA_CONTRACT_REBASE_USER_CLOSE_SHORT' - | 'RWA_CONTRACT_REBASE_USER_BUY_IN_SSM' - | 'RWA_CONTRACT_REBASE_USER_SELL_IN_SSM' - | 'RISK_LIQ_DEFAULT_USER_IN' - | 'FIXED_RISK_LIQ_DEFAULT_USER_IN' - | 'BONUS_GRANT_USER_IN' - | 'BONUS_EXPIRE_USER_OUT' - | 'BONUS_TRANSFER_USER_OUT' - | 'WITHDRAW_TRANSFER_OUT' - | 'WITHDRAW_TRANSFER_IN' - | 'DELIVERY_LONG' - | 'DELIVERY_SHORT' - | 'FIXED_DELIVERY_LONG' - | 'FIXED_DELIVERY_SHORT' - | 'REBASE_COIN_SPLIT_OUT' - | 'REBASE_COIN_SPLIT_IN' - | 'REBASE_COIN_MERGE_OUT' - | 'REBASE_COIN_MERGE_IN'; +export interface SubMasterTransferRequestV3 { + fromType: 'spot' | 'uta'; + toType: 'spot' | 'p2p' | 'uta'; + amount: string; + coin: string; + clientOid?: string; +} ⋮---- -export interface GetFinancialRecordsRequestV3 { - category: - | 'SPOT' - | 'MARGIN' - | 'USDT-FUTURES' - | 'COIN-FUTURES' - | 'USDC-FUTURES'; - coin?: string; - type?: FinancialRecordTypeV3; +export interface CreateAgentSubAccountRequestV3 { + username: string; + passphrase: string; + note?: string; +} +⋮---- +export interface MovePositionItemRequestV3 { + symbol: string; + side: 'buy' | 'sell'; + qty: string; +} +⋮---- +export interface MovePositionsRequestV3 { + fromUid: string; + toUid: string; + category: 'USDT-FUTURES' | 'COIN-FUTURES' | 'USDC-FUTURES'; + positionList: MovePositionItemRequestV3[]; +} +⋮---- +export interface GetMovePositionHistoryRequestV3 { + category: 'USDT-FUTURES' | 'COIN-FUTURES' | 'USDC-FUTURES'; + symbol?: string; startTime?: string; endTime?: string; - limit?: string; cursor?: string; + limit?: string; } ⋮---- -export interface RepayRequestV3 { - repayableCoinList: string[]; - paymentCoinList: string[]; +export interface GetEligibleSymbolsRequestV3 { + symbol?: string; } ⋮---- -// Sub-account Management Request Types +export interface GetEligibleMarginTierRequestV3 { + coin?: string; +} ⋮---- -export interface CreateSubAccountApiKeyRequestV3 { - subUid: string; - note: string; - type: 'read_write' | 'read_only'; - passphrase: string; - permissions: string[]; - ips: string[]; +export interface GetEligibleLoanInfoRequestV3 { + coin?: string; } ⋮---- -export interface DeleteSubAccountApiKeyRequestV3 { - apiKey: string; +export interface GetEligibleDiscountRateRequestV3 { + coin?: string; } ⋮---- -export interface GetSubAccountApiKeysRequestV3 { - subUid: string; +export interface GetFundingFinancialRecordsRequestV3 { + coin?: string; + type?: string; + startTime?: string; + endTime?: string; limit?: string; cursor?: string; } ⋮---- -export interface UpdateSubAccountApiKeyRequestV3 { - apiKey: string; - passphrase: string; - type?: 'read_write' | 'read_only'; - permissions?: string[]; - ips?: string[]; +export interface GetSmallAssetsRequestV3 { + coin?: string; } ⋮---- -export interface CreateSubAccountRequestV3 { - username: string; - accountMode?: 'classic' | 'unified'; - note?: string; +export interface TradeSmallAssetsRequestV3 { + fromCoinList: string[]; + toCoin?: string; } ⋮---- -export interface FreezeSubAccountRequestV3 { - subUid: string; - operation: 'freeze' | 'unfreeze'; +export interface GetSmallAssetsHistoryRequestV3 { + orderId?: string; + startTime?: string; + endTime?: string; + limit?: string; + cursor?: string; } ⋮---- -export interface GetSubAccountListRequestV3 { - limit?: string; +export interface GetRateLimitQuotaRequestV3 { + category: 'spot' | 'futures'; + /** + * Omit to list sub-accounts under the master. + * Ignored when a sub-account calls this for itself. + */ + uid?: string; cursor?: string; + limit?: string; } ⋮---- -// Transfer Request Types +/** + * Omit to list sub-accounts under the master. + * Ignored when a sub-account calls this for itself. + */ ⋮---- -export interface TransferRequestV3 { - clientOid?: string; - fromType: - | 'spot' - | 'p2p' - | 'coin_futures' - | 'usdt_futures' - | 'usdc_futures' - | 'crossed_margin' - | 'isolated_margin' - | 'uta'; - toType: - | 'spot' - | 'p2p' - | 'coin_futures' - | 'usdt_futures' - | 'usdc_futures' - | 'crossed_margin' - | 'isolated_margin' - | 'uta'; - amount: string; - coin: string; - symbol?: string; - /** Enable automatic margin borrowing when balance insufficient. yes | no */ - allowBorrow?: 'yes' | 'no'; +export interface SetRateLimitQuotaRequestV3 { + category: 'spot' | 'futures'; + /** + * Required when the master account sets quotas. + * Not required, and ignored, when a sub-account sets its own quota. + */ + uids?: string[]; + quota: string; } ⋮---- -/** Enable automatic margin borrowing when balance insufficient. yes | no */ +/** + * Required when the master account sets quotas. + * Not required, and ignored, when a sub-account sets its own quota. + */ ⋮---- -export interface GetTransferableCoinsRequestV3 { - fromType: - | 'spot' - | 'p2p' - | 'coin_futures' - | 'usdt_futures' - | 'usdc_futures' - | 'crossed_margin' - | 'isolated_margin' - | 'uta'; - toType: - | 'spot' - | 'p2p' - | 'coin_futures' - | 'usdt_futures' - | 'usdc_futures' - | 'crossed_margin' - | 'isolated_margin' - | 'uta'; +export interface CreateStpGroupRequestV3 { + /** Max 32 characters. Must be unique. */ + groupName: string; } ⋮---- -export interface GetSubTransferRecordsRequestV3 { - subUid?: string; - role?: 'initiator' | 'receiver'; - coin?: string; - startTime?: string; - endTime?: string; - clientOid?: string; - limit?: string; - cursor?: string; +/** Max 32 characters. Must be unique. */ +⋮---- +export interface StpGroupMembersRequestV3 { + /** Comma-separated sub-account UIDs. Max 50. */ + uids: string; + groupId: string; } ⋮---- -export interface SubAccountTransferRequestV3 { - fromType: - | 'spot' - | 'p2p' - | 'usdt_futures' - | 'coin_futures' - | 'usdc_futures' - | 'crossed_margin' - | 'uta'; - toType: - | 'spot' - | 'p2p' - | 'usdt_futures' - | 'coin_futures' - | 'usdc_futures' - | 'crossed_margin' - | 'uta'; - amount: string; - coin: string; - fromUserId: string; - toUserId: string; - /** Custom order ID, max 50 characters */ - clientOid: string; - /** Enable automatic margin borrowing when balance insufficient. yes | no */ - allowBorrow?: 'yes' | 'no'; +/** Comma-separated sub-account UIDs. Max 50. */ + +================ +File: src/types/request/v3/trade.ts +================ +export interface BatchModifyOrderRequestV3 { + orderId?: string; + clientOid?: string; + qty?: string; + price?: string; + /** Custom request ID. Numbers within 18 digits. */ + requestId?: number; + autoCancel?: 'yes' | 'no'; + /** Required since 30 Sep 2026 */ + symbol: string; + /** Required since 30 Sep 2026 */ + category: + | 'SPOT' + | 'MARGIN' + | 'USDT-FUTURES' + | 'COIN-FUTURES' + | 'USDC-FUTURES'; + /** Limit orders only. no rejects a price outside the band (default). yes clamps it */ + pxAmendType?: 'yes' | 'no'; } ⋮---- -/** Custom order ID, max 50 characters */ +/** Custom request ID. Numbers within 18 digits. */ ⋮---- -/** Enable automatic margin borrowing when balance insufficient. yes | no */ +/** Required since 30 Sep 2026 */ ⋮---- -export interface GetSubUnifiedAssetsRequestV3 { - subUid?: string; - cursor?: string; - limit?: string; +/** Required since 30 Sep 2026 */ +⋮---- +/** Limit orders only. no rejects a price outside the band (default). yes clamps it */ +⋮---- +export interface CancelAllOrdersRequestV3 { + category: + | 'SPOT' + | 'MARGIN' + | 'USDT-FUTURES' + | 'COIN-FUTURES' + | 'USDC-FUTURES'; + symbol?: string; } ⋮---- -export interface GetFeeRateRequestV3 { +export interface CancelBatchOrdersRequestV3 { + orderId?: string; + clientOid?: string; category: | 'SPOT' | 'MARGIN' @@ -19754,322 +19677,422 @@ export interface GetFeeRateRequestV3 { | 'COIN-FUTURES' | 'USDC-FUTURES'; symbol: string; - /** RPI fee rate flag for market maker users. Default: no */ - rpiFlag?: 'yes' | 'no'; } ⋮---- -/** RPI fee rate flag for market maker users. Default: no */ -⋮---- -export interface GetFundingAssetsRequestV3 { - coin?: string; +export interface CloseAllPositionsRequestV3 { + category: 'USDT-FUTURES' | 'COIN-FUTURES' | 'USDC-FUTURES'; + symbol?: string; + posSide?: 'long' | 'short'; } ⋮---- -export interface SwitchDeductRequestV3 { - deduct: 'on' | 'off'; +export interface CancelOrderRequestV3 { + orderId?: string; + clientOid?: string; + category?: + | 'SPOT' + | 'MARGIN' + | 'USDT-FUTURES' + | 'COIN-FUTURES' + | 'USDC-FUTURES'; } ⋮---- -// Deposit Request Types +export type FuturesMarginModeV3 = 'crossed' | 'isolated'; ⋮---- -export interface GetDepositAddressRequestV3 { - coin: string; - chain?: string; +export interface GetMaxOpenAvailableRequestV3 { + category: + | 'SPOT' + | 'MARGIN' + | 'USDT-FUTURES' + | 'COIN-FUTURES' + | 'USDC-FUTURES'; + symbol: string; + orderType: 'limit' | 'market'; + side: 'buy' | 'sell'; + price?: string; size?: string; + /** Spot only. Default: no */ + autoBorrow?: 'yes' | 'no'; + /** + * crossed (default) or isolated. + * Under isolated margin, available excludes futures trial funds. + */ + marginMode?: FuturesMarginModeV3; } ⋮---- -export interface GetSubDepositAddressRequestV3 { - subUid: string; - coin: string; - chain?: string; - size?: string; +/** Spot only. Default: no */ +⋮---- +/** + * crossed (default) or isolated. + * Under isolated margin, available excludes futures trial funds. + */ +⋮---- +export interface GetOrderInfoRequestV3 { + orderId?: string; + clientOid?: string; } ⋮---- -export interface GetDepositRecordsRequestV3 { - coin?: string; +export interface GetFillsRequestV3 { + category?: + | 'SPOT' + | 'MARGIN' + | 'USDT-FUTURES' + | 'COIN-FUTURES' + | 'USDC-FUTURES'; orderId?: string; - startTime: string; - endTime: string; + startTime?: string; + endTime?: string; limit?: string; cursor?: string; } ⋮---- -export interface GetSubDepositRecordsRequestV3 { - coin?: string; - subUid: string; - startTime: string; - endTime: string; +export interface GetUnfilledOrdersRequestV3 { + category?: + | 'SPOT' + | 'MARGIN' + | 'USDT-FUTURES' + | 'COIN-FUTURES' + | 'USDC-FUTURES'; + symbol?: string; + startTime?: string; + endTime?: string; limit?: string; cursor?: string; } ⋮---- -// Withdraw Request Types -⋮---- -export interface WithdrawRequestV3 { - coin: string; - chain?: string; - /** Deduct from funding, uta, and/or otc accounts (comma-separated). Order: funding -> otc -> uta */ - accountType?: string; - transferType: 'on_chain' | 'internal_transfer'; - address: string; - innerToType?: 'uid' | 'email' | 'mobile'; - areaCode?: string; - tag?: string; - size: string; - remark?: string; - clientOid?: string; - memberCode?: 'bithumb' | 'korbit' | 'coinone'; - identityType?: 'company' | 'user'; - companyName?: string; - firstName?: string; - lastName?: string; -} -⋮---- -/** Deduct from funding, uta, and/or otc accounts (comma-separated). Order: funding -> otc -> uta */ -⋮---- -export interface GetWithdrawRecordsRequestV3 { - coin?: string; - orderId?: string; - clientOid?: string; - startTime: string; - endTime: string; +export interface GetHistoryOrdersRequestV3 { + category: + | 'SPOT' + | 'MARGIN' + | 'USDT-FUTURES' + | 'COIN-FUTURES' + | 'USDC-FUTURES'; + symbol?: string; + startTime?: string; + endTime?: string; limit?: string; cursor?: string; } ⋮---- -export interface GetWithdrawAddressBookRequestV3 { - coin?: string; - type?: 'EVM' | 'regular' | 'universal' | 'internal'; +export interface GetPositionHistoryRequestV3 { + category: 'USDT-FUTURES' | 'COIN-FUTURES' | 'USDC-FUTURES'; + symbol?: string; + startTime?: string; + endTime?: string; limit?: string; cursor?: string; } ⋮---- -export interface CancelWithdrawalRequestV3 { +export interface GetCurrentPositionRequestV3 { + category: 'USDT-FUTURES' | 'COIN-FUTURES' | 'USDC-FUTURES'; + symbol?: string; + posSide?: 'long' | 'short'; +} +⋮---- +export interface ModifyOrderRequestV3 { orderId?: string; clientOid?: string; + qty?: string; + price?: string; + /** Custom request ID. Numbers within 18 digits. */ + requestId?: number; + autoCancel?: 'yes' | 'no'; + /** Required since 30 Sep 2026 */ + symbol: string; + /** Required since 30 Sep 2026 */ + category: + | 'SPOT' + | 'MARGIN' + | 'USDT-FUTURES' + | 'COIN-FUTURES' + | 'USDC-FUTURES'; + tpTriggerBy?: 'market' | 'mark'; + slTriggerBy?: 'market' | 'mark'; + takeProfit?: string; + stopLoss?: string; + tpOrderType?: 'limit' | 'market'; + slOrderType?: 'limit' | 'market'; + tpLimitPrice?: string; + slLimitPrice?: string; + /** Limit orders only. no rejects a price outside the band (default). yes clamps it */ + pxAmendType?: 'yes' | 'no'; } ⋮---- -export interface SetDepositAccountRequestV3 { - coin: string; - accountType: 'funding' | 'unified' | 'otc'; -} +/** Custom request ID. Numbers within 18 digits. */ ⋮---- -export interface GetMaxTransferableRequestV3 { - coin: string; +/** Required since 30 Sep 2026 */ +⋮---- +/** Required since 30 Sep 2026 */ +⋮---- +/** Limit orders only. no rejects a price outside the band (default). yes clamps it */ +⋮---- +export interface PlaceRealityOrderRequestV3 { + category?: 'SPOT' | 'MARGIN'; + symbol: string; + side: 'buy' | 'sell'; + orderType: 'limit' | 'market'; + qty: string; + price?: string; + clientOid?: string; + /** + * rToken routing. Accepted: internal_market | lit_market. Omit for default. + * internal_market = on-exchange only (not submitted to the U.S. stock broker). + * lit_market = broker only (not matched on-exchange). + * Omit / default = internal first at best price, then unfilled to broker. + * Live since 5 Nov 2026 (internalization renamed; old lit_market meaning is now default). + */ + venue?: 'internal_market' | 'lit_market'; + /** + * rToken time in force. gtd (default) = current session. + * gtc = 90 days. Same changelog note as venue. + */ + rTokenTimeInForce?: 'gtd' | 'gtc'; } ⋮---- -export interface GetOpenInterestLimitRequestV3 { +/** + * rToken routing. Accepted: internal_market | lit_market. Omit for default. + * internal_market = on-exchange only (not submitted to the U.S. stock broker). + * lit_market = broker only (not matched on-exchange). + * Omit / default = internal first at best price, then unfilled to broker. + * Live since 5 Nov 2026 (internalization renamed; old lit_market meaning is now default). + */ +⋮---- +/** + * rToken time in force. gtd (default) = current session. + * gtc = 90 days. Same changelog note as venue. + */ +⋮---- +export interface CancelRealityOrderRequestV3 { + category?: 'SPOT' | 'MARGIN'; symbol: string; - category: 'USDT-FUTURES' | 'COIN-FUTURES' | 'USDC-FUTURES'; + orderId?: string; + clientOid?: string; } ⋮---- -export interface GetTaxRecordsRequestV3 { - bizType: +export interface PlaceBatchOrdersRequestV3 { + category: | 'SPOT' | 'MARGIN' | 'USDT-FUTURES' | 'COIN-FUTURES' - | 'USDC-FUTURES' - | 'OTHER'; - marginType?: 'isolated' | 'crossed'; - coin?: string; - startTime: string; - endTime: string; - limit?: string; - cursor?: string; + | 'USDC-FUTURES'; + symbol: string; + qty: string; + price?: string; + side: 'buy' | 'sell'; + orderType: 'limit' | 'market'; + timeInForce?: 'ioc' | 'fok' | 'gtc' | 'post_only'; + posSide?: 'long' | 'short'; + clientOid?: string; + reduceOnly?: 'yes' | 'no'; + /** Limit orders only. no rejects a price outside the band (default). yes clamps it */ + pxAmendType?: 'yes' | 'no'; + /** + * Unix ms. Used with receiveWindow. + * If omitted, receiveWindow has no effect. + * An order that reaches the matching engine after requestTime + receiveWindow is canceled. + */ + requestTime?: string; + /** Validity window in ms. Range [10, 60000]. Requires requestTime. */ + receiveWindow?: string; } ⋮---- -export type CollateralTypeV3 = 'mainstream' | 'all' | 'custom'; +/** Limit orders only. no rejects a price outside the band (default). yes clamps it */ ⋮---- -export interface SetCollateralTypeRequestV3 { - collateralType: CollateralTypeV3; - /** Required when collateralType=custom. Comma-separated coin names */ - collateralCoins?: string; - /** Enable Cash+ as collateral. Official field name is allowCashPlus */ - allowCashPlus?: 'yes' | 'no'; +/** + * Unix ms. Used with receiveWindow. + * If omitted, receiveWindow has no effect. + * An order that reaches the matching engine after requestTime + receiveWindow is canceled. + */ +⋮---- +/** Validity window in ms. Range [10, 60000]. Requires requestTime. */ +⋮---- +export interface PlaceOrderRequestV3 { + category: + | 'SPOT' + | 'MARGIN' + | 'USDT-FUTURES' + | 'COIN-FUTURES' + | 'USDC-FUTURES'; + symbol: string; + /** + * Futures qty must be a multiple of quantityMultiplier + * and have at most quantityPrecision decimal places. + * Both come from /api/v3/market/instruments. Futures only. + */ + qty: string; + price?: string; + side: 'buy' | 'sell'; + /** + * Market orders always run as IOC. + * Staff-confirmed: t.me/bitgetOpenapi/153169. + * timeInForce does not change that. + */ + orderType: 'limit' | 'market'; + timeInForce?: 'ioc' | 'fok' | 'gtc' | 'post_only' | 'rpi'; + posSide?: 'long' | 'short'; + clientOid?: string; + reduceOnly?: 'yes' | 'no'; + /** Futures only. Defaults to crossed */ + marginMode?: FuturesMarginModeV3; + stpMode?: 'none' | 'cancel_taker' | 'cancel_maker' | 'cancel_both'; + tpTriggerBy?: 'market' | 'mark'; + slTriggerBy?: 'market' | 'mark'; + takeProfit?: string; + stopLoss?: string; + tpOrderType?: 'limit' | 'market'; + slOrderType?: 'limit' | 'market'; + tpLimitPrice?: string; + slLimitPrice?: string; + /** Spot only. Default: no */ + autoBorrow?: 'yes' | 'no'; + /** Limit orders only. no rejects a price outside the band (default). yes clamps it */ + pxAmendType?: 'yes' | 'no'; + /** Limit orders only. queue1, queue5, counterparty1, or counterparty5 */ + bboLevel?: 'queue1' | 'queue5' | 'counterparty1' | 'counterparty5'; + /** Market orders only. Default 0.02, range [0.001, 0.05], up to 3 decimals */ + slippageTolerance?: string; + /** + * rToken routing. Accepted: internal_market | lit_market. Omit for default. + * internal_market = on-exchange only (not submitted to the U.S. stock broker). + * lit_market = broker only (not matched on-exchange). + * Omit / default = internal first at best price, then unfilled to broker. + * Ignored for non-rToken symbols. timeInForce is also ignored for rToken. + * Live since 5 Nov 2026 (internalization renamed; old lit_market meaning is now default). + */ + venue?: 'internal_market' | 'lit_market'; + /** + * rToken time in force. gtd (default) lasts the current session. + * gtc lasts 90 days. Ignored for non-rToken symbols. + */ + rTokenTimeInForce?: 'gtd' | 'gtc'; + /** + * Unix ms. Used with receiveWindow. + * If omitted, receiveWindow has no effect. + * An order that reaches the matching engine after requestTime + receiveWindow is canceled. + */ + requestTime?: string; + /** Validity window in ms. Range [10, 60000]. Requires requestTime. */ + receiveWindow?: string; } ⋮---- -/** Required when collateralType=custom. Comma-separated coin names */ -⋮---- -/** Enable Cash+ as collateral. Official field name is allowCashPlus */ -⋮---- -export interface BorrowRequestV3 { - coin: string; - amount: string; - clientOid?: string; -} +/** + * Futures qty must be a multiple of quantityMultiplier + * and have at most quantityPrecision decimal places. + * Both come from /api/v3/market/instruments. Futures only. + */ ⋮---- -export interface GetMaxBorrowableRequestV3 { - coin: string; -} +/** + * Market orders always run as IOC. + * Staff-confirmed: t.me/bitgetOpenapi/153169. + * timeInForce does not change that. + */ ⋮---- -export interface SetRepayModeRequestV3 { - /** Account-level. Master and each sub-account keep their own setting */ - repayMode: 'auto' | 'manual'; -} +/** Futures only. Defaults to crossed */ ⋮---- -/** Account-level. Master and each sub-account keep their own setting */ +/** Spot only. Default: no */ ⋮---- -export interface DeleteSubAccountRequestV3 { - subUid: string; -} +/** Limit orders only. no rejects a price outside the band (default). yes clamps it */ ⋮---- -export interface PreSetLeverageRequestV3 { - category: 'MARGIN' | 'USDT-FUTURES' | 'COIN-FUTURES' | 'USDC-FUTURES'; - symbol?: string; - coin?: string; - marginMode: 'isolated' | 'cross'; - leverage?: string; - longLeverage?: string; - shortLeverage?: string; -} +/** Limit orders only. queue1, queue5, counterparty1, or counterparty5 */ ⋮---- -export interface SetMarginRequestV3 { - category: 'USDT-FUTURES' | 'COIN-FUTURES' | 'USDC-FUTURES'; - symbol: string; - posSide: 'long' | 'short'; - operation: 'add' | 'remove'; - amount: string; -} +/** Market orders only. Default 0.02, range [0.001, 0.05], up to 3 decimals */ ⋮---- -export interface GetMaxWithdrawalRequestV3 { - coin: string; -} +/** + * rToken routing. Accepted: internal_market | lit_market. Omit for default. + * internal_market = on-exchange only (not submitted to the U.S. stock broker). + * lit_market = broker only (not matched on-exchange). + * Omit / default = internal first at best price, then unfilled to broker. + * Ignored for non-rToken symbols. timeInForce is also ignored for rToken. + * Live since 5 Nov 2026 (internalization renamed; old lit_market meaning is now default). + */ ⋮---- -export interface GetRealityOrderBookRequestV3 { - symbol: string; -} +/** + * rToken time in force. gtd (default) lasts the current session. + * gtc lasts 90 days. Ignored for non-rToken symbols. + */ ⋮---- -export interface GetRealityOrderBookSegmentedRequestV3 { - symbol: string; -} +/** + * Unix ms. Used with receiveWindow. + * If omitted, receiveWindow has no effect. + * An order that reaches the matching engine after requestTime + receiveWindow is canceled. + */ ⋮---- -export interface GetRealityFillsRequestV3 { - symbol: string; - limit?: string; -} +/** Validity window in ms. Range [10, 60000]. Requires requestTime. */ ⋮---- -export interface SubMasterTransferRequestV3 { - fromType: 'spot' | 'uta'; - toType: 'spot' | 'p2p' | 'uta'; - amount: string; - coin: string; - clientOid?: string; +export interface CountdownCancelAllRequestV3 { + countdown: string; // seconds until auto-cancel (5-60, or 0 to disable) } ⋮---- -export interface CreateAgentSubAccountRequestV3 { - username: string; - passphrase: string; - note?: string; -} +countdown: string; // seconds until auto-cancel (5-60, or 0 to disable) + +================ +File: src/types/websockets/ws-api-request.ts +================ +import type { FuturesMarginModeV3 } from '../request/v3/trade.js'; ⋮---- -export interface MovePositionItemRequestV3 { +export interface WSAPIPlaceOrderRequestV3 { symbol: string; - side: 'buy' | 'sell'; + orderType: 'limit' | 'market'; qty: string; + price?: string; + side: 'buy' | 'sell'; + posSide?: 'long' | 'short'; + timeInForce?: 'gtc' | 'ioc' | 'fok' | 'post_only' | 'rpi'; + reduceOnly?: 'YES' | 'NO'; // Note: reduceOnly is not supported for batch place WS API. Might be supported starting late Q4 2025, but not supported yet. + /** Futures only. Defaults to crossed */ + marginMode?: FuturesMarginModeV3; + clientOid?: string; + stpMode?: 'none' | 'cancel_taker' | 'cancel_maker' | 'cancel_both'; + tpTriggerBy?: 'market' | 'mark'; + slTriggerBy?: 'market' | 'mark'; + takeProfit?: string; + stopLoss?: string; + tpOrderType?: 'limit' | 'market'; + slOrderType?: 'limit' | 'market'; + tpLimitPrice?: string; + slLimitPrice?: string; + /** Order TTL in ms [10, 60000]. Sets the envelope requestTime to String(Date.now()) unless overridden via requestFlags.requestTime */ + receiveWindow?: string; + /** Spot only. Default: no */ + autoBorrow?: 'yes' | 'no'; + /** Limit orders only. no rejects a price outside the band (default). yes clamps it */ + pxAmendType?: 'yes' | 'no'; + /** Limit orders only. queue1, queue5, counterparty1, or counterparty5. Ignored for market orders */ + bboLevel?: 'queue1' | 'queue5' | 'counterparty1' | 'counterparty5'; + /** Market orders only. Decimal, default 0.02, range 0.01-0.05 */ + slippageTolerance?: string; + /** + * rToken routing. Accepted: internal_market | lit_market. Omit for default. + * internal_market = on-exchange only; lit_market = broker only. + * Omit / default = internal first, then broker. Ignored for non-rToken symbols. + * Live since 5 Nov 2026. + */ + venue?: 'internal_market' | 'lit_market'; + /** rToken time in force. gtd (default) or gtc (90 days). */ + rTokenTimeInForce?: 'gtd' | 'gtc'; } ⋮---- -export interface MovePositionsRequestV3 { - fromUid: string; - toUid: string; - category: 'USDT-FUTURES' | 'COIN-FUTURES' | 'USDC-FUTURES'; - positionList: MovePositionItemRequestV3[]; -} -⋮---- -export interface GetMovePositionHistoryRequestV3 { - category: 'USDT-FUTURES' | 'COIN-FUTURES' | 'USDC-FUTURES'; - symbol?: string; - startTime?: string; - endTime?: string; - cursor?: string; - limit?: string; -} -⋮---- -export interface GetEligibleSymbolsRequestV3 { - symbol?: string; -} -⋮---- -export interface GetEligibleMarginTierRequestV3 { - coin?: string; -} -⋮---- -export interface GetEligibleLoanInfoRequestV3 { - coin?: string; -} -⋮---- -export interface GetEligibleDiscountRateRequestV3 { - coin?: string; -} -⋮---- -export interface GetFundingFinancialRecordsRequestV3 { - coin?: string; - type?: string; - startTime?: string; - endTime?: string; - limit?: string; - cursor?: string; -} -⋮---- -export interface GetSmallAssetsRequestV3 { - coin?: string; -} +reduceOnly?: 'YES' | 'NO'; // Note: reduceOnly is not supported for batch place WS API. Might be supported starting late Q4 2025, but not supported yet. +/** Futures only. Defaults to crossed */ ⋮---- -export interface TradeSmallAssetsRequestV3 { - fromCoinList: string[]; - toCoin?: string; -} +/** Order TTL in ms [10, 60000]. Sets the envelope requestTime to String(Date.now()) unless overridden via requestFlags.requestTime */ ⋮---- -export interface GetSmallAssetsHistoryRequestV3 { - orderId?: string; - startTime?: string; - endTime?: string; - limit?: string; - cursor?: string; -} +/** Spot only. Default: no */ ⋮---- -export interface GetRateLimitQuotaRequestV3 { - category: 'spot' | 'futures'; - /** - * Omit to list sub-accounts under the master. - * Ignored when a sub-account calls this for itself. - */ - uid?: string; - cursor?: string; - limit?: string; -} +/** Limit orders only. no rejects a price outside the band (default). yes clamps it */ ⋮---- -/** - * Omit to list sub-accounts under the master. - * Ignored when a sub-account calls this for itself. - */ +/** Limit orders only. queue1, queue5, counterparty1, or counterparty5. Ignored for market orders */ ⋮---- -export interface SetRateLimitQuotaRequestV3 { - category: 'spot' | 'futures'; - /** - * Required when the master account sets quotas. - * Not required, and ignored, when a sub-account sets its own quota. - */ - uids?: string[]; - quota: string; -} +/** Market orders only. Decimal, default 0.02, range 0.01-0.05 */ ⋮---- /** - * Required when the master account sets quotas. - * Not required, and ignored, when a sub-account sets its own quota. + * rToken routing. Accepted: internal_market | lit_market. Omit for default. + * internal_market = on-exchange only; lit_market = broker only. + * Omit / default = internal first, then broker. Ignored for non-rToken symbols. + * Live since 5 Nov 2026. */ ⋮---- -export interface CreateStpGroupRequestV3 { - /** Max 32 characters. Must be unique. */ - groupName: string; -} -⋮---- -/** Max 32 characters. Must be unique. */ -⋮---- -export interface StpGroupMembersRequestV3 { - /** Comma-separated sub-account UIDs. Max 50. */ - uids: string; - groupId: string; -} -⋮---- -/** Comma-separated sub-account UIDs. Max 50. */ +/** rToken time in force. gtd (default) or gtc (90 days). */ ================ File: src/rest-client-v3.ts @@ -21702,10 +21725,14 @@ downgradeAccountToClassic(): Promise> */ getUnifiedAccountSwitchStatus(): Promise< APIResponse<{ - status: 'processProcessing' | 'successSuccess' | 'failFailed'; + status: 'process' | 'success' | 'fail'; + /** Only returned when status is fail */ + reason?: string; }> > ⋮---- +/** Only returned when status is fail */ +⋮---- /** * Get Tax Records * @@ -21977,7 +22004,7 @@ cancelWithdrawal( /** * Place Order. * Market orders always run as IOC (staff-confirmed, t.me/bitgetOpenapi/153169). - * bboLevel is limit only. slippageTolerance is market only (default 0.02, range 0.01-0.05). + * bboLevel is limit only. slippageTolerance is market only (default 0.02, range [0.001, 0.05], up to 3 decimals). * Futures qty must be a multiple of quantityMultiplier, with at most quantityPrecision decimals. */ submitNewOrder( @@ -22181,6 +22208,10 @@ getLoanSymbols( getLoanRiskUnit(): Promise< APIResponse<{ riskUnitId: string[]; + riskUnitList: { + unitId: string; + clientType: 'Hedge' | 'HFT'; + }[]; }> > ⋮---- @@ -22957,7 +22988,7 @@ File: package.json ================ { "name": "bitget-api", - "version": "3.2.8", + "version": "3.2.9", "description": "Complete Node.js & JavaScript SDK for Bitget V1-V3 REST APIs & WebSockets, with TypeScript & end-to-end tests.", "scripts": { "test": "jest",