This file is a merged representation of a subset of the codebase, containing files not matching ignore patterns, combined into a single document by Repomix. The content has been processed where content has been compressed (code blocks are separated by ⋮---- delimiter). ================================================================ File Summary ================================================================ Purpose: -------- This file contains a packed representation of a subset of the repository's contents that is considered the most important context. It is designed to be easily consumable by AI systems for analysis, code review, or other automated processes. File Format: ------------ The content is organized as follows: 1. This summary section 2. Repository information 3. Directory structure 4. Repository files (if enabled) 5. Multiple file entries, each consisting of: a. A separator line (================) b. The file path (File: path/to/file) c. Another separator line d. The full contents of the file e. A blank line Usage Guidelines: ----------------- - This file should be treated as read-only. Any changes should be made to the original repository files, not this packed version. - When processing this file, use the file path to distinguish between different files in the repository. - Be aware that this file may contain sensitive information. Handle it with the same level of security as you would the original repository. Notes: ------ - Some files may have been excluded based on .gitignore rules and Repomix's configuration - Binary files are not included in this packed representation. Please refer to the Repository Structure section for a complete list of file paths, including binary files - Files matching these patterns are excluded: .github/, examples/apidoc/, docs/images/, docs/endpointFunctionList.md, test/, src/util/ - Files matching patterns in .gitignore are excluded - Files matching default ignore patterns are excluded - Content has been compressed - code blocks are separated by ⋮---- delimiter - Files are sorted by Git change count (files with more changes are at the bottom) ================================================================ Directory Structure ================================================================ examples/ auth/ fasterHmacSign.ts rest-private-rsa.md rest-private-rsa.ts deprecated-V1-REST/ README.md rest-private-futures.ts rest-private-spot.ts rest-public-futures.ts rest-public-spot.ts rest-trade-futures.ts rest-trade-spot.ts deprecated-V1-Websockets/ ws-private.ts ws-public.ts V2/ rest-private-futures.ts rest-private-spot.ts rest-public-futures.ts rest-public-spot.ts rest-trade-futures.ts rest-trade-spot.ts ws-demo-trading.ts ws-private.ts ws-public.ts V3/ rest-private.ts rest-public-UTA-futures.ts rest-public-UTA-spot.ts rest-trade-UTA-futures.ts rest-trade-UTA-spot.ts ws-api-client-trade.ts ws-api-trade-raw.ts ws-private.ts ws-public.ts README.md src/ constants/ enum.ts types/ request/ v1/ brokerV1.ts futuresV1.ts spotV1.ts v2/ broker.ts common.ts copytrading.ts earn.ts futures.ts margin.ts spot.ts v3/ account.ts loan.ts public.ts strategy.ts trade.ts shared.ts response/ v1/ futures.ts shared.ts spot.ts v2/ broker.ts common.ts copy-trading.ts earn.ts futures.ts margin.ts spot.ts v3/ account.ts loan.ts public.ts strategy.ts trade.ts websockets/ ws-api-request.ts ws-api-response.ts ws-api.ts ws-events.ts ws-general.ts shared.ts broker-client.ts futures-client.ts index.ts rest-client-v2.ts rest-client-v3.ts spot-client.ts websocket-api-client.ts websocket-client-legacy-v1.ts websocket-client-v2.ts websocket-client-v3.ts webpack/ webpack.config.js .eslintrc.cjs .gitignore .jshintrc .nvmrc .prettierrc jest.config.ts LICENSE.md package.json postBuild.sh README.md tea.yaml tsconfig.cjs.json tsconfig.esm.json tsconfig.json tsconfig.linting.json ================================================================ Files ================================================================ ================ File: examples/deprecated-V1-REST/README.md ================ # Deprecated V1 REST API Examples These examples are for Bitget's V1 APIs, the previous generation of their API offering. If you're building new functionality, you should look at using the V2 APIs via the RestClientV2 class in this SDK. This covers all the newer functionality offered by Bitget's APIs - with significant upgrades on all aspects of their APIs: https://www.bitget.com/api-doc/common/release-note The V1 REST clients will remain function until Bitget formally deprecates their V1 API. ================ File: examples/deprecated-V1-REST/rest-public-spot.ts ================ import { SpotClient } from '../../src/index'; ⋮---- // or // import { SpotClient } from 'bitget-api'; ================ File: src/types/request/v1/brokerV1.ts ================ export type BrokerProductType = | 'umcbl' | 'usdt' | 'swap' | 'dmcbl' | 'mix' | 'swap'; ⋮---- export interface BrokerSubListRequest { pageSize?: string; lastEndId?: number; status?: string; } ⋮---- export interface BrokerSubWithdrawalRequest { subUid: string; coin: string; address: string; chain: string; tag?: string; amount: string; remark?: string; clientOid?: string; } ⋮---- export interface BrokerSubAPIKeyModifyRequest { subUid: string; apikey: string; remark?: string; ip?: string; perm?: string; } ================ File: src/types/request/v2/copytrading.ts ================ /** * * * Copy Trading | Future copy trading | Trader Api * * */ ⋮---- 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 GetFuturesTraderHistoryOrdersRequestV2 { idLessThan?: string; idGreaterThan?: string; startTime?: string; endTime?: string; limit?: string; order?: 'asc' | 'desc'; symbol?: string; productType: CopyTradingProductTypeV2; } ⋮---- export interface ModifyFuturesTraderOrderTPSLRequestV2 { trackingNo: string; productType: CopyTradingProductTypeV2; stopSurplusPrice?: string; stopLossPrice?: string; } ⋮---- export interface GetFuturesTraderProfitShareDetailRequestV2 { coin?: string; idLessThan?: string; idGreaterThan?: string; startTime?: string; endTime?: string; limit?: string; } ⋮---- export interface FuturesTraderSymbolSettingRequestV2 { symbol: string; productType: CopyTradingProductTypeV2; settingType: 'ADD' | 'DELETE' | 'UPDATE'; stopSurplusRatio?: string; stopLossRatio?: string; } ⋮---- export interface GetFuturesTraderFollowersRequestV2 { pageNo?: string; pageSize?: string; startTime?: string; endTime?: string; } ⋮---- /** * * * Copy Trading | Future copy trading | Follower Api * * */ ⋮---- export interface GetFollowerFuturesCurrentTrackingOrdersRequestV2 { idLessThan?: string; idGreaterThan?: string; startTime?: string; endTime?: string; limit?: string; symbol?: string; productType: CopyTradingProductTypeV2; traderId?: string; } ⋮---- export interface GetFollowerFuturesHistoryTrackingOrdersRequestV2 { idLessThan?: string; idGreaterThan?: string; startTime?: string; endTime?: string; limit?: string; symbol?: string; productType: CopyTradingProductTypeV2; traderId?: string; } ⋮---- export interface UpdateFuturesFollowerTPSLRequestV2 { trackingNo: string; symbol?: string; productType: CopyTradingProductTypeV2; stopSurplusPrice?: string; stopLossPrice?: 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 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 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'; } ⋮---- export interface GetFuturesFollowerTradersRequestV2 { startTime?: string; endTime?: string; pageNo?: string; pageSize?: string; } ⋮---- /** * * * Copy Trading | Spot copy trading | Trader api * * */ ⋮---- export interface GetSpotTraderHistoryProfitRequestV2 { idLessThan?: string; idGreaterThan?: string; startTime?: string; endTime?: string; limit?: string; coin?: string; } ⋮---- export interface GetSpotTraderHistoryOrdersRequestV2 { idLessThan?: string; idGreaterThan?: string; startTime?: string; endTime?: string; limit?: string; symbol?: string; } ⋮---- export interface GetSpotTraderCurrentOrdersRequestV2 { symbol?: string; idLessThan?: string; idGreaterThan?: string; startTime?: string; endTime?: string; limit?: string; } ⋮---- export interface GetSpotTraderFollowersRequestV2 { pageNo?: string; pageSize?: string; startTime?: string; endTime?: string; } ⋮---- /** * * * Copy Trading | Spot copy trading | Follower api * * */ ⋮---- export interface SpotFollowerCopyTradeSettingV2 { symbol: string; traceType: 'percent' | 'amount' | 'count'; maxHoldSize: string; traceValue: string; stopLossRatio?: string; stopSurplusRatio?: string; } ⋮---- export interface GetSpotFollowerHistoryOrdersRequestV2 { symbol?: string; traderId?: string; idLessThan?: string; idGreaterThan?: string; startTime?: string; endTime?: string; limit?: string; } ⋮---- export interface GetSpotFollowerOpenOrdersRequestV2 { symbol?: string; traderId?: string; idLessThan?: string; idGreaterThan?: string; startTime?: string; endTime?: string; limit?: string; } ================ 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 GetLoanRepayHistoryRequestV2 { orderId?: string; loanCoin?: string; pledgeCoin?: string; startTime: string; endTime: string; pageNo?: string; pageSize?: string; } ⋮---- export interface ModifyLoanPledgeRateRequestV2 { orderId: string; amount: string; pledgeCoin: string; reviseType: string; } ⋮---- export interface GetLoanPledgeRateHistoryRequestV2 { orderId?: string; reviseSide?: string; pledgeCoin?: string; startTime: string; endTime: string; pageNo?: string; pageSize?: string; } ⋮---- export interface GetLoanHistoryRequestV2 { orderId?: string; loanCoin?: string; pledgeCoin?: string; status?: string; startTime: string; endTime: string; pageNo?: string; pageSize?: string; } ⋮---- export interface GetLiquidationRecordsRequestV2 { orderId?: string; loanCoin?: string; pledgeCoin?: string; status?: string; startTime: string; endTime: string; pageNo?: string; pageSize?: string; } ================ File: src/types/request/v2/margin.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; } ⋮---- export interface GetLiquidationHistoryRequestV2 { startTime: string; endTime?: string; limit?: string; idLessThan?: string; } ⋮---- export interface GetFinancialHistoryRequestV2 { marginType?: string; coin?: string; startTime: string; endTime?: string; limit?: string; idLessThan?: string; } ⋮---- /** * * * Margin | Cross/Isolated | Account * */ ⋮---- /** * * * Margin | Cross/Isolated | Trade * */ ⋮---- 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 MarginBatchOrderEntry { orderType: MarginOrderTypeV2; price?: string; loanType: MarginLoanTypeV2; force: MarginTimeInForceV2; baseSize?: string; quoteSize?: string; clientOid?: string; side: MarginOrderSideV2; stpMode?: MarginSTPModeV2; } ⋮---- export interface MarginBatchOrdersRequestV2 { symbol: string; orderList: MarginBatchOrderEntry[]; } ⋮---- export interface GetMarginCurrentOrdersRequestV2 { symbol: string; orderId?: string; clientOid?: string; startTime: string; endTime?: string; limit?: string; idLessThan?: string; } ⋮---- export interface GetHistoryOrdersRequestV2 { symbol: string; orderId?: string; enterPointSource?: string; clientOid?: string; startTime: string; endTime?: string; limit?: string; idLessThan?: string; } ⋮---- export interface GetMarginOrderFillsRequestV2 { symbol: string; orderId?: string; idLessThan?: string; startTime: string; endTime?: string; limit?: 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/request/v2/spot.ts ================ type SpotKlineIntervalV2 = | '1min' | '5min' | '15min' | '30min' | '1h' | '4h' | '6h' | '12h' | '1day' | '3day' | '1week' | '1M' | '6Hutc' | '12Hutc' | '1Dutc' | '3Dutc' | '1Wutc' | '1Mutc'; ⋮---- export interface SpotCandlesRequestV2 { symbol: string; granularity: SpotKlineIntervalV2; startTime?: string; endTime?: string; limit?: string; } ⋮---- export interface SpotHistoricCandlesRequestV2 { symbol: string; granularity: SpotKlineIntervalV2; endTime?: string; limit?: string; } ⋮---- export interface SpotHistoricTradesRequestV2 { symbol: string; limit?: string; idLessThan?: string; startTime?: string; endTime?: string; } ⋮---- /** * * * Spot | Trade * */ ⋮---- export type SpotOrderSideV2 = 'buy' | 'sell'; ⋮---- export type SpotOrderTypeV2 = 'limit' | 'market'; ⋮---- export type SpotOrderForceV2 = 'gtc' | 'post_only' | 'fok' | 'ioc'; ⋮---- export type SpotTPSLTypeV2 = 'normal' | 'tpsl'; ⋮---- export type SpotSTPModeV2 = | 'none' | 'cancel_taker' | 'cancel_maker' | 'cancel_both'; ⋮---- export type SpotBatchModeV2 = 'single' | 'multiple'; ⋮---- export interface SpotOrderRequestV2 { symbol: string; side: SpotOrderSideV2; orderType: SpotOrderTypeV2; force: SpotOrderForceV2; price?: string; size: string; clientOid?: string; triggerPrice?: string; tpslType?: SpotTPSLTypeV2; requestTime?: string; receiveWindow?: string; stpMode?: SpotSTPModeV2; presetTakeProfitPrice?: string; executeTakeProfitPrice?: string; presetStopLossPrice?: string; executeStopLossPrice?: string; } ⋮---- export interface SpotCancelandSubmitOrderRequestV2 { symbol: string; price: string; size: string; orderId?: string; clientOid?: string; newClientOid?: string; presetTakeProfitPrice?: string; executeTakeProfitPrice?: string; presetStopLossPrice?: string; executeStopLossPrice?: string; } ⋮---- export interface SpotCancelOrderRequestV2 { symbol: string; tpslType?: SpotTPSLTypeV2; orderId?: string; clientOid?: string; } ⋮---- export interface SpotBatchOrderRequestItemV2 { symbol?: string; side: SpotOrderSideV2; orderType: SpotOrderTypeV2; force: SpotOrderForceV2; price?: string; size: string; clientOid?: string; stpMode?: SpotSTPModeV2; presetTakeProfitPrice?: string; executeTakeProfitPrice?: string; presetStopLossPrice?: string; executeStopLossPrice?: string; } ⋮---- export interface SpotBatchOrderRequestV2 { symbol?: string; batchMode?: SpotBatchModeV2; orderList: SpotBatchOrderRequestItemV2[]; } ⋮---- export interface SpotBatchCancelOrderRequestV2 { symbol?: string; batchMode?: SpotBatchModeV2; orderList: { symbol?: string; orderId?: string; clientOid?: string; }[]; } ⋮---- export interface GetSpotOrderInfoRequestV2 { orderId?: string; clientOid?: string; requestTime?: string; receiveWindow?: string; } ⋮---- export interface GetSpotOpenOrdersRequestV2 { symbol?: string; startTime?: string; endTime?: string; idLessThan?: string; limit?: string; orderId?: string; tpslType?: SpotTPSLTypeV2; requestTime?: string; receiveWindow?: string; } ⋮---- export interface GetSpotHistoryOrdersRequestV2 { symbol?: string; startTime?: string; endTime?: string; idLessThan?: string; limit?: string; orderId?: string; tpslType?: SpotTPSLTypeV2; requestTime?: string; receiveWindow?: string; } ⋮---- export interface GetSpotFillsRequestV2 { symbol: string; orderId?: string; startTime?: string; endTime?: string; limit?: string; idLessThan?: string; } ⋮---- /** * * * Spot | Trigger Orders * */ ⋮---- export type SpotPlanTypeV2 = 'amount' | 'total'; ⋮---- export type SpotTriggerTypeV2 = 'fill_price' | 'mark_price'; ⋮---- export interface SpotPlanOrderRequestV2 { symbol: string; side: SpotOrderSideV2; triggerPrice: string; orderType: SpotOrderTypeV2; executePrice?: string; planType?: SpotPlanTypeV2; size: string; triggerType: SpotTriggerTypeV2; clientOid?: string; force?: SpotOrderForceV2; stpMode?: SpotSTPModeV2; } ⋮---- export interface SpotModifyPlanOrderRequestV2 { orderId?: string; clientOid?: string; triggerPrice: string; orderType: SpotOrderTypeV2; executePrice?: string; size: string; } ⋮---- export interface GetSpotCurrentPlanOrdersRequestV2 { symbol: string; limit?: string; idLessThan?: string; startTime?: string; endTime?: string; } ⋮---- export interface GetSpotHistoryPlanOrdersRequestV2 { symbol: string; startTime: string; endTime: string; limit?: string; } ⋮---- /** * * * Spot | Account * */ ⋮---- export type SpotBillGroupTypeV2 = | 'deposit' | 'withdraw' | 'transaction' | 'transfer' | 'other'; ⋮---- export type SpotBusinessTypeV2 = | 'deposit' | 'withdraw' | 'buy' | 'sell' | 'deduction of handling fee' | 'transfer-in' | 'transfer-out' | 'rebate rewards' | 'airdrop rewards' | 'USDT contract rewards' | 'mix contract rewards' | 'system lock' | 'user lock'; ⋮---- export type SpotAccountTypeV2 = | 'spot' | 'p2p' | 'coin_futures' | 'usdt_futures' | 'usdc_futures' | 'crossed_margin' | 'isolated_margin'; ⋮---- export interface GetSpotAccountBillsRequestV2 { coin?: string; groupType?: SpotBillGroupTypeV2; businessType?: SpotBusinessTypeV2; startTime?: string; endTime?: string; limit?: string; idLessThan?: string; } ⋮---- export interface SpotTransferRequestV2 { fromType: SpotAccountTypeV2; toType: SpotAccountTypeV2; amount: string; coin: string; symbol: string; clientOid?: string; } ⋮---- export interface SpotSubAccountTransferRequestV2 { fromType: SpotAccountTypeV2; toType: SpotAccountTypeV2; amount: string; coin: string; symbol?: string; clientOid?: string; fromUserId: string; toUserId: string; } ⋮---- export interface SpotWithdrawalRequestV2 { coin: string; transferType: 'on_chain' | 'internal_transfer'; address: string; chain?: string; innerToType?: 'email' | 'mobile' | 'uid'; areaCode?: string; tag?: string; size: string; remark?: string; clientOid?: string; } ⋮---- export interface SpotMainSubTransferRecordRequestV2 { coin?: string; role?: 'initiator' | 'receiver'; subUid?: string; startTime?: string; endTime?: string; clientOid?: string; limit?: string; idLessThan?: string; } ⋮---- export interface GetSpotTransferRecordRequestV2 { coin: string; fromType: SpotAccountTypeV2; startTime?: string; endTime?: string; clientOid?: string; limit?: string; idLessThan?: string; } ⋮---- export interface GetSpotSubAccountDepositRecordRequestV2 { subUid: string; coin?: string; startTime?: string; endTime?: string; idLessThan?: string; limit?: string; } ⋮---- export interface GetSpotWithdrawalRecordRequestV2 { coin?: string; clientOid?: string; startTime: string; endTime: string; idLessThan?: string; orderId?: string; limit?: string; } ⋮---- export interface GetSpotDepositRecordRequestV2 { coin?: string; orderId?: string; startTime: string; endTime: string; idLessThan?: string; limit?: 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; } ================ File: src/types/request/v3/public.ts ================ export interface GetPublicFillsRequestV3 { category: | 'SPOT' | 'MARGIN' | 'USDT-FUTURES' | 'COIN-FUTURES' | 'USDC-FUTURES'; symbol?: string; limit?: string; } ⋮---- export interface GetCandlesRequestV3 { category: 'SPOT' | 'USDT-FUTURES' | 'COIN-FUTURES' | 'USDC-FUTURES'; symbol: string; interval: | '1m' | '3m' | '5m' | '15m' | '30m' | '1H' | '4H' | '6H' | '12H' | '1D'; startTime?: string; endTime?: string; type?: 'MARKET' | 'MARK' | 'INDEX'; limit?: string; } ⋮---- export interface GetHistoryCandlesRequestV3 { category: 'SPOT' | 'USDT-FUTURES' | 'COIN-FUTURES' | 'USDC-FUTURES'; symbol: string; interval: | '1m' | '3m' | '5m' | '15m' | '30m' | '1H' | '4H' | '6H' | '12H' | '1D'; startTime?: string; endTime?: string; type?: 'MARKET' | 'MARK' | 'INDEX'; limit?: string; } ⋮---- export interface GetContractsOiRequestV3 { symbol?: string; category: 'USDT-FUTURES' | 'COIN-FUTURES' | 'USDC-FUTURES'; } ⋮---- export interface GetCurrentFundingRateRequestV3 { symbol: string; } ⋮---- export interface GetHistoryFundingRateRequestV3 { category: 'USDT-FUTURES' | 'COIN-FUTURES' | 'USDC-FUTURES'; symbol: string; cursor?: string; limit?: string; } ⋮---- export interface GetMarginLoansRequestV3 { coin: string; } ⋮---- export interface GetOpenInterestRequestV3 { category: 'USDT-FUTURES' | 'COIN-FUTURES' | 'USDC-FUTURES'; symbol?: string; } ⋮---- export interface GetPositionTierRequestV3 { category: 'MARGIN' | 'USDT-FUTURES' | 'COIN-FUTURES' | 'USDC-FUTURES'; symbol?: string; coin?: string; } ⋮---- export interface GetRiskReserveRequestV3 { category: 'USDT-FUTURES' | 'COIN-FUTURES' | 'USDC-FUTURES'; symbol: string; } ⋮---- export interface GetInstrumentsRequestV3 { category: | 'SPOT' | 'MARGIN' | 'USDT-FUTURES' | 'COIN-FUTURES' | 'USDC-FUTURES'; symbol?: string; } ⋮---- export interface GetOrderBookRequestV3 { category: 'SPOT' | 'USDT-FUTURES' | 'COIN-FUTURES' | 'USDC-FUTURES'; symbol: string; limit?: string; } ⋮---- export interface GetTickersRequestV3 { category: 'SPOT' | 'USDT-FUTURES' | 'COIN-FUTURES' | 'USDC-FUTURES'; symbol?: string; } ================ File: src/types/request/v3/strategy.ts ================ export interface PlaceStrategyOrderRequestV3 { category: 'USDT-FUTURES' | 'COIN-FUTURES' | 'USDC-FUTURES'; symbol: string; clientOid?: string; type?: 'tpsl'; tpslMode?: 'full' | 'partial'; qty: string; posSide: 'long' | 'short'; tpTriggerBy?: 'market' | 'mark'; slTriggerBy?: 'market' | 'mark'; takeProfit?: string; stopLoss?: string; tpOrderType?: 'limit' | 'market'; slOrderType?: 'limit' | 'market'; tpLimitPrice?: string; slLimitPrice?: string; } ⋮---- export interface ModifyStrategyOrderRequestV3 { orderId?: string; clientOid?: string; qty: string; tpTriggerBy?: 'market' | 'mark'; slTriggerBy?: 'market' | 'mark'; takeProfit?: string; stopLoss?: string; tpOrderType?: 'limit' | 'market'; slOrderType?: 'limit' | 'market'; tpLimitPrice?: string; slLimitPrice?: string; } ⋮---- export interface CancelStrategyOrderRequestV3 { orderId?: string; clientOid?: string; } ⋮---- export interface GetUnfilledStrategyOrdersRequestV3 { category: 'USDT-FUTURES' | 'COIN-FUTURES' | 'USDC-FUTURES'; type?: 'tpsl'; } ⋮---- export interface GetHistoryStrategyOrdersRequestV3 { category: 'USDT-FUTURES' | 'COIN-FUTURES' | 'USDC-FUTURES'; type?: 'tpsl'; startTime?: string; endTime?: string; limit?: string; cursor?: string; } ================ File: src/types/request/v3/trade.ts ================ export interface BatchModifyOrderRequestV3 { orderId?: string; clientOid?: string; qty?: string; price?: string; autoCancel?: 'yes' | 'no'; } ⋮---- export interface CancelAllOrdersRequestV3 { category: | 'SPOT' | 'MARGIN' | 'USDT-FUTURES' | 'COIN-FUTURES' | 'USDC-FUTURES'; symbol?: string; } ⋮---- export interface CancelBatchOrdersRequestV3 { orderId?: string; clientOid?: string; category: | 'SPOT' | 'MARGIN' | 'USDT-FUTURES' | 'COIN-FUTURES' | 'USDC-FUTURES'; symbol: string; } ⋮---- export interface CloseAllPositionsRequestV3 { category: 'USDT-FUTURES' | 'COIN-FUTURES' | 'USDC-FUTURES'; symbol?: string; posSide?: 'long' | 'short'; } ⋮---- export interface CancelOrderRequestV3 { orderId?: string; clientOid?: 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; } ⋮---- export interface GetOrderInfoRequestV3 { orderId?: string; clientOid?: string; } ⋮---- export interface GetFillsRequestV3 { 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; } ⋮---- export interface GetHistoryOrdersRequestV3 { category: | 'SPOT' | 'MARGIN' | 'USDT-FUTURES' | 'COIN-FUTURES' | 'USDC-FUTURES'; startTime?: string; endTime?: string; limit?: string; cursor?: string; } ⋮---- export interface GetPositionHistoryRequestV3 { category: 'USDT-FUTURES' | 'COIN-FUTURES' | 'USDC-FUTURES'; symbol?: string; startTime?: string; endTime?: string; limit?: string; cursor?: string; } ⋮---- 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; autoCancel?: 'yes' | 'no'; } ⋮---- 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'; clientOid?: string; reduceOnly?: 'yes' | 'no'; } ⋮---- export interface PlaceOrderRequestV3 { 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'; clientOid?: string; reduceOnly?: 'yes' | 'no'; stpMode?: 'none' | 'cancel_taker' | 'cancel_maker' | 'cancel_both'; takeProfitPrice?: string; stopLossPrice?: string; takeProfitTriggerType?: 'mark_price' | 'last_price'; stopLossTriggerType?: 'mark_price' | 'last_price'; } ⋮---- export interface CountdownCancelAllRequestV3 { countdown: string; // seconds until auto-cancel (5-60, or 0 to disable) } ⋮---- countdown: string; // seconds until auto-cancel (5-60, or 0 to disable) ================ File: src/types/request/shared.ts ================ /** Pagination */ export interface Pagination { /** Time after */ after?: string; /** Time before */ before?: string; /** Elements per page */ limit?: string; } ⋮---- /** Time after */ ⋮---- /** 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; } ⋮---- /** * The margin type, used directly in building the endpoint URL */ export type MarginType = 'crossed' | 'isolated'; ⋮---- export type FuturesProductTypeV2 = | 'USDT-FUTURES' | 'COIN-FUTURES' | 'USDC-FUTURES' | 'SUSDT-FUTURES' | 'SCOIN-FUTURES' | 'SUSDC-FUTURES'; ⋮---- export type FuturesPlanTypeV2 = | 'profit_plan' | 'loss_plan' | 'moving_plan' | 'pos_profit' | 'pos_loss'; ================ File: src/types/response/v1/shared.ts ================ export interface APIResponse { code: string; requestTime: number; msg: 'success' | string; data: T; } ⋮---- export interface VIPFeeRate { level: number; dealAmount: string; assetAmount: string; takerFeeRate?: string; makerFeeRate?: number; withdrawAmount: string; withdrawAmountUSDT: string; } ================ File: src/types/response/v1/spot.ts ================ export interface CoinBalance { coinId: number; coinName: string; available: string; frozen: string; lock: string; uTime: string; } ⋮---- export interface SymbolRules { symbol: string; symbolName: string; baseCoin: string; quoteCoin: string; minTradeAmount: string; maxTradeAmount: string; takerFeeRate: string; makerFeeRate: string; priceScale: string; quantityScale: string; status: string; } export interface SpotOrderResult { orderId: string; clientOrderId: string; } ⋮---- export interface SpotPlanOrder { orderId: string; clientOid: string; symbol: string; size: string; executePrice: string; triggerPrice: string; status: string; orderType: string; side: string; triggerType: string; enterPointSource: string; cTime: number; } ⋮---- export interface SpotMarketTrade { symbol: string; tradeId: string; side: 'buy' | 'sell'; fillPrice: string; fillQuantity: string; fillTime: string; } ⋮---- export interface SpotAccountAsset { coin: string; available: string; frozen: string; locked: string; limitAvailable: string; uTime: string; } ⋮---- export interface SpotAccountBill { cTime: string; coino: string; groupType: string; businessType: | 'SMALL_EXCHANGE_USER_IN' | 'SMALL_EXCHANGE_USER_OUT' | 'AIRDROP_REWARD' | 'WITHDRAW' | string; // TODO: complete list of possible values here? size: string; balance: string; fees: string; billd: string; } ⋮---- | string; // TODO: complete list of possible values here? ================ File: src/types/response/v2/common.ts ================ /** * * * Common | Notice * */ ⋮---- export interface AnnouncementV2 { annId: string; annTitle: string; annDesc: string; cTime: string; language: string; annUrl: string; } ⋮---- /** * * * Common | Public * */ ⋮---- /** * * * Common | Tax * */ ⋮---- export interface SpotTransactionRecordV2 { id: string; coin: string; spotTaxType: string; amount: string; fee: string; balance: string; ts: string; } ⋮---- export interface FuturesTransactionRecordV2 { id: string; symbol: string; marginCoin: string; futureTaxType: string; amount: string; fee: string; ts: string; } ⋮---- export interface MarginTransactionRecordV2 { id: string; coin: string; marginTaxType: string; amount: string; fee: string; total: string; symbol: string; ts: string; } ⋮---- export interface P2PMerchantOrdersV2 { id: string; coin: string; p2pTaxType: string; total: string; ts: string; } ⋮---- /** * * * Common | P2P * */ ⋮---- export interface P2PMerchantV2 { registerTime: string; nickName: string; isOnline: string; avgPaymentTime: string; avgReleaseTime: string; totalTrades: string; totalBuy: string; totalSell: string; totalCompletionRate: string; trades30d: string; sell30d: string; buy30d: string; completionRate30d: string; } ⋮---- export interface P2PMerchantInfoV2 { registerTime: string; nickName: string; merchantId: string; avgPaymentTime: string; avgReleaseTime: string; totalTrades: string; totalBuy: string; totalSell: string; totalCompletionRate: string; trades30d: string; sell30d: string; buy30d: string; completionRate30d: string; kycStatus: boolean; emailBindStatus: boolean; mobileBindStatus: boolean; email: string; mobile: string; } ⋮---- export interface P2PMerchantOrderV2 { orderId: string; orderNo: string; advNo: string; side: string; count: string; coin: string; price: string; fiat: string; withdrawTime: string; representTime: string; releaseTime: string; paymentTime: string; amount: string; status: string; buyerRealName: string; sellerRealName: string; ctime: string; utime: string; paymentInfo: { paymethodName: string; paymethodId: string; paymethodInfo: { name: string; required: string; type: string; value: string; }[]; }; } ⋮---- export interface P2PMerchantAdvertismentV2 { advId: string; advNo: string; side: string; advSize: string; size: string; coin: string; price: string; coinPrecision: string; fiat: string; fiatPrecision: string; fiatSymbol: string; status: string; hide: string; maxTradeAmount: string; minTradeAmount: string; payDuration: string; turnoverNum: string; turnoverRate: string; label: string | null; userLimitList: { minCompleteNum: string; maxCompleteNum: string; placeOrderNum: string; allowMerchantPlace: string; completeRate30d: string; country: string; }; paymentMethodList: { paymentMethod: string; paymentId: string; paymentInfo: { name: string; required: boolean; type: string; }[]; }[]; merchantCertifiedList: { imageUrl: string; desc: string; }[]; utime: string; ctime: string; } ⋮---- /** * * * Common | Trading insights * */ ⋮---- export interface SpotWhaleNetFlowV2 { volume: string; date: string; } ⋮---- export interface FuturesActiveBuySellVolumeV2 { buyVolume: string; sellVolume: string; ts: string; } ⋮---- export interface FuturesActiveLongShortPositionV2 { longPositionRatio: string; shortPositionRatio: string; longShortPositionRatio: string; ts: string; } ⋮---- export interface LeveragedLongShortRatioV2 { ts: string; longShortRatio: string; } ⋮---- export interface MarginLoanGrowthRateV2 { ts: string; growthRate: string; } ⋮---- export interface IsolatedMarginBorrowingRatioV2 { ts: string; borrowRate: string; } ⋮---- export interface FuturesLongShortRatioV2 { longRatio: string; shortRatio: string; longShortRatio: string; ts: string; } ⋮---- export interface SpotFundFlowV2 { whaleBuyVolume: string; dolphinBuyVolume: string; fishBuyVolume: string; whaleSellVolume: string; dolphinSellVolume: string; fishSellVolume: string; whaleBuyRatio: string; dolphinBuyRatio: string; fishBuyRatio: string; whaleSellRatio: string; dolphinSellRatio: string; fishSellRatio: string; } ⋮---- export interface FuturesActiveLongShortAccountV2 { longAccountRatio: string; shortAccountRatio: string; longShortAccountRatio: string; ts: string; } ⋮---- /** * * * Common | Virtual Subaccount * */ ⋮---- export interface CreateVirtualSubAccountV2 { failureList: { subaAccountName: string; }[]; successList: { subaAccountUid: string; subaAccountName: string; status: string; label: string; permList: string[]; cTime: string; uTime: string; }[]; } ⋮---- export interface CreateVirtualSubAccountAndApiKeyV2 { subAccountUid: string; subAccountName: string; label: string; subAccountApiKey: string; secretKey: string; permList: string[]; ipList: string[]; } ⋮---- export interface VirtualSubAccountV2 { subAccountUid: string; subAccountName: string; status: string; permList: string[]; label: string; accountType: string; bindingTime: string; cTime: string; uTime: string; } ⋮---- export interface CreateVirtualSubAccountApiKeyV2 { subAccountUid: string; label: string; subAccountApiKey: string; secretKey: string; permList: string[]; ipList: string[]; } ⋮---- export interface ModifyVirtualSubAccountApiKeyV2 { subAccountUid: string; label: string; subAccountApiKey: string; secretKey: string; permList: string[]; ipList: string[]; } ⋮---- export interface SubAccountApiKeyItemV2 { subAccountUid: string; label: string; subAccountApiKey: string; permList: string[]; ipList: string[]; } ⋮---- /** * * * Common | Assets * */ ⋮---- export interface FundingAssetV2 { coin: string; available: string; frozen: string; usdtValue: string; } ⋮---- export interface BotAssetV2 { coin: string; available: string; equity: string; bonus: string; frozen: string; usdtValue: string; } ⋮---- /** * * * Common | Convert * */ ⋮---- export interface ConvertCurrencyV2 { coin: string; available: string; maxAmount: string; minAmount: string; } ⋮---- export interface ConvertQuotedPriceV2 { fee: string; fromCoinSize: string; fromCoin: string; cnvtPrice: string; toCoinSize: string; toCoin: string; traceId: string; } ⋮---- export interface ConvertTradeResponseV2 { ts: string; cnvtPrice: string; toCoinSize: string; toCoin: string; } ⋮---- export interface ConvertRecordV2 { id: string; ts: string; cnvtPrice: string; fee: string; fromCoinSize: string; fromCoin: string; toCoinSize: string; toCoin: string; } ⋮---- /** * * * Common | BGB Convert * */ ⋮---- export interface BGBConvertCoinV2 { coin: string; available: string; bgbEstAmount: string; precision: string; feeDetail: { feeRate: string; fee: string; }[]; cTime: string; } ⋮---- export interface ConvertBGBResponseV2 { orderList: { coin: string; orderId: string; }[]; } ⋮---- export interface BGBConvertHistoryV2 { orderId: string; fromCoin: string; fromAmount: string; fromCoinPrice: string; toCoin: string; toAmount: string; toCoinPrice: string; feeDetail: { feeCoin: string; fee: string; }[]; status: string; ctime: string; } ================ File: src/types/response/v2/copy-trading.ts ================ /** * * * Copy Trading | Future copy trading | Trader Api * * */ ⋮---- 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; } ⋮---- export interface CTFuturesTraderCurrentOrdersV2 { trackingList: CTFuturesTraderCurrentOrderV2[]; endId: string; } ⋮---- 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; } ⋮---- export interface CTFuturesTraderHistoryOrderV2 { trackingList: CTFuturesTraderHistoryOrderV2[]; endId: string; } ⋮---- export interface CTRateCTimeV2 { rate: string; ctime: string; } ⋮---- export interface CTAmountCTimeV2 { amount: string; ctime: string; } ⋮---- 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; } ⋮---- export interface CTFuturesTraderProfitHistoryItemV2 { coin: string; profitCount: string; lastProfitTime: string; } ⋮---- export interface CTFuturesTraderHistoryProfitSummaryV2 { profitSummary: { yesterdayProfit: string; sumProfit: string; waitProfit: string; yesterdayTime: string; }; profitHistoryList: CTFuturesTraderProfitHistoryItemV2[]; } ⋮---- export interface CTFuturesTraderProfitShare { profitId: string; coin: string; profit: string; nickName: string; profitTime: string; } ⋮---- export interface CTFuturesTraderProfitShareHistoryV2 { profitList: CTFuturesTraderProfitShare[]; endId: string; } ⋮---- export interface CTFuturesTraderSymbolSettingsV2 { symbol: string; openTrader: string; minOpenCount: string; maxLeverage: string; stopSurplusRatio: string; stopLossRatio: string; } ⋮---- export interface CTFuturesTraderMyFollowersV2 { accountEquity: string; isRemove: string; followerHeadPic: string; followerName: string; followerUid: string; followerTime: string; } ⋮---- /** * * * Copy Trading | Future copy trading | Follower Api * * */ ⋮---- 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; } ⋮---- 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; } ⋮---- export interface CTFuturesFollowerHistoryOrdersV2 { trackingList: CTFuturesFollowerHistoryOrderV2[]; endId: string; } ⋮---- export interface CTFuturesFollowerSettingV2 { symbol: string; productType: string; marginType: string; marginCoin: string; leverType: string; longLeverage: string; shortLeverage: string; traceType: string; } ⋮---- export interface CTFuturesFollowerSettingsV2 { followerEnable: string; detailList: CTFuturesFollowerSettingV2[]; } ⋮---- 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; } ⋮---- /** * * * Copy Trading | Spot copy trading | Trader api * * */ ⋮---- export interface CTSpotTraderProfitSummaryV2 { profitSummarys: { yesterdayProfit: string; yesterdayTime: string; sumProfit: string; waitProfit: string; }; profitHistoryList: { coin: string; profitCount: string; lastProfitTime: string; historysByDateList: { profit: string; profitTime: string; }[]; }[]; } ⋮---- export interface CTSpotTraderHistoryProfitShareItemV2 { profitId: string; coin: string; distributeRatio: string; profit: string; followerName: string; profitTime: string; } ⋮---- export interface CTSpotTraderHistoryProfitSharingV2 { endId: string; profitList: CTSpotTraderHistoryProfitShareItemV2[]; } ⋮---- export interface CTSpotTraderUnrealizedProfitV2 { distributeRatio: string; coin: string; profit: string; followerName: 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 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[]; } ⋮---- 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 CTSpotTraderCurrentTrackingOrdersV2 { endId: string; trackingList: CTSpotTraderCurrentTrackingOrderV2[]; } ⋮---- export interface CTSpotTraderFollowerListV2 { accountEquity: string; isRemove: string; followerHeadPic: string | null; followerName: string; followerUid: string; followerTime: string; } ⋮---- /** * * * Copy Trading | Spot 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 CTSpotFollowerMyTradersV2 { resultList: CTSpotFollowerMyTraderV2[]; } ⋮---- export interface CTSpotFollowerTradeSettingV2 { maxTraceAmount: string; stopLossRation: string; stopSurplusRation: string; symbol: string; traceType: 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 interface CTSpotFollowerFollowConfigurationV2 { enable: string; profitRate: string; settledInDays: string; tradeSettingList: CTSpotFollowerTradeSettingV2[]; tradeSymbolSettingList: CTSpotFollowerTradeSymbolSettingV2[]; traderHeadPic: string; traderName: string; } ⋮---- 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[]; } ⋮---- 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 CTSpotFollowerCurrentOrdersV2 { endId: string; trackingList: CTSpotFollowerCurrentOrderV2[]; } ================ File: src/types/response/v2/earn.ts ================ /** * * * Earn | Savings * * */ ⋮---- export interface EarnSavingsProductsV2 { productId: string; coin: string; periodType: string; period: string; apyType: string; advanceRedeem: string; settleMethod: string; apyList: { rateLevel: string; minStepVal: string; maxStepVal: string; currentApy: string; }[]; status: string; productLevel: string; } ⋮---- export interface EarnSavingsAccountV2 { btcAmount: string; usdtAmount: string; btc24hEarning: string; usdt24hEarning: string; btcTotalEarning: string; usdtTotalEarning: string; } ⋮---- export interface EarnSavingsAssetV2 { productId: string; orderId: string; productCoin: string; interestCoin: string; periodType: string; period: string; holdAmount: string; lastProfit: string; totalProfit: string; holdDays: string; status: string; allowRedemption: string; productLevel: string; apy: { rateLevel: string; minApy: string; maxApy: string; currentApy: string; }[]; } ⋮---- export interface EarnSavingsAssetsV2 { resultList: EarnSavingsAssetV2[]; endId: string; } ⋮---- export interface EarnSavingsRecordV2 { orderId: string; coinName: string; settleCoinName: string; productType: string; period: string; productLevel: string; amount: string; ts: string; orderType: string; } ⋮---- export interface EarnSavingsRecordsV2 { resultList: EarnSavingsRecordV2[]; endId: string; } ⋮---- export interface EarnSavingsSubscriptionDetailV2 { singleMinAmount: string; singleMaxAmount: string; remainingAmount: string; subscribePrecision: string; profitPrecision: string; subscribeTime: string; interestTime: string; settleTime: string; expireTime: string; redeemTime: string; settleMethod: string; apyList: { rateLevel: string; minStepVal: string; maxStepVal: string; currentApy: string; }[]; redeemDelay: string; } ⋮---- /** * * * Earn | Earn Account * * */ ⋮---- /** * * * Earn | Shark Fin * * */ ⋮---- export interface EarnSharkfinProductV2 { 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; endTime: string; startTime: string; } ⋮---- export interface EarnSharkfinProductsV2 { resultList: EarnSharkfinProductV2[]; endId: string; } ⋮---- export interface EarnSharkfinAccountV2 { btcSubscribeAmount: string; usdtSubscribeAmount: string; btcHistoricalAmount: string; usdtHistoricalAmount: string; btcTotalEarning: string; usdtTotalEarning: string; } ⋮---- export interface EarnSharkfinAssetV2 { productId: string; interestStartTime: string; interestEndTime: string; productCoin: string; subscribeCoin: string; trend: string; settleTime: string; interestAmount: string; productStatus: string; } ⋮---- export interface EarnSharkfinAssetsV2 { resultList: EarnSharkfinAssetV2[]; endId: string; } ⋮---- export interface EarnSharkfinRecordV2 { orderId: string; product: string; period: string; amount: string; ts: string; type: string; } export interface EarnSharkfinRecordsV2 { resultList: EarnSharkfinRecordV2[]; endId: string; } ⋮---- export interface EarnSharkfinSubscriptionDetailV2 { 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; } ⋮---- /** * * * Earn | Loan * * */ ⋮---- export interface EarnLoanCurrencyLoanInfoV2 { coin: string; hourRate7D: string; rate7D: string; hourRate30D: string; rate30D: string; minUsdt: string; maxUsdt: string; min: string; max: string; } export interface EarnLoanCurrencyPledgeInfoV2 { coin: string; initRate: string; supRate: string; forceRate: string; minUsdt: string; maxUsdt: string; } ⋮---- export interface EarnLoanCurrenciesV2 { loanInfos: EarnLoanCurrencyLoanInfoV2[]; pledgeInfos: EarnLoanCurrencyPledgeInfoV2[]; } ⋮---- export interface EarnLoanOrdersV2 { 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 EarnLoanRepayResponseV2 { loanCoin: string; pledgeCoin: string; repayAmount: string; payInterest: string; repayLoanAmount: string; repayUnlockAmount: string; } ⋮---- export interface EarnLoanRepayHistoryV2 { orderId: string; loanCoin: string; pledgeCoin: string; repayAmount: string; payInterest: string; repayLoanAmount: string; repayUnlockAmount: string; repayTime: string; } ⋮---- export interface EarnLoanPledgeRateHistoryV2 { loanCoin: string; pledgeCoin: string; orderId: string; reviseTime: string; reviseSide: string; reviseAmount: string; afterPledgeRate: string; beforePledgeRate: string; } ⋮---- export interface EarnLoanHistoryV2 { orderId: string; loanCoin: string; pledgeCoin: string; initPledgeAmount: string; initLoanAmount: string; hourRate: string; daily: string; borrowTime: string; status: string; } ⋮---- export interface EarnLoanDebtPledgeInfoV2 { coin: string; amount: string; amountUsdt: string; } ⋮---- export interface EarnLoanDebtLoanInfoV2 { coin: string; amount: string; amountUsdt: string; } ⋮---- export interface EarnLoanDebtsV2 { pledgeInfos: EarnLoanDebtPledgeInfoV2[]; loanInfos: EarnLoanDebtLoanInfoV2[]; } ⋮---- export interface EarnLoanLiquidationRecordsV2 { 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/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; } ⋮---- /** * * * 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 MarginInterestHistoryItemV2 { interestId: string; interestCoin: string; dailyInterestRate: string; loanCoin: string; interestAmount: string; interstType: string; symbol: string; cTime: string; uTime: 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 MarginFinancialHistoryItemV2 { coin: string; symbol: string; marginId: string; amount: string; balance: string; fee: string; marginType: string; cTime: string; uTime: string; } ⋮---- /** * * * Margin | Cross/Isolated | Account * */ ⋮---- 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; } ⋮---- export interface CrossMaxBorrowableResponseV2 { coin: string; maxBorrowableAmount: string; } ⋮---- export interface IsolatedMaxBorrowableResponseV2 { symbol: string; baseCoin: string; baseCoinMaxBorrowAmount: string; quoteCoin: string; quoteCoinMaxBorrowAmount: string; } ⋮---- export interface CrossMaxTransferableResponseV2 { coin: string; maxTransferOutAmount: string; } ⋮---- export interface IsolatedMaxTransferableResponseV2 { baseCoin: string; symbol: string; baseCoinMaxTransferOutAmount: string; quoteCoin: string; quoteCoinMaxTransferOutAmount: 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 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 CrossTierConfigurationResponseV2 { tier: string; leverage: string; coin: string; maxBorrowableAmount: string; maintainMarginRate: 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 | Trade * */ ⋮---- export interface MarginBatchOrdersResponseV2 { successList: { orderId: string; clientOid: string; }[]; failureList: { clientOid: string; errorMsg: string; }[]; } ⋮---- 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; } ⋮---- 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; } ⋮---- 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 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/response/v2/spot.ts ================ /** * * * Spot | Market * */ ⋮---- export interface SpotCoinChainV2 { chain: string; needTag: boolean; withdrawable: boolean; rechargeable: boolean; withdrawFee: string; extraWithdrawFee: string; depositConfirm: string; withdrawConfirm: string; minDepositAmount: string; minWithdrawAmount: string; browserUrl: string; contractAddress: string; withdrawStep: string; withdrawMinScale: string; congestion: string; } ⋮---- export interface SpotCoinInfoV2 { coinId: string; coin: string; transfer: boolean; chains: SpotCoinChainV2[]; } ⋮---- export interface SpotSymbolInfoV2 { symbol: string; baseCoin: string; quoteCoin: string; minTradeAmount: string; maxTradeAmount: string; takerFeeRate: string; makerFeeRate: string; pricePrecision: string; quantityPrecision: string; quotePrecision: string; minTradeUSDT: string; status: string; buyLimitPriceRatio: string; sellLimitPriceRatio: string; orderQuantity: string; areaSymbol: string; } ⋮---- export interface SpotVipFeeRateV2 { level: number; dealAmount: string; assetAmount: string; takerFeeRate: string; makerFeeRate: string; btcWithdrawAmount: string; usdtWithdrawAmount: string; } ⋮---- export interface SpotTickerV2 { symbol: string; high24h: string; open: string; low24h: string; lastPr: string; quoteVolume: string; baseVolume: string; usdtVolume: string; bidPr: string; askPr: string; bidSz: string; askSz: string; openUtc: string; ts: string; changeUtc24h: string; change24h: string; } ⋮---- export interface SpotMergeDepthV2 { asks: [string, string][]; bids: [string, string][]; ts: string; scale: string; precision: string; isMaxPrecision: string; } ⋮---- export interface SpotOrderBookDepthV2 { asks: [string, string][]; bids: [string, string][]; ts: string; } ⋮---- export type SpotCandlestickV2 = [ string, // timestamp string, // open string, // high string, // low string, // close string, // baseVolume string, // usdtVolume string, // quoteVolume ]; ⋮---- string, // timestamp string, // open string, // high string, // low string, // close string, // baseVolume string, // usdtVolume string, // quoteVolume ⋮---- export interface SpotTradeV2 { symbol: string; tradeId: string; side: string; price: string; size: string; ts: string; } ⋮---- /** * * * Spot | Trade * */ ⋮---- export interface CancelAndSubmitSpotOrderResponseV2 { orderId: string; clientOid: string | null; success: string; msg: string | null; } ⋮---- export interface SubmitSpotBatchOrdersResponseV2 { successList: { orderId: string; clientOid: string; }[]; failureList: { orderId: string; clientOid: string; errorMsg: string; errorCode?: string; }[]; } ⋮---- export interface SpotOrderInfoV2 { userId: string; symbol: string; orderId: string; clientOid: string; price: string; size: string; orderType: string; side: string; status: string; priceAvg: string; baseVolume: string; quoteVolume: string; enterPointSource: string; feeDetail: { BGB?: { deduction: boolean; feeCoinCode: string; totalDeductionFee: string; totalFee: string; }; newFees?: { c: number; d: number; deduction: boolean; r: string; t: string; totalDeductionFee: number; }; }; orderSource: string; cancelReason: string; cTime: string; uTime: string; } ⋮---- export interface SpotOpenOrderV2 { userId: string; symbol: string; orderId: string; clientOid: string; priceAvg: string; size: string; orderType: string; side: string; status: string; basePrice: string; baseVolume: string; quoteVolume: string; enterPointSource: string; orderSource?: string; presetTakeProfitPrice: string; executeTakeProfitPrice: string; presetStopLossPrice: string; executeStopLossPrice: string; cTime: string; uTime?: string; tpslType: string; triggerPrice: string | null; } ⋮---- export interface SpotFillV2 { userId: string; symbol: string; orderId: string; tradeId: string; orderType: string; side: string; priceAvg: string; size: string; amount: string; feeDetail: { deduction: string; feeCoin: string; totalDeductionFee: string; totalFee: string; }; tradeScope: string; cTime: string; uTime: string; } ⋮---- /** * * * Spot | Trigger Orders * */ ⋮---- export interface SpotCurrentPlanOrderV2 { orderId: string; clientOid: string; symbol: string; size: string; executePrice: string; triggerPrice: string; status: string; orderType: string; side: string; planType: string; triggerType: string; enterPointSource: string; uTime: string; cTime: string; } ⋮---- export interface SpotHistoryPlanOrderV2 { orderId: string; clientOid: string; symbol: string; size: string; executePrice: string; triggerPrice: string; status: string; orderType: string; side: string; planType: string; triggerType: string; enterPointSource: string; uTime: string; cTime: string; } ⋮---- export interface SpotPlanSubOrderV2 { orderId: string; price: string; type: string; status: string; } ⋮---- export interface SpotCancelPlanOrdersV2 { successList: { orderId: string; clientOid: string; }[]; failureList: { orderId: string; clientOid: string; errorMsg: string; }[]; } ⋮---- /** * * * Spot | Account * */ ⋮---- export interface SpotAccountInfoV2 { userId: string; inviterId: string; ips: string; authorities: string[]; parentId: number; traderType: string; channelCode: string; channel: string; regisTime: string; } ⋮---- export interface SpotAccountAssetV2 { coin: string; available: string; frozen: string; locked: string; limitAvailable: string; uTime: string; } ⋮---- export interface SpotSubAccountAssetV2 { coin: string; available: string; limitAvailable: string; frozen: string; locked: string; uTime: string; } export interface SpotSubAccountAssetsV2 { userId: number; assetsList: SpotSubAccountAssetV2[]; } ⋮---- export interface SpotAccountBillV2 { cTime: string; coin: string; groupType: string; businessType: string; size: string; balance: string; fees: string; billId: string; } ⋮---- export interface SpotMainSubTransferRecordV2 { coin: string; status: string; toType: string; fromType: string; size: string; ts: string; clientOid: string; transferId: string; fromUserId: string; toUserId: string; } ⋮---- export interface SpotTransferRecordV2 { coin: string; status: string; toType: string; toSymbol: string; fromType: string; fromSymbol: string; size: string; ts: string; clientOid: string; transferId: string; } ⋮---- export interface SpotDepositAddressV2 { address: string; chain: string; coin: string; tag: string; url: string; } ⋮---- export interface SpotSubAccountDepositRecordV2 { orderId: string; tradeId: string; coin: string; size: string; status: string; toAddress: string; dest: string; chain: string; fromAddress: string; clientOid?: string; confirm?: string; tag?: string; cTime: string; uTime: string; } ⋮---- export interface SpotWithdrawalRecordV2 { orderId: string; tradeId: string; coin: string; dest: string; clientOid: string; type: string; tag: string; size: string; fee: string; status: string; toAddress: string; fromAddress: string; confirm: string; chain: string; cTime: string; uTime: string; } ⋮---- export interface SpotDepositRecordV2 { orderId: string; tradeId: string; coin: string; type: string; size: string; status: string; toAddress: string; dest: string; chain: string; fromAddress: string; cTime: string; uTime: string; } ================ File: src/types/response/v3/loan.ts ================ export interface LoanTransfersV3 { coin: string; transfered: string; userId: string; } ⋮---- export interface LoanSymbolSettingV3 { symbol: string; leverage: string; } ⋮---- export interface LoanSymbolsV3 { productId: string; spotSymbols: string[]; marginLeverage: string; usdtContractLeverage: string; coinContractLeverage: string; usdcContractLeverage: string; usdtContractSymbols: LoanSymbolSettingV3[]; coinContractSymbols: LoanSymbolSettingV3[]; usdcContractSymbols: LoanSymbolSettingV3[]; } ⋮---- export interface RepaidHistoryItemV3 { repayOrderId: string; businessType: 'normal' | 'liquidation'; repayType: 'all' | 'part'; repaidTime: string; coin: string; repayAmount: string; repayInterest: 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 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 CoinInfoV3 { coin: string; convertRatio: string; maxConvertValue: string; } ⋮---- 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; subAccountUids: string[]; unpaidUsdtAmount: string; usdtBalance: string; unpaidInfo: UnpaidInfoV3[]; balanceInfo: BalanceInfoV3[]; } ================ File: src/types/response/v3/strategy.ts ================ export interface PlaceStrategyOrderResponseV3 { orderId: string; clientOid: string; } ⋮---- export interface ModifyStrategyOrderResponseV3 { orderId: string; clientOid: string; } ⋮---- export interface StrategyOrderV3 { orderId: string; clientOid: string; category: 'USDT-FUTURES' | 'COIN-FUTURES' | 'USDC-FUTURES'; symbol: string; qty: string; posSide: 'long' | 'short'; tpTriggerBy: 'market' | 'mark'; slTriggerBy: 'market' | 'mark'; takeProfit: string; stopLoss: string; tpOrderType: 'limit' | 'market'; slOrderType: 'limit' | 'market'; tpLimitPrice: string; slLimitPrice: string; createdTime: string; updatedTime: 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; } ⋮---- export interface WSPositionSnapshotUMCBL extends WsBaseEvent<'snapshot'> { arg: { instType: 'umcbl'; channel: 'positions'; instId: string; }; data: WsPositionSnapshotDataUMCBL[]; } ================ File: .jshintrc ================ { "esversion": 8, "asi": true, "laxbreak": true, "predef": [ "-Promise" ] } ================ File: .prettierrc ================ { "tabWidth": 2, "singleQuote": true, "trailingComma": "all" } ================ 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: tea.yaml ================ # https://tea.xyz/what-is-this-file --- version: 1.0.0 codeOwners: - '0xeb1a7BF44a801e33a339705A266Afc0Cba3D6D54' quorum: 1 ================ File: examples/auth/fasterHmacSign.ts ================ import { createHmac } from 'crypto'; ⋮---- import { DefaultLogger, RestClientV3, WebsocketClientV3 } from '../../src/'; ⋮---- // or // import { createHmac } from 'crypto'; // import { DefaultLogger, RestClientV3, WebsocketClientV3 } from 'bitget-api'; ⋮---- /** * Injecting a custom signMessage function. * * As of version 3.0.0 of the bitget-api Node.js/TypeScript/JavaScript * SDK for Bitget, the SDK uses the Web Crypto API for signing requests. * While it is compatible with Node and Browser environments, it is * slightly slower than using Node's native crypto module (only * available in backend Node environments). * * For latency sensitive users, you can inject the previous node crypto sign * method (or your own even faster implementation), if this change affects you. * * This example demonstrates how to inject a custom sign function, to achieve * the same peformance as seen before the Web Crypto API was introduced. * * For context on standard usage, the "signMessage" function is used: * - During every single API call * - After opening a new private WebSocket connection */ ⋮---- /** * Set this to true to enable demo trading: */ ⋮---- /** * Overkill in almost every case, but if you need any optimisation available, * you can inject a faster sign mechanism such as node's native createHmac: */ ⋮---- // Optional, uncomment the "trace" override to log a lot more info about what the WS client is doing ⋮---- // trace: (...params) => console.log('trace', ...params), ⋮---- /** * Set this to true to enable demo trading for the private account data WS * Topics: order,execution,position,wallet,greeks */ ⋮---- /** * Overkill in almost every case, but if you need any optimisation available, * you can inject a faster sign mechanism such as node's native createHmac: */ ⋮---- function setWsClientEventListeners( websocketClient: WebsocketClientV3, accountRef: string, ): Promise ⋮---- // console.log('raw message received ', JSON.stringify(data, null, 2)); ⋮---- // Simple promise to ensure we're subscribed before trying anything else ⋮---- // Start trading ================ File: examples/auth/rest-private-rsa.md ================ # RSA Authentication with Bitget APIs in Node.js, JavaScript & TypeScript ## Creating RSA Keys Officially, Bitget recommends downloading and running a key generator from their repo. Guidance for this can be found on the Bitget's website when trying to add a new RSA API key. However, openssl can be used to create the public & private key files using the following steps: ```bash # Generate a private key with either 2048 or 4096 bit length openssl genrsa -out rsa-private-key.pem 4096 # Generate a corresponding public key openssl rsa -in rsa-private-key.pem -pubout -out rsa-public-key.pem ``` ## Using the RSA public key to get an API key from Bitget Once created, keep your **private key** completely secret! The **public** key needs to be provided to Bitget when creating new API credentials with the "Self-generated" option. Your public key should look something like this: ```pem -----BEGIN PUBLIC KEY----- MIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEA1uWxxOXZUaX6AeZszf4x rBsU6axA5ipwxG7VPihVgssphDrrSOD0hZqnBmtF2bvT9ee1U0XOfMn+H+J5SH+1 jgUpfioqH0L+KXl6wmLoPsadgfJz0SiQlFnKTkDXvMmecr6cdMHi2qNEx4CMc68C obvQ4Voz5qqpDwbohGtJh0p10PB//0Ejcoz0UwrTDq8BGeFmWa9pL/7h2vHtw+QU UxlnGmt98M8KkKqqvVicMK+IVtng/QlDw9ofG2kQcbBkPRaTjNI+8ULtCDH0sOkZ nT8PtGm4sEwmWH/dRWtUTWkMnUwCzuo/rWPb7WMprW2pKDTrLjUAr9M161t3Xa6W JO03K3NOxupy7ilululLY8d/WKWYDOZMvS5bPiPRUoZqlJneC0CT/2q1W6GfWzsT DCDTpgq/Ao7jTtnME9iadpwvFn0nMtNgJSrFDWPq8vKY9pRcEp/Na5qvIEOQIFnp /kIDPuMf+LZwO8lGFO3jnndY+62835rm7t6ZNM3NLoNCarvUCEasobgDJHw7x7c1 fW/OxYtLrWGdMpsP0MewgGJZXcT7mvlBjQ+JWLoyIc5rYMIDw9RLWUPnrlRCxvPp sD9kDX7eaipdoik5yLyMaRvd16Vt9Bck/9pbSHazm41m/nd4KCZeGdsvrAA2beww zFWQQV9EX6/VLBgbnGTsMe0CAwEAAQ== -----END PUBLIC KEY----- ``` Submit this in the "Upload public key" form, shown when creating a new API key on Bitget and choosing the "self-generated"/RSA option. Note: the "-----BEGIN PUBLIC KEY-----" and "-----END PUBLIC KEY-----" header & footer can be included. After using the public key to create a new API key, you will be given an API Key such as the following: ``` SIHqWcDeRoj6gkOjLjQh1dnV1CD7IgwQTfL4LVa8wu04zNTYVSmJBIHsjQjgwWqt ``` This is the first piece, used as the "apiKey" in the [rest-private-rsa.ts](./rest-private-rsa.ts) example. ## Using the RSA private key for RSA authentication with Bitget APIs in Node.js Your private key, if generated with the above steps, should look something like this (but with much more text): ```pem -----BEGIN RSA PRIVATE KEY----- uayyi6wFTaNeG1/WCqhrowj2kCx8eB6NDZYl+OS9ZI9WC q/44iFERNuP0TXvQx8tgvSZXyu4/G618QzKh0Ii1uAATt2upa8dp1uGl2U7EqBE8 p5y4pPzJuwvB3j6LQON20u2Wpbg8PQZACMfKym7lYDO+9MloK/gAQpyeYJzbw92C YE/ymq4JVjCMCQKCAQEA4/X0I9TO8vT0D0l83o693QA3C09uSZ6j9Obx5UrtDnA9 sMkkRoe+R/vvIpVDzukMEEOmCuxbcdPoniVUKlTooK0Llo6JJ1l8CdFzQsOR97Pe csB6pxkLLH2qHx05xPBy4PyoB -----END RSA PRIVATE KEY----- ``` This is your secret, you should never share this with anyone, not even Bitget! Treat this like a password. As part of this authentication process, your private key is used to generate a signature (using `RSA-SHA256`). This SDK handles this process automatically for you. RSA authentication is automatically detected if the "api_secret" parameter contains the words "PRIVATE KEY", such as the header shown in the example above. From here, simply use the key provided by Bitget as the `api_key` parameter and your private key (with the header) as the `api_secret` parameter. Based on the above example, the following would prepare the main REST client using the above credentials: ```typescript // Received after creating a new API key with a self-generated RSA public key on Bitget const API_KEY = 'bg_0866563123123123123f567e83e52fd'; // The self-generated RSA private key, this is never directly given to Bitget, but used to generate a signature // Note: this MUST include the "BEGIN PRIVATE KEY" header so that the SDK understands this is RSA auth const rsaPrivateKey = ` -----BEGIN PRIVATE KEY----- MIIJQQIBADANBgkqhkiG9w0BAQEFAASCCSswggknAgEAAoICAQC4kNgO71O0xkuH FjHnr5pimpEeiGPAtDTAeJoS55+kVrh3ThHsm0ARf36zimU gwrCWAnKqPlbqzWzs9mH9JvZWrEaOgWy 8wMSJ21vtz1rRJhfaUUsOC1KLoWyvzqWW44zKaxoKSqCUMJqDbxIq7RjGlmc8KGJ scFWRSdfGEEpvqLlpTLoEtWHZP0pUUamSWrH/IgieFFhKaOPvmED24DJAlqSeEFw z7TW4dfWPRgjCRu4AAfgCtjb+3/7ONeQfx5XFvKFM7VNi/9sRh+alRqpzKrlI 79bM1p/egrC4c8KUqrNk2s5c3HIU......THISISANEXAMPLE -----END PRIVATE KEY----- `; // This is set by you when registering your RSA API key in Bitget's website. const API_PASS = 'TestingRSA'; const client = new RestClientV2({ apiKey: API_KEY, apiSecret: rsaPrivateKey, apiPass: API_PASS, }); const clientV3 = new RestClientV3({ apiKey: API_KEY, apiSecret: rsaPrivateKey, apiPass: API_PASS, }); ``` For a complete example, refer to the [rest-private-rsa.ts](./rest-private-rsa.ts) file on GitHub. ================ File: examples/auth/rest-private-rsa.ts ================ import { RestClientV2, RestClientV3 } from '../../src'; ⋮---- // Import frmo NPM: // import { RestClientV2, RestClientV3 } from 'bitget-api'; // or if you prefer require: // const { RestClientV2, RestClientV3 } = require('bitget-api'); ⋮---- // Received after creating a new API key with a self-generated RSA public key on Bitget ⋮---- // The self-generated RSA private key, this is never directly given to Bitget, but used to generate a signature // Note: this MUST include the "BEGIN PRIVATE KEY" header so that the SDK understands this is RSA auth ⋮---- // This is set by you when registering your RSA API key in Bitget's website. ⋮---- // const wsClient = new WebsocketClientV2({ // apiKey: API_KEY, // apiSecret: rsaPrivateKey, // apiPass: API_PASS, // }); ================ File: examples/deprecated-V1-REST/rest-private-futures.ts ================ import { FuturesClient } from '../../src/index'; ⋮---- // or // import { SpotClient } from 'bitget-api'; ⋮---- // read from environmental variables ⋮---- // apiKey: 'apiKeyHere', // apiSecret: 'apiSecretHere', // apiPass: 'apiPassHere', ⋮---- /** 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 */ ⋮---- startTime: now.getTime() + '', // should be sent as a string endTime: toTime.getTime() + '', // should be sent as a string ================ File: examples/deprecated-V1-REST/rest-private-spot.ts ================ import { SpotClient } from '../../src/index'; ⋮---- // or // import { SpotClient } from 'bitget-api'; ⋮---- // read from environmental variables ⋮---- // apiKey: 'apiKeyHere', // apiSecret: 'apiSecretHere', // apiPass: 'apiPassHere', ⋮---- /** 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 */ ================ File: examples/deprecated-V1-REST/rest-public-futures.ts ================ import { FuturesClient } from '../../src/index'; ⋮---- // or // import { SpotClient } from 'bitget-api'; ⋮---- // Fetch the last 1000 1min candles for a symbol ⋮---- const msPerCandle = 60 * 1000; // 60 seconds x 1000 ================ File: examples/deprecated-V1-REST/rest-trade-futures.ts ================ /* eslint-disable @typescript-eslint/no-unused-vars */ import { FuturesClient, isWsFuturesAccountSnapshotEvent, isWsFuturesPositionsSnapshotEvent, NewFuturesOrder, WebsocketClientLegacyV1, } from '../../src'; ⋮---- // or // import { // FuturesClient, // isWsFuturesAccountSnapshotEvent, // isWsFuturesPositionsSnapshotEvent, // NewFuturesOrder, // WebsocketClient, // } from 'bitget-api'; ⋮---- // read from environmental variables ⋮---- // apiKey: 'apiKeyHere', // apiSecret: 'apiSecretHere', // apiPass: 'apiPassHere', ⋮---- function logWSEvent(type, data) ⋮---- // simple sleep function function promiseSleep(milliseconds) ⋮---- // WARNING: for sensitive math you should be using a library such as decimal.js! function roundDown(value, decimals) ⋮---- /** WS event handler that uses type guards to narrow down event type */ async function handleWsUpdate(event) ⋮---- /** * 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 * * The corresponding UI for this is at https://www.bitget.com/en/mix/usdt/BTCUSDT_UMCBL */ ⋮---- // Add event listeners to log websocket events on account ⋮---- // Subscribe to private account topics ⋮---- // : 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/deprecated-V1-REST/rest-trade-spot.ts ================ import { SpotClient, WebsocketClientLegacyV1 } from '../../src/index'; ⋮---- // or // import { SpotClient } from 'bitget-api'; ⋮---- // read from environmental variables ⋮---- // apiKey: 'apiKeyHere', // apiSecret: 'apiSecretHere', // apiPass: 'apiPassHere', ⋮---- function logWSEvent(type, data) ⋮---- // simple sleep function function promiseSleep(milliseconds) ⋮---- // WARNING: for sensitive math you should be using a library such as decimal.js! function roundDown(value, decimals) ⋮---- /** 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 ⋮---- // 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); ⋮---- // console.log('balance: ', JSON.stringify(balances, null, 2)); ⋮---- // const quantityRoundedDown = btcAmount - btcAmount % 0.01 ================ File: examples/deprecated-V1-Websockets/ws-public.ts ================ import { DefaultLogger, WebsocketClientLegacyV1, WS_KEY_MAP } from '../../src'; ⋮---- // or // import { DefaultLogger, WS_KEY_MAP, WebsocketClient } 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 // wsClient.subscribeTopic('SP', 'ticker', symbol); // // candles // wsClient.subscribeTopic('SP', 'candle1m', symbol); // // orderbook updates ⋮---- // // trades // wsClient.subscribeTopic('SP', 'trade', symbol); ⋮---- // // Futures public ⋮---- // // tickers // wsClient.subscribeTopic('MC', 'ticker', symbol); // // candles // wsClient.subscribeTopic('MC', 'candle1m', symbol); // // orderbook updates // wsClient.subscribeTopic('MC', 'books', symbol); // // trades // wsClient.subscribeTopic('MC', 'trade', symbol); ⋮---- // Topics are tracked per websocket type // Get a list of subscribed topics (e.g. for spot topics) (after a 5 second delay) ================ File: examples/V2/rest-private-futures.ts ================ import { RestClientV2 } from '../../src/index'; ⋮---- // or // import { RestClientV2 } from 'bitget-api'; ⋮---- // 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-private-futures.ts ⋮---- // note the single quotes, preventing special characters such as $ from being incorrectly passed ⋮---- // apiKey: 'apiKeyHere', // apiSecret: 'apiSecretHere', // apiPass: 'apiPassHere', ⋮---- /** 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 */ ⋮---- startTime: fromTime.getTime() + '', // should be sent as a string endTime: now.getTime() + '', // should be sent as a string ================ File: examples/V2/rest-private-spot.ts ================ import { RestClientV2 } from '../../src/index'; ⋮---- // or // import { RestClientV2 } from 'bitget-api'; ⋮---- // 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-private-spot.ts ⋮---- // note the single quotes, preventing special characters such as $ from being incorrectly passed ⋮---- // apiKey: 'apiKeyHere', // apiSecret: 'apiSecretHere', // apiPass: 'apiPassHere', ⋮---- /** 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 */ ================ File: examples/V2/rest-public-futures.ts ================ import { RestClientV2 } from '../../src/index'; ⋮---- // or // import { RestClientV2 } from 'bitget-api'; ⋮---- // Fetch the last 1000 1min candles for a symbol ⋮---- const msPerCandle = 60 * 1000; // 60 seconds x 1000 ================ File: examples/V2/rest-public-spot.ts ================ import { RestClientV2 } from '../../src/index'; ⋮---- // or // import { RestClientV2 } from 'bitget-api'; ================ File: examples/V2/rest-trade-futures.ts ================ import { FuturesPlaceOrderRequestV2, RestClientV2, WebsocketClientV2, } from '../../src'; ⋮---- // 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, data) ⋮---- // simple sleep function function promiseSleep(milliseconds) ⋮---- /** * 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/rest-trade-spot.ts ================ import { RestClientV2, SpotOrderRequestV2, WebsocketClientV2, } from '../../src/index'; ⋮---- // 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, data) ⋮---- // simple sleep function function promiseSleep(milliseconds) ⋮---- /** 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/ws-demo-trading.ts ================ import { DefaultLogger, WebsocketClientV2 } from '../../src'; ⋮---- // 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/ws-private.ts ================ import { DefaultLogger, WebsocketClientV2 } from '../../src'; ⋮---- // 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/ws-public.ts ================ import { DefaultLogger, WebsocketClientV2, WS_KEY_MAP } from '../../src'; ⋮---- // 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/rest-private.ts ================ import { RestClientV3 } from '../../src/index'; ⋮---- // or // import { RestClientV3 } from 'bitget-api'; ⋮---- // 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-private-futures.ts ⋮---- // note the single quotes, preventing special characters such as $ from being incorrectly passed ⋮---- // apiKey: 'apiKeyHere', // apiSecret: 'apiSecretHere', // apiPass: 'apiPassHere', ⋮---- /** This is a simple script wrapped in a immediately invoked function expression, designed to check account assets for futures trading */ ================ File: examples/V3/rest-public-UTA-futures.ts ================ import { RestClientV3 } from '../../src/index'; ⋮---- // or // import { RestClientV3 } from 'bitget-api'; ================ File: examples/V3/rest-public-UTA-spot.ts ================ import { RestClientV3 } from '../../src/index'; ⋮---- // or // import { RestClientV3 } from 'bitget-api'; ================ File: examples/V3/ws-api-client-trade.ts ================ import { DefaultLogger } from '../../src'; import { WebsocketAPIClient } from '../../src/websocket-api-client'; ⋮---- // or // import { DefaultLogger, WS_KEY_MAP, WebsocketAPIClient } from 'bitget-api'; ⋮---- // 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); // }); // } ⋮---- // 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()); ⋮---- // 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. ⋮---- /** * 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! */ ⋮---- /** * 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: examples/V3/ws-api-trade-raw.ts ================ import { DefaultLogger, WebsocketClientV3, WS_KEY_MAP } from '../../src'; ⋮---- // 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: examples/V3/ws-public.ts ================ import { DefaultLogger, WebsocketClientV3, WS_KEY_MAP } from '../../src'; ⋮---- // 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: ================ File: src/types/request/v1/futuresV1.ts ================ import { OrderTimeInForce } from '../shared.js'; ⋮---- export type FuturesProductType = | 'umcbl' | 'dmcbl' | 'cmcbl' | 'sumcbl' | 'sdmcbl' | 'scmcbl'; ⋮---- export type FuturesKlineInterval = | '1m' | '3m' | '5m' | '15m' | '30m' | '1H' | '2H' | '4H' | '6H' | '12H' | '1D' | '3D' | '1W' | '1M' | '6Hutc' | '12Hutc' | '1Dutc' | '3Dutc' | '1Wutc' | '1Mutc'; ⋮---- export type FuturesHoldSide = 'long' | 'short'; ⋮---- export type FuturesMarginMode = 'fixed' | 'crossed'; ⋮---- export type FuturesHoldMode = 'double_hold' | 'single_hold'; ⋮---- export interface FuturesAccountBillRequest { symbol: string; marginCoin: string; startTime: string; endTime: string; pageSize?: number; lastEndId?: string; next?: boolean; } ⋮---- export interface FuturesBusinessBillRequest { productType: FuturesProductType; startTime: string; endTime: string; pageSize?: number; lastEndId?: string; next?: boolean; } ⋮---- export type FuturesOrderType = 'limit' | 'market'; export type FuturesOrderSide = | 'open_long' | 'open_short' | 'close_long' | 'close_short' | 'buy_single' | 'sell_single'; ⋮---- export interface NewFuturesOrder { symbol: string; productType: string; marginCoin: string; size?: string; quantity?: string; price?: string; side: FuturesOrderSide; orderType: FuturesOrderType; timeInForceValue?: OrderTimeInForce; clientOid?: string; reduceOnly?: boolean; reverse?: boolean; presetTakeProfitPrice?: string; presetStopLossPrice?: string; } ⋮---- export interface NewBatchFuturesOrder { size: string; price?: string; side: string; orderType: string; timeInForceValue?: string; clientOid?: string; } ⋮---- export interface ModifyFuturesOrder { symbol: string; orderId?: string; clientOid?: string; newClientOid?: string; size?: string; price?: string; presetTakeProfitPrice?: string; presetStopLossPrice?: string; } ⋮---- export interface FuturesHistoricPositions { startTime: string; endTime: string; productType?: FuturesProductType; symbol?: string; pageSize?: number; lastEndId?: string; } ⋮---- export interface FuturesPagination { startTime?: string; endTime?: string; lastEndId?: string; } ⋮---- export interface NewFuturesPlanOrder { symbol: string; marginCoin: string; size: string; executePrice?: string; triggerPrice: string; triggerType: 'fill_price' | 'market_price'; side: FuturesOrderSide; orderType: FuturesOrderType; clientOid?: string; presetTakeProfitPrice?: string; presetStopLossPrice?: string; reduceOnly?: string; } ⋮---- export interface ModifyFuturesPlanOrder { orderId: string; marginCoin: string; symbol: string; executePrice?: string; triggerPrice: string; triggerType: 'fill_price' | 'market_price'; orderType: FuturesOrderType; } ⋮---- export interface ModifyFuturesPlanOrderTPSL { orderId?: string; clientOid?: string; marginCoin: string; symbol: string; presetTakeProfitPrice?: string; presetStopLossPrice?: string; } ⋮---- export type FuturesPlanType = | 'profit_plan' | 'loss_plan' | 'normal_plan' | 'pos_profit' | 'pos_loss' | 'moving_plan' | 'track_plan'; ⋮---- export interface NewFuturesPlanStopOrder { symbol: string; marginCoin: string; planType: FuturesPlanType; triggerPrice: string; triggerType?: 'fill_price' | 'market_price'; holdSide: FuturesHoldSide; size?: string; rangeRate?: string; clientOid?: string; } ⋮---- export interface NewFuturesPlanTrailingStopOrder { symbol: string; marginCoin: string; triggerPrice: string; triggerType?: 'fill_price' | 'market_price'; size?: string; side: FuturesOrderSide; rangeRate?: string; clientOid?: string; } ⋮---- export interface NewFuturesPlanPositionTPSL { symbol: string; marginCoin: string; planType: FuturesPlanType; triggerPrice: string; triggerType?: 'fill_price' | 'market_price'; holdSide: FuturesHoldSide; clientOid?: string; } ⋮---- export interface ModifyFuturesPlanStopOrder { orderId?: string; clientOid?: string; marginCoin: string; symbol: string; triggerPrice?: string; planType: FuturesPlanType; } ⋮---- export interface CancelFuturesPlanTPSL { orderId?: string; clientOid?: string; symbol: string; marginCoin: string; planType: FuturesPlanType; } ⋮---- export interface HistoricPlanOrderTPSLRequest { symbol: string; startTime: string; endTime: string; pageSize?: number; isPre?: boolean; isPlan?: string; } ⋮---- /** * @typedef {string[6]} FuturesCandleData * @property {Array[0]} Timestamp in milliseconds * @property {Array[1]} Opening price * @property {Array[2]} Highest price * @property {Array[3]} Lowest price * @property {Array[4]} Closing price - Value of the latest candle stick might change * @property {Array[5]} Base currency trading volume * @property {Array[6]} Quote currency trading volume */ export type FuturesCandleData = string[6]; ================ File: src/types/request/v1/spotV1.ts ================ import { OrderTimeInForce } from '../shared.js'; ⋮---- export type WalletType = 'spot' | 'mix_usdt' | 'mix_usd'; ⋮---- export type SpotKlineInterval = | '1min' | '5min' | '15min' | '30min' | '1h' | '4h' | '6h' | '12h' | '1day' | '3day' | '1week' | '1M' | '6Hutc' | '12Hutc' | '1Dutc' | '3Dutc' | '1Wutc' | '1Mutc'; ⋮---- export interface NewWalletTransfer { fromType: WalletType; toType: WalletType; amount: string; coin: string; clientOid?: string; } ⋮---- export interface NewSpotSubTransfer { fromType: WalletType; toType: WalletType; amount: string; coin: string; clientOid: string; fromUserId: string; toUserId: string; } ⋮---- export interface NewSpotWithdraw { coin: string; address: string; chain: string; tag?: string; amount: string; remark?: string; clientOid?: string; } ⋮---- export interface NewSpotOrder { symbol: string; side: 'buy' | 'sell'; orderType: 'limit' | 'market'; force: OrderTimeInForce; price?: string; size?: string; quantity?: string; clientOrderId?: string; } ⋮---- export type NewBatchSpotOrder = Omit; ⋮---- export interface CancelSpotOrderV2 { symbol: string; orderId?: string; clientOid?: string; } ⋮---- export interface BatchCancelSpotOrderV2 { symbol: string; orderIds?: string[]; clientOids?: string[]; } ⋮---- export interface NewSpotPlanOrder { symbol: string; side: 'buy' | 'sell'; triggerPrice: number; executePrice?: number; size: number; triggerType: 'fill_price' | 'market_price'; orderType: 'limit' | 'market'; clientOid?: string; timeInForceValue?: string; } ⋮---- export interface ModifySpotPlanOrder { orderId?: string; clientOid?: string; triggerPrice: number; executePrice?: number; size?: string; orderType: 'limit' | 'market'; } ⋮---- export interface CancelSpotPlanOrderParams { orderId?: string; clientOid?: string; } ⋮---- export interface GetSpotPlanOrdersParams { symbol: string; pageSize: string; lastEndId?: string; } ⋮---- export interface GetHistoricPlanOrdersParams { symbol: string; pageSize: string; lastEndId?: string; startTime: string; endTime: string; } ⋮---- export interface SpotCandleData { open: string; high: string; low: string; close: string; quoteVol: string; baseVol: string; usdtVol: string; ts: string; } ================ File: src/types/request/v2/common.ts ================ import { FuturesProductTypeV2, MarginType } from '../shared.js'; ⋮---- /** * * * Common | Notice * */ ⋮---- export interface GetAnnouncementsRequestV2 { annType?: string; startTime?: string; endTime?: string; language: string; } ⋮---- /** * * * Common | Public * */ ⋮---- export interface GetTradeRateRequestV2 { symbol: string; businessType: string; } ⋮---- /** * * * Common | Tax * */ ⋮---- export interface GetSpotTransactionsRequestV2 { coin?: string; startTime: string; endTime: string; limit?: string; idLessThan?: string; } ⋮---- export interface GetFuturesTransactionsRequestV2 { productType?: FuturesProductTypeV2; marginCoin?: string; startTime: string; endTime: string; limit?: string; idLessThan?: string; } ⋮---- export interface GetMarginTransactionsRequestV2 { marginType?: MarginType; coin?: string; startTime: string; endTime: string; limit?: string; idLessThan?: string; } ⋮---- export interface GetP2PTransactionsRequestV2 { coin?: string; startTime: string; endTime: string; limit?: string; idLessThan?: string; } ⋮---- /** * * * Common | P2P * */ ⋮---- export interface GetP2PMerchantsRequestV2 { online?: 'yes' | 'no'; idLessThan?: string; limit?: string; } ⋮---- export interface GetMerchantP2POrdersRequestV2 { startTime: string; endTime?: string; idLessThan?: string; limit?: string; status?: string; advNo: string; side?: string; coin?: string; language: string; fiat?: string; orderNo?: string; } ⋮---- export interface GetMerchantAdvertisementsRequestV2 { startTime: string; endTime?: string; idLessThan?: string; limit?: string; status: string; advNo?: string; side: string; coin: string; language?: string; fiat: string; orderBy?: string; payMethodId?: string; sourceType?: string; } ⋮---- /** * * * Common | Virtual Subaccount * */ ⋮---- export interface ModifyVirtualSubRequestV2 { subAccountUid: string; permList: string[]; status: string; } ⋮---- export interface CreateVirtualSubRequestV2 { subAccountName: string; passphrase: string; label: string; ipList?: string[]; permList?: string[]; } ⋮---- export interface CreateVirtualSubApiKeyRequestV2 { subAccountUid: string; passphrase: string; label: string; ipList?: string[]; permList?: string[]; } ⋮---- export interface ModifyVirtualSubApiKeyRequestV2 { subAccountUid: string; subAccountApiKey: string; passphrase: string; label: string; ipList?: string[]; permList?: string[]; } ⋮---- /** * * * Common | Convert * */ ⋮---- export interface ConvertQuoteRequestV2 { fromCoin: string; fromCoinSize?: string; toCoin: string; toCoinSize?: string; } ⋮---- export interface ConvertRequestV2 { fromCoin: string; fromCoinSize: string; cnvtPrice: string; toCoin: string; toCoinSize: string; traceId: string; } ⋮---- export interface GetConvertHistoryRequestV2 { startTime: string; endTime: string; limit?: string; idLessThan?: string; } ⋮---- /** * * * Common | BGB Convert * */ ⋮---- export interface GetConvertBGBHistoryRequestV2 { orderId?: string; startTime: string; endTime: string; limit?: string; idLessThan?: string; } ================ File: src/types/response/v1/futures.ts ================ import { FuturesHoldMode, FuturesHoldSide, FuturesMarginMode, } from '../../request/v1/futuresV1.js'; ⋮---- export interface FuturesMarketTrade { tradeId: string; price: string; size: string; side: 'buy' | 'sell'; timestamp: string; symbol: string; } ⋮---- export interface FuturesAccount { marginCoin: string; locked: number; available: number; crossMaxAvailable: number; fixedMaxAvailable: number; maxTransferOut: number; equity: number; usdtEquity: number; btcEquity: number; crossRiskRate: number; crossMarginLeverage: number; fixedLongLeverage: number; fixedShortLeverage: number; marginMode: string; holdMode: string; } ⋮---- export interface FuturesSymbolRule { baseCoin: string; buyLimitPriceRatio: string; feeRateUpRatio: string; limitOpenTime: string; maintainTime: string; makerFeeRate: string; maxOrderNum: string; maxPositionNum: string; minTradeNum: string; minTradeUSDT: string; offTime: string; openCostUpRatio: string; priceEndStep: string; pricePlace: string; quoteCoin: string; sellLimitPriceRatio: string; sizeMultiplier: string; supportMarginCoins: string[]; symbol: string; symbolName: string; symbolStatus: string; symbolType: string; takerFeeRate: string; volumePlace: string; } ⋮---- export interface FuturesPosition { marginCoin: string; symbol: string; holdSide: FuturesHoldSide; openDelegateCount: string; margin: string; available: string; locked: string; total: string; leverage: number; achievedProfits: string; averageOpenPrice: string; marginMode: FuturesMarginMode; holdMode: FuturesHoldMode; unrealizedPL: string; liquidationPrice: string; keepMarginRate: string; marketPrice: string; cTime: string; } ================ File: src/types/response/v3/public.ts ================ export interface PublicFillV3 { execId: string; price: string; size: string; side: 'sell' | 'buy'; ts: string; } ⋮---- export interface CandlestickV3 extends Array { 0: string; // timestamp 1: string; // open price 2: string; // high price 3: string; // low price 4: string; // close price 5: string; // volume 6: string; // turnover } ⋮---- 0: string; // timestamp 1: string; // open price 2: string; // high price 3: string; // low price 4: string; // close price 5: string; // volume 6: string; // turnover ⋮---- export interface ContractOiV3 { symbol: string; notionalValue: string; totalNotionalValue: string; } ⋮---- export interface CurrentFundingRateV3 { symbol: string; fundingRate: string; fundingRateInterval: string; nextUpdate: string; minFundingRate: string; maxFundingRate: string; } ⋮---- export interface DiscountRateTierV3 { tierStartValue: string; discountRate: string; } ⋮---- export interface DiscountRateV3 { coin: string; list: DiscountRateTierV3[]; } ⋮---- export interface HistoryFundingRateV3 { symbol: string; fundingRate: string; fundingRateTimestamp: string; } ⋮---- export interface MarginLoanV3 { dailyInterest: string; annualInterest: string; limit: string; } ⋮---- export interface OpenInterestItemV3 { symbol: string; openInterest: string; } ⋮---- export interface OpenInterestV3 { list: OpenInterestItemV3[]; ts: string; } ⋮---- export interface PositionTierV3 { tier: string; minTierValue: string; maxTierValue: string; leverage: string; mmr: string; } ⋮---- export interface RiskReserveRecordV3 { balance: string; amount: string; ts: string; } ⋮---- export interface RiskReserveV3 { coin: string; riskReserveRecords: RiskReserveRecordV3[]; } ⋮---- export interface InstrumentV3 { symbol: string; category: | 'SPOT' | 'MARGIN' | 'USDT-FUTURES' | 'COIN-FUTURES' | 'USDC-FUTURES'; baseCoin: string; quoteCoin: string; buyLimitPriceRatio: string; sellLimitPriceRatio: string; feeRateUpRatio: string; minOrderQty: string; maxOrderQty: string; maxMarketOrderQty: string; pricePrecision: string; quantityPrecision: string; quotePrecision: string; minOrderAmount: string; maxSymbolOrderNum: string; maxProductOrderNum: string; status: | 'listed' | 'online' | 'limit_open' | 'limit_close' | 'offline' | 'restrictedAPI'; offTime: string; limitOpenTime: string; maintainTime: string; areaSymbol?: string; // Futures specific fields makerFeeRate?: string; takerFeeRate?: string; openCostUpRatio?: string; priceMultiplier?: string; quantityMultiplier?: string; symbolType?: 'perpetual' | 'delivery'; maxPositionNum?: string; deliveryTime?: string; deliveryStartTime?: string; deliveryPeriod?: string; launchTime?: string; fundInterval?: string; minLeverage?: string; maxLeverage?: string; // Margin specific fields isIsolatedBaseBorrowable?: 'YES' | 'NO'; isIsolatedQuotedBorrowable?: 'YES' | 'NO'; warningRiskRatio?: string; liquidationRiskRatio?: string; maxCrossedLeverage?: string; maxIsolatedLeverage?: string; userMinBorrow?: string; } ⋮---- // Futures specific fields ⋮---- // Margin specific fields ⋮---- export interface OrderBookV3 { a: string[][]; // asks - [price, size] b: string[][]; // bids - [price, size] ts: string; } ⋮---- a: string[][]; // asks - [price, size] b: string[][]; // bids - [price, size] ⋮---- export interface TickerV3 { category: 'SPOT' | 'USDT-FUTURES' | 'COIN-FUTURES' | 'USDC-FUTURES'; symbol: string; lastPrice: string; openPrice24h: string; highPrice24h: string; lowPrice24h: string; ask1Price: string; bid1Price: string; bid1Size: string; ask1Size: string; price24hPcnt: string; volume24h: string; turnover24h: string; // Futures specific fields indexPrice?: string; markPrice?: string; fundingRate?: string; openInterest?: string; deliveryStartTime?: string; deliveryTime?: string; deliveryStatus?: string; } ⋮---- // Futures specific fields ⋮---- export interface ProofOfReservesV3 { merkleRootHash: string; totalReserveRatio: string; list: { coin: string; userAssets: string; platformAssets: string; reserveRatio: string; }[]; } ================ File: src/types/response/v3/trade.ts ================ export interface BatchModifyOrderResponseV3 { orderId: string; clientOid: string; } ⋮---- export interface CancelAllOrdersResponseV3 { list: { orderId: string; clientOid: string; code: string; msg: string; }[]; } ⋮---- export interface CancelBatchOrdersResponseV3 { orderId: string; clientOid: string; code?: string; msg?: string; } ⋮---- export interface CloseAllPositionsResponseV3 { list: { orderId: string; clientOid: string; code: string; msg: string; }[]; } ⋮---- export interface CancelOrderResponseV3 { orderId: string; clientOid: string; } ⋮---- export interface GetMaxOpenAvailableResponseV3 { available: string; maxOpen: string; buyOpenCost: string; sellOpenCost: string; maxBuyOpen: string; maxSellOpen: string; } ⋮---- export interface FeeDetailV3 { feeCoin: string; fee: string; } ⋮---- export interface OrderInfoV3 { orderId: string; clientOid: string; category: string; symbol: string; orderType: string; side: string; price: string; qty: string; amount: string; cumExecQty: string; cumExecValue: string; avgPrice: string; timeInForce: string; orderStatus: string; posSide: string; holdMode: string; reduceOnly: string; feeDetail: FeeDetailV3[]; cancelReason: string; execType: string; stpMode?: string; createdTime: string; updatedTime: string; } ⋮---- export interface FillV3 { execId: string; orderId: string; category: string; symbol: string; orderType: string; side: string; execPrice: string; execQty: string; execValue: string; tradeScope: string; feeDetail: FeeDetailV3[]; execPnl?: string; tradeSide?: string; createdTime: string; updatedTime: string; } ⋮---- export interface UnfilledOrderV3 { orderId: string; clientOid: string; category: string; symbol: string; orderType: string; side: string; price: string; qty: string; amount: string; cumExecQty: string; cumExecValue: string; avgPrice: string; timeInForce: string; orderStatus: string; posSide: string; holdMode: string; reduceOnly: string; feeDetail: FeeDetailV3[]; stpMode?: string; createdTime: string; updatedTime: string; } ⋮---- export interface HistoryOrderV3 { orderId: string; clientOid: string; category: string; symbol: string; orderType: string; side: string; price: string; qty: string; amount: string; cumExecQty: string; cumExecValue: string; avgPrice: string; timeInForce: string; orderStatus: string; posSide: string; holdMode: string; reduceOnly: string; feeDetail: FeeDetailV3[]; cancelReason: string; execType: string; stpMode?: string; createdTime: string; updatedTime: string; } ⋮---- export interface PositionHistoryV3 { positionId: string; category: string; symbol: string; marginCoin: string; holdMode: string; posSide: string; marginMode: string; openPriceAvg: string; closePriceAvg: string; openTotalPos: string; closeTotalPos: string; cumRealisedPnl: string; netProfit: string; totalFunding: string; openFeeTotal: string; closeFeeTotal: string; createdTime: string; updatedTime: string; } ⋮---- export interface CurrentPositionV3 { category: string; symbol: string; marginCoin: string; holdMode: string; posSide: string; marginMode: string; positionBalance: string; available: string; frozen: string; total: string; leverage: string; curRealisedPnl: string; avgPrice: string; positionStatus: string; unrealisedPnl: string; liquidationPrice: string; mmr: string; profitRate: string; markPrice: string; breakEvenPrice: string; totalFunding: string; openFeeTotal: string; closeFeeTotal: string; createdTime: string; updatedTime: string; } ⋮---- 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-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'; ⋮---- export type numberInString = string; ⋮---- export type OrderSide = 'Buy' | 'Sell'; ⋮---- /** * @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'; ⋮---- export type RestClientType = (typeof REST_CLIENT_TYPE_ENUM)[keyof typeof REST_CLIENT_TYPE_ENUM]; ================ File: src/broker-client.ts ================ import { BrokerProductType, BrokerSubAPIKeyModifyRequest, BrokerSubListRequest, BrokerSubWithdrawalRequest, } from './types/request/v1/brokerV1.js'; import { APIResponse } from './types/response/v1/shared.js'; import BaseRestClient from './util/BaseRestClient.js'; import { REST_CLIENT_TYPE_ENUM } from './util/requestUtils.js'; ⋮---- /** * REST API client for the V1 bitget Broker APIs. These are the previous generation of Bitget's APIs and should be considered deprecated. * These will be removed in a future release, once Bitget formally deprecates them. * * @deprecated use RestClientV2 instead */ export class BrokerClient extends BaseRestClient ⋮---- getClientType() ⋮---- /** * * Sub Account Interface * */ ⋮---- /** Get Broker Info */ getBrokerInfo(): Promise> ⋮---- /** Create Sub Account */ createSubAccount( subName: string, remark?: string, ): Promise> ⋮---- /** Get Sub List */ getSubAccounts(params?: BrokerSubListRequest): Promise> ⋮---- /** Modify Sub Account */ modifySubAccount( subUid: string, perm: string, status: 'normal' | 'freeze' | 'del', ): Promise> ⋮---- /** Modify Sub Email */ modifySubEmail(subUid: string, subEmail: string): Promise> ⋮---- /** Get Sub Email */ getSubEmail(subUid: string): Promise> ⋮---- /** Get Sub Spot Assets */ getSubSpotAssets(subUid: string): Promise> ⋮---- /** Get Sub Future Assets */ getSubFutureAssets( subUid: string, productType: BrokerProductType, ): Promise> ⋮---- /** Get Sub Deposit Address (Only Broker) */ getSubDepositAddress( subUid: string, coin: string, chain?: string, ): Promise> ⋮---- /** Sub Withdrawal (Only Broker) */ subWithdrawal(params: BrokerSubWithdrawalRequest): Promise> ⋮---- /** Sub Deposit Auto Transfer (Only Broker) */ setSubDepositAutoTransfer( subUid: string, coin: string, toAccountType: 'spot' | 'mix_usdt' | 'mix_usd' | 'mix_usdc', ): Promise> ⋮---- /** * * Sub API Interface * */ ⋮---- /** Create Sub ApiKey (Only Broker) */ createSubAPIKey( subUid: string, passphrase: string, remark: string, ip: string, perm?: string, ): Promise> ⋮---- /** Get Sub ApiKey List */ getSubAPIKeys(subUid: string): Promise> ⋮---- /** Modify Sub ApiKey (Only Broker) */ modifySubAPIKey( params: BrokerSubAPIKeyModifyRequest, ): Promise> ⋮---- /** * Undocumented endpoints */ ⋮---- getAgentCommissionDetail(params?: { startTime?: string; endTime?: string; limit?: string; idLessThan?: string; }): Promise> ⋮---- /** Get Agent Customer List */ getAgentCustomerList(params?: { startTime?: string; endTime?: string; pageNo?: string; pageSize?: string; uid?: string; referralCode?: string; }): Promise> ⋮---- /** * Get Agent Customer Deposit List * Includes both on-chain deposits and internal transfers * Note: Can only query data within the last 90 days */ getAgentCustomerDepositList(params?: { startTime?: string; endTime?: string; pageNo?: string; pageSize?: string; uid?: string; }): Promise> ⋮---- /** * Get Agent Customer Trade Volume List * Includes trading volume for both spot and futures * Note: Data updates every 10 minutes and can only query last 90 days */ getAgentCustomerTradeVolumeList(params?: { startTime?: string; endTime?: string; pageNo?: string; pageSize?: string; uid?: string; }): Promise> ⋮---- /** * Get Agent Customer Assets List * Returns account balances for customer accounts * Note: Data updates every 10 minutes */ getAgentCustomerAssetsList(params?: { pageNo?: string; pageSize?: string; uid?: string; }): Promise> ⋮---- /** * Get Agent Direct Commissions * Returns commission data for direct customers * Note: Data updates on T+1 (UTC+8) basis and can only query last 90 days */ getAgentCustomerCommissions(params?: { startTime?: string; endTime?: string; idLessThan?: string; limit?: string; uid?: string; coin?: string; symbol?: string; }): Promise> ⋮---- /** * Get Agent Customer KYC Result * Returns KYC verification status for customers */ getAgentCustomerKycResult(params?: { startTime?: string; endTime?: string; pageNo?: string; pageSize?: string; uid?: string; }): Promise> ================ File: src/futures-client.ts ================ import { GetHistoricTradesParams } from './types/request/shared.js'; import { CancelFuturesPlanTPSL, FuturesAccountBillRequest, FuturesBusinessBillRequest, FuturesCandleData, FuturesHistoricPositions, FuturesKlineInterval, FuturesMarginMode, FuturesPagination, FuturesPlanType, FuturesProductType, HistoricPlanOrderTPSLRequest, ModifyFuturesOrder, ModifyFuturesPlanOrder, ModifyFuturesPlanOrderTPSL, ModifyFuturesPlanStopOrder, NewBatchFuturesOrder, NewFuturesOrder, NewFuturesPlanOrder, NewFuturesPlanPositionTPSL, NewFuturesPlanStopOrder, NewFuturesPlanTrailingStopOrder, } from './types/request/v1/futuresV1.js'; import { FuturesAccount, FuturesMarketTrade, FuturesPosition, FuturesSymbolRule, } from './types/response/v1/futures.js'; import { APIResponse, VIPFeeRate } from './types/response/v1/shared.js'; import BaseRestClient from './util/BaseRestClient.js'; import { REST_CLIENT_TYPE_ENUM } from './util/requestUtils.js'; ⋮---- /** * REST API client for the V1 bitget Futures APIs. These are the previous generation of Bitget's APIs and should be considered deprecated. * These will be removed in a future release, once Bitget formally deprecates them. * * @deprecated use RestClientV2 instead */ export class FuturesClient extends BaseRestClient ⋮---- getClientType() ⋮---- /** * * Market * */ ⋮---- /** Get Symbols : Get basic configuration information of all trading pairs (including rules) */ getSymbols( productType: FuturesProductType, ): Promise> ⋮---- /** Get Depth */ getDepth(symbol: string, limit?: string): Promise> ⋮---- /** Get Single Symbol Ticker */ getTicker(symbol: string): Promise> ⋮---- /** Get All Tickers */ getAllTickers(productType: FuturesProductType): Promise> ⋮---- /** Get VIP fee rates */ getVIPFeeRates(): Promise> ⋮---- /** Get most recent trades (up to 500, 100 by default) */ getRecentTrades( symbol: string, limit?: string, ): Promise> ⋮---- /** Get historic trades, up to 30 days at a time. Same-parameter responses are cached for 10 minutes. */ getHistoricTrades( params: GetHistoricTradesParams, ): Promise> ⋮---- /** * @deprecated use getRecentTrades() instead. This method will be removed soon. */ getMarketTrades( symbol: string, limit?: string, ): Promise> ⋮---- /** Get Candle Data */ getCandles( symbol: string, granularity: FuturesKlineInterval, startTime: string, endTime: string, limit?: string, kLineType?: 'market' | 'mark' | 'index', ): Promise> ⋮---- /** Get symbol index price */ getIndexPrice(symbol: string): Promise> ⋮---- /** Get symbol next funding time */ getNextFundingTime(symbol: string): Promise> ⋮---- /** Get Withdraw List */ getHistoricFundingRate( symbol: string, pageSize?: string, pageNo?: string, nextPage?: boolean, ): Promise> ⋮---- /** Get symbol current funding time */ getCurrentFundingRate(symbol: string): Promise> ⋮---- /** Get symbol open interest */ getOpenInterest(symbol: string): Promise> ⋮---- /** Get symbol mark price */ getMarkPrice(symbol: string): Promise> ⋮---- /** Get symbol min/max leverage rules */ getLeverageMinMax(symbol: string): Promise> ⋮---- /** Get Position Tier */ getPositionTier( symbol: string, productType: FuturesProductType, ): Promise> ⋮---- /** * * Account Endpoints * */ ⋮---- /** Get Single Account */ getAccount( symbol: string, marginCoin: string, ): Promise> ⋮---- /** Get Account List */ getAccounts(productType: FuturesProductType): Promise> ⋮---- /** Get Sub Account Contract Assets */ getSubAccountContractAssets( productType: FuturesProductType, ): Promise> ⋮---- /** * This interface is only used to calculate the maximum number of positions that can be opened when the user does not hold a position by default. * The result does not represent the actual number of positions opened. */ getOpenCount( symbol: string, marginCoin: string, openPrice: number, openAmount: number, leverage?: number, ): Promise> ⋮---- /** Change Leverage */ setLeverage( symbol: string, marginCoin: string, leverage: string, holdSide?: string, ): Promise> ⋮---- /** Change Margin */ setMargin( symbol: string, marginCoin: string, amount: string, holdSide?: string, ): Promise> ⋮---- /** Change Margin Mode */ setMarginMode( symbol: string, marginCoin: string, marginMode: FuturesMarginMode, ): Promise> ⋮---- /** Change Hold Mode */ setHoldMode( productType: FuturesProductType, holdMode: 'single_hold' | 'double_hold', ): Promise> ⋮---- /** Get Symbol Position */ getPosition( symbol: string, marginCoin?: string, ): Promise> ⋮---- /** Get Symbol Position V2 */ getPositionV2( symbol: string, marginCoin: string, ): Promise> ⋮---- /** Get All Position */ getPositions( productType: FuturesProductType, marginCoin?: string, ): Promise> ⋮---- /** Get All Position V2 */ getPositionsV2( productType: FuturesProductType, marginCoin?: string, ): Promise> ⋮---- /** Get All historic positions, only supports Query within 3 months */ getHistoryPositions( params: FuturesHistoricPositions, ): Promise> ⋮---- /** Get Account Bill */ getAccountBill(params: FuturesAccountBillRequest): Promise> ⋮---- /** Get Business Account Bill */ getBusinessBill( params: FuturesBusinessBillRequest, ): Promise> ⋮---- /** * * Trade Endpoints * */ ⋮---- /** Place Order */ submitOrder(params: NewFuturesOrder): Promise> ⋮---- /** Batch Order */ batchSubmitOrder( symbol: string, marginCoin: string, orders: NewBatchFuturesOrder[], ): Promise> ⋮---- /** Cancel Order */ cancelOrder( symbol: string, marginCoin: string, orderId?: string, clientOid?: string, ): Promise> ⋮---- /** Batch Cancel Order */ batchCancelOrder( symbol: string, marginCoin: string, orderIds: string[], ): Promise> ⋮---- /** Modify Order */ modifyOrder(params: ModifyFuturesOrder): Promise> ⋮---- /** * Cancel all futures orders for a symbol */ cancelSymbolOrders( symbol: string, marginCoin: string, ): Promise> ⋮---- /** Cancel All Order */ cancelAllOrders( productType: FuturesProductType, marginCoin: string, ): Promise> ⋮---- /** Get Open Order */ getOpenSymbolOrders(symbol: string): Promise> ⋮---- /** Get All Open Order */ getOpenOrders( productType: FuturesProductType, marginCoin: string, ): Promise> ⋮---- /** Get History Orders */ getOrderHistory( symbol: string, startTime: string, endTime: string, pageSize: string, lastEndId?: string, isPre?: boolean, clientOid?: string, ): Promise> ⋮---- /** Get ProductType History Orders */ getProductTypeOrderHistory( productType: FuturesProductType, startTime: string, endTime: string, pageSize: string, lastEndId?: string, isPre?: boolean, clientOid?: string, ): Promise> ⋮---- /** Get order details */ getOrder( symbol: string, orderId?: string, clientOid?: string, ): Promise> ⋮---- /** Get transaction details / history (fills) */ getOrderFills( symbol: string, orderId?: string, pagination?: FuturesPagination, ): Promise> ⋮---- /** Get ProductType Order fill detail */ getProductTypeOrderFills( productType: FuturesProductType, pagination?: FuturesPagination, ): Promise> ⋮---- /** Place Plan order */ submitPlanOrder(params: NewFuturesPlanOrder): Promise> ⋮---- /** Modify Plan Order */ modifyPlanOrder(params: ModifyFuturesPlanOrder): Promise> ⋮---- /** Modify Plan Order TPSL */ modifyPlanOrderTPSL( params: ModifyFuturesPlanOrderTPSL, ): Promise> ⋮---- /** Place Stop order */ submitStopOrder(params: NewFuturesPlanStopOrder): Promise> ⋮---- /** Place Trailing Stop order */ submitTrailingStopOrder( params: NewFuturesPlanTrailingStopOrder, ): Promise> ⋮---- /** Place Position TPSL */ submitPositionTPSL( params: NewFuturesPlanPositionTPSL, ): Promise> ⋮---- /** Modify Stop Order */ modifyStopOrder( params: ModifyFuturesPlanStopOrder, ): Promise> ⋮---- /** Cancel Plan Order (TPSL) */ cancelPlanOrderTPSL( params: CancelFuturesPlanTPSL, ): Promise> ⋮---- /** Cancel Symbol Plan Order (TPSL) */ cancelSymbolPlanOrders( symbol: string, planType: FuturesPlanType, ): Promise> ⋮---- /** Cancel All Trigger Order (TPSL) */ cancelAllPlanOrders( productType: FuturesProductType, planType: FuturesPlanType, ): Promise> ⋮---- /** Get Plan Order (TPSL) List */ getPlanOrderTPSLs( symbol: string, isPlan?: string, productType?: FuturesProductType, ): Promise> ⋮---- /** Get History Plan Orders (TPSL) */ getHistoricPlanOrdersTPSL( params: HistoricPlanOrderTPSLRequest, ): Promise> ⋮---- /** * * Copy Trade Endpoints * */ ⋮---- /** Get Trader Open order */ getCopyTraderOpenOrder( symbol: string, productType: FuturesProductType, pageSize: number, pageNo: number, ): Promise> ⋮---- /** Get Followers Open Order */ getCopyFollowersOpenOrder( symbol: string, productType: FuturesProductType, pageSize: number, pageNo: number, ): Promise> ⋮---- /** Trader Close Position */ closeCopyTraderPosition( symbol: string, trackingNo: string, ): Promise> ⋮---- /** Trader Modify TPSL */ modifyCopyTraderTPSL( symbol: string, trackingNo: string, changes?: { stopProfitPrice?: number; stopLossPrice?: number; }, ): Promise> ⋮---- /** Get Traders History Orders */ getCopyTraderOrderHistory( startTime: string, endTime: string, pageSize: number, pageNo: number, ): Promise> ⋮---- /** Get Trader Profit Summary */ getCopyTraderProfitSummary(): Promise> ⋮---- /** Get Trader History Profit Summary (according to settlement currency) */ getCopyTraderHistoricProfitSummary(): Promise> ⋮---- /** Get Trader History Profit Summary (according to settlement currency and date) */ getCopyTraderHistoricProfitSummaryByDate( marginCoin: string, dateMs: string, pageSize: number, pageNo: number, ): Promise> ⋮---- /** Get Trader Histroy Profit Detail */ getCopyTraderHistoricProfitDetail( marginCoin: string, dateMs: string, pageSize: number, pageNo: number, ): Promise> ⋮---- /** Get Trader Profits Details */ getCopyTraderProfitDetails( pageSize: number, pageNo: number, ): Promise> ⋮---- /** Get CopyTrade Symbols */ getCopyTraderSymbols(): Promise> ⋮---- /** Trader Change CopyTrade symbol */ setCopyTraderSymbols( symbol: string, operation: 'add' | 'delete', ): Promise> ================ File: src/spot-client.ts ================ import { GetHistoricTradesParams, Pagination } from './types/request/shared.js'; import { BatchCancelSpotOrderV2, CancelSpotOrderV2, CancelSpotPlanOrderParams, GetHistoricPlanOrdersParams, GetSpotPlanOrdersParams, ModifySpotPlanOrder, NewBatchSpotOrder, NewSpotOrder, NewSpotPlanOrder, NewSpotSubTransfer, NewSpotWithdraw, NewWalletTransfer, SpotCandleData, SpotKlineInterval, } from './types/request/v1/spotV1.js'; import { APIResponse, VIPFeeRate } from './types/response/v1/shared.js'; import { CoinBalance, SpotMarketTrade, SpotOrderResult, SpotPlanOrder, SymbolRules, } from './types/response/v1/spot.js'; import BaseRestClient from './util/BaseRestClient.js'; import { REST_CLIENT_TYPE_ENUM } from './util/requestUtils.js'; ⋮---- /** * REST API client for the V1 bitget Spot APIs. These are the previous generation of Bitget's APIs and should be considered deprecated. * These will be removed in a future release, once Bitget formally deprecates them. * * @deprecated use RestClientV2 instead */ export class SpotClient extends BaseRestClient ⋮---- getClientType() ⋮---- async fetchServerTime(): Promise ⋮---- /** * * Public * */ /** Get Server Time */ getServerTime(): Promise> ⋮---- /** Get Coin List : Get all coins information on the platform */ getCoins(): Promise> ⋮---- /** Get Symbols : Get basic configuration information of all trading pairs (including rules) */ getSymbols(): Promise> ⋮---- /** Get Single Symbol : Get basic configuration information for one symbol */ getSymbol(symbol: string): Promise> ⋮---- /** * * Market * */ ⋮---- /** Get Single Ticker */ getTicker(symbol: string): Promise> ⋮---- /** Get All Tickers */ getAllTickers(): Promise> ⋮---- /** Get most recent trades (up to 500, 100 by default) */ getRecentTrades( symbol: string, limit?: string, ): Promise> ⋮---- /** Get historic trades, up to 30 days at a time. Same-parameter responses are cached for 10 minutes. */ getHistoricTrades( params: GetHistoricTradesParams, ): Promise> ⋮---- /** * @deprecated use getRecentTrades() instead. This method will be removed soon. */ getMarketTrades( symbol: string, limit?: string, ): Promise> ⋮---- /** Get Candle Data */ getCandles( symbol: string, period: SpotKlineInterval, pagination?: Pagination, ): Promise> ⋮---- /** Get Depth */ getDepth( symbol: string, type: 'step0' | 'step1' | 'step2' | 'step3' | 'step4' | 'step5', limit?: string, ): Promise> ⋮---- /** Get VIP fee rates */ getVIPFeeRates(): Promise> ⋮---- /** * * Wallet Endpoints * */ ⋮---- /** Initiate wallet transfer */ transfer(params: NewWalletTransfer): Promise> ⋮---- /** Initiate wallet transfer (v2 endpoint) */ transferV2(params: NewWalletTransfer): Promise> ⋮---- /** * Transfer main-sub, sub-sub or sub-main */ subTransfer(params: NewSpotSubTransfer): Promise> ⋮---- /** Get Coin Address */ getDepositAddress(coin: string, chain?: string): Promise> ⋮---- /** Withdraw Coins On Chain */ withdraw(params: NewSpotWithdraw): Promise> ⋮---- /** Withdraw Coins On Chain (v2 endpoint) */ withdrawV2(params: NewSpotWithdraw): Promise> ⋮---- /** Inner Withdraw : Internal withdrawal means that both users are on the Bitget platform */ innerWithdraw( coin: string, toUid: string, amount: string, clientOid?: string, ): Promise> ⋮---- /** Inner Withdraw (v2 endpoint) : Internal withdrawal means that both users are on the Bitget platform */ innerWithdrawV2( coin: string, toUid: string, amount: string, clientOid?: string, ): Promise> ⋮---- /** Get Withdraw List */ getWithdrawals( coin: string, startTime: string, endTime: string, pageSize?: string, pageNo?: string, clientOid?: string, ): Promise> ⋮---- /** Get Deposit List */ getDeposits( coin: string, startTime: string, endTime: string, pageSize?: string, pageNo?: string, ): Promise> ⋮---- /** * * Account Endpoints * */ ⋮---- /** Get ApiKey Info */ getApiKeyInfo(): Promise> ⋮---- /** Get Account : get account assets */ getBalance(coin?: string): Promise> ⋮---- /** Get sub Account Spot Asset */ getSubAccountSpotAssets(): Promise> ⋮---- /** Get Bills : get transaction detail flow */ getTransactionHistory(params?: { coinId?: number; groupType?: string; bizType?: string; after?: string; before?: string; limit?: number; }): Promise> ⋮---- /** Get Transfer List */ getTransferHistory(params?: { coinId?: number; fromType?: string; after?: string; before?: string; limit?: number; clientOid?: string; }): Promise> ⋮---- /** * * Trade Endpoints * */ ⋮---- /** Place order */ submitOrder(params: NewSpotOrder): Promise> ⋮---- /** Place orders in batches, up to 50 at a time */ batchSubmitOrder( symbol: string, orderList: NewBatchSpotOrder[], ): Promise> ⋮---- /** Cancel order */ cancelOrder(symbol: string, orderId: string): Promise> ⋮---- /** Cancel order (v2 endpoint - supports orderId or clientOid) */ cancelOrderV2(params?: CancelSpotOrderV2): Promise> ⋮---- /** * Cancel all spot orders for a symbol */ cancelSymbolOrders(symbol: string): Promise> ⋮---- /** Cancel order in batch (per symbol) */ batchCancelOrder( symbol: string, orderIds: string[], ): Promise> ⋮---- /** Cancel order in batch (per symbol). V2 endpoint, supports orderIds or clientOids. */ batchCancelOrderV2( params: BatchCancelSpotOrderV2, ): Promise> ⋮---- /** Get order details */ getOrder( symbol: string, orderId: string, clientOrderId?: string, ): Promise> ⋮---- /** Get order list (open orders) */ getOpenOrders(symbol?: string): Promise> ⋮---- /** Get order history for a symbol */ getOrderHistory( symbol: string, pagination?: Pagination, ): Promise> ⋮---- /** Get transaction details / history (fills) for an order */ getOrderFills( symbol: string, orderId: string, pagination?: Pagination, ): Promise> ⋮---- /** Place plan order */ submitPlanOrder( params: NewSpotPlanOrder, ): Promise> ⋮---- /** Modify plan order */ modifyPlanOrder( params: ModifySpotPlanOrder, ): Promise> ⋮---- /** Cancel plan order */ cancelPlanOrder( params: CancelSpotPlanOrderParams, ): Promise> ⋮---- /** Get current plan orders */ getCurrentPlanOrders(params: GetSpotPlanOrdersParams): Promise< APIResponse<{ nextFlag: boolean; endId: number; orderList: SpotPlanOrder[]; }> > { return this.postPrivate('/api/spot/v1/plan/currentPlan', params); ⋮---- /** Get history plan orders */ getHistoricPlanOrders(params: GetHistoricPlanOrdersParams): Promise< APIResponse<{ nextFlag: boolean; endId: number; orderList: SpotPlanOrder[]; }> > { return this.postPrivate('/api/spot/v1/plan/historyPlan', params); ================ File: webpack/webpack.config.js ================ function generateConfig(name) ⋮---- // Add '.ts' and '.tsx' as resolvable extensions. ⋮---- // All files with a '.ts' or '.tsx' extension will be handled by 'ts-loader'. ⋮---- // All output '.js' files will have any sourcemaps re-processed by 'source-map-loader'. ================ File: .nvmrc ================ v22.17.1 ================ File: jest.config.ts ================ /** * For a detailed explanation regarding each configuration property, visit: * https://jestjs.io/docs/configuration */ ⋮---- import type { Config } from 'jest'; ⋮---- // All imported modules in your tests should be mocked automatically // automock: false, ⋮---- // Stop running tests after `n` failures // bail: 0, bail: false, // enable to stop test when an error occur, ⋮---- // The directory where Jest should store its cached dependency information // cacheDirectory: "/private/var/folders/kf/2k3sz4px6c9cbyzj1h_b192h0000gn/T/jest_dx", ⋮---- // Automatically clear mock calls, instances, contexts and results before every test ⋮---- // Indicates whether the coverage information should be collected while executing the test ⋮---- // An array of glob patterns indicating a set of files for which coverage information should be collected ⋮---- // The directory where Jest should output its coverage files ⋮---- // An array of regexp pattern strings used to skip coverage collection // coveragePathIgnorePatterns: [ // "/node_modules/" // ], ⋮---- // Indicates which provider should be used to instrument code for coverage ⋮---- // A list of reporter names that Jest uses when writing coverage reports // coverageReporters: [ // "json", // "text", // "lcov", // "clover" // ], ⋮---- // An object that configures minimum threshold enforcement for coverage results // coverageThreshold: undefined, ⋮---- // A path to a custom dependency extractor // dependencyExtractor: undefined, ⋮---- // Make calling deprecated APIs throw helpful error messages // errorOnDeprecated: false, ⋮---- // The default configuration for fake timers // fakeTimers: { // "enableGlobally": false // }, ⋮---- // Force coverage collection from ignored files using an array of glob patterns // forceCoverageMatch: [], ⋮---- // A path to a module which exports an async function that is triggered once before all test suites // globalSetup: undefined, ⋮---- // A path to a module which exports an async function that is triggered once after all test suites // globalTeardown: undefined, ⋮---- // A set of global variables that need to be available in all test environments // globals: {}, ⋮---- // The maximum amount of workers used to run your tests. Can be specified as % or a number. E.g. maxWorkers: 10% will use 10% of your CPU amount + 1 as the maximum worker number. maxWorkers: 2 will use a maximum of 2 workers. // maxWorkers: "50%", ⋮---- // An array of directory names to be searched recursively up from the requiring module's location // moduleDirectories: [ // "node_modules" // ], ⋮---- // An array of file extensions your modules use ⋮---- // modulePaths: ['src'], ⋮---- // A map from regular expressions to module names or to arrays of module names that allow to stub out resources with a single module // moduleNameMapper: {}, ⋮---- // An array of regexp pattern strings, matched against all module paths before considered 'visible' to the module loader // modulePathIgnorePatterns: [], ⋮---- // Activates notifications for test results // notify: false, ⋮---- // An enum that specifies notification mode. Requires { notify: true } // notifyMode: "failure-change", ⋮---- // A preset that is used as a base for Jest's configuration // preset: undefined, ⋮---- // Run tests from one or more projects // projects: undefined, ⋮---- // Use this configuration option to add custom reporters to Jest // reporters: undefined, ⋮---- // Automatically reset mock state before every test // resetMocks: false, ⋮---- // Reset the module registry before running each individual test // resetModules: false, ⋮---- // A path to a custom resolver // resolver: undefined, ⋮---- // Automatically restore mock state and implementation before every test // restoreMocks: false, ⋮---- // The root directory that Jest should scan for tests and modules within // rootDir: undefined, ⋮---- // A list of paths to directories that Jest should use to search for files in // roots: [ // "" // ], ⋮---- // Allows you to use a custom runner instead of Jest's default test runner // runner: "jest-runner", ⋮---- // The paths to modules that run some code to configure or set up the testing environment before each test // setupFiles: [], ⋮---- // A list of paths to modules that run some code to configure or set up the testing framework before each test // setupFilesAfterEnv: [], ⋮---- // The number of seconds after which a test is considered as slow and reported as such in the results. // slowTestThreshold: 5, ⋮---- // A list of paths to snapshot serializer modules Jest should use for snapshot testing // snapshotSerializers: [], ⋮---- // The test environment that will be used for testing // testEnvironment: "jest-environment-node", ⋮---- // Options that will be passed to the testEnvironment // testEnvironmentOptions: {}, ⋮---- // Adds a location field to test results // testLocationInResults: false, ⋮---- // The glob patterns Jest uses to detect test files ⋮---- // "**/__tests__/**/*.[jt]s?(x)", ⋮---- // An array of regexp pattern strings that are matched against all test paths, matched tests are skipped // testPathIgnorePatterns: [ // "/node_modules/" // ], ⋮---- // The regexp pattern or array of patterns that Jest uses to detect test files // testRegex: [], ⋮---- // This option allows the use of a custom results processor // testResultsProcessor: undefined, ⋮---- // This option allows use of a custom test runner // testRunner: "jest-circus/runner", ⋮---- // A map from regular expressions to paths to transformers // transform: undefined, ⋮---- // An array of regexp pattern strings that are matched against all source file paths, matched files will skip transformation // transformIgnorePatterns: [ // "/node_modules/", // "\\.pnp\\.[^\\/]+$" // ], ⋮---- // Prevents import esm module error from v1 axios release, issue #5026 ⋮---- // An array of regexp pattern strings that are matched against all modules before the module loader will automatically return a mock for them // unmockedModulePathPatterns: undefined, ⋮---- // Indicates whether each individual test should be reported during the run // verbose: undefined, verbose: true, // report individual test ⋮---- // An array of regexp patterns that are matched against all source file paths before re-running tests in watch mode // watchPathIgnorePatterns: [], ⋮---- // Whether to use watchman for file crawling // watchman: true, ================ File: postBuild.sh ================ #!/bin/bash # # Add package.json files to cjs/mjs subtrees # cat >dist/cjs/package.json <dist/mjs/package.json < 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/futures.ts ================ import { FuturesPlanTypeV2, FuturesProductTypeV2 } from '../shared.js'; import { FuturesKlineInterval } from '../v1/futuresV1.js'; ⋮---- export type FuturesKlineTypeV2 = 'MARKET' | 'MARK' | 'INDEX'; ⋮---- export interface FuturesAccountBillRequestV2 { productType: FuturesProductTypeV2; symbol?: string; coin?: string; businessType?: string; idLessThan?: string; startTime?: string; endTime?: string; limit?: string; } ⋮---- /** * * * Futures | Market * */ ⋮---- export interface FuturesMergeDepthRequestV2 { symbol: string; productType: FuturesProductTypeV2; precision?: 'scale0' | 'scale1' | 'scale2' | 'scale3'; limit?: '1' | '5' | '15' | '50' | 'max'; } ⋮---- export interface FuturesRecentTradesRequestV2 { symbol: string; productType: FuturesProductTypeV2; limit?: string; } ⋮---- export interface FuturesHistoricTradesRequestV2 { symbol: string; productType: FuturesProductTypeV2; limit?: string; idLessThan?: string; startTime?: string; endTime?: string; } ⋮---- export interface FuturesCandlesRequestV2 { symbol: string; productType: FuturesProductTypeV2; granularity: FuturesKlineInterval; startTime?: string; endTime?: string; kLineType?: FuturesKlineTypeV2; limit?: string; } ⋮---- /** * * * Futures | Account * */ ⋮---- export interface FuturesSingleAccountRequestV2 { symbol: string; productType: FuturesProductTypeV2; marginCoin: string; } ⋮---- export interface FuturesInterestHistoryRequestV2 { productType: 'USDT-FUTURES' | 'SUSDT-FUTURES'; coin?: string; idLessThan?: string; startTime?: string; endTime?: string; limit?: string; } ⋮---- export interface FuturesOpenCountRequestV2 { symbol: string; productType: FuturesProductTypeV2; marginCoin: string; openAmount: string; openPrice: string; leverage?: string; } ⋮---- export interface FuturesSetAutoMarginRequestV2 { symbol: string; autoMargin: 'on' | 'off'; marginCoin: string; amount: string; holdSide?: 'long' | 'short'; } ⋮---- export interface FuturesSetLeverageRequestV2 { symbol: string; productType: FuturesProductTypeV2; marginCoin: string; leverage: string; holdSide?: 'long' | 'short'; } ⋮---- export interface FuturesSetPositionMarginRequestV2 { symbol: string; productType: FuturesProductTypeV2; marginCoin: string; holdSide: 'long' | 'short'; amount: string; } ⋮---- export interface FuturesSetMarginModeRequestV2 { symbol: string; productType: FuturesProductTypeV2; marginCoin: string; marginMode: 'isolated' | 'crossed'; } ⋮---- /** * * * Futures | Position * */ ⋮---- export interface FuturesHistoricalPositionsRequestV2 { symbol?: string; productType?: FuturesProductTypeV2; idLessThan?: string; startTime?: string; endTime?: string; limit?: string; } ⋮---- /** * * * Futures | Trade * */ ⋮---- export interface FuturesPlaceOrderRequestV2 { symbol: string; productType: FuturesProductTypeV2; marginMode: 'isolated' | 'crossed'; marginCoin: string; size: string; price?: string; side: 'buy' | 'sell'; tradeSide?: 'open' | 'close'; orderType: 'limit' | 'market'; force?: 'ioc' | 'fok' | 'gtc' | 'post_only'; clientOid?: string; reduceOnly?: 'YES' | 'NO'; presetStopSurplusPrice?: string; presetStopLossPrice?: string; stpMode?: 'none' | 'cancel_taker' | 'cancel_maker' | 'cancel_both'; } ⋮---- export interface FuturesReversalOrderRequestV2 { symbol: string; productType: FuturesProductTypeV2; marginCoin: string; size: string; side?: 'buy' | 'sell'; tradeSide?: 'open' | 'close'; clientOid?: string; } ⋮---- interface FuturesBatchOrderItem { size: string; price?: string; side: 'buy' | 'sell'; tradeSide?: 'open' | 'close'; orderType: 'limit' | 'market'; force?: 'ioc' | 'fok' | 'gtc' | 'post_only'; clientOid?: string; reduceOnly?: 'YES' | 'NO'; presetStopSurplusPrice?: string; presetStopLossPrice?: string; stpMode?: 'none' | 'cancel_taker' | 'cancel_maker' | 'cancel_both'; } ⋮---- export interface FuturesBatchOrderRequestV2 { symbol: string; productType: FuturesProductTypeV2; marginCoin: string; marginMode: 'isolated' | 'crossed'; orderList: FuturesBatchOrderItem[]; } ⋮---- export interface FuturesModifyOrderRequestV2 { orderId?: string; clientOid?: string; symbol: string; productType: FuturesProductTypeV2; newClientOid: string; newSize?: string; newPrice?: string; newPresetStopSurplusPrice?: string; newPresetStopLossPrice?: string; } ⋮---- export interface FuturesCancelOrderRequestV2 { symbol: string; productType: FuturesProductTypeV2; marginCoin?: string; orderId?: string; clientOid?: string; } ⋮---- interface FuturesBatchCancelOrderItem { orderId?: string; clientOid?: string; } ⋮---- export interface FuturesBatchCancelOrderRequestV2 { orderIdList?: FuturesBatchCancelOrderItem[]; symbol?: string; productType: FuturesProductTypeV2; marginCoin?: string; } ⋮---- export interface FuturesFlashClosePositionsRequestV2 { symbol?: string; productType: FuturesProductTypeV2; holdSide?: 'long' | 'short'; } ⋮---- export interface FuturesGetOrderRequestV2 { symbol: string; productType: FuturesProductTypeV2; orderId?: string; clientOid?: string; } ⋮---- export interface FuturesGetOrderFillsRequestV2 { orderId?: string; symbol?: string; productType: FuturesProductTypeV2; idLessThan?: string; startTime?: string; endTime?: string; limit?: string; } ⋮---- export interface FuturesGetHistoricalFillsRequestV2 { orderId?: string; symbol?: string; productType: FuturesProductTypeV2; startTime?: string; endTime?: string; idLessThan?: string; limit?: string; } ⋮---- export interface FuturesGetOpenOrdersRequestV2 { orderId?: string; clientOid?: string; symbol?: string; productType: FuturesProductTypeV2; status?: 'live' | 'partially_filled'; idLessThan?: string; startTime?: string; endTime?: string; limit?: string; } ⋮---- export type FuturesOrderSourceV2 = | 'normal' | 'market' | 'profit_market' | 'loss_market' | 'Trader_delegate' | 'trader_profit' | 'trader_loss' | 'reverse' | 'trader_reverse' | 'profit_limit' | 'loss_limit' | 'liquidation' | 'delivery_close_long' | 'delivery_close_short' | 'pos_profit_limit' | 'pos_profit_market' | 'pos_loss_limit' | 'pos_loss_market'; ⋮---- export interface FuturesGetHistoryOrdersRequestV2 { orderId?: string; clientOid?: string; symbol?: string; productType: FuturesProductTypeV2; idLessThan?: string; orderSource?: FuturesOrderSourceV2; startTime?: string; endTime?: string; limit?: string; } ⋮---- export interface FuturesCancelAllOrdersRequestV2 { symbol?: string; productType: FuturesProductTypeV2; marginCoin?: string; requestTime?: string; receiveWindow?: string; } ⋮---- /** * * * Futures | Trigger Orders * */ ⋮---- export type FuturesTriggerTypeV2 = 'fill_price' | 'mark_price'; ⋮---- export type FuturesStpModeV2 = | 'none' | 'cancel_taker' | 'cancel_maker' | 'cancel_both'; ⋮---- export interface FuturesTPSLOrderRequestV2 { marginCoin: string; productType: FuturesProductTypeV2; symbol: string; planType: FuturesPlanTypeV2; triggerPrice: string; triggerType?: FuturesTriggerTypeV2; executePrice?: string; holdSide: 'long' | 'short' | 'buy' | 'sell'; size: string; rangeRate?: string; clientOid?: string; stpMode?: FuturesStpModeV2; } ⋮---- export type FuturesTriggerPriceTypeV2 = | 'fill_price' | 'mark_price' | 'index_price'; ⋮---- export interface FuturesPlanOrderRequestV2 { planType: 'normal_plan' | 'track_plan'; symbol: string; productType: FuturesProductTypeV2; marginMode: 'isolated' | 'crossed'; marginCoin: string; size: string; price?: string; callbackRatio?: string; triggerPrice: string; triggerType: 'mark_price' | 'fill_price'; side: 'buy' | 'sell'; tradeSide?: 'open' | 'close'; orderType: 'limit' | 'market'; clientOid?: string; reduceOnly?: 'YES' | 'NO'; stopSurplusTriggerPrice?: string; stopSurplusExecutePrice?: string; stopSurplusTriggerType?: FuturesTriggerPriceTypeV2; stopLossTriggerPrice?: string; stopLossExecutePrice?: string; stopLossTriggerType?: FuturesTriggerPriceTypeV2; stpMode?: FuturesStpModeV2; } ⋮---- export interface FuturesModifyTPSLOrderRequestV2 { orderId?: string; clientOid?: string; marginCoin: string; productType: FuturesProductTypeV2; symbol: string; triggerPrice: string; triggerType?: 'fill_price' | 'mark_price'; executePrice?: string; size: string; rangeRate?: string; } ⋮---- export interface FuturesModifyPlanOrderRequestV2 { planType: 'normal_plan' | 'track_plan'; orderId?: string; clientOid?: string; symbol: string; productType: FuturesProductTypeV2; newSize?: string; newPrice?: string; newCallbackRatio?: string; newTriggerPrice?: string; newTriggerType?: 'fill_price' | 'mark_price'; newStopSurplusTriggerPrice?: string; newStopSurplusExecutePrice?: string; newStopSurplusTriggerType?: FuturesTriggerPriceTypeV2; newStopLossTriggerPrice?: string; newStopLossExecutePrice?: string; newStopLossTriggerType?: FuturesTriggerPriceTypeV2; } ⋮---- export interface FuturesGetPlanOrdersRequestV2 { orderId?: string; clientOid?: string; symbol?: string; planType: 'normal_plan' | 'track_plan' | 'profit_loss'; productType: FuturesProductTypeV2; idLessThan?: string; startTime?: string; endTime?: string; limit?: string; } ⋮---- interface FuturesCancelPlanOrderItemV2 { orderId?: string; clientOid?: string; } ⋮---- export type FuturesPlanOrderTypeV2 = | 'normal_plan' | 'profit_plan' | 'loss_plan' | 'pos_profit' | 'pos_loss' | 'moving_plan'; ⋮---- export interface FuturesCancelPlanOrderRequestV2 { orderIdList?: FuturesCancelPlanOrderItemV2[]; symbol?: string; productType: FuturesProductTypeV2; marginCoin?: string; planType?: FuturesPlanOrderTypeV2; } ⋮---- export type FuturesPlanStatusV2 = 'executed' | 'fail_trigger' | 'cancelled'; ⋮---- export interface FuturesGetHistoryPlanOrdersRequestV2 { orderId?: string; clientOid?: string; planType: 'normal_plan' | 'track_plan' | 'profit_loss'; planStatus?: FuturesPlanStatusV2; symbol?: string; productType: FuturesProductTypeV2; idLessThan?: string; startTime?: string; endTime?: string; limit?: string; } ⋮---- /** * * * Futures | Union Margin * */ ⋮---- export interface GetUnionTransferLimitsRequestV2 { coin: string; } ⋮---- export interface UnionConvertRequestV2 { coin: string; amount: string; } ⋮---- /** * * * Futures | Account | Max Openable Quantity * */ ⋮---- export interface FuturesMaxOpenRequestV2 { symbol: string; productType: FuturesProductTypeV2; marginCoin: string; posSide: 'long' | 'short'; orderType: 'limit' | 'market'; openPrice?: string; } ⋮---- /** * * * Futures | Account | Liquidation Price * */ ⋮---- export interface FuturesLiquidationPriceRequestV2 { symbol: string; productType: FuturesProductTypeV2; marginCoin: string; posSide: 'long' | 'short'; orderType: 'limit' | 'market'; openAmount: string; openPrice?: string; } ⋮---- /** * * * Futures | Account | Isolated Symbols * */ ⋮---- export interface FuturesIsolatedSymbolsRequestV2 { productType: FuturesProductTypeV2; } ================ File: src/types/response/v3/account.ts ================ // Account Management Response Types export interface AccountSymbolConfigV3 { category: string; symbol: string; marginMode: string; leverage: string; } ⋮---- export interface AccountCoinConfigV3 { coin: string; leverage: string; } ⋮---- export interface AccountSettingsV3 { assetMode: string; holdMode: string; symbolConfigList: AccountSymbolConfigV3[]; coinConfigList: AccountCoinConfigV3[]; } ⋮---- export interface AccountAssetV3 { coin: string; equity: string; usdValue: string; balance: string; available: string; debt: string; locked: 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; assets: AccountAssetV3[]; } ⋮---- export interface ConvertRecordV3 { fromCoin: string; fromCoinSize: string; toCoin: string; toCoinSize: string; price: string; ts: string; } ⋮---- export interface FinancialRecordV3 { category: string; id: string; symbol: string; coin: string; type: string; amount: string; fee: string; balance: string; ts: string; } ⋮---- export interface PaymentCoinV3 { coin: string; size: string; amount: string; } ⋮---- export interface RepayableCoinV3 { coin: string; size: string; amount: string; } ⋮---- export interface RepayResponseV3 { result: string; repayAmount: string; } ⋮---- // Sub-account Management Response Types ⋮---- 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; } ⋮---- export interface UpdateSubAccountApiKeyResponseV3 { note: string; apiKey: string; type: string; permissions: string[]; ips: string[]; } ⋮---- export interface CreateSubAccountResponseV3 { username: string; subUid: string; status: string; note: string; createdTime: string; updatedTime: string; } ⋮---- export interface SubAccountV3 { subUid: string; username: string; status: string; accountMode: string; type: string; note: string; createdTime: string; updatedTime: string; } ⋮---- // Transfer Response Types ⋮---- export interface TransferResponseV3 { transferId: string; } ⋮---- export interface SubTransferRecordV3 { transferId: string; oldTransferId?: string; fromType: string; toType: string; amount: string; coin: string; fromUserId: string; toUserId: string; status: string; clientOid: string; createdTime: string; updatedTime: string; } ⋮---- export interface SubUnifiedAssetV3 { coin: string; equity: string; usdValue: string; balance: string; available: string; debt: string; locked: string; } ⋮---- export interface SubUnifiedAssetV3 { subUid: string; cursor: string; assets: SubUnifiedAssetV3[]; } ⋮---- export interface GetFeeRateResponseV3 { makerFeeRate: string; takerFeeRate: string; } ⋮---- export interface FundingAssetV3 { coin: string; available: string; frozen: string; balance: string; } ⋮---- // Deposit Response Types ⋮---- export interface DepositAddressV3 { address: string; chain: string; coin: string; tag: string; url: 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; } ⋮---- // Withdraw Response Types ⋮---- export interface WithdrawResponseV3 { orderId: string; clientOid: 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 MaxTransferableV3 { coin: string; maxTransfer: string; borrowMaxTransfer: string; } ⋮---- export interface OpenInterestLimitV3 { symbol: string; singleUserLimit: string; masterSubLimit: string; marketMakerLimit: string; } ⋮---- export interface TaxRecordV3 { id: string; coin: string; type: string; amount: string; fee: string; balance: string; ts: string; } ================ File: src/websocket-client-legacy-v1.ts ================ /* eslint-disable @typescript-eslint/no-unsafe-declaration-merging */ import { EventEmitter } from 'events'; import WebSocket from 'isomorphic-ws'; ⋮---- import { BitgetInstType, WebsocketClientOptions, WSClientConfigurableOptions, WsKey, WsTopic, WsTopicSubscribeEventArgs, } from './types/websockets/ws-general.js'; import { DefaultLogger } from './util/logger.js'; import { isWsPong } from './util/requestUtils.js'; import { signMessage } from './util/webCryptoAPI.js'; import { getMaxTopicsPerSubscribeEvent, getWsKeyForTopicV1, isPrivateChannel, neverGuard, safeTerminateWs, WS_AUTH_ON_CONNECT_KEYS, WS_BASE_URL_MAP, WS_KEY_MAP, } from './util/websocket-util.js'; import WsStore from './util/WsStore.js'; import { WsConnectionStateEnum } from './util/WsStore.types.js'; ⋮---- export type WsClientEvent = | 'open' | 'update' | 'close' | 'exception' | 'reconnect' | 'reconnected' | 'response'; ⋮---- interface WebsocketClientEvents { /** Connection opened. If this connection was previously opened and reconnected, expect the reconnected event instead */ open: (evt: { wsKey: WsKey; event: any }) => void; /** Reconnecting a dropped connection */ reconnect: (evt: { wsKey: WsKey; event: any }) => void; /** Successfully reconnected a connection that dropped */ reconnected: (evt: { wsKey: WsKey; event: any }) => void; /** Connection closed */ close: (evt: { wsKey: WsKey; event: any }) => void; /** Received reply to websocket command (e.g. after subscribing to topics) */ response: (response: any & { wsKey: WsKey }) => void; /** Received data for topic */ update: (response: any & { wsKey: WsKey }) => void; /** Exception from ws client OR custom listeners (e.g. if you throw inside your event handler) */ exception: (response: any & { wsKey: WsKey }) => void; /** Confirmation that a connection successfully authenticated */ authenticated: (event: { wsKey: WsKey; event: any }) => void; } ⋮---- /** Connection opened. If this connection was previously opened and reconnected, expect the reconnected event instead */ ⋮---- /** Reconnecting a dropped connection */ ⋮---- /** Successfully reconnected a connection that dropped */ ⋮---- /** Connection closed */ ⋮---- /** Received reply to websocket command (e.g. after subscribing to topics) */ ⋮---- /** Received data for topic */ ⋮---- /** Exception from ws client OR custom listeners (e.g. if you throw inside your event handler) */ ⋮---- /** Confirmation that a connection successfully authenticated */ ⋮---- // Type safety for on and emit handlers: https://stackoverflow.com/a/61609010/880837 export declare interface WebsocketClientLegacyV1 { on( event: U, listener: WebsocketClientEvents[U], ): this; emit( event: U, ...args: Parameters ): boolean; } ⋮---- on( event: U, listener: WebsocketClientEvents[U], ): this; ⋮---- emit( event: U, ...args: Parameters ): boolean; ⋮---- /** * @deprecated use WebsocketClientV2 instead */ export class WebsocketClientLegacyV1 extends EventEmitter ⋮---- constructor( options: WSClientConfigurableOptions, logger?: typeof DefaultLogger, ) ⋮---- /** * Subscribe to topics & track/persist them. They will be automatically resubscribed to if the connection drops/reconnects. * @param wsTopics topic or list of topics * @param isPrivateTopic optional - the library will try to detect private topics, you can use this to mark a topic as private (if the topic isn't recognised yet) */ public subscribe( wsTopics: WsTopicSubscribeEventArgs[] | WsTopicSubscribeEventArgs, isPrivateTopic?: boolean, ) ⋮---- // Persist this topic to the expected topics list ⋮---- // if connected, send subscription request ⋮---- // if not authenticated, dont sub to private topics yet. // This'll happen automatically once authenticated ⋮---- // start connection process if it hasn't yet begun. Topics are automatically subscribed to on-connect ⋮---- /** * Unsubscribe from topics & remove them from memory. They won't be re-subscribed to if the connection reconnects. * @param wsTopics topic or list of topics * @param isPrivateTopic optional - the library will try to detect private topics, you can use this to mark a topic as private (if the topic isn't recognised yet) */ public unsubscribe( wsTopics: WsTopicSubscribeEventArgs[] | WsTopicSubscribeEventArgs, isPrivateTopic?: boolean, ) ⋮---- // unsubscribe request only necessary if active connection exists ⋮---- /** Get the WsStore that tracks websockets & topics */ public getWsStore(): typeof this.wsStore ⋮---- public close(wsKey: WsKey, force?: boolean) ⋮---- public closeAll(force?: boolean) ⋮---- /** * Request connection of all dependent (public & private) websockets, instead of waiting for automatic connection by library */ public connectAll(): Promise[] ⋮---- /** * Request connection to a specific websocket, instead of waiting for automatic connection. */ private async connect(wsKey: WsKey): Promise ⋮---- const url = this.getWsUrl(wsKey); // + authParams; ⋮---- private parseWsError(context: string, error: any, wsKey: WsKey) ⋮---- private async getWsAuthSignature( apiKey: string | undefined, apiSecret: string | undefined, apiPass: string | undefined, recvWindow: number = 0, ): Promise< ⋮---- /** Get a signature, build the auth request and send it */ private async sendAuthRequest(wsKey: WsKey): Promise ⋮---- // console.log('ws auth req', request); ⋮---- private reconnectWithDelay(wsKey: WsKey, connectionDelayMs: number) ⋮---- private ping(wsKey: WsKey) ⋮---- private clearTimers(wsKey: WsKey) ⋮---- // Send a ping at intervals private clearPingTimer(wsKey: WsKey) ⋮---- // Expect a pong within a time limit private clearPongTimer(wsKey: WsKey) ⋮---- /** * @private Use the `subscribe(topics)` method to subscribe to topics. Send WS message to subscribe to topics. */ private requestSubscribeTopics( wsKey: WsKey, topics: WsTopicSubscribeEventArgs[], ) ⋮---- /** * @private Use the `unsubscribe(topics)` method to unsubscribe from topics. Send WS message to unsubscribe from topics. */ private requestUnsubscribeTopics( wsKey: WsKey, topics: WsTopicSubscribeEventArgs[], ) ⋮---- public tryWsSend(wsKey: WsKey, wsMessage: string) ⋮---- private connectToWsUrl(url: string, wsKey: WsKey): WebSocket ⋮---- private async onWsOpen(event: WebSocket.Event, wsKey: WsKey) ⋮---- // Some websockets require an auth packet to be sent after opening the connection ⋮---- // Reconnect to topics known before it connected // Private topics will be resubscribed to once reconnected ⋮---- /** Handle subscription to private topics _after_ authentication successfully completes asynchronously */ private onWsAuthenticated(wsKey: WsKey) ⋮---- private onWsMessage(event: unknown, wsKey: WsKey) ⋮---- // any message can clear the pong timer - wouldn't get a message if the ws wasn't working ⋮---- // messageType: typeof msg, // messageString: JSON.stringify(msg), ⋮---- // messageType: typeof msg, // messageString: JSON.stringify(msg), ⋮---- // fallback emit anyway ⋮---- private onWsClose(event: unknown, wsKey: WsKey) ⋮---- private getWs(wsKey: WsKey) ⋮---- private setWsState(wsKey: WsKey, state: WsConnectionStateEnum) ⋮---- private getWsUrl(wsKey: WsKey): 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. * * @deprecated use WebsocketClientV2 instead */ public subscribeTopic( instType: BitgetInstType, topic: WsTopic, instId: string = 'default', ) ⋮---- /** * 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. * * @deprecated use WebsocketClientV2 instead */ public unsubscribeTopic( instType: BitgetInstType, topic: WsTopic, instId: string = 'default', ) ================ 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 { 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'; ⋮---- /** * 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< ⋮---- 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[] ⋮---- /** * 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). * * 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 ⋮---- /** * 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, ) ⋮---- /** * * * Internal methods required to integrate with the BaseWSClient * * */ ⋮---- protected sendPingEvent(wsKey: WsKey): void ⋮---- protected sendPongEvent(wsKey: WsKey): void ⋮---- protected isWsPing(data: any): boolean ⋮---- protected isWsPong(data: any): boolean ⋮---- protected isPrivateTopicRequest( _request: WsTopicRequest, wsKey: WsKey, ): boolean ⋮---- protected getPrivateWSKeys(): WsKey[] ⋮---- protected isAuthOnConnectWsKey(wsKey: WsKey): boolean ⋮---- protected async getWsUrl(wsKey: WsKey): Promise ⋮---- protected getMaxTopicsPerSubscribeEvent(wsKey: WsKey): number | null ⋮---- /** * @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>[]> ⋮---- // Previously used to track topics in a request. Keeping this for subscribe/unsubscribe requests, no need for incremental values ⋮---- /** { "op":"subscribe", "args":[ { "instType":"spot", "topic":"ticker", "symbol":"BTCUSDT" }, { "instType":"spot", "topic":"candle5m", "symbol":"BTCUSDT" } ] } */ ⋮---- // const request = { // topic: 'ticker', // payload: { instType: 'spot', symbol: 'BTCUSDT' }, // }; // becomes: // const request = { // topic: 'ticker', // instType: 'spot', // symbol: 'BTCUSDT', // }; ⋮---- private async getWsAuthSignature( wsKey: WsKey, ): Promise< ⋮---- private async signMessage( paramsStr: string, secret: string, method: 'hex' | 'base64', algorithm: SignAlgorithm, ): Promise ⋮---- protected async getWsAuthRequestEvent( wsKey: WsKey, ): Promise> ⋮---- /** * Abstraction called to sort ws events into emittable event types (response to a request, data update, etc) */ protected resolveEmittableEvents( wsKey: WsKey, event: MessageEventLike, ): EmittableEvent[] ⋮---- /** * WS API response handling */ ⋮---- // 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), ⋮---- // 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 * * @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 ⋮---- // this.logger.trace('sendWSAPIRequest(): assertIsAuthenticated(${wsKey})...'); ⋮---- // 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: 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: src/websocket-api-client.ts ================ import { CancelOrderRequestV3 } from './types/request/v3/trade.js'; import { CancelOrderResponseV3 } 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'; ⋮---- /** * 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; } ⋮---- /** * 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(....)`. */ ⋮---- /** * 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 ⋮---- constructor( options?: WSClientConfigurableOptions & Partial, logger?: DefaultLogger, ) ⋮---- public getWSClient(): WebsocketClientV3 ⋮---- public setTimeOffsetMs(newOffset: number): void ⋮---- /* * 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 * * @returns */ submitNewOrder( category: BitgetInstTypeV3, params: WSAPIPlaceOrderRequestV3, ): Promise> ⋮---- /** * Submit a new order * * https://www.bitget.com/api-doc/uta/websocket/private/Batch-Place-Order-Channel * * @returns */ placeBatchOrders( category: BitgetInstTypeV3, params: WSAPIPlaceOrderRequestV3[], ): 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 * * @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> ⋮---- /** * * * * * * * * Private methods for handling some of the convenience/automation provided by the WS API Client * * * * * * * */ ⋮---- private setupDefaultEventListeners() ⋮---- /** * General event handlers for monitoring the WebsocketClient */ ⋮---- // Blind JSON.stringify can fail on circular references ⋮---- // JSON.stringify({ ...data, target: 'WebSocket' }), ================ File: src/types/websockets/ws-api.ts ================ import { WS_KEY_MAP } from '../../util/websocket-util.js'; import { CancelOrderRequestV3 } from '../request/v3/trade.js'; import { CancelOrderResponseV3 } 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'; ⋮---- 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[]; } ⋮---- export interface WSAPIRequestFlags { /** If true, will skip auth requirement for WS API connection */ authIsOptional?: boolean | undefined; } ⋮---- /** If true, will skip auth requirement for WS API connection */ ⋮---- 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 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; } ⋮---- /** Auto-generated */ ⋮---- /** * List of operations supported for this WsKey (connection) */ export interface WsAPIWsKeyTopicMap { [WS_KEY_MAP.v3Private]: WSAPIOperation; } ⋮---- /** * 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/api-doc/uta/websocket/private/Batch-Cancel-Order-Channel 'batch-cancel': CancelOrderRequestV3[]; } ⋮---- // 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/api-doc/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/api-doc/uta/websocket/private/Batch-Cancel-Order-Channel 'batch-cancel': 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/api-doc/uta/websocket/private/Batch-Cancel-Order-Channel ================ File: src/index.ts ================ ================ File: .eslintrc.cjs ================ // 'no-unused-vars': ['warn'], ================ File: src/types/websockets/ws-general.ts ================ import { RestClientOptions } from '../../util/requestUtils.js'; import { WS_KEY_MAP } from '../../util/websocket-util.js'; import { FuturesProductTypeV2 } from '../request/shared.js'; ⋮---- export type BitgetInstType = 'SP' | 'SPBL' | 'MC' | 'UMCBL' | 'DMCBL'; export type BitgetInstTypeV2 = 'SPOT' | FuturesProductTypeV2; export type BitgetInstTypeV3 = | 'UTA' // for account-level topics | 'spot' | 'usdt-futures' | 'coin-futures' | 'usdc-futures'; ⋮---- | 'UTA' // for account-level topics ⋮---- /** * * V1 list of topics for WebSocket consumers * */ ⋮---- export type WsPublicSpotTopic = | 'ticker' | 'candle1W' | 'candle1D' | 'candle12H' | 'candle4H' | 'candle1H' | 'candle30m' | 'candle15m' | 'candle5m' | 'candle1m' | 'books' | 'books5' | 'trade'; ⋮---- // Futures currently has the same public topics as spot export type WsPublicFuturesTopic = WsPublicSpotTopic; export type WsPrivateSpotTopic = 'account' | 'orders'; ⋮---- export type WsPrivateFuturesTopic = | 'account' | 'positions' | 'orders' | 'ordersAlgo'; ⋮---- export type WsPublicTopic = WsPublicSpotTopic | WsPublicFuturesTopic; ⋮---- export type WsPrivateTopic = WsPrivateSpotTopic | WsPrivateFuturesTopic; export type WsTopic = WsPublicTopic | WsPrivateTopic; ⋮---- /** * * V2 list of topics for WebSocket consumers * */ ⋮---- export type WsPublicTopicV2 = | 'index-price' // margin only | 'ticker' | 'candle1m' | 'candle5m' | 'candle15m' | 'candle30m' | 'candle1H' | 'candle4H' | 'candle6H' | 'candle12H' | 'candle1D' | 'candle3D' | 'candle1W' | 'candle1M' | 'candle6Hutc' | 'candle12Hutc' | 'candle1Dutc' | 'candle3Dutc' | 'candle1Wutc' | 'candle1Mutc' | 'trade' | 'books' | 'books1' | 'books5' | 'books15'; ⋮---- | 'index-price' // margin only ⋮---- // Also update PRIVATE_TOPICS_V2 if this is updated export type WSPrivateTopicFuturesV2 = | 'positions' | 'orders-algo' | 'positions-history'; ⋮---- // Also update PRIVATE_TOPICS_V2 if this is updated export type WSPrivateTopicMarginV2 = | 'orders-crossed' | 'account-crossed' | 'account-isolated' | 'orders-isolated'; ⋮---- // Also update PRIVATE_TOPICS_V2 if this is updated export type WsPrivateTopicV2 = | 'account' | 'orders' | WSPrivateTopicFuturesV2 | WSPrivateTopicMarginV2; ⋮---- export type WsTopicV2 = WsPublicTopicV2 | WsPrivateTopicV2; ⋮---- /** * * V3 / UTA list of topics for WebSocket consumers * */ export type WsPublicTopicV3 = 'ticker' | 'kline' | 'books' | 'publicTrade'; // Also update PRIVATE_TOPICS_V3 if this is updated export type WsPrivateTopicV3 = 'account' | 'position' | 'fill' | 'order'; export type WsTopicV3 = WsPublicTopicV3 | WsPrivateTopicV3; ⋮---- /** This is used to differentiate between each of the available websocket streams */ export type WsKey = (typeof WS_KEY_MAP)[keyof typeof WS_KEY_MAP]; ⋮---- /** * Event args for subscribing/unsubscribing */ ⋮---- export interface WsTopicSubscribeEventArgs { instType: BitgetInstType; channel: WsTopic; instId?: string; } ⋮---- export type WsTopicSubscribePublicArgsV2 = { instType: BitgetInstTypeV2; channel: WsPublicTopicV2; /** The symbol, e.g. "BTCUSDT" */ instId: string; }; ⋮---- /** The symbol, e.g. "BTCUSDT" */ ⋮---- export type WsInstIdChannelsV2 = | 'orders' | WSPrivateTopicFuturesV2 | 'orders-crossed' | 'orders-isolated'; ⋮---- export type WsTopicSubscribePrivateInstIdArgsV2 = { instType: BitgetInstTypeV2; channel: WsInstIdChannelsV2; /** The symbol, e.g. "BTCUSDT" */ instId?: string; }; ⋮---- /** The symbol, e.g. "BTCUSDT" */ ⋮---- export type WsCoinChannelsV2 = | 'account' | 'account-crossed' | 'account-isolated'; ⋮---- export type WsTopicSubscribePrivateCoinArgsV2 = { instType: BitgetInstTypeV2; channel: WsCoinChannelsV2; coin: 'default' | string; }; ⋮---- export type WsTopicSubscribePrivateArgsV2 = | WsTopicSubscribePrivateInstIdArgsV2 | WsTopicSubscribePrivateCoinArgsV2; ⋮---- export type WsTopicSubscribeEventArgsV2 = | WsTopicSubscribePublicArgsV2 | WsTopicSubscribePrivateArgsV2; ⋮---- /** General configuration for the WebsocketClient */ export interface WSClientConfigurableOptions { /** Your API key */ apiKey?: string; /** Your API secret */ apiSecret?: string; /** The passphrase you set when creating the API Key (NOT your account password) */ apiPass?: string; /** * Set to `true` to connect to Bitget's demo trading WebSockets: * * - V2: https://www.bitget.com/api-doc/common/demotrading/websocket * - V3/UTA: https://www.bitget.com/api-doc/uta/guide#demo-trading */ demoTrading?: boolean; /** Define a recv window when preparing a private websocket signature. This is in milliseconds, so 5000 == 5 seconds */ recvWindow?: number; // Disable ping/pong ws heartbeat mechanism (not recommended) disableHeartbeat?: boolean; /** How often to check if the connection is alive */ pingInterval?: number; /** How long to wait for a pong (heartbeat reply) before assuming the connection is dead */ pongTimeout?: number; /** Delay in milliseconds before respawning the connection */ reconnectTimeout?: number; requestOptions?: RestClientOptions; wsOptions?: { protocols?: string[]; agent?: any; }; wsUrl?: string; /** * Allows you to provide a custom "signMessage" function, e.g. to use node's much faster createHmac method * * Look in the examples folder for a demonstration on using node's createHmac instead. */ customSignMessageFn?: (message: string, secret: string) => Promise; } ⋮---- /** Your API key */ ⋮---- /** Your API secret */ ⋮---- /** The passphrase you set when creating the API Key (NOT your account password) */ ⋮---- /** * Set to `true` to connect to Bitget's demo trading WebSockets: * * - V2: https://www.bitget.com/api-doc/common/demotrading/websocket * - V3/UTA: https://www.bitget.com/api-doc/uta/guide#demo-trading */ ⋮---- /** Define a recv window when preparing a private websocket signature. This is in milliseconds, so 5000 == 5 seconds */ ⋮---- // Disable ping/pong ws heartbeat mechanism (not recommended) ⋮---- /** How often to check if the connection is alive */ ⋮---- /** How long to wait for a pong (heartbeat reply) before assuming the connection is dead */ ⋮---- /** Delay in milliseconds before respawning the connection */ ⋮---- /** * Allows you to provide a custom "signMessage" function, e.g. to use node's much faster createHmac method * * Look in the examples folder for a demonstration on using node's createHmac instead. */ ⋮---- export interface WebsocketClientOptions extends WSClientConfigurableOptions { pingInterval: number; pongTimeout: number; reconnectTimeout: number; recvWindow: number; authPrivateConnectionsOnConnect: boolean; authPrivateRequests: boolean; } ================ 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'; ⋮---- 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[] ⋮---- /** 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 ⋮---- /** * 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', ) ⋮---- /** * 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', ) ⋮---- /** * 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 ⋮---- /** * 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, ) ⋮---- /** * * * Internal methods required to integrate with the BaseWSClient * * */ ⋮---- protected sendPingEvent(wsKey: WsKey): void ⋮---- protected sendPongEvent(wsKey: WsKey): void ⋮---- protected isWsPing(data: any): boolean ⋮---- protected isWsPong(data: any): boolean ⋮---- protected isPrivateTopicRequest( _request: WsTopicRequest, wsKey: WsKey, ): boolean ⋮---- protected getPrivateWSKeys(): WsKey[] ⋮---- protected isAuthOnConnectWsKey(wsKey: WsKey): boolean ⋮---- protected async getWsUrl(wsKey: WsKey): Promise ⋮---- protected getMaxTopicsPerSubscribeEvent(wsKey: WsKey): number | null ⋮---- /** * @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>[]> ⋮---- // Previously used to track topics in a request. Keeping this for subscribe/unsubscribe requests, no need for incremental values ⋮---- /** { "op":"subscribe", "args":[ { "instType":"SPOT", "channel":"ticker", "instId":"BTCUSDT" }, { "instType":"SPOT", "channel":"candle5m", "instId":"BTCUSDT" } ] } */ ⋮---- // const request = { // topic: 'ticker', // payload: { instType: 'SPOT', instId: 'BTCUSDT' }, // }; // becomes: // const request = { // channel: 'ticker', // instType: 'SPOT', // instId: 'BTCUSDT', // }; ⋮---- private async getWsAuthSignature( wsKey: WsKey, ): Promise< ⋮---- private async signMessage( paramsStr: string, secret: string, method: SignEncodeMethod, algorithm: SignAlgorithm, ): Promise ⋮---- protected async getWsAuthRequestEvent( wsKey: WsKey, ): Promise> ⋮---- /** * 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 ⋮---- // v2 authentication event ⋮---- // messageType: typeof msg, // messageString: JSON.stringify(msg), ⋮---- // messageType: typeof msg, // messageString: JSON.stringify(msg), ⋮---- // fallback emit anyway ⋮---- /** * @deprecrated not supported by Bitget's V2 API offering */ async sendWSAPIRequest(): Promise ================ File: src/rest-client-v2.ts ================ import { FuturesProductTypeV2, MarginType } from './types/request/shared.js'; import { CreateSubAccountApiKeyRequestV2, GetAllSubDepositWithdrawalRequestV2, GetBrokerCommissionsRequestV2, GetBrokerOrderCommissionRequestV2, GetBrokerRebateInfoRequestV2, GetBrokerSubaccountsRequestV2, GetBrokerTotalCommissionRequestV2, GetBrokerTradeVolumeRequestV2, GetSubAccountsRequestV2, ModifySubAccountApiKeyRequestV2, ModifySubRequestV2, SubDepositRecordsRequestV2, SubWithdrawalRecordsRequestV2, SubWithdrawalRequestV2, } from './types/request/v2/broker.js'; import { ConvertQuoteRequestV2, ConvertRequestV2, CreateVirtualSubApiKeyRequestV2, CreateVirtualSubRequestV2, GetAnnouncementsRequestV2, GetConvertBGBHistoryRequestV2, GetConvertHistoryRequestV2, GetFuturesTransactionsRequestV2, GetMarginTransactionsRequestV2, GetMerchantAdvertisementsRequestV2, GetMerchantP2POrdersRequestV2, GetP2PMerchantsRequestV2, GetP2PTransactionsRequestV2, GetSpotTransactionsRequestV2, GetTradeRateRequestV2, ModifyVirtualSubApiKeyRequestV2, ModifyVirtualSubRequestV2, } from './types/request/v2/common.js'; import { CloseFuturesFollowerPositionsRequestV2, CopyTradingProductTypeV2, FuturesTraderSymbolSettingRequestV2, GetFollowerFuturesCurrentTrackingOrdersRequestV2, GetFollowerFuturesHistoryTrackingOrdersRequestV2, GetFuturesFollowerTradersRequestV2, GetFuturesTraderCurrentOrdersRequestV2, GetFuturesTraderFollowersRequestV2, GetFuturesTraderHistoryOrdersRequestV2, GetFuturesTraderProfitShareDetailRequestV2, GetSpotFollowerHistoryOrdersRequestV2, GetSpotFollowerOpenOrdersRequestV2, GetSpotTraderCurrentOrdersRequestV2, GetSpotTraderFollowersRequestV2, GetSpotTraderHistoryOrdersRequestV2, GetSpotTraderHistoryProfitRequestV2, ModifyFuturesTraderOrderTPSLRequestV2, SpotFollowerCopyTradeSettingV2, UpdateFuturesFollowerSettingsRequestV2, UpdateFuturesFollowerTPSLRequestV2, } from './types/request/v2/copytrading.js'; import { BorrowLoanRequestV2, GetEarnSavingsAssetsRequestV2, GetEarnSavingsRecordsRequestV2, GetLiquidationRecordsRequestV2, GetLoanEstInterestAndBorrowableRequestV2, GetLoanHistoryRequestV2, GetLoanPledgeRateHistoryRequestV2, GetLoanRepayHistoryRequestV2, GetSharkfinAssetsRequestV2, GetSharkfinRecordsRequestV2, ModifyLoanPledgeRateRequestV2, RedeemSavingsRequestV2, RepayLoanRequestV2, } from './types/request/v2/earn.js'; import { FuturesAccountBillRequestV2, FuturesBatchCancelOrderRequestV2, FuturesBatchOrderRequestV2, FuturesCancelAllOrdersRequestV2, FuturesCancelOrderRequestV2, FuturesCancelPlanOrderRequestV2, FuturesCandlesRequestV2, FuturesFlashClosePositionsRequestV2, FuturesGetHistoricalFillsRequestV2, FuturesGetHistoryOrdersRequestV2, FuturesGetHistoryPlanOrdersRequestV2, FuturesGetOpenOrdersRequestV2, FuturesGetOrderFillsRequestV2, FuturesGetOrderRequestV2, FuturesGetPlanOrdersRequestV2, FuturesHistoricalPositionsRequestV2, FuturesHistoricTradesRequestV2, FuturesInterestHistoryRequestV2, FuturesIsolatedSymbolsRequestV2, FuturesLiquidationPriceRequestV2, FuturesMaxOpenRequestV2, FuturesMergeDepthRequestV2, FuturesModifyOrderRequestV2, FuturesModifyPlanOrderRequestV2, FuturesModifyTPSLOrderRequestV2, FuturesOpenCountRequestV2, FuturesPlaceOrderRequestV2, FuturesPlanOrderRequestV2, FuturesRecentTradesRequestV2, FuturesReversalOrderRequestV2, FuturesSetAutoMarginRequestV2, FuturesSetLeverageRequestV2, FuturesSetMarginModeRequestV2, FuturesSetPositionMarginRequestV2, FuturesSingleAccountRequestV2, FuturesTPSLOrderRequestV2, GetUnionTransferLimitsRequestV2, UnionConvertRequestV2, } from './types/request/v2/futures.js'; import { GetBorrowHistoryRequestV2, GetFinancialHistoryRequestV2, GetHistoryOrdersRequestV2, GetInterestHistoryRequestV2, GetLiquidationHistoryRequestV2, GetMarginCurrentOrdersRequestV2, GetMarginLiquidationOrdersRequestV2, GetMarginOrderFillsRequestV2, GetRepayHistoryRequestV2, MarginBatchOrdersRequestV2, MarginPlaceOrderRequestV2, } from './types/request/v2/margin.js'; import { GetSpotAccountBillsRequestV2, GetSpotCurrentPlanOrdersRequestV2, GetSpotDepositRecordRequestV2, GetSpotFillsRequestV2, GetSpotHistoryOrdersRequestV2, GetSpotHistoryPlanOrdersRequestV2, GetSpotOpenOrdersRequestV2, GetSpotOrderInfoRequestV2, GetSpotSubAccountDepositRecordRequestV2, GetSpotTransferRecordRequestV2, GetSpotWithdrawalRecordRequestV2, SpotAccountTypeV2, SpotBatchCancelOrderRequestV2, SpotBatchOrderRequestV2, SpotCancelandSubmitOrderRequestV2, SpotCancelOrderRequestV2, SpotCandlesRequestV2, SpotHistoricCandlesRequestV2, SpotHistoricTradesRequestV2, SpotMainSubTransferRecordRequestV2, SpotModifyPlanOrderRequestV2, SpotOrderRequestV2, SpotPlanOrderRequestV2, SpotSubAccountTransferRequestV2, SpotTransferRequestV2, SpotWithdrawalRequestV2, } from './types/request/v2/spot.js'; import { APIResponse } from './types/response/v1/shared.js'; import { AllSubDepositWithdrawalRecordV2, BrokerCommissionV2, BrokerOrderCommissionV2, BrokerRebateInfoV2, BrokerSubaccountFutureAssetV2, BrokerSubaccountInfoV2, BrokerSubaccountSpotAssetV2, BrokerSubaccountV2, BrokerSubaccountWithdrawalV2, BrokerTotalCommissionV2, BrokerTradeVolumeV2, CreateSubaccountApiKeyResponseV2, CreateSubaccountDepositAddressV2, CreateSubaccountResponseV2, ModifySubaccountApiKeyResponseV2, ModifySubaccountResponseV2, SubaccountApiKeyV2, SubaccountDepositV2, SubaccountEmailV2, } from './types/response/v2/broker.js'; import { AnnouncementV2, BGBConvertCoinV2, BGBConvertHistoryV2, BotAssetV2, ConvertBGBResponseV2, ConvertCurrencyV2, ConvertQuotedPriceV2, ConvertRecordV2, ConvertTradeResponseV2, CreateVirtualSubAccountAndApiKeyV2, CreateVirtualSubAccountApiKeyV2, CreateVirtualSubAccountV2, FundingAssetV2, FuturesActiveBuySellVolumeV2, FuturesActiveLongShortAccountV2, FuturesActiveLongShortPositionV2, FuturesLongShortRatioV2, FuturesTransactionRecordV2, IsolatedMarginBorrowingRatioV2, LeveragedLongShortRatioV2, MarginLoanGrowthRateV2, MarginTransactionRecordV2, ModifyVirtualSubAccountApiKeyV2, P2PMerchantAdvertismentV2, P2PMerchantInfoV2, P2PMerchantOrdersV2, P2PMerchantOrderV2, P2PMerchantV2, SpotFundFlowV2, SpotTransactionRecordV2, SpotWhaleNetFlowV2, SubAccountApiKeyItemV2, VirtualSubAccountV2, } from './types/response/v2/common.js'; import { CTFuturesFollowerCurrentOrdersV2, CTFuturesFollowerHistoryOrdersV2, CTFuturesFollowerMyTradersV2, CTFuturesFollowerSettingsV2, CTFuturesTraderCurrentOrdersV2, CTFuturesTraderHistoryOrderV2, CTFuturesTraderHistoryProfitSummaryV2, CTFuturesTraderMyFollowersV2, CTFuturesTraderProfitShareHistoryV2, CTFuturesTraderSymbolSettingsV2, CTFuturesTraderTotalOrderSummaryV2, CTSpotFollowerCurrentOrdersV2, CTSpotFollowerFollowConfigurationV2, CTSpotFollowerHistoryOrdersV2, CTSpotFollowerMyTradersV2, CTSpotTraderCurrentTrackingOrdersV2, CTSpotTraderFollowerListV2, CTSpotTraderHistoryOrdersV2, CTSpotTraderHistoryProfitSharingV2, CTSpotTraderProfitSummaryV2, CTSpotTraderTotalOrderDetailV2, CTSpotTraderUnrealizedProfitV2, } from './types/response/v2/copy-trading.js'; import { EarnLoanCurrenciesV2, EarnLoanDebtsV2, EarnLoanHistoryV2, EarnLoanLiquidationRecordsV2, EarnLoanOrdersV2, EarnLoanPledgeRateHistoryV2, EarnLoanRepayHistoryV2, EarnLoanRepayResponseV2, EarnSavingsAccountV2, EarnSavingsAssetsV2, EarnSavingsProductsV2, EarnSavingsRecordsV2, EarnSavingsSubscriptionDetailV2, EarnSharkfinAccountV2, EarnSharkfinAssetsV2, EarnSharkfinProductsV2, EarnSharkfinRecordsV2, EarnSharkfinSubscriptionDetailV2, } from './types/response/v2/earn.js'; import { FuturesAccountBillV2, FuturesAccountsV2, FuturesAccountV2, FuturesBatchOrderResponseV2, FuturesCancelAllOrdersV2, FuturesCancelPlanOrderV2, FuturesCandlestickV2, FuturesClosePositionResponseV2, FuturesContractConfigV2, FuturesDiscountRatesV2, FuturesFillV2, FuturesFundingTimeV2, FuturesHistoricalFundingRateV2, FuturesHistoryInterestRateV2, FuturesHistoryOrderV2, FuturesHistoryPlanOrderV2, FuturesHistoryPositionV2, FuturesInterestExchangeRateV2, FuturesInterestHistoryV2, FuturesIsolatedSymbolV2, FuturesLiquidationPriceV2, FuturesMaxOpenV2, FuturesMergeDepthV2, FuturesOpenInterestV2, FuturesOpenOrderV2, FuturesOrderDetailV2, FuturesOrderFillV2, FuturesPendingPlanOrderV2, FuturesPositionTierV2, FuturesPositionV2, FuturesSubAccountAssetV2, FuturesSymbolPriceV2, FuturesTickerV2, FuturesTriggerSubOrderV2, FuturesVipFeeRateV2, SetLeverageResponseV2, SetMarginModeResponseV2, UnionConfigV2, UnionConvertV2, UnionSwitchUsdtV2, UnionTransferLimitsV2, } from './types/response/v2/futures.js'; import { CrossInterestRateAndLimitResponseV2, CrossMaxBorrowableResponseV2, CrossMaxTransferableResponseV2, CrossTierConfigurationResponseV2, IsolatedInterestRateAndLimitResponseV2, IsolatedMaxBorrowableResponseV2, IsolatedMaxTransferableResponseV2, IsolatedTierConfigurationResponseV2, MarginAccountAssetV2, MarginBatchOrdersResponseV2, MarginBorrowHistoryItemV2, MarginCurrencyV2, MarginCurrentOrderV2, MarginFinancialHistoryItemV2, MarginHistoryOrderV2, MarginInterestHistoryItemV2, MarginLiquidationHistoryItemV2, MarginLiquidationOrderV2, MarginOrderFillV2, MarginRepaymentHistoryItemV2, } from './types/response/v2/margin.js'; import { CancelAndSubmitSpotOrderResponseV2, SpotAccountAssetV2, SpotAccountBillV2, SpotAccountInfoV2, SpotCancelPlanOrdersV2, SpotCandlestickV2, SpotCoinInfoV2, SpotCurrentPlanOrderV2, SpotDepositAddressV2, SpotDepositRecordV2, SpotFillV2, SpotHistoryPlanOrderV2, SpotMainSubTransferRecordV2, SpotMergeDepthV2, SpotOpenOrderV2, SpotOrderBookDepthV2, SpotOrderInfoV2, SpotPlanSubOrderV2, SpotSubAccountAssetsV2, SpotSubAccountDepositRecordV2, SpotSymbolInfoV2, SpotTickerV2, SpotTradeV2, SpotTransferRecordV2, SpotVipFeeRateV2, SpotWithdrawalRecordV2, SubmitSpotBatchOrdersResponseV2, } from './types/response/v2/spot.js'; import BaseRestClient from './util/BaseRestClient.js'; import { REST_CLIENT_TYPE_ENUM } from './util/requestUtils.js'; import { assertMarginType } from './util/type-guards.js'; ⋮---- /** * REST API client for all V2 endpoints */ export class RestClientV2 extends BaseRestClient ⋮---- getClientType() ⋮---- /** * * Custom SDK functions * */ ⋮---- /** * This method is used to get the latency and time sync between the client and the server. * This is not official API endpoint and is only used for internal testing purposes. * Use this method to check the latency and time sync between the client and the server. * Final values might vary slightly, but it should be within few ms difference. * If you have any suggestions or improvements to this measurement, please create an issue or pull request on GitHub. */ async fetchLatencySummary(): Promise ⋮---- // Adjust server time by adding estimated one-way latency ⋮---- // Calculate time difference between adjusted server time and local time ⋮---- async fetchServerTime(): Promise ⋮---- /** * * Bitget misc functions * */ ⋮---- /** * * * Common * * */ ⋮---- /** * * * Common | Notice * */ ⋮---- getAnnouncements( params?: GetAnnouncementsRequestV2, ): Promise> ⋮---- /** * * * Common | Public * */ ⋮---- getServerTime(): Promise< APIResponse<{ serverTime: string; }> > { return this.get('/api/v2/public/time'); ⋮---- getTradeRate(params: GetTradeRateRequestV2): Promise< APIResponse<{ makerFeeRate: string; takerFeeRate: string; }> > { return this.getPrivate('/api/v2/common/trade-rate', params); ⋮---- /** * * * Common | Tax * */ ⋮---- getSpotTransactionRecords( params: GetSpotTransactionsRequestV2, ): Promise> ⋮---- getFuturesTransactionRecords( params: GetFuturesTransactionsRequestV2, ): Promise> ⋮---- getMarginTransactionRecords( params: GetMarginTransactionsRequestV2, ): Promise> ⋮---- getP2PTransactionRecords( params: GetP2PTransactionsRequestV2, ): Promise> ⋮---- /** * * * Common | P2P * */ ⋮---- getP2PMerchantList(params?: GetP2PMerchantsRequestV2): Promise< APIResponse<{ merchantList: P2PMerchantV2[]; minMerchantId: string; }> > { return this.getPrivate('/api/v2/p2p/merchantList', params); ⋮---- getP2PMerchantInfo(): Promise> ⋮---- getP2PMerchantOrders(params: GetMerchantP2POrdersRequestV2): Promise< APIResponse<{ orderList: P2PMerchantOrderV2[]; minOrderId: string; }> > { return this.getPrivate('/api/v2/p2p/orderList', params); ⋮---- getP2PMerchantAdvertisementList( params: GetMerchantAdvertisementsRequestV2, ): Promise< APIResponse<{ advList: P2PMerchantAdvertismentV2[]; minAdvId: string; }> > { return this.getPrivate('/api/v2/p2p/advList', params); ⋮---- /** * * * Common | Trading insights * */ ⋮---- getSpotWhaleNetFlowData(params: { symbol: string; }): Promise> ⋮---- getFuturesActiveTakerBuySellVolumeData(params: { symbol: string; period?: string; }): Promise> ⋮---- getFuturesActiveLongShortPositionData(params: { symbol: string; period?: string; }): Promise> ⋮---- getFuturesLongShortRatio(params: { symbol: string; period?: string; coin?: string; }): Promise> ⋮---- getMarginLoanGrowthRate(params: { symbol: string; period?: string; coin?: string; }): Promise> ⋮---- getIsolatedMarginBorrowingRatio(params: { symbol: string; period?: string; }): Promise> ⋮---- getFuturesActiveBuySellVolumeData(params: { symbol: string; period?: string; }): Promise> ⋮---- getSpotFundFlow(params: { symbol: string; period?: string; }): Promise> ⋮---- getTradeDataSupportSymbols(): Promise< APIResponse<{ spotList: string[]; futureList: string[]; }> > { return this.get('/api/v2/spot/market/support-symbols'); ⋮---- getSpotFundNetFlowData(params: { symbol: string }): Promise< APIResponse< { netFlow: string; ts: string; }[] > > { return this.get('/api/v2/spot/market/fund-net-flow', params); ⋮---- getFuturesActiveLongShortAccountData(params: { symbol: string; period?: string; }): Promise> ⋮---- /** * * * Common | Virtual Subaccount * */ ⋮---- createVirtualSubaccount(params: { subAccountList: string[]; }): Promise> ⋮---- modifyVirtualSubaccount(params: ModifyVirtualSubRequestV2): Promise< APIResponse<{ result: string; }> > { return this.postPrivate('/api/v2/user/modify-virtual-subaccount', params); ⋮---- batchCreateVirtualSubaccountAndAPIKey( params: CreateVirtualSubRequestV2, ): Promise> ⋮---- getVirtualSubaccounts(params?: { limit?: string; idLessThan?: string; status?: 'normal' | 'freeze'; }): Promise< APIResponse<{ endId: string; subAccountList: VirtualSubAccountV2[]; }> > { return this.getPrivate('/api/v2/user/virtual-subaccount-list', params); ⋮---- createVirtualSubaccountAPIKey( params: CreateVirtualSubApiKeyRequestV2, ): Promise> ⋮---- modifyVirtualSubaccountAPIKey( params: ModifyVirtualSubApiKeyRequestV2, ): Promise> ⋮---- getVirtualSubaccountAPIKeys(params: { subAccountUid: string; }): Promise> ⋮---- /** * * * Common | Assets * */ getFundingAssets(params?: { coin?: string; }): Promise> ⋮---- getBotAccount(params?: { accountType?: string; }): Promise> ⋮---- /** Get assets overview */ getBalances(): Promise< APIResponse< { accountType: string; usdtBalance: string; }[] > > { return this.getPrivate('/api/v2/account/all-account-balance'); ⋮---- /** * * * Common | Convert * */ ⋮---- getConvertCoins(): Promise> ⋮---- getConvertQuotedPrice( params: ConvertQuoteRequestV2, ): Promise> ⋮---- convert( params: ConvertRequestV2, ): Promise> ⋮---- getConvertHistory(params: GetConvertHistoryRequestV2): Promise< APIResponse<{ dataList: ConvertRecordV2[]; endId: string; }> > { return this.getPrivate('/api/v2/convert/convert-record', params); ⋮---- /** * * * Common | BGB Convert * */ ⋮---- getConvertBGBCoins(): Promise< APIResponse<{ coinList: BGBConvertCoinV2[]; }> > { return this.getPrivate('/api/v2/convert/bgb-convert-coin-list'); ⋮---- convertBGB(params: { coinList: string; }): Promise> ⋮---- getConvertBGBHistory( params: GetConvertBGBHistoryRequestV2, ): Promise> ⋮---- /** * * * Spot * * */ ⋮---- /** * * * Spot | Market * */ ⋮---- getSpotCoinInfo(params?: { coin?: string; }): Promise> ⋮---- getSpotSymbolInfo(params?: { symbol?: string; }): Promise> ⋮---- getSpotVIPFeeRate(): Promise> ⋮---- getSpotTicker(params?: { symbol?: string; }): Promise> ⋮---- getSpotMergeDepth(params: { symbol: string; precision?: string; limit?: string; }): Promise> ⋮---- getSpotOrderBookDepth(params: { symbol: string; type?: string; limit?: string; }): Promise> ⋮---- getSpotCandles( params: SpotCandlesRequestV2, ): Promise> ⋮---- getSpotHistoricCandles( params: SpotHistoricCandlesRequestV2, ): Promise> ⋮---- getSpotRecentTrades(params: { symbol: string; limit?: string; }): Promise> ⋮---- getSpotHistoricTrades( params: SpotHistoricTradesRequestV2, ): Promise> ⋮---- /** * * * Spot | Trade * */ ⋮---- spotSubmitOrder(params: SpotOrderRequestV2): Promise< APIResponse<{ orderId: string; clientOid: string; }> > { return this.postPrivate('/api/v2/spot/trade/place-order', params); ⋮---- spotCancelandSubmitOrder( params: SpotCancelandSubmitOrderRequestV2, ): Promise> ⋮---- spotBatchCancelandSubmitOrder(params: { orderList: SpotCancelandSubmitOrderRequestV2[]; }): Promise> ⋮---- spotCancelOrder(params: SpotCancelOrderRequestV2): Promise< APIResponse<{ orderId: string; clientOid: string; }> > { return this.postPrivate('/api/v2/spot/trade/cancel-order', params); ⋮---- spotBatchSubmitOrders( params: SpotBatchOrderRequestV2, ): Promise> ⋮---- spotBatchCancelOrders( params: SpotBatchCancelOrderRequestV2, ): Promise> ⋮---- spotCancelSymbolOrder(params: { symbol: string }): Promise< APIResponse<{ symbol: string; }> > { return this.postPrivate('/api/v2/spot/trade/cancel-symbol-order', params); ⋮---- getSpotOrder( params?: GetSpotOrderInfoRequestV2, ): Promise> ⋮---- getSpotOpenOrders( params?: GetSpotOpenOrdersRequestV2, ): Promise> ⋮---- getSpotHistoricOrders( params?: GetSpotHistoryOrdersRequestV2, ): Promise> ⋮---- getSpotFills( params: GetSpotFillsRequestV2, ): Promise> ⋮---- /** * * * Spot | Trigger Orders * */ ⋮---- spotSubmitPlanOrder(params: SpotPlanOrderRequestV2): Promise< APIResponse<{ orderId: string; clientOid: string; }> > { return this.postPrivate('/api/v2/spot/trade/place-plan-order', params); ⋮---- spotModifyPlanOrder(params: SpotModifyPlanOrderRequestV2): Promise< APIResponse<{ orderId: string; clientOid: string; }> > { return this.postPrivate('/api/v2/spot/trade/modify-plan-order', params); ⋮---- spotCancelPlanOrder(params: { clientOid?: string; orderId?: string; }): Promise< APIResponse<{ result: string; }> > { return this.postPrivate('/api/v2/spot/trade/cancel-plan-order', params); ⋮---- getSpotCurrentPlanOrders(params: GetSpotCurrentPlanOrdersRequestV2): Promise< APIResponse<{ nextFlag: boolean; idLessThan: string; orderList: SpotCurrentPlanOrderV2[]; }> > { return this.getPrivate('/api/v2/spot/trade/current-plan-order', params); ⋮---- getSpotPlanSubOrder(params: { planOrderId: string; }): Promise> ⋮---- getSpotHistoricPlanOrders(params: GetSpotHistoryPlanOrdersRequestV2): Promise< APIResponse<{ nextFlag: boolean; idLessThan: string; orderList: SpotHistoryPlanOrderV2[]; }> > { return this.getPrivate('/api/v2/spot/trade/history-plan-order', params); ⋮---- spotCancelPlanOrders(params?: { symbolList?: string[]; }): Promise> ⋮---- /** * * * Spot | Account * */ ⋮---- getSpotAccount(): Promise> ⋮---- getSpotAccountAssets(params?: { coin?: string; assetType?: string; }): Promise> ⋮---- getSpotSubAccountAssets(): Promise> ⋮---- spotModifyDepositAccount(params: { accountType: string; coin: string; }): Promise> ⋮---- getSpotAccountBills( params?: GetSpotAccountBillsRequestV2, ): Promise> ⋮---- spotTransfer(params: SpotTransferRequestV2): Promise< APIResponse<{ transferId: string; clientOid: string; }> > { return this.postPrivate('/api/v2/spot/wallet/transfer', params); ⋮---- getSpotTransferableCoins(params: { fromType: SpotAccountTypeV2; toType: SpotAccountTypeV2; }): Promise> ⋮---- spotSubTransfer(params: SpotSubAccountTransferRequestV2): Promise< APIResponse<{ transferId: string; clientOid: string; }> > { return this.postPrivate('/api/v2/spot/wallet/subaccount-transfer', params); ⋮---- spotWithdraw(params: SpotWithdrawalRequestV2): Promise< APIResponse<{ orderId: string; clientOid: string; }> > { return this.postPrivate('/api/v2/spot/wallet/withdrawal', params); ⋮---- getSpotMainSubTransferRecord( params: SpotMainSubTransferRecordRequestV2, ): Promise> ⋮---- getSpotTransferHistory( params: GetSpotTransferRecordRequestV2, ): Promise> ⋮---- spotSwitchBGBDeduct(params: { deduct: boolean; }): Promise> ⋮---- getSpotDepositAddress(params: { coin: string; chain?: string; size: string; }): Promise> ⋮---- getSpotSubDepositAddress(params: { subUid: string; coin: string; chain?: string; size: string; }): Promise> ⋮---- getSpotBGBDeductInfo(): Promise< APIResponse<{ deduct: string; }> > { return this.getPrivate('/api/v2/spot/account/deduct-info'); ⋮---- spotCancelWithdrawal(params: { orderId: string; }): Promise> ⋮---- getSubAccountDepositRecords( params: GetSpotSubAccountDepositRecordRequestV2, ): Promise> ⋮---- getSpotWithdrawalHistory( params: GetSpotWithdrawalRecordRequestV2, ): Promise> ⋮---- getSpotDepositHistory( params: GetSpotDepositRecordRequestV2, ): Promise> ⋮---- /** * Upgrade Account - Upgrade to unified account mode * No account type restrictions; both parent and sub-accounts are supported. * This interface is only used for upgrading to the unified account mode. * Please note that as the account upgrade process takes approximately 1 minute, * the successful response you receive only indicates that the request has been received, * and does not mean that the account has been successfully upgraded to a unified account. * Please use the query upgrade status interface to confirm whether the account upgrade is successful. */ upgradeToUnifiedAccount(params?: { subUid?: string; }): Promise> ⋮---- /** * Get Upgrade Status - Get account upgrade status * No account type restrictions; both parent and sub-accounts are supported. */ getUnifiedAccountSwitchStatus(params?: { subUid?: string }): Promise< APIResponse<{ status: 'processProcessing' | 'successSuccess' | 'failFailed'; }> > { return this.getPrivate('/api/v2/spot/account/upgrade-status', params); ⋮---- /** * * * Futures * * */ ⋮---- /** * * * Futures | Market * */ ⋮---- getFuturesVIPFeeRate(): Promise> ⋮---- getFuturesInterestRateHistory(params: { coin: string }): Promise< APIResponse<{ coin: string; historyInterestRateList: FuturesHistoryInterestRateV2[]; }> > { return this.get('/api/v2/mix/market/union-interest-rate-history', params); ⋮---- getFuturesInterestExchangeRate(): Promise< APIResponse< { coin: string; exchangeRateList: FuturesInterestExchangeRateV2[]; }[] > > { return this.get('/api/v2/mix/market/exchange-rate'); ⋮---- getFuturesDiscountRate(): Promise> ⋮---- getFuturesMergeDepth( params: FuturesMergeDepthRequestV2, ): Promise> ⋮---- getFuturesTicker(params: { symbol: string; productType: FuturesProductTypeV2; }): Promise> ⋮---- getFuturesAllTickers(params: { productType: FuturesProductTypeV2; }): Promise> ⋮---- getFuturesRecentTrades( params: FuturesRecentTradesRequestV2, ): Promise> ⋮---- getFuturesHistoricTrades( params: FuturesHistoricTradesRequestV2, ): Promise> ⋮---- getFuturesCandles( params: FuturesCandlesRequestV2, ): Promise> ⋮---- getFuturesHistoricCandles( params: FuturesCandlesRequestV2, ): Promise> ⋮---- getFuturesHistoricIndexPriceCandles( params: FuturesCandlesRequestV2, ): Promise> ⋮---- getFuturesHistoricMarkPriceCandles( params: FuturesCandlesRequestV2, ): Promise> ⋮---- getFuturesOpenInterest(params: { symbol: string; productType: FuturesProductTypeV2; }): Promise< APIResponse<{ openInterestList: FuturesOpenInterestV2[]; ts: string; }> > { return this.get('/api/v2/mix/market/open-interest', params); ⋮---- getFuturesNextFundingTime(params: { symbol: string; productType: FuturesProductTypeV2; }): Promise> ⋮---- getFuturesSymbolPrice(params: { symbol: string; productType: FuturesProductTypeV2; }): Promise> ⋮---- getFuturesHistoricFundingRates(params: { symbol: string; productType: FuturesProductTypeV2; pageSize?: string; pageNo?: string; }): Promise> ⋮---- getFuturesCurrentFundingRate(params: { symbol?: string; productType: FuturesProductTypeV2; }): Promise< APIResponse< { symbol: string; fundingRate: string; // '0.0001'; fundingRateInterval: string; // hours, example: '1' | '2' | '4' | '8'; nextUpdate: string; // timestamp in milliseconds minFundingRate: string; maxFundingRate: string; }[] > > { return this.get('/api/v2/mix/market/current-fund-rate', params); ⋮---- fundingRate: string; // '0.0001'; fundingRateInterval: string; // hours, example: '1' | '2' | '4' | '8'; nextUpdate: string; // timestamp in milliseconds ⋮---- getFuturesContractConfig(params: { symbol?: string; productType: FuturesProductTypeV2; }): Promise> ⋮---- /** * * * Futures | Account * */ ⋮---- getFuturesAccountAsset( params: FuturesSingleAccountRequestV2, ): Promise> ⋮---- getFuturesAccountAssets(params: { productType: FuturesProductTypeV2; }): Promise> ⋮---- getFuturesSubAccountAssets(params: { productType: FuturesProductTypeV2; }): Promise< APIResponse< { userId: number; assetList: FuturesSubAccountAssetV2[]; }[] > > { return this.getPrivate('/api/v2/mix/account/sub-account-assets', params); ⋮---- getFuturesInterestHistory( params: FuturesInterestHistoryRequestV2, ): Promise> ⋮---- getFuturesOpenCount(params: FuturesOpenCountRequestV2): Promise< APIResponse<{ size: string; }> > { return this.getPrivate('/api/v2/mix/account/open-count', params); ⋮---- setFuturesPositionAutoMargin( params: FuturesSetAutoMarginRequestV2, ): Promise> ⋮---- setFuturesLeverage( params: FuturesSetLeverageRequestV2, ): Promise> ⋮---- setFuturesPositionMargin( params: FuturesSetPositionMarginRequestV2, ): Promise> ⋮---- setFuturesAssetMode(params: { productType: 'USDT-FUTURES' | 'SUSDT-FUTURES'; assetMode: 'single' | 'union'; }): Promise> ⋮---- setFuturesMarginMode( params: FuturesSetMarginModeRequestV2, ): Promise> ⋮---- setFuturesPositionMode(params: { productType: FuturesProductTypeV2; posMode: 'one_way_mode' | 'hedge_mode'; }): Promise< APIResponse<{ posMode: 'one_way_mode' | 'hedge_mode'; }> > { return this.postPrivate('/api/v2/mix/account/set-position-mode', params); ⋮---- getFuturesAccountBills(params: FuturesAccountBillRequestV2): Promise< APIResponse<{ bills: FuturesAccountBillV2[]; endId: string; }> > { return this.getPrivate('/api/v2/mix/account/bill', params); ⋮---- /** * Get Union Transfer Limits * * - Rate limit: 1 time/1s (uid) * - Get union margin currency transfer limits */ getUnionTransferLimits( params: GetUnionTransferLimitsRequestV2, ): Promise> ⋮---- /** * Get Union Config * * - Rate limit: 1 time/1s (uid) * - Get API for union margin configuration parameters (Liability Initial Margin Rate, Liability Maintenance Margin Rate, Personal Liability Limit, Personal Liability Limit Ratio) */ getUnionConfig(): Promise> ⋮---- /** * Get Switch Union USDT * * - Rate limit: 1 time/1s (uid) * - Get USDT quota for switching from union margin to single margin */ getSwitchUnionUsdt(): Promise> ⋮---- /** * Union Convert * * - Rate limit: 1 time/1s (uid) * - Union margin exchange */ unionConvert( params: UnionConvertRequestV2, ): Promise> ⋮---- /** * Get Max Openable Quantity * * - Rate limit: 20 req/sec/UID * - Get Max Openable Quantity */ getFuturesMaxOpenableQuantity( params: FuturesMaxOpenRequestV2, ): Promise> ⋮---- /** * Get Liquidation Price * * - Rate limit: 20 req/sec/UID * - Get Liquidation Price */ getFuturesLiquidationPrice( params: FuturesLiquidationPriceRequestV2, ): Promise> ⋮---- /** * Get Isolated Symbols * * - Rate limits: 10 time/1s (uid) * - Retrieve trading pairs with isolated margin mode under the account. */ getFuturesIsolatedSymbols( params: FuturesIsolatedSymbolsRequestV2, ): Promise> ⋮---- /** * * * Futures | Position * */ ⋮---- getFuturesPositionTier(params: { productType: FuturesProductTypeV2; symbol: string; }): Promise> ⋮---- getFuturesPosition(params: { productType: FuturesProductTypeV2; symbol: string; marginCoin: string; }): Promise> ⋮---- getFuturesPositions(params: { productType: FuturesProductTypeV2; marginCoin?: string; }): Promise> ⋮---- getFuturesHistoricPositions( params?: FuturesHistoricalPositionsRequestV2, ): Promise< APIResponse<{ list: FuturesHistoryPositionV2[]; endId: string; }> > { return this.getPrivate('/api/v2/mix/position/history-position', params); ⋮---- /** * * * Futures | Trade * */ ⋮---- futuresSubmitOrder(params: FuturesPlaceOrderRequestV2): Promise< APIResponse<{ orderId: string; clientOid: string; }> > { return this.postPrivate('/api/v2/mix/order/place-order', params); ⋮---- futuresSubmitReversal(params: FuturesReversalOrderRequestV2): Promise< APIResponse<{ orderId: string; clientOid: string; }> > { return this.postPrivate('/api/v2/mix/order/click-backhand', params); ⋮---- futuresBatchSubmitOrders( params: FuturesBatchOrderRequestV2, ): Promise> ⋮---- futuresModifyOrder(params: FuturesModifyOrderRequestV2): Promise< APIResponse<{ orderId: string; clientOid: string; }> > { return this.postPrivate('/api/v2/mix/order/modify-order', params); ⋮---- futuresCancelOrder(params: FuturesCancelOrderRequestV2): Promise< APIResponse<{ orderId: string; clientOid: string; }> > { return this.postPrivate('/api/v2/mix/order/cancel-order', params); ⋮---- futuresBatchCancelOrders( params: FuturesBatchCancelOrderRequestV2, ): Promise> ⋮---- futuresFlashClosePositions( params: FuturesFlashClosePositionsRequestV2, ): Promise> ⋮---- getFuturesOrder( params: FuturesGetOrderRequestV2, ): Promise> ⋮---- getFuturesFills(params: FuturesGetOrderFillsRequestV2): Promise< APIResponse<{ fillList: FuturesOrderFillV2[]; endId: string; }> > { return this.getPrivate('/api/v2/mix/order/fills', params); ⋮---- getFuturesHistoricOrderFills( params: FuturesGetHistoricalFillsRequestV2, ): Promise< APIResponse<{ fillList: FuturesOrderFillV2[]; endId: string; }> > { return this.getPrivate('/api/v2/mix/order/fill-history', params); ⋮---- getFuturesOpenOrders(params: FuturesGetOpenOrdersRequestV2): Promise< APIResponse<{ entrustedList: FuturesOpenOrderV2[]; endId: string; }> > { return this.getPrivate('/api/v2/mix/order/orders-pending', params); ⋮---- getFuturesHistoricOrders(params: FuturesGetHistoryOrdersRequestV2): Promise< APIResponse<{ entrustedList: FuturesHistoryOrderV2[]; endId: string; }> > { return this.getPrivate('/api/v2/mix/order/orders-history', params); ⋮---- futuresCancelAllOrders( params: FuturesCancelAllOrdersRequestV2, ): Promise> ⋮---- /** * * * Futures | Trigger Orders * */ ⋮---- getFuturesTriggerSubOrder(params: { planType: 'normal_plan' | 'track_plan'; planOrderId: string; productType: FuturesProductTypeV2; }): Promise> ⋮---- futuresSubmitTPSLOrder(params: FuturesTPSLOrderRequestV2): Promise< APIResponse<{ orderId: string; clientOid: string; }> > { return this.postPrivate('/api/v2/mix/order/place-tpsl-order', params); ⋮---- futuresSubmitPlanOrder(params: FuturesPlanOrderRequestV2): Promise< APIResponse<{ orderId: string; clientOid: string; }> > { return this.postPrivate('/api/v2/mix/order/place-plan-order', params); ⋮---- futuresModifyTPSLPOrder(params: FuturesModifyTPSLOrderRequestV2): Promise< APIResponse<{ orderId: string; clientOid: string; }> > { return this.postPrivate('/api/v2/mix/order/modify-tpsl-order', params); ⋮---- futuresModifyPlanOrder(params: FuturesModifyPlanOrderRequestV2): Promise< APIResponse<{ orderId: string; clientOid: string; }> > { return this.postPrivate('/api/v2/mix/order/modify-plan-order', params); ⋮---- getFuturesPlanOrders(params: FuturesGetPlanOrdersRequestV2): Promise< APIResponse<{ entrustedList: FuturesPendingPlanOrderV2[]; endId: string; }> > { return this.getPrivate('/api/v2/mix/order/orders-plan-pending', params); ⋮---- futuresCancelPlanOrder( params: FuturesCancelPlanOrderRequestV2, ): Promise> ⋮---- getFuturesHistoricPlanOrders( params: FuturesGetHistoryPlanOrdersRequestV2, ): Promise< APIResponse<{ entrustedList: FuturesHistoryPlanOrderV2[]; endId: string; }> > { return this.getPrivate('/api/v2/mix/order/orders-plan-history', params); ⋮---- /** * * * Broker * * */ ⋮---- /** * * * Broker | Subaccount * */ ⋮---- modifySubaccountEmail(params: { subUid: string; subaccountEmail: string; }): Promise> ⋮---- getBrokerInfo(): Promise< APIResponse<{ subAccountSize: string; maxSubAccountSize: string; uTime: string; }> > { return this.getPrivate('/api/v2/broker/account/info'); ⋮---- createSubaccount(params: { subaccountName: string; label: string; }): Promise> ⋮---- getSubaccounts(params?: GetSubAccountsRequestV2): Promise< APIResponse<{ hasNextPage: boolean; idLessThan: number; subList: BrokerSubaccountV2[]; }> > { return this.getPrivate('/api/v2/broker/account/subaccount-list', params); ⋮---- modifySubaccount( params: ModifySubRequestV2, ): Promise> ⋮---- getSubaccountEmail(params: { subUid: string; }): Promise> ⋮---- getSubaccountSpotAssets(params: { subUid: string; coin?: string; assetType?: 'hold_only' | 'all'; }): Promise< APIResponse<{ assetsList: BrokerSubaccountSpotAssetV2[]; }> > { return this.getPrivate( '/api/v2/broker/account/subaccount-spot-assets', params, ); ⋮---- getSubaccountFuturesAssets(params: { subUid: string; productType: FuturesProductTypeV2; }): Promise< APIResponse<{ assetsList: BrokerSubaccountFutureAssetV2[]; }> > { return this.getPrivate( '/api/v2/broker/account/subaccount-future-assets', params, ); ⋮---- createSubaccountDepositAddress(params: { subUid: string; coin: string; chain?: string; }): Promise> ⋮---- subaccountWithdrawal(params: SubWithdrawalRequestV2): Promise< APIResponse<{ orderId: string; clientOid: string; }> > { return this.postPrivate( '/api/v2/broker/account/subaccount-withdrawal', params, ); ⋮---- subaccountSetAutoTransfer(params: { subUid: string; coin: string; toAccountType: string; }): Promise> ⋮---- /** * Sub Deposit Records * * - Only applicable for ND broker main-account to get ND sub-accounts deposit record */ subaccountDepositRecords( params: SubDepositRecordsRequestV2, ): Promise> ⋮---- /** * Sub Withdrawal Records * * - Only applicable for ND broker main-account */ subaccountWithdrawalRecords(params: SubWithdrawalRecordsRequestV2): Promise< APIResponse<{ resultList: BrokerSubaccountWithdrawalV2[]; endId: string; }> > { return this.getPrivate('/api/v2/broker/subaccount-withdrawal', params); ⋮---- /** * * Broker | Api Key * */ ⋮---- createSubaccountApiKey( params: CreateSubAccountApiKeyRequestV2, ): Promise> ⋮---- getSubaccountApiKey(params: { subUid: string; }): Promise> ⋮---- modifySubaccountApiKey( params: ModifySubAccountApiKeyRequestV2, ): Promise> ⋮---- /** * Get All Sub-accounts Deposit and Withdrawal Records * * - Only applicable for ND broker main-account * - Rate limit: 5 req/sec/UID * - Able to get ND sub-accounts deposit and withdrawal records within 90 days */ getAllSubDepositWithdrawalRecords( params?: GetAllSubDepositWithdrawalRequestV2, ): Promise< APIResponse<{ list: AllSubDepositWithdrawalRecordV2[]; endId: string; }> > { return this.getPrivate('/api/v2/broker/all-sub-deposit-withdrawal', params); ⋮---- /** * Get Broker Subaccounts * * - Rate limit: 5 req/sec/UID * - Please contact your BD or RM to apply for access permissions */ getBrokerSubaccounts( params?: GetBrokerSubaccountsRequestV2, ): Promise> ⋮---- /** * Get Broker Subaccounts Commissions * * - Rate limit: 5 req/sec/UID * - Please contact your BD or RM to apply for access permissions */ getBrokerCommissions( params?: GetBrokerCommissionsRequestV2, ): Promise> ⋮---- /** * Get Broker Trade Volume * * - Rate limit: 5 req/sec/UID * - Please contact your BD or RM to apply for access permissions */ getBrokerTradeVolume( params?: GetBrokerTradeVolumeRequestV2, ): Promise> ⋮---- /** * Get Total Commission * * - Rate limit: 20 req/sec/UID * - Data retention: 365 days * - Historical data available from: 2025/6/1 * - Data granularity: daily * - Data update granularity: daily, previous day's data is updated on the current day * - Time zone: UTC+8 * - startTime and endTime should either both be set or both left unset * - This API supports retrieving data within the past 365 days (data is available starting from 2025/6/1 at the earliest) * - If startTime and endTime are not set in the request, the default returned information will be for yesterday (00:00-23:59 UTC+8) * - Data update frequency: T+1 (UTC+8) */ getBrokerTotalCommission( params?: GetBrokerTotalCommissionRequestV2, ): Promise> ⋮---- /** * Get Order Commission * * - Rate limit: 20 req/sec/UID * - Data storage: 30 days * - Historical data backtracking: 2025/9/1 * - Data granularity: daily * - Data update frequency: daily, previous day's data is updated on the current day * - Time zone: UTC+8 * - startTime and endTime should either both be set or both not set * - The maximum time span supported for startTime and endTime is 30 days * - This API supports retrieving data within the past 30 days * - If startTime and endTime are not set in the request, the default return will be information for yesterday (00:00-23:59 UTC+8) * - This API data is updated on a T+1 basis * - Transaction details only show those marked with broker channel id */ getBrokerOrderCommission( params?: GetBrokerOrderCommissionRequestV2, ): Promise> ⋮---- /** * Get Rebate Info * * - Rate limit: 20 req/sec/UID * - Data retention: 30 days * - Real-time data */ getBrokerRebateInfo( params: GetBrokerRebateInfoRequestV2, ): Promise> ⋮---- /** * * * Margin * * */ ⋮---- /** * * * Margin | Common * */ ⋮---- getMarginCurrencies(): Promise> ⋮---- /** * * * Margin | Cross/Isolated | Order Record * */ ⋮---- getMarginBorrowHistory( marginType: MarginType, params: GetBorrowHistoryRequestV2, ): Promise< APIResponse<{ resultList: MarginBorrowHistoryItemV2[]; maxId: string; minId: string; }> > { assertMarginType(marginType); ⋮---- getMarginRepayHistory( marginType: MarginType, params: GetRepayHistoryRequestV2, ): Promise< APIResponse<{ resultList: MarginRepaymentHistoryItemV2[]; maxId: string; minId: string; }> > { assertMarginType(marginType); ⋮---- getMarginInterestHistory( marginType: MarginType, params: GetInterestHistoryRequestV2, ): Promise< APIResponse<{ resultList: MarginInterestHistoryItemV2[]; maxId: string; minId: string; }> > { assertMarginType(marginType); ⋮---- getMarginLiquidationHistory( marginType: MarginType, params: GetLiquidationHistoryRequestV2, ): Promise< APIResponse<{ resultList: MarginLiquidationHistoryItemV2[]; maxId: string; minId: string; }> > { assertMarginType(marginType); ⋮---- getMarginFinancialHistory( marginType: MarginType, params: GetFinancialHistoryRequestV2, ): Promise< APIResponse<{ resultList: MarginFinancialHistoryItemV2[]; maxId: string; minId: string; }> > { assertMarginType(marginType); ⋮---- /** * * * 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; }> > { assertMarginType(marginType); ⋮---- 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; }> > { assertMarginType(marginType); ⋮---- getMarginRiskRate(marginType: MarginType): Promise< APIResponse< { symbol: string; riskRateRatio: string; }[] > > { assertMarginType(marginType); ⋮---- getMarginMaxBorrowable( marginType: MarginType, params: { coin: string }, ): Promise< APIResponse > { assertMarginType(marginType); ⋮---- getMarginMaxTransferable( marginType: MarginType, params: { coin: string }, ): Promise< APIResponse< CrossMaxTransferableResponseV2 | IsolatedMaxTransferableResponseV2 > > { assertMarginType(marginType); ⋮---- getMarginInterestRateAndMaxBorrowable( marginType: MarginType, params: { coin: string }, ): Promise< APIResponse< | IsolatedInterestRateAndLimitResponseV2[] | CrossInterestRateAndLimitResponseV2[] > > { assertMarginType(marginType); ⋮---- getMarginTierConfiguration( marginType: MarginType, params: { coin: string }, ): Promise< APIResponse< CrossTierConfigurationResponseV2[] | IsolatedTierConfigurationResponseV2[] > > { assertMarginType(marginType); ⋮---- marginFlashRepay( marginType: MarginType, params: { coin: string }, ): Promise< APIResponse<{ repayId: string; coin?: string; symbol?: string; result?: string; }> > { assertMarginType(marginType); ⋮---- getMarginFlashRepayResult( marginType: MarginType, params: { idList: string }, ): Promise< APIResponse< { repayId: string; status: string; }[] > > { assertMarginType(marginType); ⋮---- /** * * * Margin | Cross/Isolated | Trade * */ ⋮---- marginSubmitOrder( marginType: MarginType, params: MarginPlaceOrderRequestV2, ): Promise< APIResponse<{ orderId: string; clientOid: string; }> > { assertMarginType(marginType); ⋮---- marginBatchSubmitOrders( marginType: MarginType, params: MarginBatchOrdersRequestV2, ): Promise> ⋮---- marginCancelOrder( marginType: MarginType, params: { symbol: string; orderId?: string; clientOid?: string; }, ): Promise< APIResponse<{ orderId: string; clientOid: string; }> > { assertMarginType(marginType); ⋮---- marginBatchCancelOrders( marginType: MarginType, params: { symbol: string; orderIdList: string[]; }, ): Promise> ⋮---- getMarginOpenOrders( marginType: MarginType, params: GetMarginCurrentOrdersRequestV2, ): Promise< APIResponse<{ orderList: MarginCurrentOrderV2[]; maxId: string; minId: string; }> > { assertMarginType(marginType); ⋮---- getMarginHistoricOrders( marginType: MarginType, params: GetHistoryOrdersRequestV2, ): Promise< APIResponse<{ orderList: MarginHistoryOrderV2[]; maxId: string; minId: string; }> > { assertMarginType(marginType); ⋮---- getMarginHistoricOrderFills( marginType: MarginType, params: GetMarginOrderFillsRequestV2, ): Promise< APIResponse<{ fills: MarginOrderFillV2[]; minId: string; maxId: string; }> > { assertMarginType(marginType); ⋮---- getMarginLiquidationOrders( marginType: MarginType, params: GetMarginLiquidationOrdersRequestV2, ): Promise< APIResponse<{ resultList: MarginLiquidationOrderV2[]; idLessThan: string; }> > { assertMarginType(marginType); ⋮---- /** * * * Copy Trading * * */ ⋮---- /** * * * Copy Trading | Future copy trading | Trader Api * * */ ⋮---- getFuturesTraderCurrentOrder( params: GetFuturesTraderCurrentOrdersRequestV2, ): Promise> ⋮---- getFuturesTraderHistoryOrders( params: GetFuturesTraderHistoryOrdersRequestV2, ): Promise> ⋮---- modifyFuturesTraderOrderTPSL( params: ModifyFuturesTraderOrderTPSLRequestV2, ): Promise> ⋮---- getFuturesTraderOrder(): Promise< APIResponse > { return this.getPrivate('/api/v2/copy/mix-trader/order-total-detail'); ⋮---- getFuturesTraderProfitHistory(): Promise< APIResponse > { return this.getPrivate('/api/v2/copy/mix-trader/profit-history-summarys'); ⋮---- getFuturesTraderProfitShareHistory( params: GetFuturesTraderProfitShareDetailRequestV2, ): Promise> ⋮---- closeFuturesTraderOrder(params: { trackingNo: string; symbol: string; productType: CopyTradingProductTypeV2; }): Promise< APIResponse< { trackingNo: string; symbol: string; productType: string; }[] > > { return this.postPrivate( '/api/v2/copy/mix-trader/order-close-positions', params, ); ⋮---- getFuturesTraderProfitShare(params?: { coin?: string; pageSize?: string; pageNo?: string; }): Promise< APIResponse< { coin: string; profit: string; nickName: string; }[] > > { return this.getPrivate('/api/v2/copy/mix-trader/profit-details', params); ⋮---- getFuturesTraderProfitShareGroup(params?: { pageSize?: string; pageNo?: string; }): Promise< APIResponse< { coin: string; profit: string; profitTime: string; }[] > > { return this.getPrivate( '/api/v2/copy/mix-trader/profits-group-coin-date', params, ); ⋮---- 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 * * */ ⋮---- getFuturesFollowerCurrentOrders( params: GetFollowerFuturesCurrentTrackingOrdersRequestV2, ): Promise> ⋮---- getFuturesFollowerHistoryOrders( params: GetFollowerFuturesHistoryTrackingOrdersRequestV2, ): Promise> ⋮---- updateFuturesFollowerTPSL( params: UpdateFuturesFollowerTPSLRequestV2, ): Promise> ⋮---- updateFuturesFollowerSettings( params: UpdateFuturesFollowerSettingsRequestV2, ): Promise> ⋮---- getFuturesFollowerSettings(params: { traderId: string; }): Promise> ⋮---- closeFuturesFollowerPositions( params: CloseFuturesFollowerPositionsRequestV2, ): Promise< APIResponse<{ orderIdList: string[]; }> > { return this.postPrivate( '/api/v2/copy/mix-follower/close-positions', params, ); ⋮---- getFuturesFollowerTraders( params: GetFuturesFollowerTradersRequestV2, ): Promise> ⋮---- getFuturesFollowerFollowLimit(params: { symbol: string; productType: CopyTradingProductTypeV2; }): Promise< APIResponse< { maxFollowSize: string; minFollowSize: string; symbol: string; }[] > > { return this.getPrivate( '/api/v2/copy/mix-follower/query-quantity-limit', params, ); ⋮---- unfollowFuturesTrader(params: { traderId: string; }): Promise> ⋮---- /** * * * Copy Trading | Future copy trading | Broker api * * */ ⋮---- getBrokerTraders(params: object): Promise> ⋮---- getBrokerTradersHistoricalOrders(params: object): Promise> ⋮---- getBrokerTradersPendingOrders(params: object): Promise> ⋮---- /** * * * 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> ⋮---- /** * * * Copy Trading | Spot copy trading | Follower api * * */ ⋮---- 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[]; }> > { return this.getPrivate( '/api/v2/copy/spot-follower/query-trader-symbols', params, ); ⋮---- 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> ⋮---- getEarnSavingsSubscription(params: { productId: string; periodType: string; }): Promise> ⋮---- earnSubscribeSavings(params: { productId: string; periodType: string; amount: string; }): Promise< APIResponse<{ orderId: string; status: string; }> > { return this.postPrivate('/api/v2/earn/savings/subscribe', params); ⋮---- getEarnSavingsSubscriptionResult(params: { productId: string; periodType: string; }): Promise< APIResponse<{ result: 'success' | 'fail'; msg: string; }> > { return this.getPrivate('/api/v2/earn/savings/subscribe-result', params); ⋮---- earnRedeemSavings(params: RedeemSavingsRequestV2): Promise< APIResponse<{ orderId: string; status: string; }> > { return this.postPrivate('/api/v2/earn/savings/redeem', params); ⋮---- getEarnSavingsRedemptionResult(params: { orderId: string; periodType: string; }): Promise< APIResponse<{ result: 'success' | 'fail'; msg: string; }> > { return this.getPrivate('/api/v2/earn/savings/redeem-result', params); ⋮---- /** * * * Earn | Earn Account * * */ ⋮---- getEarnAccount(params?: { coin?: string }): Promise< APIResponse< { coin: string; amount: string; }[] > > { return this.getPrivate('/api/v2/earn/account/assets', params); ⋮---- /** * * * Earn | Shark Fin * * */ ⋮---- 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; }> > { return this.postPrivate('/api/v2/earn/sharkfin/subscribe', params); ⋮---- getSharkfinSubscriptionResult(params: { orderId: string }): Promise< APIResponse<{ result: 'success' | 'fail'; msg: string; }> > { return this.getPrivate('/api/v2/earn/sharkfin/subscribe-result', params); ⋮---- /** * * * Earn | Loan * * */ ⋮---- getLoanCurrencies(params?: { coin?: string; }): Promise> ⋮---- getLoanEstInterestAndBorrowable( params: GetLoanEstInterestAndBorrowableRequestV2, ): Promise< APIResponse<{ hourInterest: string; loanAmount: string; }> > { return this.get('/api/v2/earn/loan/public/hour-interest', params); ⋮---- borrowLoan(params: BorrowLoanRequestV2): Promise< APIResponse<{ orderId: string; }> > { return this.postPrivate('/api/v2/earn/loan/borrow', params); ⋮---- getOngoingLoanOrders(params?: { orderId?: string; loanCoin?: string; pledgeCoin?: string; }): Promise> ⋮---- repayLoan( params: RepayLoanRequestV2, ): Promise> ⋮---- getRepayHistory( params: GetLoanRepayHistoryRequestV2, ): Promise> ⋮---- updateLoanPledgeRate(params: ModifyLoanPledgeRateRequestV2): Promise< APIResponse<{ loanCoin: string; pledgeCoin: string; afterPledgeRate: string; }> > { return this.postPrivate('/api/v2/earn/loan/revise-pledge', params); ⋮---- getLoanPledgeRateHistory( params: GetLoanPledgeRateHistoryRequestV2, ): Promise> ⋮---- getLoanHistory( params: GetLoanHistoryRequestV2, ): Promise> ⋮---- getLoanDebts(): Promise> ⋮---- getLoanLiquidationRecords( params: GetLiquidationRecordsRequestV2, ): Promise> ================ File: src/rest-client-v3.ts ================ import { CreateSubAccountApiKeyRequestV3, CreateSubAccountRequestV3, DeleteSubAccountApiKeyRequestV3, FreezeSubAccountRequestV3, GetConvertRecordsRequestV3, GetDepositAddressRequestV3, GetDepositRecordsRequestV3, GetFeeRateRequestV3, GetFinancialRecordsRequestV3, GetFundingAssetsRequestV3, GetMaxTransferableRequestV3, GetOpenInterestLimitRequestV3, GetSubAccountApiKeysRequestV3, GetSubAccountListRequestV3, GetSubDepositAddressRequestV3, GetSubDepositRecordsRequestV3, GetSubTransferRecordsRequestV3, GetSubUnifiedAssetsRequestV3, GetTaxRecordsRequestV3, GetTransferableCoinsRequestV3, GetWithdrawRecordsRequestV3, RepayRequestV3, SetDepositAccountRequestV3, SetLeverageRequestV3, SubAccountTransferRequestV3, SwitchDeductRequestV3, TransferRequestV3, UpdateSubAccountApiKeyRequestV3, WithdrawRequestV3, } from './types/request/v3/account.js'; import { BindUidRequestV3, GetEnsureCoinsRequestV3, GetLoanOrderRequestV3, GetLTVConvertRequestV3, GetProductInfosRequestV3, GetRepaidHistoryRequestV3, GetSymbolsRequestV3, GetTransferedRequestV3, } from './types/request/v3/loan.js'; import { GetCandlesRequestV3, GetContractsOiRequestV3, GetCurrentFundingRateRequestV3, GetHistoryCandlesRequestV3, GetHistoryFundingRateRequestV3, GetInstrumentsRequestV3, GetMarginLoansRequestV3, GetOpenInterestRequestV3, GetOrderBookRequestV3, GetPositionTierRequestV3, GetPublicFillsRequestV3, GetRiskReserveRequestV3, GetTickersRequestV3, } from './types/request/v3/public.js'; import { CancelStrategyOrderRequestV3, GetHistoryStrategyOrdersRequestV3, GetUnfilledStrategyOrdersRequestV3, ModifyStrategyOrderRequestV3, PlaceStrategyOrderRequestV3, } from './types/request/v3/strategy.js'; import { BatchModifyOrderRequestV3, CancelAllOrdersRequestV3, CancelBatchOrdersRequestV3, CancelOrderRequestV3, CloseAllPositionsRequestV3, CountdownCancelAllRequestV3, GetCurrentPositionRequestV3, GetFillsRequestV3, GetHistoryOrdersRequestV3, GetMaxOpenAvailableRequestV3, GetOrderInfoRequestV3, GetPositionHistoryRequestV3, GetUnfilledOrdersRequestV3, ModifyOrderRequestV3, PlaceBatchOrdersRequestV3, PlaceOrderRequestV3, } from './types/request/v3/trade.js'; import { APIResponse } from './types/response/v1/shared.js'; import { AccountAssetsV3, AccountSettingsV3, ConvertRecordV3, CreateSubAccountApiKeyResponseV3, CreateSubAccountResponseV3, DepositAddressV3, DepositRecordV3, FinancialRecordV3, FundingAssetV3, MaxTransferableV3, OpenInterestLimitV3, PaymentCoinV3, RepayableCoinV3, RepayResponseV3, SubAccountApiKeyV3, SubAccountV3, SubTransferRecordV3, SubUnifiedAssetV3, TaxRecordV3, TransferResponseV3, UpdateSubAccountApiKeyResponseV3, WithdrawRecordV3, WithdrawResponseV3, } from './types/response/v3/account.js'; import { BindUidResponseV3, CoinInfoV3, LoanOrderV3, LoanProductInfoV3, LoanSymbolsV3, LoanTransfersV3, LTVConvertResponseV3, RepaidHistoryItemV3, } from './types/response/v3/loan.js'; import { CandlestickV3, ContractOiV3, CurrentFundingRateV3, DiscountRateV3, HistoryFundingRateV3, InstrumentV3, MarginLoanV3, OpenInterestV3, OrderBookV3, PositionTierV3, ProofOfReservesV3, PublicFillV3, RiskReserveV3, TickerV3, } from './types/response/v3/public.js'; import { ModifyStrategyOrderResponseV3, PlaceStrategyOrderResponseV3, StrategyOrderV3, } from './types/response/v3/strategy.js'; import { BatchModifyOrderResponseV3, CancelAllOrdersResponseV3, CancelBatchOrdersResponseV3, CancelOrderResponseV3, CloseAllPositionsResponseV3, CurrentPositionV3, FillV3, GetMaxOpenAvailableResponseV3, HistoryOrderV3, ModifyOrderResponseV3, OrderInfoV3, PlaceBatchOrdersResponseV3, PlaceOrderResponseV3, PositionAdlRankV3, PositionHistoryV3, UnfilledOrderV3, } from './types/response/v3/trade.js'; import BaseRestClient from './util/BaseRestClient.js'; import { REST_CLIENT_TYPE_ENUM } from './util/requestUtils.js'; ⋮---- /** * REST API client for all V3 endpoints */ export class RestClientV3 extends BaseRestClient ⋮---- getClientType() ⋮---- /** * * Custom SDK functions * */ ⋮---- /** * This method is used to get the latency and time sync between the client and the server. * This is not official API endpoint and is only used for internal testing purposes. * Use this method to check the latency and time sync between the client and the server. * Final values might vary slightly, but it should be within few ms difference. * If you have any suggestions or improvements to this measurement, please create an issue or pull request on GitHub. */ async fetchLatencySummary(): Promise ⋮---- // Adjust server time by adding estimated one-way latency ⋮---- // Calculate time difference between adjusted server time and local time ⋮---- async fetchServerTime(): Promise ⋮---- /** * * Public endpoints * */ ⋮---- getServerTime(): Promise< APIResponse<{ serverTime: string; }> > { return this.get('/api/v3/public/time'); ⋮---- /** * * =====Market======= endpoints * */ ⋮---- /** * Get Instruments */ getInstruments( params: GetInstrumentsRequestV3, ): Promise> ⋮---- /** * Get Tickers */ getTickers(params: GetTickersRequestV3): Promise> ⋮---- /** * Get OrderBook */ getOrderBook( params: GetOrderBookRequestV3, ): Promise> ⋮---- /** * Get Recent Public Fills */ getFills( params: GetPublicFillsRequestV3, ): Promise> ⋮---- /** * Get Proof Of Reserves */ getProofOfReserves(): Promise> ⋮---- /** * Get Open Interest */ getOpenInterest( params: GetOpenInterestRequestV3, ): Promise> ⋮---- /** * Get Kline/Candlestick * Maximum number of returned entries: 1,000 */ getCandles( params: GetCandlesRequestV3, ): Promise> ⋮---- /** * Get Kline/Candlestick History */ getHistoryCandles( params: GetHistoryCandlesRequestV3, ): Promise> ⋮---- /** * Get Current Funding Rate */ getCurrentFundingRate( params: GetCurrentFundingRateRequestV3, ): Promise> ⋮---- /** * Get Funding Rate History */ getHistoryFundingRate( params: GetHistoryFundingRateRequestV3, ): Promise> ⋮---- /** * Get Risk Reserve */ getRiskReserve( params: GetRiskReserveRequestV3, ): Promise> ⋮---- /** * Get Discount Rate */ getDiscountRate(): Promise> ⋮---- /** * Get Margin Loan */ getMarginLoans( params: GetMarginLoansRequestV3, ): Promise> ⋮---- /** * Get Position Tier */ getPositionTier( params: GetPositionTierRequestV3, ): Promise> ⋮---- /** * Get Open Interest Limit */ getContractsOi( params: GetContractsOiRequestV3, ): Promise> ⋮---- /** * * =====Account======= endpoints * */ ⋮---- /** * Get Account Assets */ getBalances(): Promise> ⋮---- /** * Get Fund Account Assets */ getFundingAssets( params?: GetFundingAssetsRequestV3, ): Promise> ⋮---- /** * Get Account Info */ getAccountSettings(): Promise> ⋮---- /** * Set Leverage */ setLeverage(params: SetLeverageRequestV3): Promise> ⋮---- /** * Set Holding Mode */ setHoldMode(params: { holdMode: 'one_way_mode' | 'hedge_mode'; }): Promise> ⋮---- /** * Get Financial Records */ getFinancialRecords(params: GetFinancialRecordsRequestV3): Promise< APIResponse<{ list: FinancialRecordV3[]; cursor: string; }> > { return this.getPrivate('/api/v3/account/financial-records', params); ⋮---- /** * Get Repayable Coins */ getRepayableCoins(): Promise< APIResponse<{ repayableCoinList: RepayableCoinV3[]; maxSelection: string; }> > { return this.getPrivate('/api/v3/account/repayable-coins'); ⋮---- /** * Get Payment Coins */ getPaymentCoins(): Promise< APIResponse<{ paymentCoinList: PaymentCoinV3[]; maxSelection: string; }> > { return this.getPrivate('/api/v3/account/payment-coins'); ⋮---- /** * Repay */ submitRepay(params: RepayRequestV3): Promise> ⋮---- /** * Get Convert Records */ getConvertRecords(params: GetConvertRecordsRequestV3): Promise< APIResponse<{ list: ConvertRecordV3[]; cursor: string; }> > { return this.getPrivate('/api/v3/account/convert-records', params); ⋮---- /** * Set up deposit account - Configure default recharge account for a certain symbol * This configuration item remains valid for a long time. That is, once a user sets a default * recharge account for a certain symbol, it will be retained permanently, and there is no need to reconfigure it. * Permission: UTA mgt. (read & write) */ setDepositAccount( params: SetDepositAccountRequestV3, ): Promise> ⋮---- /** * Switch Deduct - Set BGB deduction */ switchDeduct(params: SwitchDeductRequestV3): Promise> ⋮---- /** * Get Deduct Info - Get BGB deduction status */ getDeductInfo(): Promise< APIResponse<{ deduct: 'on' | 'off'; }> > { return this.getPrivate('/api/v3/account/deduct-info'); ⋮---- /** * Get Trading Fee Rate */ getFeeRate(params: GetFeeRateRequestV3): Promise< APIResponse<{ makerFeeRate: string; takerFeeRate: string; }> > { return this.getPrivate('/api/v3/account/fee-rate', params); ⋮---- /** * Get Max Transferable * * - Rate limit: 3 req/sec/UID * - Permission: UTA mgt. (read) * - Get the maximum transferable amount for the unified account. */ getMaxTransferable( params: GetMaxTransferableRequestV3, ): Promise> ⋮---- /** * Get Open Interest Limit * * - Rate limit: 5/sec/UID * - Get open interest limit for a symbol */ getOpenInterestLimit( params: GetOpenInterestLimitRequestV3, ): Promise> ⋮---- /** * Switch Account - Switch to classic account mode * Only supports parent accounts. * This endpoint is only used for switching to classic account mode. * Please note that since the account switching process takes approximately 1 minute, * the successful response you receive only indicates that the request has been received, * and does not mean that the account has been successfully switched to the classic account. * Please use the query switching status interface to confirm whether the account switching is successful. */ downgradeAccountToClassic(): Promise> ⋮---- /** * Get Switch Status - Get account switching status * Only supports parent accounts. */ getUnifiedAccountSwitchStatus(): Promise< APIResponse<{ status: 'processProcessing' | 'successSuccess' | 'failFailed'; }> > { return this.getPrivate('/api/v3/account/switch-status'); ⋮---- /** * Get Tax Records * * - Rate limit: 1/sec/UID * - Data query range: 366 days * - Please use the tax API Key to request Creation Portal * - Get Unified Account Tax Records */ getTaxRecords( params: GetTaxRecordsRequestV3, ): Promise> ⋮---- /** * * =====SubAccount======= endpoints * */ ⋮---- /** * Create Sub-account */ createSubAccount( params: CreateSubAccountRequestV3, ): Promise> ⋮---- /** * Freeze/Unfreeze Sub-account */ freezeSubAccount( params: FreezeSubAccountRequestV3, ): Promise> ⋮---- /** * Get Sub-account Unified Account Assets */ getSubUnifiedAssets( params?: GetSubUnifiedAssetsRequestV3, ): Promise> ⋮---- /** * Get Sub-account List */ getSubAccountList(params?: GetSubAccountListRequestV3): Promise< APIResponse<{ list: SubAccountV3[]; hasNext: boolean; cursor: string; }> > { return this.getPrivate('/api/v3/user/sub-list', params); ⋮---- /** * Create Sub-account API Key */ createSubAccountApiKey( params: CreateSubAccountApiKeyRequestV3, ): Promise> ⋮---- /** * Modify Sub-account API Key */ updateSubAccountApiKey( params: UpdateSubAccountApiKeyRequestV3, ): Promise> ⋮---- /** * Delete Sub-account API Key */ deleteSubAccountApiKey( params: DeleteSubAccountApiKeyRequestV3, ): Promise> ⋮---- /** * Get Sub-account API Keys */ getSubAccountApiKeys(params: GetSubAccountApiKeysRequestV3): Promise< APIResponse<{ items: SubAccountApiKeyV3[]; hasNext: boolean; cursor: string; }> > { return this.getPrivate('/api/v3/user/sub-api-list', params); ⋮---- /** * * =====Transfer======= endpoints * */ ⋮---- /** * Get Transferable Coins */ getTransferableCoins( params: GetTransferableCoinsRequestV3, ): Promise> ⋮---- /** * Transfer */ submitTransfer( params: TransferRequestV3, ): Promise> ⋮---- /** * Main-Sub Account Transfer */ subAccountTransfer(params: SubAccountTransferRequestV3): Promise< APIResponse<{ transferId: string; clientOid: string; }> > { return this.postPrivate('/api/v3/account/sub-transfer', params); ⋮---- /** * Get Main-Sub Transfer Records */ getSubTransferRecords(params?: GetSubTransferRecordsRequestV3): Promise< APIResponse<{ items: SubTransferRecordV3[]; cursor: string; }> > { return this.getPrivate('/api/v3/account/sub-transfer-record', params); ⋮---- /** * * =====Deposit======= endpoints * */ ⋮---- /** * Get Deposit Address */ getDepositAddress( params: GetDepositAddressRequestV3, ): Promise> ⋮---- /** * Get Sub Deposit Address */ getSubDepositAddress( params: GetSubDepositAddressRequestV3, ): Promise> ⋮---- /** * Get Deposit Records */ getDepositRecords( params: GetDepositRecordsRequestV3, ): Promise> ⋮---- /** * Get Sub Deposit Records */ getSubDepositRecords( params: GetSubDepositRecordsRequestV3, ): Promise> ⋮---- /** * * =====Withdraw======= endpoints * */ ⋮---- /** * Withdraw - Includes on-chain withdrawals and internal transfers */ submitWithdraw( params: WithdrawRequestV3, ): Promise> ⋮---- /** * Get Withdraw Records */ getWithdrawRecords( params: GetWithdrawRecordsRequestV3, ): Promise> ⋮---- /** * * =====Trade======= endpoints * */ ⋮---- /** * Place Order */ submitNewOrder( params: PlaceOrderRequestV3, ): Promise> ⋮---- /** * Modify Order */ modifyOrder( params: ModifyOrderRequestV3, ): Promise> ⋮---- /** * Cancel Order */ cancelOrder( params: CancelOrderRequestV3, ): Promise> ⋮---- /** * Batch Order */ placeBatchOrders( params: PlaceBatchOrdersRequestV3[], ): Promise> ⋮---- /** * Batch Modify Orders */ batchModifyOrders( params: BatchModifyOrderRequestV3[], ): Promise> ⋮---- /** * Batch Cancel */ cancelBatchOrders( params: CancelBatchOrdersRequestV3[], ): Promise> ⋮---- /** * Cancel All Orders */ cancelAllOrders( params: CancelAllOrdersRequestV3, ): Promise> ⋮---- /** * Close All Positions */ closeAllPositions( params: CloseAllPositionsRequestV3, ): Promise> ⋮---- /** * Get Order Details */ getOrderInfo( params: GetOrderInfoRequestV3, ): Promise> ⋮---- /** * Get Open Orders */ getUnfilledOrders(params?: GetUnfilledOrdersRequestV3): Promise< APIResponse<{ list: UnfilledOrderV3[]; cursor: string; }> > { return this.getPrivate('/api/v3/trade/unfilled-orders', params); ⋮---- /** * Get Order History */ getHistoryOrders(params: GetHistoryOrdersRequestV3): Promise< APIResponse<{ list: HistoryOrderV3[]; cursor: string; }> > { return this.getPrivate('/api/v3/trade/history-orders', params); ⋮---- /** * Get Fill History */ getTradeFills(params?: GetFillsRequestV3): Promise< APIResponse<{ list: FillV3[]; cursor: string; }> > { return this.getPrivate('/api/v3/trade/fills', params); ⋮---- /** * Get Position Info */ getCurrentPosition(params: GetCurrentPositionRequestV3): Promise< APIResponse<{ list: CurrentPositionV3[]; }> > { return this.getPrivate('/api/v3/position/current-position', params); ⋮---- /** * Get Positions History */ getPositionHistory(params: GetPositionHistoryRequestV3): Promise< APIResponse<{ list: PositionHistoryV3[]; cursor: string; }> > { return this.getPrivate('/api/v3/position/history-position', params); ⋮---- /** * Get Max Open Available */ getMaxOpenAvailable( params: GetMaxOpenAvailableRequestV3, ): Promise> ⋮---- /** * Get Position ADL Rank - Get position auto-deleveraging ranking */ getPositionAdlRank(): Promise> ⋮---- /** * CountDown Cancel All */ countdownCancelAll( params: CountdownCancelAllRequestV3, ): Promise> ⋮---- /** * * =====Inst Loan======= endpoints * */ ⋮---- /** * Get Transferred Quantity */ getLoanTransfered( params: GetTransferedRequestV3, ): Promise> ⋮---- /** * Get Trade Symbols */ getLoanSymbols( params: GetSymbolsRequestV3, ): Promise> ⋮---- /** * Get Risk Unit */ getLoanRiskUnit(): Promise< APIResponse<{ riskUnitId: string[]; }> > { return this.getPrivate('/api/v3/ins-loan/risk-unit'); ⋮---- /** * Get Repayment Orders */ getLoanRepaidHistory( params?: GetRepaidHistoryRequestV3, ): Promise> ⋮---- /** * Get Product Info */ getLoanProductInfo( params: GetProductInfosRequestV3, ): Promise> ⋮---- /** * Get Loan Orders */ getLoanOrder( params?: GetLoanOrderRequestV3, ): Promise> ⋮---- /** * Get LTV */ getLoanLTVConvert( params?: GetLTVConvertRequestV3, ): Promise> ⋮---- /** * Get Margin Coin Info */ getLoanMarginCoinInfo(params: GetEnsureCoinsRequestV3): Promise< APIResponse<{ productId: string; coinInfo: CoinInfoV3[]; }> > { return this.getPrivate('/api/v3/ins-loan/ensure-coins-convert', params); ⋮---- /** * Bind/Unbind UID to Risk Unit */ bindLoanUid( params: BindUidRequestV3, ): Promise> ⋮---- /** * * =====Strategy======= endpoints * */ ⋮---- /** * Place Strategy Order */ submitStrategyOrder( params: PlaceStrategyOrderRequestV3, ): Promise> ⋮---- /** * Modify Strategy Order */ modifyStrategyOrder( params: ModifyStrategyOrderRequestV3, ): Promise> ⋮---- /** * Cancel Strategy Order */ cancelStrategyOrder( params: CancelStrategyOrderRequestV3, ): Promise> ⋮---- /** * Get Unfilled Strategy Orders */ getUnfilledStrategyOrders( params: GetUnfilledStrategyOrdersRequestV3, ): Promise> ⋮---- /** * Get Strategy Order History */ getHistoryStrategyOrders(params: GetHistoryStrategyOrdersRequestV3): Promise< APIResponse<{ list: StrategyOrderV3[]; cursor?: string; }> > { return this.getPrivate('/api/v3/trade/history-strategy-orders', params); ================ File: README.md ================ # Node.js & Typescript Bitget API SDK [![Build & Test](https://github.com/tiagosiebler/bitget-api/actions/workflows/e2etests.yml/badge.svg?branch=master)](https://github.com/tiagosiebler/bitget-api/actions/workflows/e2etests.yml) [![npm version](https://img.shields.io/npm/v/bitget-api)][1] [![npm size](https://img.shields.io/bundlephobia/min/bitget-api/latest)][1] [![npm downloads](https://img.shields.io/npm/dt/bitget-api)][1] [![last commit](https://img.shields.io/github/last-commit/tiagosiebler/bitget-api)][1] [![CodeFactor](https://www.codefactor.io/repository/github/tiagosiebler/bitget-api/badge)](https://www.codefactor.io/repository/github/tiagosiebler/bitget-api) [![Telegram](https://img.shields.io/badge/chat-on%20telegram-blue.svg)](https://t.me/nodetraders)

SDK Logo

[1]: https://www.npmjs.com/package/bitget-api Updated & performant JavaScript & Node.js SDK for the Bitget V2 REST APIs and WebSockets: - Professional, robust & performant Bitget SDK with extensive production use in live trading environments. - Complete integration with all Bitget APIs. - [x] Supports V1 REST APIs & WebSockets (legacy) - [x] Supports V2 REST APIs & WebSockets - [x] Supports V3/UTA REST APIs & WebSockets (latest) - [x] Supports order placement via V3 WebSocket API - Complete TypeScript support (with type declarations for all API requests & responses). - Strongly typed requests and responses. - Automated end-to-end tests on most API calls, ensuring no breaking changes are released to npm. - Actively maintained with a modern, promise-driven interface. - Over 100 integration tests making real API calls & WebSocket connections, validating any changes before they reach npm. - Robust WebSocket integration with configurable connection heartbeats & automatic reconnect then resubscribe workflows. - Event driven messaging. - Smart WebSocket persistence with automatic reconnection handling. - Emit `reconnected` event when dropped connection is restored. - Optional beautification of WebSocket events for improved readability. - Officially listed Node.js SDK in [Bitget API docs](https://bitgetlimited.github.io/apidoc/en/spot/#sdk-code-example). - Browser support (via webpack bundle - see "Browser Usage" below). - Support all authentication methods supported by Bitget: - [x] HMAC - [x] RSA - Heavy automated end-to-end testing with real API calls. - End-to-end testing before any release. - Real API calls in e2e tests. - Proxy support via axios integration. - Active community support & collaboration in telegram: [Node.js Algo Traders](https://t.me/nodetraders). ## Table of Contents - [Installation](#installation) - [Examples](#examples) - [Issues & Discussion](#issues--discussion) - [Related Projects](#related-projects) - [Documentation](#documentation) - [Structure](#structure) - [Usage](#usage) - [REST API Clients](#rest-api-clients) - [V3 REST APIs (Unified Trading Account)](#v3-rest-apis) - [V2 REST APIs](#v2-rest-apis) - [WebSockets](#websockets) - [V3 Unified Trading Account](#v3-unified-trading-account) - [Sending Orders via WebSockets](#sending-orders-via-websockets) - [Receiving Realtime Data](#receiving-realtime-data) - [V2 WebSockets](#v2-websockets) - [Customise Logging](#logging) - [Custom Logger](#customise-logging) - [Debug HTTP Requests](#debug-http-requests) - [Frontend Usage](#browser-usage) - [Import](#import) - [Webpack](#webpack) - [LLMs & AI](#use-with-llms--ai) - [Used By](#used-by) - [Contributions & Thanks](#contributions--thanks) ## Installation `npm install --save bitget-api` ## Examples Refer to the [examples](./examples) folder for implementation demos. ## Issues & Discussion - Issues? Check the [issues tab](https://github.com/tiagosiebler/bitget-api/issues). - Discuss & collaborate with other node devs? Join our [Node.js Algo Traders](https://t.me/nodetraders) engineering community on telegram. - Follow our announcement channel for real-time updates on [X/Twitter](https://x.com/sieblyio) ## Related projects Check out my related JavaScript/TypeScript/Node.js projects: - Try my REST API & WebSocket SDKs: - [Bybit-api Node.js SDK](https://www.npmjs.com/package/bybit-api) - [Okx-api Node.js SDK](https://www.npmjs.com/package/okx-api) - [Binance Node.js SDK](https://www.npmjs.com/package/binance) - [Gateio-api Node.js SDK](https://www.npmjs.com/package/gateio-api) - [Bitget-api Node.js SDK](https://www.npmjs.com/package/bitget-api) - [Kucoin-api Node.js SDK](https://www.npmjs.com/package/kucoin-api) - [Coinbase-api Node.js SDK](https://www.npmjs.com/package/coinbase-api) - [Bitmart-api Node.js SDK](https://www.npmjs.com/package/bitmart-api) - Try my misc utilities: - [OrderBooks Node.js](https://www.npmjs.com/package/orderbooks) - [Crypto Exchange Account State Cache](https://www.npmjs.com/package/accountstate) - Check out my examples: - [awesome-crypto-examples Node.js](https://github.com/tiagosiebler/awesome-crypto-examples) ## Documentation Most methods accept JS objects. These can be populated using parameters specified by Bitget's API documentation, or check the type definition in each class within this repository (see table below for convenient links to each class). - Bitget API Documentation - [V3/UTA API Documentation](https://www.bitget.com/api-doc/uta/intro) (Latest - Unified Trading Account) - [V2 API Documentation](https://www.bitget.com/api-doc/common/intro) - [Legacy V1 API Documentation](https://bitgetlimited.github.io/apidoc/en/spot/#introduction) (deprecated) - [REST Endpoint Function List](./docs/endpointFunctionList.md) - [TSDoc Documentation (autogenerated using typedoc)](https://tsdocs.dev/docs/bitget-api) ## Structure This connector is fully compatible with both TypeScript and pure JavaScript projects, while the connector is written in TypeScript. A pure JavaScript version can be built using `npm run build`, which is also the version published to [npm](https://www.npmjs.com/package/bitget-api). The version on npm is the output from the `build` command and can be used in projects without TypeScript (although TypeScript is definitely recommended). - [src](./src) - the whole connector written in TypeScript - [lib](./lib) - the JavaScript version of the project (built from TypeScript). This should not be edited directly, as it will be overwritten with each release. - [dist](./dist) - the webpack bundle of the project for use in browser environments (see guidance on webpack below). - [examples](./examples) - some implementation examples & demonstrations. Contributions are welcome! --- # Usage Create API credentials at Bitget: - [Livenet API Management](https://www.bitget.com/en/support/articles/360011132814-How-to-create-API) - [Demo Trading Environment](https://www.bitget.com/en/demo-trading) ## REST API Clients Each REST API group has a dedicated REST client. To avoid confusion, here are the available REST clients and the corresponding API groups: | Class | Description | |:------------------------------------: |:---------------------------------------------------------------------------------------------: | | [RestClientV3](src/rest-client-v3.ts) | [V3/UTA REST APIs for Bitget's Unified Trading Account](https://www.bitget.com/api-doc/uta/intro) | | [WebsocketClientV3](src/websocket-client-v3.ts) | Universal WS client for Bitget's V3/UTA WebSockets | | [WebsocketAPIClient](src/websocket-api-client.ts) | Websocket API Client, for RESTlike order placement via Bitget's V3/UTA WebSocket API | | [RestClientV2](src/rest-client-v2.ts) | [V2 REST APIs](https://www.bitget.com/api-doc/common/intro) | | [WebsocketClientV2](src/websocket-client-v2.ts) | Universal WS client for all Bitget's V2 WebSockets | | [~~SpotClient~~ (deprecated, use RestClientV2)](src/spot-client.ts) | [~~Spot APIs~~](https://bitgetlimited.github.io/apidoc/en/spot/#introduction) | | [~~FuturesClient~~ (deprecated, use RestClientV2)](src/futures-client.ts) | [~~Futures APIs~~](https://bitgetlimited.github.io/apidoc/en/mix/#introduction) | | [~~BrokerClient~~ (deprecated, use RestClientV2)](src/broker-client.ts) | [~~Broker APIs~~](https://bitgetlimited.github.io/apidoc/en/broker/#introduction) | | [~~WebsocketClient~~ (deprecated, use WebsocketClientV2)](src/websocket-client.ts) | ~~Universal client for all Bitget's V1 WebSockets~~ | Examples for using each client can be found in: - the [examples](./examples) folder. - the [awesome-crypto-examples](https://github.com/tiagosiebler/awesome-crypto-examples) repository. If you're missing an example, you're welcome to request one. Priority will be given to [github sponsors](https://github.com/sponsors/tiagosiebler). ### Getting Started All REST APIs are integrated in each dedicated Rest Client class. See the above table for which REST client to use. If you've upgraded to the Unified Trading Account, you should use the V3 REST APIs and WebSockets. There are several REST API modules as there are some differences in each API group: 1. `RestClientV3` for the latest V3/UTA APIs (Unified Trading Account) - recommended for new projects. 2. `RestClientV2` for V2 APIs - use if you haven't upgraded to UTA yet. 3. Legacy V1 clients (`SpotClient`, `FuturesClient`, `BrokerClient`) - deprecated, migrate to V2 or V3. More Node.js & JavaScript examples for Bitget's REST APIs & WebSockets can be found in the [examples](./examples) folder on GitHub. #### V3 REST APIs These are only available if you have upgraded to the Unified Trading Account. If not, use the V2 APIs instead. ```javascript import { RestClientV3 } from 'bitget-api'; // or if you prefer require: // const { RestClientV3 } = require('bitget-api'); // note the single quotes, preventing special characters such as $ from being incorrectly passed const client = new RestClientV3({ apiKey: process.env.API_KEY_COM || 'insert_api_key_here', apiSecret: process.env.API_SECRET_COM || 'insert_api_secret_here', apiPass: process.env.API_PASS_COM || 'insert_api_pass_here', }); (async () => { try { console.log(await client.getBalances()); const newOrder = await client.submitNewOrder({ category: 'USDT-FUTURES', orderType: 'market', side: 'buy', qty: '0.001', symbol: 'BTCUSDT', }); console.log('Order submitted: ', newOrder); } catch (e) { console.error('request failed: ', e); } })(); ``` #### V2 REST APIs Not sure which function to call or which parameters to use? Click the class name in the table above to look at all the function names (they are in the same order as the official API docs), and check the API docs for a list of endpoints/parameters/responses. If you found the method you're looking for in the API docs, you can also search for the endpoint in the [RestClientV2](src/rest-client-v2.ts) class. This class has all V2 endpoints available. ```javascript import { RestClientV2 } from 'bitget-api'; // or if you prefer require: // const { RestClientV2 } = require('bitget-api'); const API_KEY = 'xxx'; const API_SECRET = 'yyy'; const API_PASS = 'zzz'; const client = new RestClientV2({ apiKey: API_KEY, apiSecret: API_SECRET, apiPass: API_PASS, }); // For public-only API calls, simply don't provide a key & secret or set them to undefined // const client = new RestClientV2(); client .getSpotAccount() .then((result) => { console.log('getSpotAccount result: ', result); }) .catch((err) => { console.error('getSpotAccount error: ', err); }); client .getSpotCandles({ symbol: 'BTCUSDT', granularity: '1min', limit: '1000', }) .then((result) => { console.log('getCandles result: ', result); }) .catch((err) => { console.error('getCandles error: ', err); }); ``` ## WebSockets All WebSocket functionality is supported via the WebsocketClient. Since there are currently 3 generations of Bitget's API, there are 3 WebsocketClient classes in this Node.js, JavaScript & TypeScript SDK for Bitget. Use the following guidance to decide which one to use: - **Unified Trading Account / V3** (latest generation): - For receiving data, use the [WebsocketClientV3](./src/websocket-client-v3.ts). - For sending orders via WebSockets, use the [WebsocketAPIClient](./src/websocket-api-client.ts). - **V2** (not upgraded to Unified Trading Account yet) - Use the [WebsocketClientV2](./src/websocket-client-v2.ts). - **V1** (deprecated) - This is the oldest API group supported by Bitget. You should migrate to V3 or V2 as soon as possible. - If you're not ready to migrate, you can use the [WebsocketClientLegacyV1](./src/websocket-client-legacy-v1.ts) class in the meantime. All WebSocket clients support: - Event driven messaging - Smart WebSocket persistence with automatic reconnection - Heartbeat mechanisms to detect disconnections - Automatic resubscription after reconnection - Error handling and connection monitoring - Optional data beautification Higher level examples below, while more thorough examples can be found in the examples folder on GitHub. ##### V3 Unified Trading Account ###### Sending orders via WebSockets The V3 / Unified Trading Account APIs introduce 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. The recommended route is to use the dedicated WebsocketAPIClient class, included with this SDK. 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. A simple example is below, but for a more thorough example, check the example here: [./examples/V3/ws-api-client-trade.ts](./examples/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)); ``` ###### Receiving realtime data Use the WebsocketClientV3 to receive data via the V3 WebSockets ```typescript import { WebsocketClientV3 } from "bitget-api"; // or if you prefer require: // const { WebsocketClientV3 } = require("bitget-api"); const API_KEY = "yourAPIKeyHere"; const API_SECRET = "yourAPISecretHere; const API_PASS = "yourAPIPassHere"; const wsClient = new WebsocketClientV3( { // Only necessary if you plan on using private/account websocket topics apiKey: API_KEY, apiSecret: API_SECRET, apiPass: API_PASS, } ); // Connect event handlers to process incoming events wsClient.on('update', (data) => { console.log('WS raw message received ', data); // console.log('WS raw message received ', JSON.stringify(data, null, 2)); }); wsClient.on('open', (data) => { console.log('WS connection opened:', data.wsKey); }); wsClient.on('response', (data) => { console.log('WS response: ', JSON.stringify(data, null, 2)); }); wsClient.on('reconnect', ({ wsKey }) => { console.log('WS automatically reconnecting.... ', wsKey); }); wsClient.on('reconnected', (data) => { console.log('WS reconnected ', data?.wsKey); }); wsClient.on('exception', (data) => { console.log('WS error', data); }); /** * Subscribe to topics as you wish */ // You can subscribe to one topic at a time wsClient.subscribe( { topic: 'account', payload: { 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 const ACCOUNT_INST_TYPE = 'UTA'; const ACCOUNT_WS_KEY = WS_KEY_MAP.v3Private; // Or multiple at once: wsClient.subscribe( [ { topic: 'account', payload: { instType: ACCOUNT_INST_TYPE, }, }, { topic: 'position', payload: { instType: ACCOUNT_INST_TYPE, }, }, { topic: 'fill', payload: { instType: ACCOUNT_INST_TYPE, }, }, { topic: 'order', payload: { instType: ACCOUNT_INST_TYPE, }, }, ], ACCOUNT_WS_KEY, ); // Example public events wsClient.subscribe( [ { topic: 'ticker', payload: { instType: 'spot', symbol: 'BTCUSDT', }, }, { topic: 'ticker', payload: { instType: 'spot', symbol: 'ETHUSDT', }, }, { topic: 'ticker', payload: { instType: 'spot', symbol: 'XRPUSDT', }, }, { topic: 'ticker', payload: { instType: 'usdt-futures', symbol: 'BTCUSDT', }, }, { topic: 'ticker', payload: { instType: 'usdt-futures', symbol: 'BTCUSDT', }, }, ], WS_KEY_MAP.v3Public, ); ``` For more examples, including how to use websockets with Bitget, check the [examples](./examples/) and [test](./test/) folders. ### V2 WebSockets If you haven't upgraded to the Unified Trading Account, use the V2 WebSocket client: ```javascript import { WebsocketClientV2 } from 'bitget-api'; // or if you prefer require: // const { WebsocketClientV2 } = require('bitget-api'); const API_KEY = 'xxx'; const API_SECRET = 'yyy'; const API_PASS = 'zzz'; const wsClient = new WebsocketClientV2({ apiKey: API_KEY, apiSecret: API_SECRET, apiPass: API_PASS, // Optional: connect to demo trading environment // demoTrading: true, }); // Handle incoming messages wsClient.on('update', (data) => { console.log('WS update received: ', data); }); wsClient.on('open', (data) => { console.log('WS connection opened: ', data.wsKey); }); wsClient.on('reconnected', (data) => { console.log('WS reconnected: ', data?.wsKey); }); wsClient.on('exception', (data) => { console.log('WS error: ', data); }); // Subscribe to public data streams wsClient.subscribeTopic('SPOT', 'ticker', symbol); // Subscribe to private data streams (requires authentication) wsClient.subscribeTopic('SPOT', 'account'); ``` --- ## Logging ### Customise logging Pass a custom logger which supports the log methods `trace`, `info` and `error`, or override methods from the default logger as desired. ```javascript import { WebsocketClientV2, DefaultLogger } from 'bitget-api'; // or if you prefer require: // const { WebsocketClientV2, DefaultLogger } = require('bitget-api'); // Disable all logging on the trace level (less console logs) const customLogger = { ...DefaultLogger, trace: () => {}, }; const ws = new WebsocketClientV2( { apiKey: 'API_KEY', apiSecret: 'API_SECRET', apiPass: 'API_PASS', }, customLogger, ); ``` ### Debug HTTP requests In rare situations, you may want to see the raw HTTP requets being built as well as the API response. These can be enabled by setting the `BITGETTRACE` env var to `true`. ## Browser Usage ### Import This is the "modern" way, allowing the package to be directly imported into frontend projects with full typescript support. 1. Install these dependencies ```sh npm install crypto-browserify stream-browserify ``` 2. Add this to your `tsconfig.json` ```json { "compilerOptions": { "paths": { "crypto": [ "./node_modules/crypto-browserify" ], "stream": [ "./node_modules/stream-browserify" ] } ``` 3. Declare this in the global context of your application (ex: in polyfills for angular) ```js (window as any).global = window; ``` ### Webpack This is the "old" way of using this package on webpages. This will build a minified js bundle that can be pulled in using a script tag on a website. Build a bundle using webpack: - `npm install` - `npm build` - `npm pack` The bundle can be found in `dist/`. Altough usage should be largely consistent, smaller differences will exist. Documentation is still TODO - contributions welcome. ## Use with LLMs & AI This SDK includes a bundled `llms.txt` file in the root of the repository. If you're developing with LLMs, use the included `llms.txt` with your LLM - it will significantly improve the LLMs understanding of how to correctly use this SDK. This file contains AI optimised structure of all the functions in this package, and their parameters for easier use with any learning models or artificial intelligence. --- ## Used By [![Repository Users Preview Image](https://dependents.info/tiagosiebler/bitget-api/image)](https://github.com/tiagosiebler/bitget-api/network/dependents) --- ### Contributions & Thanks Have my projects helped you? Share the love, there are many ways you can show your thanks: - Star & share my projects. - Are my projects useful? Sponsor me on Github and support my effort to maintain & improve them: https://github.com/sponsors/tiagosiebler - Have an interesting project? Get in touch & invite me to it. - Or buy me all the coffee: - ETH(ERC20): `0xA3Bda8BecaB4DCdA539Dc16F9C54a592553Be06C` ### Contributions & Pull Requests 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=tiagosiebler/bybit-api,tiagosiebler/okx-api,tiagosiebler/binance,tiagosiebler/bitget-api,tiagosiebler/bitmart-api,tiagosiebler/gateio-api,tiagosiebler/kucoin-api,tiagosiebler/coinbase-api,tiagosiebler/orderbooks,tiagosiebler/accountstate,tiagosiebler/awesome-crypto-examples&type=Date)](https://star-history.com/#tiagosiebler/bybit-api&tiagosiebler/okx-api&tiagosiebler/binance&tiagosiebler/bitget-api&tiagosiebler/bitmart-api&tiagosiebler/gateio-api&tiagosiebler/kucoin-api&tiagosiebler/coinbase-api&tiagosiebler/orderbooks&tiagosiebler/accountstate&tiagosiebler/awesome-crypto-examples&Date) ================ File: package.json ================ { "name": "bitget-api", "version": "3.0.11", "description": "Complete Node.js & JavaScript SDK for Bitget V1-V3 REST APIs & WebSockets, with TypeScript & end-to-end tests.", "scripts": { "test": "jest", "test:watch": "jest --watch", "test:public": "jest --testPathIgnorePatterns='.*private.*'", "test:private": "jest --testPathPattern='.*private.*'", "clean": "rm -rf lib dist", "build": "npm run clean && tsc -p tsconfig.esm.json && tsc -p tsconfig.cjs.json && bash ./postBuild.sh", "build:clean": "npm run clean && npm run build", "build:watch": "npm run clean && tsc --watch", "pack": "webpack --config webpack/webpack.config.js", "lint": "eslint src", "prepublish": "npm run build:clean", "betapublish": "npm publish --tag beta" }, "main": "dist/cjs/index.js", "module": "dist/mjs/index.js", "types": "dist/mjs/index.d.ts", "exports": { ".": { "import": "./dist/mjs/index.js", "require": "./dist/cjs/index.js", "types": "./dist/mjs/index.d.ts" } }, "files": [ "dist/*", "llms.txt" ], "type": "module", "author": "Tiago Siebler (https://github.com/tiagosiebler)", "contributors": [], "dependencies": { "axios": "^1.12.2", "isomorphic-ws": "^5.0.0", "ws": "^8.18.3" }, "devDependencies": { "@types/jest": "^29.0.3", "@types/node": "^22.10.2", "@types/ws": "^8.18.1", "@typescript-eslint/eslint-plugin": "^8.18.0", "@typescript-eslint/parser": "^8.18.0", "eslint": "^8.24.0", "eslint-config-prettier": "^9.1.0", "eslint-plugin-prettier": "^5.2.1", "eslint-plugin-require-extensions": "^0.1.3", "eslint-plugin-simple-import-sort": "^12.1.1", "jest": "^29.7.0", "ts-jest": "^29.4.0", "ts-node": "^10.9.2", "typescript": "^5.7.3" }, "optionalDependencies": { "source-map-loader": "^4.0.0", "ts-loader": "^9.4.1", "webpack": "^5.74.0", "webpack-cli": "^4.10.0" }, "keywords": [ "bitget", "bitget api", "bitget nodejs", "bitget javascript", "bitget typescript", "bitget sdk", "bitget v3 api", "bitget UTA api", "api", "websocket", "rest", "rest api", "usdt", "trading bots", "nodejs", "node", "trading", "cryptocurrency", "bitcoin", "best" ], "funding": { "type": "individual", "url": "https://github.com/sponsors/tiagosiebler" }, "license": "MIT", "repository": { "type": "git", "url": "https://github.com/tiagosiebler/bitget-api" }, "bugs": { "url": "https://github.com/tiagosiebler/bitget-api/issues" }, "homepage": "https://github.com/tiagosiebler/bitget-api#readme" } ================================================================ End of Codebase ================================================================