@yuants/vendor-huobi 0.18.5 → 0.18.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (33) hide show
  1. package/dist/api/private-api.js +32 -0
  2. package/dist/api/private-api.js.map +1 -1
  3. package/dist/services/accounts/spot.js +1 -0
  4. package/dist/services/accounts/spot.js.map +1 -1
  5. package/dist/services/accounts/super-margin.js +2 -1
  6. package/dist/services/accounts/super-margin.js.map +1 -1
  7. package/dist/services/accounts/swap.js +45 -1
  8. package/dist/services/accounts/swap.js.map +1 -1
  9. package/dist/services/exchange.js +19 -8
  10. package/dist/services/exchange.js.map +1 -1
  11. package/dist/services/orders/submitOrder.js +29 -2
  12. package/dist/services/orders/submitOrder.js.map +1 -1
  13. package/lib/api/private-api.d.ts +113 -0
  14. package/lib/api/private-api.d.ts.map +1 -1
  15. package/lib/api/private-api.js +37 -1
  16. package/lib/api/private-api.js.map +1 -1
  17. package/lib/services/accounts/spot.d.ts.map +1 -1
  18. package/lib/services/accounts/spot.js +1 -0
  19. package/lib/services/accounts/spot.js.map +1 -1
  20. package/lib/services/accounts/super-margin.d.ts.map +1 -1
  21. package/lib/services/accounts/super-margin.js +2 -1
  22. package/lib/services/accounts/super-margin.js.map +1 -1
  23. package/lib/services/accounts/swap.d.ts +1 -0
  24. package/lib/services/accounts/swap.d.ts.map +1 -1
  25. package/lib/services/accounts/swap.js +46 -1
  26. package/lib/services/accounts/swap.js.map +1 -1
  27. package/lib/services/exchange.js +17 -6
  28. package/lib/services/exchange.js.map +1 -1
  29. package/lib/services/orders/submitOrder.d.ts.map +1 -1
  30. package/lib/services/orders/submitOrder.js +28 -1
  31. package/lib/services/orders/submitOrder.js.map +1 -1
  32. package/package.json +1 -1
  33. package/temp/package-deps.json +9 -9
@@ -131,6 +131,14 @@ export const postSpotOrder = (credential, params) => {
131
131
  export const postSwapOrder = (credential, params) => {
132
132
  return linearSwapPrivateTradeRequest(credential, 'POST', '/linear-swap-api/v1/swap_cross_order', params);
133
133
  };
134
+ /**
135
+ * 联合保证金模式合约下单
136
+ *
137
+ * https://www.htx.com/zh-cn/opend/newApiPages/?id=8cb89359-77b5-11ed-9966-1957dd521e6
138
+ */
139
+ export const postUnionAccountSwapOrder = (credential, params) => {
140
+ return linearSwapPrivateTradeRequest(credential, 'POST', '/v5/trade/order', params);
141
+ };
134
142
  /**
135
143
  * 获取现货存款地址
136
144
  *
@@ -266,4 +274,28 @@ export const getV2ReferenceCurrencies = (credential, params) => {
266
274
  export const getAccountHistory = (credential, params) => {
267
275
  return spotPrivateQueryRequest(credential, 'GET', '/v1/account/history', params);
268
276
  };
277
+ /**
278
+ * 查询资产模式
279
+ *
280
+ * https://www.htx.com/zh-cn/opend/newApiPages/?id=8cb89359-77b5-11ed-9966-1957dd37de0
281
+ */
282
+ export const getAccountAssetsMode = (credential) => {
283
+ return linearSwapPrivateQueryRequest(credential, 'GET', '/v5/account/asset_mode');
284
+ };
285
+ /**
286
+ * 查询联合保证金账户余额
287
+ *
288
+ * https://www.htx.com/zh-cn/opend/newApiPages/?id=8cb89359-77b5-11ed-9966-195703a12d5
289
+ */
290
+ export const getUnionAccountBalance = (credential) => {
291
+ return linearSwapPrivateQueryRequest(credential, 'GET', '/v5/account/balance');
292
+ };
293
+ /**
294
+ * 查询联合保证金账户持仓
295
+ *
296
+ * https://www.htx.com/zh-cn/opend/newApiPages/?id=8cb89359-77b5-11ed-9966-1957f1fbee4
297
+ */
298
+ export const getUnionAccountPositions = (credential) => {
299
+ return linearSwapPrivateQueryRequest(credential, 'GET', '/v5/trade/position/opens');
300
+ };
269
301
  //# sourceMappingURL=private-api.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"private-api.js","sourceRoot":"","sources":["../../src/api/private-api.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC;AAE9F,MAAM,aAAa,GA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E;IACH,OAAO,uBAAuB,CAAC,UAAU,EAAE,KAAK,EAAE,qBAAqB,EAAE,MAAM,CAAC,CAAC;AACnF,CAAC,CAAC","sourcesContent":["import { encodeBase64, formatTime, HmacSHA256, scopeError, tokenBucket } from '@yuants/utils';\n\nconst SPOT_API_ROOT = 'api.huobi.pro';\nconst LINEAR_SWAP_API_ROOT = 'api.hbdm.com';\n\nexport interface ICredential {\n access_key: string;\n secret_key: string;\n}\n\nexport const getDefaultCredential = (): ICredential => {\n return {\n access_key: process.env.ACCESS_KEY!,\n secret_key: process.env.SECRET_KEY!,\n };\n};\n\n// https://www.htx.com/zh-cn/opend/newApiPages/?id=474\ntype HuobiBusiness = 'spot' | 'linear-swap';\ntype HuobiPrivateInterfaceType = 'trade' | 'query';\n\nconst createdBuckets = new Set<string>();\nconst getOrCreatePrivateBucket = (bucketId: string) => {\n if (!createdBuckets.has(bucketId)) {\n createdBuckets.add(bucketId);\n tokenBucket(bucketId, { capacity: 36, refillAmount: 36, refillInterval: 3000 });\n }\n return tokenBucket(bucketId);\n};\n\nconst acquirePrivate = (bucketId: string, meta: Record<string, unknown>) => {\n const bucket = getOrCreatePrivateBucket(bucketId);\n scopeError('HUOBI_API_RATE_LIMIT', { ...meta, bucketId }, () => bucket.acquireSync(1));\n};\n\nconst privateRequestWithRateLimit = async (\n credential: ICredential,\n interfaceType: HuobiPrivateInterfaceType,\n business: HuobiBusiness,\n method: string,\n path: string,\n api_root: string,\n params?: any,\n) => {\n const meta = { method, api_root, path, business, interfaceType, access_key: credential.access_key };\n\n const interfaceTypeUpper = interfaceType.toUpperCase();\n const businessUpper = business.toUpperCase();\n const globalBucketId = `HUOBI_PRIVATE_${interfaceTypeUpper}_UID_3S_ALL:${credential.access_key}`;\n const businessBucketId = `HUOBI_PRIVATE_${interfaceTypeUpper}_UID_3S_${businessUpper}:${credential.access_key}`;\n acquirePrivate(globalBucketId, meta);\n acquirePrivate(businessBucketId, meta);\n\n const requestParams = `AccessKeyId=${\n credential.access_key\n }&SignatureMethod=HmacSHA256&SignatureVersion=2&Timestamp=${encodeURIComponent(\n new Date().toISOString().split('.')[0],\n )}${\n method === 'GET' && params !== undefined\n ? `&${Object.entries(params)\n .filter(([, v]) => v !== undefined)\n .sort(([a], [b]) => a.localeCompare(b))\n .map(([k, v]) => `${k}=${v}`)\n .join('&')}`\n : ''\n }`;\n\n const body = method === 'GET' ? '' : JSON.stringify(params);\n\n const requestString = `${method}\\n${api_root}\\n${path}\\n${requestParams}`;\n\n const str = encodeBase64(\n await HmacSHA256(\n new TextEncoder().encode(requestString),\n new TextEncoder().encode(credential.secret_key),\n ),\n );\n\n const url = new URL(`https://${api_root}${path}?${requestParams}&Signature=${encodeURIComponent(str)}`);\n // url.searchParams.sort();\n console.info(formatTime(Date.now()), method, url.href, body);\n const res = await fetch(url.href, {\n method,\n headers: { 'Content-Type': 'application/json' },\n body: body || undefined,\n });\n\n const retStr = await res.text();\n console.info(formatTime(Date.now()), 'PrivateResponse', url.toString(), res.status);\n try {\n return JSON.parse(retStr);\n } catch (e) {\n console.error(formatTime(Date.now()), 'huobiRequestFailed', path, JSON.stringify(params), retStr);\n throw e;\n }\n};\n\nconst spotPrivateQueryRequest = (credential: ICredential, method: string, path: string, params?: any) =>\n privateRequestWithRateLimit(credential, 'query', 'spot', method, path, SPOT_API_ROOT, params);\n\nconst spotPrivateTradeRequest = (credential: ICredential, method: string, path: string, params?: any) =>\n privateRequestWithRateLimit(credential, 'trade', 'spot', method, path, SPOT_API_ROOT, params);\n\nconst linearSwapPrivateQueryRequest = (credential: ICredential, method: string, path: string, params?: any) =>\n privateRequestWithRateLimit(credential, 'query', 'linear-swap', method, path, LINEAR_SWAP_API_ROOT, params);\n\nconst linearSwapPrivateTradeRequest = (credential: ICredential, method: string, path: string, params?: any) =>\n privateRequestWithRateLimit(credential, 'trade', 'linear-swap', method, path, LINEAR_SWAP_API_ROOT, params);\n\n/**\n * 获取账户信息\n *\n * https://www.htx.com/zh-cn/opend/newApiPages/?id=7ec40743-7773-11ed-9966-0242ac110003\n */\nexport const getAccount = (\n credential: ICredential,\n): Promise<{\n status: string;\n data: {\n id: number;\n type: string;\n state: string;\n subtype: string;\n }[];\n}> => {\n return spotPrivateQueryRequest(credential, 'GET', '/v1/account/accounts');\n};\n\n/**\n * 获取用户ID\n *\n * https://www.htx.com/zh-cn/opend/newApiPages/?id=7ec491c9-7773-11ed-9966-0242ac110003\n */\nexport const getUid = (credential: ICredential): Promise<{ data: number; code: number }> => {\n return spotPrivateQueryRequest(credential, 'GET', '/v2/user/uid');\n};\n\n/**\n * 获取统一账户信息\n *\n * https://www.htx.com/zh-cn/opend/newApiPages/?id=10000073-77b7-11ed-9966-0242ac110003\n */\nexport const getUnifiedAccountInfo = (\n credential: ICredential,\n): Promise<{\n status: string;\n code: number;\n msg: string;\n data: {\n margin_asset: string;\n margin_balance: number;\n margin_static: number;\n cross_margin_static: number;\n cross_profit_unreal: number;\n withdraw_available: number;\n }[];\n}> => {\n return linearSwapPrivateQueryRequest(credential, 'GET', '/linear-swap-api/v3/unified_account_info');\n};\n\n/**\n * 获取合约持仓信息\n *\n * https://www.htx.com/zh-cn/opend/newApiPages/?id=8cb74963-77b5-11ed-9966-0242ac110003\n */\nexport const getSwapCrossPositionInfo = (\n credential: ICredential,\n params?: {\n contract_code?: string;\n pair?: string;\n contract_type: string;\n },\n): Promise<{\n status: string;\n ts: number;\n data: {\n symbol: string;\n contract_code: string;\n volume: number;\n available: number;\n frozen: number;\n cost_open: number;\n cost_hold: number;\n profit_unreal: number;\n profit_rate: number;\n lever_rate: number;\n position_margin: number;\n direction: string;\n profit: number;\n last_price: number;\n margin_asset: string;\n margin_mode: string;\n margin_account: string;\n contract_type: string;\n pair: string;\n business_type: string;\n position_mode: string;\n adl_risk_percent: string;\n liquidation_price?: number;\n }[];\n}> => {\n return linearSwapPrivateQueryRequest(\n credential,\n 'POST',\n '/linear-swap-api/v1/swap_cross_position_info',\n params,\n );\n};\n\n/**\n * 获取合约挂单\n *\n * https://www.htx.com/zh-cn/opend/newApiPages/?id=8cb784d4-77b5-11ed-9966-0242ac110003\n */\nexport const getSwapOpenOrders = (\n credential: ICredential,\n params?: {\n contract_code?: string;\n pair?: string;\n page_index?: number;\n page_size?: number;\n sort_by?: string;\n trade_type?: string;\n },\n): Promise<{\n status: string;\n data: {\n orders: {\n order_id_str: string;\n contract_code: string;\n order_price_type: string;\n direction: string;\n offset: string;\n volume: number;\n created_at: number;\n price: number;\n trade_volume: number;\n }[];\n };\n}> => {\n return linearSwapPrivateQueryRequest(\n credential,\n 'POST',\n '/linear-swap-api/v1/swap_cross_openorders',\n params,\n );\n};\n\n/**\n * 获取现货账户余额\n *\n * https://www.htx.com/zh-cn/opend/newApiPages/?id=7ec40922-7773-11ed-9966-0242ac110003\n */\nexport const getSpotAccountBalance = (\n credential: ICredential,\n account_uid: number,\n): Promise<{\n status: string;\n data: {\n list: {\n currency: string;\n balance: string;\n type: string;\n }[];\n };\n}> => {\n return spotPrivateQueryRequest(credential, 'GET', `/v1/account/accounts/${account_uid}/balance`);\n};\n\n/**\n * 获取杠杆借贷信息\n *\n * https://www.htx.com/zh-cn/opend/newApiPages/?id=7ec41863-7773-11ed-9966-0242ac110003\n */\nexport const getCrossMarginLoanInfo = (\n credential: ICredential,\n): Promise<{\n status: string;\n code: number;\n data: {\n currency: string;\n 'loanable-amt': string;\n }[];\n}> => {\n return spotPrivateQueryRequest(credential, 'GET', '/v1/cross-margin/loan-info');\n};\n\n/**\n * 现货下单\n *\n * https://www.htx.com/zh-cn/opend/newApiPages/?id=10000065-77b7-11ed-9966-0242ac110003\n */\nexport const postSpotOrder = (\n credential: ICredential,\n params: {\n symbol: string;\n 'account-id': string;\n amount: string;\n market_amount?: string;\n 'borrow-amount'?: string;\n type: string;\n 'trade-purpose': string;\n price?: string;\n source: string;\n 'client-order-id'?: string;\n },\n): Promise<{ success: boolean; code: number; message: string; data: { orderId: number } }> => {\n return spotPrivateTradeRequest(credential, 'POST', `/v1/order/auto/place`, params);\n};\n\n/**\n * 合约下单\n *\n * https://www.htx.com/zh-cn/opend/newApiPages/?id=8cb77159-77b5-11ed-9966-0242ac110003\n */\nexport const postSwapOrder = (\n credential: ICredential,\n params: {\n contract_code: string;\n contract_type: string;\n price?: number;\n volume: number;\n offset: string;\n direction: string;\n lever_rate: number;\n order_price_type: string;\n channel_code?: string;\n },\n): Promise<{ status: string; ts: number; data: { order_id: number; order_id_str: string } }> => {\n return linearSwapPrivateTradeRequest(credential, 'POST', '/linear-swap-api/v1/swap_cross_order', params);\n};\n\n/**\n * 获取现货存款地址\n *\n * https://www.htx.com/zh-cn/opend/newApiPages/?id=7ec45fb7-7773-11ed-9966-0242ac110003\n */\nexport const getSpotAccountDepositAddresses = (\n credential: ICredential,\n params: { currency: string },\n): Promise<{\n code: number;\n message: string;\n data: {\n currency: string;\n chain: string;\n address: string;\n }[];\n}> => {\n return spotPrivateQueryRequest(credential, 'GET', `/v2/account/deposit/address`, params);\n};\n\n/**\n * 获取账户流水\n *\n * https://www.htx.com/zh-cn/opend/newApiPages/?id=7ec4610b-7773-11ed-9966-0242ac110003\n */\nexport const getAccountLedger = (\n credential: ICredential,\n params: { accountId: string; currency: string },\n): Promise<{\n status: string;\n data: {\n transactTime: number;\n transactAmt: number;\n }[];\n}> => {\n return spotPrivateQueryRequest(credential, 'GET', `/v2/account/ledger`, params);\n};\n\n/**\n * 超级杠杆转出\n *\n * https://www.htx.com/zh-cn/opend/newApiPages/?id=7ec41ff0-7773-11ed-9966-0242ac110003\n */\nexport const postSuperMarginAccountTransferOut = (\n credential: ICredential,\n params: {\n currency: string;\n amount: string;\n },\n): Promise<{ status: string; data: number }> => {\n return spotPrivateTradeRequest(credential, 'POST', `/v1/cross-margin/transfer-out`, params);\n};\n\n/**\n * 超级杠杆转入\n *\n * https://www.htx.com/zh-cn/opend/newApiPages/?id=7ec41f0e-7773-11ed-9966-0242ac110003\n */\nexport const postSuperMarginAccountTransferIn = (\n credential: ICredential,\n params: {\n currency: string;\n amount: string;\n },\n): Promise<{ status: string; data: number }> => {\n return spotPrivateTradeRequest(credential, 'POST', `/v1/cross-margin/transfer-in`, params);\n};\n\n/**\n * 现货账户转账\n *\n * https://www.htx.com/zh-cn/opend/newApiPages/?id=10000095-77b7-11ed-9966-0242ac110003\n */\nexport const postSpotAccountTransfer = (\n credential: ICredential,\n params: {\n from: string;\n to: string;\n currency: string;\n amount: number;\n 'margin-account': string;\n },\n): Promise<{ success: boolean; data: number; code: number; message: string }> => {\n return spotPrivateTradeRequest(credential, 'POST', `/v2/account/transfer`, params);\n};\n\n/**\n * 借贷\n *\n * https://www.htx.com/zh-cn/opend/newApiPages/?id=7ec41b5d-7773-11ed-9966-0242ac110003\n */\nexport const postBorrow = (\n credential: ICredential,\n params: { currency: string; amount: string },\n): Promise<{\n status: string;\n data: number;\n}> => {\n return spotPrivateTradeRequest(credential, 'POST', `/v1/cross-margin/orders`, params);\n};\n\n/**\n * 提现\n *\n * https://www.htx.com/zh-cn/opend/newApiPages/?id=7ec42cfd-7773-11ed-9966-0242ac110003\n */\nexport const postWithdraw = (\n credential: ICredential,\n params: {\n address: string;\n amount: string;\n currency: string;\n fee: string;\n chain: string;\n },\n): Promise<{\n status: string;\n data: number;\n}> => {\n return spotPrivateTradeRequest(credential, 'POST', `/v1/dw/withdraw/api/create`, params);\n};\n\n/**\n * 获取充提历史\n *\n * https://www.htx.com/zh-cn/opend/newApiPages/?id=7ec44f99-7773-11ed-9966-0242ac110003\n */\nexport const getDepositWithdrawHistory = (\n credential: ICredential,\n params: {\n currency: string;\n type: string;\n from?: string;\n size?: string;\n direct?: string;\n },\n): Promise<{\n status: string;\n 'error-code': string;\n 'error-msg': string;\n data: {\n id: number;\n type: string;\n currency: string;\n 'tx-hash': string;\n chain: string;\n amount: string;\n address: string;\n 'address-tag': string;\n fee: string;\n state: string;\n 'create-at': number;\n 'update-at': number;\n }[];\n}> => {\n return spotPrivateQueryRequest(credential, 'GET', `/v1/query/deposit-withdraw`, params);\n};\n\n/**\n * 资产划转(母子用户之间)\n *\n * 接口权限: 交易\n *\n * 限频: 2次/2s\n *\n * https://www.htx.com/zh-cn/opend/newApiPages/?id=7ec45d8e-7773-11ed-9966-0242ac110003\n */\nexport const postSubUserTransfer = (\n credential: ICredential,\n params: {\n 'sub-uid': number;\n currency: string;\n amount: number;\n 'client-order-id'?: string;\n type: string;\n },\n): Promise<{\n data: number;\n status: string;\n}> => {\n return spotPrivateTradeRequest(credential, 'POST', '/v1/subuser/transfer', params);\n};\n\n/**\n * 获取子用户列表\n *\n * 接口权限: 读取\n *\n * https://www.htx.com/zh-cn/opend/newApiPages/?id=7ec48f09-7773-11ed-9966-0242ac110003\n */\nexport const getSubUserList = (\n credential: ICredential,\n params?: { fromId?: number },\n): Promise<{\n code: number;\n message?: string;\n data: {\n uid: number;\n userState: string;\n subUserName: string;\n note: string;\n }[];\n nextId?: number;\n ok: boolean;\n}> => {\n return spotPrivateQueryRequest(credential, 'GET', `/v2/sub-user/user-list`, params);\n};\n\n/**\n * 账户类型查询\n *\n * 是否验签: 是\n *\n * 接口权限: 读取\n *\n * 限频: 每个UID 3秒最多 144 次请求(交易接口3秒最多 72 次请求,查询接口3秒最多 72 次请求) (该UID的所有币种和不同到期日的合约的所有私有接口共享该限制) 。\n *\n * 接口描述: 此接口用于客户查询的账号类型,当前U本位合约有统一账户和非统一账户(全仓逐仓账户)类型。统一账户类型资产放在USDT一个账户上,全仓逐仓账户类型资产放在不同的币对。\n * 统一账户类型为最新升级的,当前不支持API下单。若需要用用API下单请切换账户类型为非统一账户。\n *\n * https://www.htx.com/zh-cn/opend/newApiPages/?id=8cb71825-77b5-11ed-9966-0242ac110003\n */\nexport const getSwapUnifiedAccountType = (\n credential: ICredential,\n): Promise<{\n code: number;\n msg: string;\n ts: number;\n data: {\n account_type: number;\n };\n}> => {\n return linearSwapPrivateQueryRequest(credential, 'GET', '/linear-swap-api/v3/swap_unified_account_type');\n};\n\n/**\n * 账户类型更改接口\n *\n * 是否验签: 是\n *\n * 接口权限: 交易\n *\n * 限频: 每个UID 3秒最多 144 次请求(交易接口3秒最多 72 次请求,查询接口3秒最多 72 次请求) (该UID的所有币种和不同到期日的合约的所有私有接口共享该限制) 。\n *\n * 接口描述: 调用该接口前需要保证U本位合约无持仓和挂单,当由非统一账户(全仓逐仓账户)变为统一账户还需将资产从逐仓账户划转到全仓账户。\n *\n * https://www.htx.com/zh-cn/opend/newApiPages/?id=8cb7196b-77b5-11ed-9966-0242ac110003\n */\nexport const postSwapSwitchAccountType = (\n credential: ICredential,\n params: { account_type: number },\n): Promise<{\n code: number;\n msg: string;\n ts: number;\n data: {\n account_type: number;\n };\n}> => {\n return linearSwapPrivateTradeRequest(\n credential,\n 'POST',\n '/linear-swap-api/v3/swap_switch_account_type',\n params,\n );\n};\n\n/**\n * APIv2币链参考信息\n *\n * https://www.htx.com/zh-cn/opend/newApiPages/?id=7ec478f0-7773-11ed-9966-0242ac110003\n */\nexport const getV2ReferenceCurrencies = (\n credential: ICredential,\n params: {\n currency?: string;\n authorizedUser?: string;\n },\n): Promise<{\n code: number;\n data: {\n currency: string;\n assetType: number;\n chains: {\n chain: string;\n displayName: string;\n fullName: string;\n baseChain?: string;\n baseChainProtocol?: string;\n isDynamic?: boolean;\n numOfConfirmations: number;\n numOfFastConfirmations: number;\n depositStatus: string;\n minDepositAmt: string;\n withdrawStatus: string;\n minWithdrawAmt: string;\n withdrawPrecision: number;\n maxWithdrawAmt: string;\n withdrawQuotaPerDay: string;\n withdrawQuotaPerYear: null;\n withdrawQuotaTotal: null;\n withdrawFeeType: string;\n transactFeeWithdraw?: string;\n addrWithTag: boolean;\n addrDepositTag: boolean;\n minTransactFeeWithdraw?: string;\n transactFeeRateWithdraw?: string;\n maxTransactFeeWithdraw?: string;\n }[];\n instStatus: string;\n }[];\n}> => {\n return spotPrivateQueryRequest(credential, 'GET', '/v2/reference/currencies', params);\n};\n\n/**\n * 获取账户历史\n *\n * https://www.htx.com/zh-cn/opend/newApiPages/?id=7ec41049-7773-11ed-9966-0242ac110003\n */\nexport const getAccountHistory = (\n credential: ICredential,\n params: {\n 'account-id': string;\n currency?: string;\n 'transact-types'?: number;\n 'start-time'?: number;\n 'end-time'?: number;\n sort?: 'asc' | 'desc';\n size?: number;\n 'from-id'?: number;\n },\n): Promise<{\n // code: number;\n 'transact-amt': string;\n 'avail-balance': string;\n 'acct-balance': string;\n 'transact-time': string;\n 'record-id': string;\n status: string;\n data: {\n 'account-id': string;\n currency: string;\n 'record-id': string;\n 'transact-amt': string;\n 'transact-type': string;\n 'avail-balance': string;\n 'acct-balance': string;\n 'transact-time': string;\n }[];\n}> => {\n return spotPrivateQueryRequest(credential, 'GET', '/v1/account/history', params);\n};\n"]}
1
+ {"version":3,"file":"private-api.js","sourceRoot":"","sources":["../../src/api/private-api.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC;AAE9F,MAAM,aAAa,GAAG,eAAe,CAAC;AACtC,MAAM,oBAAoB,GAAG,cAAc,CAAC;AAO5C,MAAM,CAAC,MAAM,oBAAoB,GAAG,GAAgB,EAAE;IACpD,OAAO;QACL,UAAU,EAAE,OAAO,CAAC,GAAG,CAAC,UAAW;QACnC,UAAU,EAAE,OAAO,CAAC,GAAG,CAAC,UAAW;KACpC,CAAC;AACJ,CAAC,CAAC;AAMF,MAAM,cAAc,GAAG,IAAI,GAAG,EAAU,CAAC;AACzC,MAAM,wBAAwB,GAAG,CAAC,QAAgB,EAAE,EAAE;IACpD,IAAI,CAAC,cAAc,CAAC,GAAG,CAAC,QAAQ,CAAC,EAAE;QACjC,cAAc,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC;QAC7B,WAAW,CAAC,QAAQ,EAAE,EAAE,QAAQ,EAAE,EAAE,EAAE,YAAY,EAAE,EAAE,EAAE,cAAc,EAAE,IAAI,EAAE,CAAC,CAAC;KACjF;IACD,OAAO,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AAqB,CAAC,CAAC;AACjF,CAAC,CAAC;AAEF;;;;GAIG;AACH,MAAM,CAAC,MAAM,wBAAwB,GAAG,CACtC,UAAuB,EA2BtB,EAAE;IACH,OAAO,6BAA6B,CAAC,UAAU,EAAE,KAAK,EAAE,0BAA0B,CAAC,CAAC;AACtF,CAAC,CAAC","sourcesContent":["import { encodeBase64, formatTime, HmacSHA256, scopeError, tokenBucket } from '@yuants/utils';\n\nconst SPOT_API_ROOT = 'api.huobi.pro';\nconst LINEAR_SWAP_API_ROOT = 'api.hbdm.com';\n\nexport interface ICredential {\n access_key: string;\n secret_key: string;\n}\n\nexport const getDefaultCredential = (): ICredential => {\n return {\n access_key: process.env.ACCESS_KEY!,\n secret_key: process.env.SECRET_KEY!,\n };\n};\n\n// https://www.htx.com/zh-cn/opend/newApiPages/?id=474\ntype HuobiBusiness = 'spot' | 'linear-swap';\ntype HuobiPrivateInterfaceType = 'trade' | 'query';\n\nconst createdBuckets = new Set<string>();\nconst getOrCreatePrivateBucket = (bucketId: string) => {\n if (!createdBuckets.has(bucketId)) {\n createdBuckets.add(bucketId);\n tokenBucket(bucketId, { capacity: 36, refillAmount: 36, refillInterval: 3000 });\n }\n return tokenBucket(bucketId);\n};\n\nconst acquirePrivate = (bucketId: string, meta: Record<string, unknown>) => {\n const bucket = getOrCreatePrivateBucket(bucketId);\n scopeError('HUOBI_API_RATE_LIMIT', { ...meta, bucketId }, () => bucket.acquireSync(1));\n};\n\nconst privateRequestWithRateLimit = async (\n credential: ICredential,\n interfaceType: HuobiPrivateInterfaceType,\n business: HuobiBusiness,\n method: string,\n path: string,\n api_root: string,\n params?: any,\n) => {\n const meta = { method, api_root, path, business, interfaceType, access_key: credential.access_key };\n\n const interfaceTypeUpper = interfaceType.toUpperCase();\n const businessUpper = business.toUpperCase();\n const globalBucketId = `HUOBI_PRIVATE_${interfaceTypeUpper}_UID_3S_ALL:${credential.access_key}`;\n const businessBucketId = `HUOBI_PRIVATE_${interfaceTypeUpper}_UID_3S_${businessUpper}:${credential.access_key}`;\n acquirePrivate(globalBucketId, meta);\n acquirePrivate(businessBucketId, meta);\n\n const requestParams = `AccessKeyId=${\n credential.access_key\n }&SignatureMethod=HmacSHA256&SignatureVersion=2&Timestamp=${encodeURIComponent(\n new Date().toISOString().split('.')[0],\n )}${\n method === 'GET' && params !== undefined\n ? `&${Object.entries(params)\n .filter(([, v]) => v !== undefined)\n .sort(([a], [b]) => a.localeCompare(b))\n .map(([k, v]) => `${k}=${v}`)\n .join('&')}`\n : ''\n }`;\n\n const body = method === 'GET' ? '' : JSON.stringify(params);\n\n const requestString = `${method}\\n${api_root}\\n${path}\\n${requestParams}`;\n\n const str = encodeBase64(\n await HmacSHA256(\n new TextEncoder().encode(requestString),\n new TextEncoder().encode(credential.secret_key),\n ),\n );\n\n const url = new URL(`https://${api_root}${path}?${requestParams}&Signature=${encodeURIComponent(str)}`);\n // url.searchParams.sort();\n console.info(formatTime(Date.now()), method, url.href, body);\n const res = await fetch(url.href, {\n method,\n headers: { 'Content-Type': 'application/json' },\n body: body || undefined,\n });\n\n const retStr = await res.text();\n console.info(formatTime(Date.now()), 'PrivateResponse', url.toString(), res.status);\n try {\n return JSON.parse(retStr);\n } catch (e) {\n console.error(formatTime(Date.now()), 'huobiRequestFailed', path, JSON.stringify(params), retStr);\n throw e;\n }\n};\n\nconst spotPrivateQueryRequest = (credential: ICredential, method: string, path: string, params?: any) =>\n privateRequestWithRateLimit(credential, 'query', 'spot', method, path, SPOT_API_ROOT, params);\n\nconst spotPrivateTradeRequest = (credential: ICredential, method: string, path: string, params?: any) =>\n privateRequestWithRateLimit(credential, 'trade', 'spot', method, path, SPOT_API_ROOT, params);\n\nconst linearSwapPrivateQueryRequest = (credential: ICredential, method: string, path: string, params?: any) =>\n privateRequestWithRateLimit(credential, 'query', 'linear-swap', method, path, LINEAR_SWAP_API_ROOT, params);\n\nconst linearSwapPrivateTradeRequest = (credential: ICredential, method: string, path: string, params?: any) =>\n privateRequestWithRateLimit(credential, 'trade', 'linear-swap', method, path, LINEAR_SWAP_API_ROOT, params);\n\n/**\n * 获取账户信息\n *\n * https://www.htx.com/zh-cn/opend/newApiPages/?id=7ec40743-7773-11ed-9966-0242ac110003\n */\nexport const getAccount = (\n credential: ICredential,\n): Promise<{\n status: string;\n data: {\n id: number;\n type: string;\n state: string;\n subtype: string;\n }[];\n}> => {\n return spotPrivateQueryRequest(credential, 'GET', '/v1/account/accounts');\n};\n\n/**\n * 获取用户ID\n *\n * https://www.htx.com/zh-cn/opend/newApiPages/?id=7ec491c9-7773-11ed-9966-0242ac110003\n */\nexport const getUid = (credential: ICredential): Promise<{ data: number; code: number }> => {\n return spotPrivateQueryRequest(credential, 'GET', '/v2/user/uid');\n};\n\n/**\n * 获取统一账户信息\n *\n * https://www.htx.com/zh-cn/opend/newApiPages/?id=10000073-77b7-11ed-9966-0242ac110003\n */\nexport const getUnifiedAccountInfo = (\n credential: ICredential,\n): Promise<{\n status: string;\n code: number;\n msg: string;\n data: {\n margin_asset: string;\n margin_balance: number;\n margin_static: number;\n cross_margin_static: number;\n cross_profit_unreal: number;\n withdraw_available: number;\n }[];\n}> => {\n return linearSwapPrivateQueryRequest(credential, 'GET', '/linear-swap-api/v3/unified_account_info');\n};\n\n/**\n * 获取合约持仓信息\n *\n * https://www.htx.com/zh-cn/opend/newApiPages/?id=8cb74963-77b5-11ed-9966-0242ac110003\n */\nexport const getSwapCrossPositionInfo = (\n credential: ICredential,\n params?: {\n contract_code?: string;\n pair?: string;\n contract_type: string;\n },\n): Promise<{\n status: string;\n ts: number;\n data: {\n symbol: string;\n contract_code: string;\n volume: number;\n available: number;\n frozen: number;\n cost_open: number;\n cost_hold: number;\n profit_unreal: number;\n profit_rate: number;\n lever_rate: number;\n position_margin: number;\n direction: string;\n profit: number;\n last_price: number;\n margin_asset: string;\n margin_mode: string;\n margin_account: string;\n contract_type: string;\n pair: string;\n business_type: string;\n position_mode: string;\n adl_risk_percent: string;\n liquidation_price?: number;\n }[];\n}> => {\n return linearSwapPrivateQueryRequest(\n credential,\n 'POST',\n '/linear-swap-api/v1/swap_cross_position_info',\n params,\n );\n};\n\n/**\n * 获取合约挂单\n *\n * https://www.htx.com/zh-cn/opend/newApiPages/?id=8cb784d4-77b5-11ed-9966-0242ac110003\n */\nexport const getSwapOpenOrders = (\n credential: ICredential,\n params?: {\n contract_code?: string;\n pair?: string;\n page_index?: number;\n page_size?: number;\n sort_by?: string;\n trade_type?: string;\n },\n): Promise<{\n status: string;\n data: {\n orders: {\n order_id_str: string;\n contract_code: string;\n order_price_type: string;\n direction: string;\n offset: string;\n volume: number;\n created_at: number;\n price: number;\n trade_volume: number;\n }[];\n };\n}> => {\n return linearSwapPrivateQueryRequest(\n credential,\n 'POST',\n '/linear-swap-api/v1/swap_cross_openorders',\n params,\n );\n};\n\n/**\n * 获取现货账户余额\n *\n * https://www.htx.com/zh-cn/opend/newApiPages/?id=7ec40922-7773-11ed-9966-0242ac110003\n */\nexport const getSpotAccountBalance = (\n credential: ICredential,\n account_uid: number,\n): Promise<{\n status: string;\n data: {\n list: {\n currency: string;\n balance: string;\n type: string;\n }[];\n };\n}> => {\n return spotPrivateQueryRequest(credential, 'GET', `/v1/account/accounts/${account_uid}/balance`);\n};\n\n/**\n * 获取杠杆借贷信息\n *\n * https://www.htx.com/zh-cn/opend/newApiPages/?id=7ec41863-7773-11ed-9966-0242ac110003\n */\nexport const getCrossMarginLoanInfo = (\n credential: ICredential,\n): Promise<{\n status: string;\n code: number;\n data: {\n currency: string;\n 'loanable-amt': string;\n }[];\n}> => {\n return spotPrivateQueryRequest(credential, 'GET', '/v1/cross-margin/loan-info');\n};\n\n/**\n * 现货下单\n *\n * https://www.htx.com/zh-cn/opend/newApiPages/?id=10000065-77b7-11ed-9966-0242ac110003\n */\nexport const postSpotOrder = (\n credential: ICredential,\n params: {\n symbol: string;\n 'account-id': string;\n amount: string;\n market_amount?: string;\n 'borrow-amount'?: string;\n type: string;\n 'trade-purpose': string;\n price?: string;\n source: string;\n 'client-order-id'?: string;\n },\n): Promise<{ success: boolean; code: number; message: string; data: { orderId: number } }> => {\n return spotPrivateTradeRequest(credential, 'POST', `/v1/order/auto/place`, params);\n};\n\n/**\n * 合约下单\n *\n * https://www.htx.com/zh-cn/opend/newApiPages/?id=8cb77159-77b5-11ed-9966-0242ac110003\n */\nexport const postSwapOrder = (\n credential: ICredential,\n params: {\n contract_code: string;\n contract_type: string;\n price?: number;\n volume: number;\n offset: string;\n direction: string;\n lever_rate: number;\n order_price_type: string;\n channel_code?: string;\n },\n): Promise<{ status: string; ts: number; data: { order_id: number; order_id_str: string } }> => {\n return linearSwapPrivateTradeRequest(credential, 'POST', '/linear-swap-api/v1/swap_cross_order', params);\n};\n\n/**\n * 联合保证金模式合约下单\n *\n * https://www.htx.com/zh-cn/opend/newApiPages/?id=8cb89359-77b5-11ed-9966-1957dd521e6\n */\nexport const postUnionAccountSwapOrder = (\n credential: ICredential,\n params: {\n time_in_force?: string;\n price_protect?: string;\n contract_code: string;\n margin_mode: string;\n position_side: string;\n price?: number;\n volume: number;\n side: string;\n type: string;\n tp_trigger_price?: string;\n tp_order_price?: string;\n tp_trigger_price_type?: string;\n tp_type?: string;\n sl_trigger_price?: string;\n sl_order_price?: string;\n sl_trigger_price_type?: string;\n sl_type?: string;\n },\n): Promise<{ code: number; message: string; data: { order_id: number; order_id_str: string } }> => {\n return linearSwapPrivateTradeRequest(credential, 'POST', '/v5/trade/order', params);\n};\n\n/**\n * 获取现货存款地址\n *\n * https://www.htx.com/zh-cn/opend/newApiPages/?id=7ec45fb7-7773-11ed-9966-0242ac110003\n */\nexport const getSpotAccountDepositAddresses = (\n credential: ICredential,\n params: { currency: string },\n): Promise<{\n code: number;\n message: string;\n data: {\n currency: string;\n chain: string;\n address: string;\n }[];\n}> => {\n return spotPrivateQueryRequest(credential, 'GET', `/v2/account/deposit/address`, params);\n};\n\n/**\n * 获取账户流水\n *\n * https://www.htx.com/zh-cn/opend/newApiPages/?id=7ec4610b-7773-11ed-9966-0242ac110003\n */\nexport const getAccountLedger = (\n credential: ICredential,\n params: { accountId: string; currency: string },\n): Promise<{\n status: string;\n data: {\n transactTime: number;\n transactAmt: number;\n }[];\n}> => {\n return spotPrivateQueryRequest(credential, 'GET', `/v2/account/ledger`, params);\n};\n\n/**\n * 超级杠杆转出\n *\n * https://www.htx.com/zh-cn/opend/newApiPages/?id=7ec41ff0-7773-11ed-9966-0242ac110003\n */\nexport const postSuperMarginAccountTransferOut = (\n credential: ICredential,\n params: {\n currency: string;\n amount: string;\n },\n): Promise<{ status: string; data: number }> => {\n return spotPrivateTradeRequest(credential, 'POST', `/v1/cross-margin/transfer-out`, params);\n};\n\n/**\n * 超级杠杆转入\n *\n * https://www.htx.com/zh-cn/opend/newApiPages/?id=7ec41f0e-7773-11ed-9966-0242ac110003\n */\nexport const postSuperMarginAccountTransferIn = (\n credential: ICredential,\n params: {\n currency: string;\n amount: string;\n },\n): Promise<{ status: string; data: number }> => {\n return spotPrivateTradeRequest(credential, 'POST', `/v1/cross-margin/transfer-in`, params);\n};\n\n/**\n * 现货账户转账\n *\n * https://www.htx.com/zh-cn/opend/newApiPages/?id=10000095-77b7-11ed-9966-0242ac110003\n */\nexport const postSpotAccountTransfer = (\n credential: ICredential,\n params: {\n from: string;\n to: string;\n currency: string;\n amount: number;\n 'margin-account': string;\n },\n): Promise<{ success: boolean; data: number; code: number; message: string }> => {\n return spotPrivateTradeRequest(credential, 'POST', `/v2/account/transfer`, params);\n};\n\n/**\n * 借贷\n *\n * https://www.htx.com/zh-cn/opend/newApiPages/?id=7ec41b5d-7773-11ed-9966-0242ac110003\n */\nexport const postBorrow = (\n credential: ICredential,\n params: { currency: string; amount: string },\n): Promise<{\n status: string;\n data: number;\n}> => {\n return spotPrivateTradeRequest(credential, 'POST', `/v1/cross-margin/orders`, params);\n};\n\n/**\n * 提现\n *\n * https://www.htx.com/zh-cn/opend/newApiPages/?id=7ec42cfd-7773-11ed-9966-0242ac110003\n */\nexport const postWithdraw = (\n credential: ICredential,\n params: {\n address: string;\n amount: string;\n currency: string;\n fee: string;\n chain: string;\n },\n): Promise<{\n status: string;\n data: number;\n}> => {\n return spotPrivateTradeRequest(credential, 'POST', `/v1/dw/withdraw/api/create`, params);\n};\n\n/**\n * 获取充提历史\n *\n * https://www.htx.com/zh-cn/opend/newApiPages/?id=7ec44f99-7773-11ed-9966-0242ac110003\n */\nexport const getDepositWithdrawHistory = (\n credential: ICredential,\n params: {\n currency: string;\n type: string;\n from?: string;\n size?: string;\n direct?: string;\n },\n): Promise<{\n status: string;\n 'error-code': string;\n 'error-msg': string;\n data: {\n id: number;\n type: string;\n currency: string;\n 'tx-hash': string;\n chain: string;\n amount: string;\n address: string;\n 'address-tag': string;\n fee: string;\n state: string;\n 'create-at': number;\n 'update-at': number;\n }[];\n}> => {\n return spotPrivateQueryRequest(credential, 'GET', `/v1/query/deposit-withdraw`, params);\n};\n\n/**\n * 资产划转(母子用户之间)\n *\n * 接口权限: 交易\n *\n * 限频: 2次/2s\n *\n * https://www.htx.com/zh-cn/opend/newApiPages/?id=7ec45d8e-7773-11ed-9966-0242ac110003\n */\nexport const postSubUserTransfer = (\n credential: ICredential,\n params: {\n 'sub-uid': number;\n currency: string;\n amount: number;\n 'client-order-id'?: string;\n type: string;\n },\n): Promise<{\n data: number;\n status: string;\n}> => {\n return spotPrivateTradeRequest(credential, 'POST', '/v1/subuser/transfer', params);\n};\n\n/**\n * 获取子用户列表\n *\n * 接口权限: 读取\n *\n * https://www.htx.com/zh-cn/opend/newApiPages/?id=7ec48f09-7773-11ed-9966-0242ac110003\n */\nexport const getSubUserList = (\n credential: ICredential,\n params?: { fromId?: number },\n): Promise<{\n code: number;\n message?: string;\n data: {\n uid: number;\n userState: string;\n subUserName: string;\n note: string;\n }[];\n nextId?: number;\n ok: boolean;\n}> => {\n return spotPrivateQueryRequest(credential, 'GET', `/v2/sub-user/user-list`, params);\n};\n\n/**\n * 账户类型查询\n *\n * 是否验签: 是\n *\n * 接口权限: 读取\n *\n * 限频: 每个UID 3秒最多 144 次请求(交易接口3秒最多 72 次请求,查询接口3秒最多 72 次请求) (该UID的所有币种和不同到期日的合约的所有私有接口共享该限制) 。\n *\n * 接口描述: 此接口用于客户查询的账号类型,当前U本位合约有统一账户和非统一账户(全仓逐仓账户)类型。统一账户类型资产放在USDT一个账户上,全仓逐仓账户类型资产放在不同的币对。\n * 统一账户类型为最新升级的,当前不支持API下单。若需要用用API下单请切换账户类型为非统一账户。\n *\n * https://www.htx.com/zh-cn/opend/newApiPages/?id=8cb71825-77b5-11ed-9966-0242ac110003\n */\nexport const getSwapUnifiedAccountType = (\n credential: ICredential,\n): Promise<{\n code: number;\n msg: string;\n ts: number;\n data: {\n account_type: number;\n };\n}> => {\n return linearSwapPrivateQueryRequest(credential, 'GET', '/linear-swap-api/v3/swap_unified_account_type');\n};\n\n/**\n * 账户类型更改接口\n *\n * 是否验签: 是\n *\n * 接口权限: 交易\n *\n * 限频: 每个UID 3秒最多 144 次请求(交易接口3秒最多 72 次请求,查询接口3秒最多 72 次请求) (该UID的所有币种和不同到期日的合约的所有私有接口共享该限制) 。\n *\n * 接口描述: 调用该接口前需要保证U本位合约无持仓和挂单,当由非统一账户(全仓逐仓账户)变为统一账户还需将资产从逐仓账户划转到全仓账户。\n *\n * https://www.htx.com/zh-cn/opend/newApiPages/?id=8cb7196b-77b5-11ed-9966-0242ac110003\n */\nexport const postSwapSwitchAccountType = (\n credential: ICredential,\n params: { account_type: number },\n): Promise<{\n code: number;\n msg: string;\n ts: number;\n data: {\n account_type: number;\n };\n}> => {\n return linearSwapPrivateTradeRequest(\n credential,\n 'POST',\n '/linear-swap-api/v3/swap_switch_account_type',\n params,\n );\n};\n\n/**\n * APIv2币链参考信息\n *\n * https://www.htx.com/zh-cn/opend/newApiPages/?id=7ec478f0-7773-11ed-9966-0242ac110003\n */\nexport const getV2ReferenceCurrencies = (\n credential: ICredential,\n params: {\n currency?: string;\n authorizedUser?: string;\n },\n): Promise<{\n code: number;\n data: {\n currency: string;\n assetType: number;\n chains: {\n chain: string;\n displayName: string;\n fullName: string;\n baseChain?: string;\n baseChainProtocol?: string;\n isDynamic?: boolean;\n numOfConfirmations: number;\n numOfFastConfirmations: number;\n depositStatus: string;\n minDepositAmt: string;\n withdrawStatus: string;\n minWithdrawAmt: string;\n withdrawPrecision: number;\n maxWithdrawAmt: string;\n withdrawQuotaPerDay: string;\n withdrawQuotaPerYear: null;\n withdrawQuotaTotal: null;\n withdrawFeeType: string;\n transactFeeWithdraw?: string;\n addrWithTag: boolean;\n addrDepositTag: boolean;\n minTransactFeeWithdraw?: string;\n transactFeeRateWithdraw?: string;\n maxTransactFeeWithdraw?: string;\n }[];\n instStatus: string;\n }[];\n}> => {\n return spotPrivateQueryRequest(credential, 'GET', '/v2/reference/currencies', params);\n};\n\n/**\n * 获取账户历史\n *\n * https://www.htx.com/zh-cn/opend/newApiPages/?id=7ec41049-7773-11ed-9966-0242ac110003\n */\nexport const getAccountHistory = (\n credential: ICredential,\n params: {\n 'account-id': string;\n currency?: string;\n 'transact-types'?: number;\n 'start-time'?: number;\n 'end-time'?: number;\n sort?: 'asc' | 'desc';\n size?: number;\n 'from-id'?: number;\n },\n): Promise<{\n // code: number;\n 'transact-amt': string;\n 'avail-balance': string;\n 'acct-balance': string;\n 'transact-time': string;\n 'record-id': string;\n status: string;\n data: {\n 'account-id': string;\n currency: string;\n 'record-id': string;\n 'transact-amt': string;\n 'transact-type': string;\n 'avail-balance': string;\n 'acct-balance': string;\n 'transact-time': string;\n }[];\n}> => {\n return spotPrivateQueryRequest(credential, 'GET', '/v1/account/history', params);\n};\n\n/**\n * 查询资产模式\n *\n * https://www.htx.com/zh-cn/opend/newApiPages/?id=8cb89359-77b5-11ed-9966-1957dd37de0\n */\nexport const getAccountAssetsMode = (\n credential: ICredential,\n): Promise<{\n code: number;\n msg: string;\n data: {\n asset_mode: number;\n };\n ts: number;\n}> => {\n return linearSwapPrivateQueryRequest(credential, 'GET', '/v5/account/asset_mode');\n};\n\n/**\n * 查询联合保证金账户余额\n *\n * https://www.htx.com/zh-cn/opend/newApiPages/?id=8cb89359-77b5-11ed-9966-195703a12d5\n */\nexport const getUnionAccountBalance = (\n credential: ICredential,\n): Promise<{\n code: number;\n message: string;\n data: {\n available_margin: string;\n created_time: number;\n details: {\n available: string;\n created_time: number;\n currency: string;\n equity: string;\n initial_margin: string;\n initial_margin_rate: string;\n maintenance_margin: string;\n maintenance_margin_rate: string;\n profit_unreal: string;\n voucher: string;\n voucher_value: string;\n withdraw_available: string;\n updated_time: number;\n }[];\n equity: string;\n initial_margin: string;\n maintenance_margin: string;\n maintenance_margin_rate: string;\n profit_unreal: string;\n state: string;\n voucher_value: string;\n updated_time: number;\n };\n ts: number;\n}> => {\n return linearSwapPrivateQueryRequest(credential, 'GET', '/v5/account/balance');\n};\n\n/**\n * 查询联合保证金账户持仓\n *\n * https://www.htx.com/zh-cn/opend/newApiPages/?id=8cb89359-77b5-11ed-9966-1957f1fbee4\n */\nexport const getUnionAccountPositions = (\n credential: ICredential,\n): Promise<{\n code: number;\n message: string;\n data: {\n contract_code: string;\n position_side: string;\n direction: string;\n margin_mode: string;\n open_avg_price: string;\n volume: string;\n available: string;\n lever_rate: number;\n adl_risk_percent: null;\n liquidation_price: string;\n initial_margin: string;\n maintenance_margin: string;\n profit_unreal: string;\n profit_rate: string;\n margin_rate: string;\n mark_price: string;\n margin_currency: string;\n contract_type: string;\n created_time: number;\n updated_time: number;\n }[];\n ts: number;\n}> => {\n return linearSwapPrivateQueryRequest(credential, 'GET', '/v5/trade/position/opens');\n};\n"]}
@@ -23,6 +23,7 @@ export const getSpotAccountInfo = async (credential) => {
23
23
  volume: +((_b = v.balance) !== null && _b !== void 0 ? _b : 0),
24
24
  free_volume: +((_c = v.balance) !== null && _c !== void 0 ? _c : 0),
25
25
  closable_price: closable_price,
26
+ size: v.balance,
26
27
  }));
27
28
  }
28
29
  return positions;
@@ -1 +1 @@
1
- {"version":3,"file":"spot.js","sourceRoot":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,EAAE;YAC5B,aAAa,EAAE,KAAK;YACpB,UAAU,EAAE,UAAU;YACtB,MAAM,EAAE,CAAC,CAAC,MAAA,CAAC,CAAC,OAAO,mCAAI,CAAC,CAAC;YACzB,WAAW,EAAE,CAAC,CAAC,MAAA,CAAC,CAAC,OAAO,mCAAI,CAAC,CAAC;YAC9B,cAAc,EAAE,cAAc;SAC/B,CAAC,CACH,CAAC;KACH;IACD,OAAO,SAAS,CAAC;AACnB,CAAC,CAAC","sourcesContent":["import { IActionHandlerOfGetAccountInfo, IPosition, makeSpotPosition } from '@yuants/data-account';\nimport { getSpotAccountBalance, ICredential } from '../../api/private-api';\nimport { spotAccountUidCache } from '../uid';\nimport { encodePath } from '@yuants/utils';\nimport { quoteCache } from '../market-data/quote';\n\nexport const getSpotAccountInfo: IActionHandlerOfGetAccountInfo<ICredential> = async (credential) => {\n const spotAccountUid = await spotAccountUidCache.query(JSON.stringify(credential));\n if (!spotAccountUid) throw new Error('Failed to get Spot Account UID');\n const spotBalance = await getSpotAccountBalance(credential, spotAccountUid);\n\n const positions: IPosition[] = [];\n\n for (const v of spotBalance.data.list) {\n if (v.balance === '0') continue;\n const product_id = encodePath('HTX', 'SPOT', v.currency + 'usdt');\n const quote = await quoteCache.query(product_id);\n const closable_price = v.currency === 'usdt' ? 1 : +(quote?.ask_price ?? 0);\n positions.push(\n makeSpotPosition({\n position_id: `${v.currency}`,\n datasource_id: 'HTX',\n product_id: product_id,\n volume: +(v.balance ?? 0),\n free_volume: +(v.balance ?? 0),\n closable_price: closable_price,\n }),\n );\n }\n return positions;\n};\n"]}
1
+ {"version":3,"file":"spot.js","sourceRoot":"","sources":["../../../src/services/accounts/spot.ts"],"names":[],"mappings":"AAAA,OAAO,EAA6C,gBAAgB,EAAE,MAAM,sBAAsB,CAAC;AACnG,OAAO,EAAE,qBAAqB,EAAe,MAAM,uBAAuB,CAAC;AAC3E,OAAO,EAAE,mBAAmB,EAAE,MAAM,QAAQ,CAAC;AAC7C,OAAO,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c,EAAE,cAAc;YAC9B,IAAI,EAAE,CAAC,CAAC,OAAO;SAChB,CAAC,CACH,CAAC;KACH;IACD,OAAO,SAAS,CAAC;AACnB,CAAC,CAAC","sourcesContent":["import { IActionHandlerOfGetAccountInfo, IPosition, makeSpotPosition } from '@yuants/data-account';\nimport { getSpotAccountBalance, ICredential } from '../../api/private-api';\nimport { spotAccountUidCache } from '../uid';\nimport { encodePath } from '@yuants/utils';\nimport { quoteCache } from '../market-data/quote';\n\nexport const getSpotAccountInfo: IActionHandlerOfGetAccountInfo<ICredential> = async (credential) => {\n const spotAccountUid = await spotAccountUidCache.query(JSON.stringify(credential));\n if (!spotAccountUid) throw new Error('Failed to get Spot Account UID');\n const spotBalance = await getSpotAccountBalance(credential, spotAccountUid);\n\n const positions: IPosition[] = [];\n\n for (const v of spotBalance.data.list) {\n if (v.balance === '0') continue;\n const product_id = encodePath('HTX', 'SPOT', v.currency + 'usdt');\n const quote = await quoteCache.query(product_id);\n const closable_price = v.currency === 'usdt' ? 1 : +(quote?.ask_price ?? 0);\n positions.push(\n makeSpotPosition({\n position_id: `${v.currency}`,\n datasource_id: 'HTX',\n product_id: product_id,\n volume: +(v.balance ?? 0),\n free_volume: +(v.balance ?? 0),\n closable_price: closable_price,\n size: v.balance,\n }),\n );\n }\n return positions;\n};\n"]}
@@ -19,7 +19,7 @@ export const getSuperMarginAccountInfo = async (credential) => {
19
19
  for (const currencyData of balanceList) {
20
20
  if (currencyData.balance === '0')
21
21
  continue;
22
- const product_id = encodePath('HTX', 'SPOT', currencyData.currency + 'usdt');
22
+ const product_id = encodePath('HTX', 'SUPER-MARGIN', currencyData.currency + 'usdt');
23
23
  const quote = await quoteCache.query(currencyData.currency);
24
24
  const closable_price = currencyData.currency === 'usdt' ? 1 : +((_b = quote === null || quote === void 0 ? void 0 : quote.ask_price) !== null && _b !== void 0 ? _b : 0);
25
25
  positions.push(makeSpotPosition({
@@ -28,6 +28,7 @@ export const getSuperMarginAccountInfo = async (credential) => {
28
28
  volume: +currencyData.balance,
29
29
  free_volume: +currencyData.balance,
30
30
  closable_price: closable_price,
31
+ size: currencyData.balance,
31
32
  }));
32
33
  }
33
34
  return positions;
@@ -1 +1 @@
1
- {"version":3,"file":"super-margin.js","sourceRoot":"","sources":["../../../src/services/accounts/super-margin.ts"],"names":[],"mappings":"AAAA,OAAO,EAA6C,gBAAgB,EAAE,MAAM,sBAAsB,CAAC;AACnG,OAAO,EAAE,UAAU,EAAE,MAAM,eAAe,CAAC;AAC3C,OAAO,EAAE,qBAAqB,EAAe,MAAM,uBAAuB,CAAC;AAC3E,OAAO,EAAE,UAAU,EAAE,MAAM,sBAAsB,CAAC;AAClD,OAAO,EAAE,0BAA0B,EAAE,MAAM,QAAQ,CAAC;AAEpD;;GAEG;AACH,MAAM,CAAC,MAAM,yBAAyB,GAAgD,KAAK,EAAE,UAAU,EAAE,EAAE;;IACzG,MAAM,SAAS,GAAgB,EAAE,CAAC;IAClC,sBAAsB;IACtB,MAAM,qBAAqB,GAAG,MAAM,0BAA0B,CAAC,KAAK,CAAC,IAAI,CAAC,SAAS,CAAC,UAAU,CAAC,CAAC,CAAC;IACjG,IAAI,CAAC,qBAAqB;QAAE,MAAM,IAAI,KAAK,CAAC,wCAAwC,CAAC,CAAC;IACtF,MAAM,cAAc,GAAG,MAAM,qBAAqB,CAAC,UAAU,EAAE,qBAAqB,CAAC,CAAC;IACtF,MAAM,WAAW,GAAG,CAAA,MAAA,cAAc,CAAC,IAAI,0CAAE,IAAI,KAAI,EAAE,CAAC;IAEpD,kCAAkC;IAClC,KAAK,MAAM,YAAY,IAAI,WAAW,EAAE;QACtC,IAAI,YAAY,CAAC,OAAO,KAAK,GAAG;YAAE,SAAS;QAC3C,MAAM,UAAU,GAAG,UAAU,CAAC,KAAK,EAAE,MAAM,EAAE,YAAY,CAAC,QAAQ,GAAG,MAAM,CAAC,CAAC;QAC7E,MAAM,KAAK,GAAG,MAAM,UAAU,CAAC,KAAK,CAAC,YAAY,CAAC,QAAQ,CAAC,CAAC;QAC5D,MAAM,cAAc,GAAG,YAAY,CAAC,QAAQ,KAAK,MAAM,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,MAAA,KAAK,aAAL,KAAK,uBAAL,KAAK,CAAE,SAAS,mCAAI,CAAC,CAAC,CAAC;QAEvF,SAAS,CAAC,IAAI,CACZ,gBAAgB,CAAC;YACf,WAAW,EAAE,GAAG,YAAY,CAAC,QAAQ,YAAY;YACjD,UAAU,EAAE,UAAU;YACtB,MAAM,EAAE,CAAC,YAAY,CAAC,OAAO;YAC7B,WAAW,EAAE,CAAC,YAAY,CAAC,OAAO;YAClC,cAAc,EAAE,cAAc;SAC/B,CAAC,CACH,CAAC;KACH;IAED,OAAO,SAAS,CAAC;AACnB,CAAC,CAAC","sourcesContent":["import { IActionHandlerOfGetAccountInfo, IPosition, makeSpotPosition } from '@yuants/data-account';\nimport { encodePath } from '@yuants/utils';\nimport { getSpotAccountBalance, ICredential } from '../../api/private-api';\nimport { quoteCache } from '../market-data/quote';\nimport { superMarginAccountUidCache } from '../uid';\n\n/**\n * 全仓杠杆账户 (Super Margin Account)\n */\nexport const getSuperMarginAccountInfo: IActionHandlerOfGetAccountInfo<ICredential> = async (credential) => {\n const positions: IPosition[] = [];\n // get account balance\n const superMarginAccountUid = await superMarginAccountUidCache.query(JSON.stringify(credential));\n if (!superMarginAccountUid) throw new Error('Failed to get Super Margin Account UID');\n const accountBalance = await getSpotAccountBalance(credential, superMarginAccountUid);\n const balanceList = accountBalance.data?.list || [];\n\n // get prices and create positions\n for (const currencyData of balanceList) {\n if (currencyData.balance === '0') continue;\n const product_id = encodePath('HTX', 'SPOT', currencyData.currency + 'usdt');\n const quote = await quoteCache.query(currencyData.currency);\n const closable_price = currencyData.currency === 'usdt' ? 1 : +(quote?.ask_price ?? 0);\n\n positions.push(\n makeSpotPosition({\n position_id: `${currencyData.currency}/usdt/spot`,\n product_id: product_id,\n volume: +currencyData.balance,\n free_volume: +currencyData.balance,\n closable_price: closable_price,\n }),\n );\n }\n\n return positions;\n};\n"]}
1
+ {"version":3,"file":"super-margin.js","sourceRoot":"","sources":["../../../src/services/accounts/super-margin.ts"],"names":[],"mappings":"AAAA,OAAO,EAA6C,gBAAgB,EAAE,MAAM,sBAAsB,CAAC;AACnG,OAAO,EAAE,UAAU,EAAE,MAAM,eAAe,CAAC;AAC3C,OAAO,EAAE,qBAAqB,EAAe,MAAM,uBAAuB,CAAC;AAC3E,OAAO,EAAE,UAAU,EAAE,MAAM,sBAAsB,CAAC;AAClD,OAAO,EAAE,0BAA0B,EAAE,MAAM,QAAQ,CAAC;AAEpD;;GAEG;AACH,MAAM,CAAC,MAAM,yBAAyB,GAAgD,KAAK,EAAE,UAAU,EAAE,EAAE;;IACzG,MAAM,SAAS,GAAgB,EAAE,CAAC;IAClC,sBAAsB;IACtB,MAAM,qBAAqB,GAAG,MAAM,0BAA0B,CAAC,KAAK,CAAC,IAAI,CAAC,SAAS,CAAC,UAAU,CAAC,CAAC,CAAC;IACjG,IAAI,CAAC,qBAAqB;QAAE,MAAM,IAAI,KAAK,CAAC,wCAAwC,CAAC,CAAC;IACtF,MAAM,cAAc,GAAG,MAAM,qBAAqB,CAAC,UAAU,EAAE,qBAAqB,CAAC,CAAC;IACtF,MAAM,WAAW,GAAG,CAAA,MAAA,cAAc,CAAC,IAAI,0CAAE,IAAI,KAAI,EAAE,CAAC;IAEpD,kCAAkC;IAClC,KAAK,MAAM,YAAY,IAAI,WAAW,EAAE;QACtC,IAAI,YAAY,CAAC,OAAO,KAAK,GAAG;YAAE,SAAS;QAC3C,MAAM,UAAU,GAAG,UAAU,CAAC,KAAK,EAAE,cAAc,EAAE,YAAY,CAAC,QAAQ,GAAG,MAAM,CAAC,CAAC;QACrF,MAAM,KAAK,GAAG,MAAM,UAAU,CAAC,KAAK,CAAC,YAAY,CAAC,QAAQ,CAAC,CAAC;QAC5D,MAAM,cAAc,GAAG,YAAY,CAAC,QAAQ,KAAK,MAAM,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,MAAA,KAAK,aAAL,KAAK,uBAAL,KAAK,CAAE,SAAS,mCAAI,CAAC,CAAC,CAAC;QAEvF,SAAS,CAAC,IAAI,CACZ,gBAAgB,CAAC;YACf,WAAW,EAAE,GAAG,YAAY,CAAC,QAAQ,YAAY;YACjD,UAAU,EAAE,UAAU;YACtB,MAAM,EAAE,CAAC,YAAY,CAAC,OAAO;YAC7B,WAAW,EAAE,CAAC,YAAY,CAAC,OAAO;YAClC,cAAc,EAAE,cAAc;YAC9B,IAAI,EAAE,YAAY,CAAC,OAAO;SAC3B,CAAC,CACH,CAAC;KACH;IAED,OAAO,SAAS,CAAC;AACnB,CAAC,CAAC","sourcesContent":["import { IActionHandlerOfGetAccountInfo, IPosition, makeSpotPosition } from '@yuants/data-account';\nimport { encodePath } from '@yuants/utils';\nimport { getSpotAccountBalance, ICredential } from '../../api/private-api';\nimport { quoteCache } from '../market-data/quote';\nimport { superMarginAccountUidCache } from '../uid';\n\n/**\n * 全仓杠杆账户 (Super Margin Account)\n */\nexport const getSuperMarginAccountInfo: IActionHandlerOfGetAccountInfo<ICredential> = async (credential) => {\n const positions: IPosition[] = [];\n // get account balance\n const superMarginAccountUid = await superMarginAccountUidCache.query(JSON.stringify(credential));\n if (!superMarginAccountUid) throw new Error('Failed to get Super Margin Account UID');\n const accountBalance = await getSpotAccountBalance(credential, superMarginAccountUid);\n const balanceList = accountBalance.data?.list || [];\n\n // get prices and create positions\n for (const currencyData of balanceList) {\n if (currencyData.balance === '0') continue;\n const product_id = encodePath('HTX', 'SUPER-MARGIN', currencyData.currency + 'usdt');\n const quote = await quoteCache.query(currencyData.currency);\n const closable_price = currencyData.currency === 'usdt' ? 1 : +(quote?.ask_price ?? 0);\n\n positions.push(\n makeSpotPosition({\n position_id: `${currencyData.currency}/usdt/spot`,\n product_id: product_id,\n volume: +currencyData.balance,\n free_volume: +currencyData.balance,\n closable_price: closable_price,\n size: currencyData.balance,\n }),\n );\n }\n\n return positions;\n};\n"]}
@@ -1,6 +1,6 @@
1
1
  import { makeSpotPosition } from '@yuants/data-account';
2
2
  import { encodePath } from '@yuants/utils';
3
- import { getSwapCrossPositionInfo, getUnifiedAccountInfo } from '../../api/private-api';
3
+ import { getSwapCrossPositionInfo, getUnifiedAccountInfo, getUnionAccountBalance, getUnionAccountPositions, } from '../../api/private-api';
4
4
  import { productCache } from '../product';
5
5
  const usdAssets = new Set(['USDT', 'USDC', 'USDD']);
6
6
  export const getSwapAccountInfo = async (credential) => {
@@ -44,4 +44,48 @@ export const getSwapAccountInfo = async (credential) => {
44
44
  }
45
45
  return positions;
46
46
  };
47
+ export const getUnionAccountInfo = async (credential) => {
48
+ const positions = [];
49
+ // balance
50
+ const [balance, position] = await Promise.all([
51
+ getUnionAccountBalance(credential),
52
+ getUnionAccountPositions(credential),
53
+ ]);
54
+ if (!balance.data || !balance.data.details) {
55
+ throw new Error('Failed to get union account balance');
56
+ }
57
+ for (const v of balance.data.details || []) {
58
+ positions.push(makeSpotPosition({
59
+ position_id: encodePath('HTX', 'SWAP-ASSET', v.currency),
60
+ datasource_id: 'HTX',
61
+ product_id: encodePath('HTX', 'SWAP-ASSET', v.currency),
62
+ volume: +v.available,
63
+ free_volume: +v.withdraw_available,
64
+ closable_price: usdAssets.has(v.currency) ? 1 : 0,
65
+ size: v.available,
66
+ }));
67
+ }
68
+ if (!position || !position.data) {
69
+ throw new Error('Failed to get union account positions');
70
+ }
71
+ for (const v of position.data || []) {
72
+ const product_id = encodePath('HTX', 'SWAP', v.contract_code);
73
+ const theProduct = await productCache.query(product_id);
74
+ const valuation = +v.volume * +v.mark_price * ((theProduct === null || theProduct === void 0 ? void 0 : theProduct.value_scale) || 1);
75
+ positions.push({
76
+ position_id: `${product_id}/${v.contract_type}/${v.direction}/${v.margin_mode}`,
77
+ datasource_id: 'HTX',
78
+ product_id,
79
+ direction: v.direction === 'buy' ? 'LONG' : 'SHORT',
80
+ volume: +v.volume,
81
+ free_volume: +v.available,
82
+ position_price: +v.open_avg_price,
83
+ closable_price: +v.mark_price,
84
+ floating_profit: +v.profit_unreal,
85
+ liquidation_price: v.liquidation_price ? `${v.liquidation_price}` : undefined,
86
+ valuation,
87
+ });
88
+ }
89
+ return positions;
90
+ };
47
91
  //# sourceMappingURL=swap.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"swap.js","sourceRoot":"","sources":["../../../src/services/accounts/swap.ts"],"names":[],"mappings":"AAAA,OAAO,EAAa,gBAAgB,EAAE,MAAM,sBAAsB,CAAC;AACnE,OAAO,EAAE,UAAU,EAAE,MAAM,eAAe,CAAC;AAC3C,OAAO,EAAE,wBAAwB,EAAE,qBAAqB,EAAe,MAAM,uBAAuB,CAAC;AACrG,OAAO,EAAE,YAAY,EAAE,MAAM,YAAY,CAAC;AAE1C,MAAM,SAAS,GAAG,IAAI,GAAG,CAAC,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,CAAC,CAAC,CAAC;AAEpD,MAAM,CAAC,MAAM,kBAAkB,GAAG,KAAK,EAAE,UAAuB,EAAwB,EAAE;IACxF,MAAM,SAAS,GAAgB,EAAE,CAAC;IAClC,UAAU;IACV,MAAM,OAAO,GAAG,MAAM,qBAAqB,CAAC,UAAU,CAAC,CAAC;IACxD,IAAI,CAAC,OAAO,CAAC,IAAI,EAAE;QACjB,MAAM,IAAI,KAAK,CAAC,oCAAoC,CAAC,CAAC;KACvD;IAED,KAAK,MAAM,CAAC,IAAI,OAAO,CAAC,IAAI,IAAI,EAAE,EAAE;QAClC,IAAI,CAAC,CAAC,cAAc,KAAK,CAAC;YAAE,SAAS;QACrC,SAAS,CAAC,IAAI,CACZ,gBAAgB,CAAC;YACf,WAAW,EAAE,UAAU,CAAC,KAAK,EAAE,YAAY,EAAE,CAAC,CAAC,YAAY,CAAC;YAC5D,aAAa,EAAE,KAAK;YACpB,UAAU,EAAE,UAAU,CAAC,KAAK,EAAE,YAAY,EAAE,CAAC,CAAC,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iB,EAAE,CAAC,CAAC,CAAC,SAAS;YAC7E,SAAS;SACV,CAAC,CAAC;KACJ;IAED,OAAO,SAAS,CAAC;AACnB,CAAC,CAAC","sourcesContent":["import { IPosition, makeSpotPosition } from '@yuants/data-account';\nimport { encodePath } from '@yuants/utils';\nimport { getSwapCrossPositionInfo, getUnifiedAccountInfo, ICredential } from '../../api/private-api';\nimport { productCache } from '../product';\n\nconst usdAssets = new Set(['USDT', 'USDC', 'USDD']);\n\nexport const getSwapAccountInfo = async (credential: ICredential): Promise<IPosition[]> => {\n const positions: IPosition[] = [];\n // balance\n const balance = await getUnifiedAccountInfo(credential);\n if (!balance.data) {\n throw new Error('Failed to get unified account info');\n }\n\n for (const v of balance.data || []) {\n if (v.margin_balance === 0) continue;\n positions.push(\n makeSpotPosition({\n position_id: encodePath('HTX', 'SWAP-ASSET', v.margin_asset),\n datasource_id: 'HTX',\n product_id: encodePath('HTX', 'SWAP-ASSET', v.margin_asset),\n volume: +v.margin_static,\n free_volume: +v.withdraw_available,\n closable_price: usdAssets.has(v.margin_asset) ? 1 : 0,\n }),\n );\n }\n\n // positions\n const positionsRes = await getSwapCrossPositionInfo(credential);\n for (const v of positionsRes.data || []) {\n const product_id = encodePath('HTX', 'SWAP', v.contract_code);\n const theProduct = await productCache.query(product_id);\n const valuation = v.volume * v.last_price * (theProduct?.value_scale || 1);\n positions.push({\n position_id: `${product_id}/${v.contract_type}/${v.direction}/${v.margin_mode}`,\n datasource_id: 'HTX',\n product_id,\n direction: v.direction === 'buy' ? 'LONG' : 'SHORT',\n volume: v.volume,\n free_volume: v.available,\n position_price: v.cost_hold,\n closable_price: v.last_price,\n floating_profit: v.profit_unreal,\n liquidation_price: v.liquidation_price ? `${v.liquidation_price}` : undefined,\n valuation,\n });\n }\n\n return positions;\n};\n"]}
1
+ {"version":3,"file":"swap.js","sourceRoot":"","sources":["../../../src/services/accounts/swap.ts"],"names":[],"mappings":"AAAA,OAAO,EAAa,gBAAgB,EAAE,MAAM,sB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CAAA,UAAU,aAAV,UAAU,uBAAV,UAAU,CAAE,WAAW,KAAI,CAAC,CAAC,CAAC;QAC7E,SAAS,CAAC,IAAI,CAAC;YACb,WAAW,EAAE,GAAG,UAAU,IAAI,CAAC,CAAC,aAAa,IAAI,CAAC,CAAC,SAAS,IAAI,CAAC,CAAC,WAAW,EAAE;YAC/E,aAAa,EAAE,KAAK;YACpB,UAAU;YACV,SAAS,EAAE,CAAC,CAAC,SAAS,KAAK,KAAK,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,OAAO;YACnD,MAAM,EAAE,CAAC,CAAC,CAAC,MAAM;YACjB,WAAW,EAAE,CAAC,CAAC,CAAC,SAAS;YACzB,cAAc,EAAE,CAAC,CAAC,CAAC,cAAc;YACjC,cAAc,EAAE,CAAC,CAAC,CAAC,UAAU;YAC7B,eAAe,EAAE,CAAC,CAAC,CAAC,aAAa;YACjC,iBAAiB,EAAE,CAAC,CAAC,iBAAiB,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,iBAAiB,EAAE,CAAC,CAAC,CAAC,SAAS;YAC7E,SAAS;SACV,CAAC,CAAC;KACJ;IAED,OAAO,SAAS,CAAC;AACnB,CAAC,CAAC","sourcesContent":["import { IPosition, makeSpotPosition } from '@yuants/data-account';\nimport { encodePath } from '@yuants/utils';\nimport {\n getSwapCrossPositionInfo,\n getUnifiedAccountInfo,\n getUnionAccountBalance,\n getUnionAccountPositions,\n ICredential,\n} from '../../api/private-api';\nimport { productCache } from '../product';\n\nconst usdAssets = new Set(['USDT', 'USDC', 'USDD']);\n\nexport const getSwapAccountInfo = async (credential: ICredential): Promise<IPosition[]> => {\n const positions: IPosition[] = [];\n // balance\n const balance = await getUnifiedAccountInfo(credential);\n if (!balance.data) {\n throw new Error('Failed to get unified account info');\n }\n\n for (const v of balance.data || []) {\n if (v.margin_balance === 0) continue;\n positions.push(\n makeSpotPosition({\n position_id: encodePath('HTX', 'SWAP-ASSET', v.margin_asset),\n datasource_id: 'HTX',\n product_id: encodePath('HTX', 'SWAP-ASSET', v.margin_asset),\n volume: +v.margin_static,\n free_volume: +v.withdraw_available,\n closable_price: usdAssets.has(v.margin_asset) ? 1 : 0,\n }),\n );\n }\n\n // positions\n const positionsRes = await getSwapCrossPositionInfo(credential);\n for (const v of positionsRes.data || []) {\n const product_id = encodePath('HTX', 'SWAP', v.contract_code);\n const theProduct = await productCache.query(product_id);\n const valuation = v.volume * v.last_price * (theProduct?.value_scale || 1);\n positions.push({\n position_id: `${product_id}/${v.contract_type}/${v.direction}/${v.margin_mode}`,\n datasource_id: 'HTX',\n product_id,\n direction: v.direction === 'buy' ? 'LONG' : 'SHORT',\n volume: v.volume,\n free_volume: v.available,\n position_price: v.cost_hold,\n closable_price: v.last_price,\n floating_profit: v.profit_unreal,\n liquidation_price: v.liquidation_price ? `${v.liquidation_price}` : undefined,\n valuation,\n });\n }\n\n return positions;\n};\n\nexport const getUnionAccountInfo = async (credential: ICredential): Promise<IPosition[]> => {\n const positions: IPosition[] = [];\n // balance\n const [balance, position] = await Promise.all([\n getUnionAccountBalance(credential),\n getUnionAccountPositions(credential),\n ]);\n\n if (!balance.data || !balance.data.details) {\n throw new Error('Failed to get union account balance');\n }\n for (const v of balance.data.details || []) {\n positions.push(\n makeSpotPosition({\n position_id: encodePath('HTX', 'SWAP-ASSET', v.currency),\n datasource_id: 'HTX',\n product_id: encodePath('HTX', 'SWAP-ASSET', v.currency),\n volume: +v.available,\n free_volume: +v.withdraw_available,\n closable_price: usdAssets.has(v.currency) ? 1 : 0,\n size: v.available,\n }),\n );\n }\n if (!position || !position.data) {\n throw new Error('Failed to get union account positions');\n }\n for (const v of position.data || []) {\n const product_id = encodePath('HTX', 'SWAP', v.contract_code);\n const theProduct = await productCache.query(product_id);\n const valuation = +v.volume * +v.mark_price * (theProduct?.value_scale || 1);\n positions.push({\n position_id: `${product_id}/${v.contract_type}/${v.direction}/${v.margin_mode}`,\n datasource_id: 'HTX',\n product_id,\n direction: v.direction === 'buy' ? 'LONG' : 'SHORT',\n volume: +v.volume,\n free_volume: +v.available,\n position_price: +v.open_avg_price,\n closable_price: +v.mark_price,\n floating_profit: +v.profit_unreal,\n liquidation_price: v.liquidation_price ? `${v.liquidation_price}` : undefined,\n valuation,\n });\n }\n\n return positions;\n};\n"]}
@@ -1,10 +1,10 @@
1
1
  import { provideExchangeServices } from '@yuants/exchange';
2
2
  import { Terminal } from '@yuants/protocol';
3
3
  import { decodePath, encodePath, newError } from '@yuants/utils';
4
- import { getUid } from '../api/private-api';
4
+ import { getAccountAssetsMode, getUid } from '../api/private-api';
5
5
  import { getSpotAccountInfo } from './accounts/spot';
6
6
  import { getSuperMarginAccountInfo } from './accounts/super-margin';
7
- import { getSwapAccountInfo } from './accounts/swap';
7
+ import { getSwapAccountInfo, getUnionAccountInfo } from './accounts/swap';
8
8
  import { listSwapOrders } from './orders/listOrders';
9
9
  import { submitOrder } from './orders/submitOrder';
10
10
  import { listProducts } from './product';
@@ -25,12 +25,23 @@ provideExchangeServices(terminal, {
25
25
  },
26
26
  listProducts,
27
27
  getPositions: async (credential) => {
28
- const [swap, spot, superMargin] = await Promise.all([
29
- getSwapAccountInfo(credential),
30
- getSpotAccountInfo(credential, 'spot'),
31
- getSuperMarginAccountInfo(credential, 'super-margin'),
32
- ]);
33
- return [...swap, ...spot, ...superMargin];
28
+ const accountMode = await getAccountAssetsMode(credential);
29
+ if (accountMode.data.asset_mode === 1) {
30
+ const [swap, spot, superMargin] = await Promise.all([
31
+ getUnionAccountInfo(credential),
32
+ getSpotAccountInfo(credential, 'spot'),
33
+ getSuperMarginAccountInfo(credential, 'super-margin'),
34
+ ]);
35
+ return [...swap, ...spot, ...superMargin];
36
+ }
37
+ else {
38
+ const [swap, spot, superMargin] = await Promise.all([
39
+ getSwapAccountInfo(credential),
40
+ getSpotAccountInfo(credential, 'spot'),
41
+ getSuperMarginAccountInfo(credential, 'super-margin'),
42
+ ]);
43
+ return [...swap, ...spot, ...superMargin];
44
+ }
34
45
  },
35
46
  getOrders: async (credential) => {
36
47
  const swapOrders = await listSwapOrders(credential);
@@ -1 +1 @@
1
- {"version":3,"file":"exchange.js","sourceRoot":"","sources":["../../src/services/exchange.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,uBAAuB,EAAE,MAAM,kBAAkB,CAAC;AAC3D,OAAO,EAAE,QAAQ,EAAE,MAAM,kBAAkB,CAAC;AAC5C,OAAO,EAAE,UAAU,EAAE,UAAU,EAAE,QAAQ,EAAE,MAAM,eAAe,CAAC;AACjE,OAAO,EAAe,MAAM,EAAE,MAAM,oBAAoB,CAAC;AACzD,OAAO,EAAE,kBAAkB,EAAE,MAAM,iBAAiB,CAAC;AACrD,OAAO,EAAE,yBAAyB,EAAE,MAAM,yBAAyB,CAAC;AACpE,OAAO,EAAE,kBAAkB,EAAE,MAAM,iBAAiB,CAAC;AACrD,OAAO,EAAE,cAAc,EAAE,MAAM,qBAAqB,CAAC;AACrD,OAAO,EAAE,WAAW,EAAE,MAAM,sBAAsB,CAAC;AACnD,OAAO,EAAE,YAAY,EAAE,MAAM,WAAW,CAAC;AAEzC,MAAM,QAAQ,GAAG,QAAQ,CAAC,WAAW,EAAE,CAAC;AAExC,uBAAuB,CAAc,QAAQ,EAAE;IAC7C,IAAI,EAAE,KAAK;IACX,gBAAgB,EAAE;QAChB,IAAI,EAAE,QAAQ;QACd,QAAQ,EAAE,CAAC,YAAY,EAAE,YAAY,CAAC;QACtC,UAAU,EAAE;YACV,UAAU,EAAE,EAAE,IAAI,EAAE,QAAQ,EAAE;YAC9B,UAAU,EAAE,EAAE,IAAI,EAAE,QAAQ,EAAE;SAC/B;KACF;IACD,eAAe,EAAE,KAAK,EAAE,UAAU,EAAE,EAAE;QACpC,MAAM,GAAG,GAAG,MAAM,MAAM,CAAC,UAAU,CAAC,CAAC;QACrC,OAAO,UAAU,CAAC,KAAK,EAAE,GAAG,CAAC,IAAI,CAAC,CAAC;IACrC,CAAC;IACD,YAAY;IACZ,YAAY,EAAE,KAAK,E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,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,GAAG,CAAC,UAAU,KAAK,UAAU,CAAC,CAAC;SACjE;QACD,IAAI,QAAQ,KAAK,cAAc,EAAE;YAC/B,MAAM,SAAS,GAAG,MAAM,yBAAyB,CAAC,UAAU,EAAE,UAAU,CAAC,CAAC;YAC1E,OAAO,SAAS,CAAC,MAAM,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,GAAG,CAAC,UAAU,KAAK,UAAU,CAAC,CAAC;SACjE;QACD,MAAM,QAAQ,CAAC,sBAAsB,EAAE,EAAE,UAAU,EAAE,CAAC,CAAC;IACzD,CAAC;IACD,oBAAoB,EAAE,KAAK,EAAE,UAAuB,EAAE,UAAkB,EAAqB,EAAE;QAC7F,MAAM,CAAC,EAAE,QAAQ,CAAC,GAAG,UAAU,CAAC,UAAU,CAAC,CAAC;QAC5C,6BAA6B;QAC7B,iEAAiE;QACjE,sEAAsE;QACtE,IAAI;QACJ,IAAI,QAAQ,KAAK,MAAM,EAAE;YACvB,MAAM,MAAM,GAAG,MAAM,cAAc,CAAC,UAAU,CAAC,CAAC;YAChD,OAAO,MAAM,CAAC,MAAM,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,UAAU,KAAK,UAAU,CAAC,CAAC;SAClE;QACD,MAAM,QAAQ,CAAC,sBAAsB,EAAE,EAAE,UAAU,EAAE,CAAC,CAAC;IACzD,CAAC;CACF,CAAC,CAAC","sourcesContent":["import { IOrder } from '@yuants/data-order';\nimport { provideExchangeServices } from '@yuants/exchange';\nimport { Terminal } from '@yuants/protocol';\nimport { decodePath, encodePath, newError } from '@yuants/utils';\nimport { ICredential, getUid } from '../api/private-api';\nimport { getSpotAccountInfo } from './accounts/spot';\nimport { getSuperMarginAccountInfo } from './accounts/super-margin';\nimport { getSwapAccountInfo } from './accounts/swap';\nimport { listSwapOrders } from './orders/listOrders';\nimport { submitOrder } from './orders/submitOrder';\nimport { listProducts } from './product';\n\nconst terminal = Terminal.fromNodeEnv();\n\nprovideExchangeServices<ICredential>(terminal, {\n name: 'HTX',\n credentialSchema: {\n type: 'object',\n required: ['access_key', 'secret_key'],\n properties: {\n access_key: { type: 'string' },\n secret_key: { type: 'string' },\n },\n },\n getCredentialId: async (credential) => {\n const res = await getUid(credential);\n return encodePath('HTX', res.data);\n },\n listProducts,\n getPositions: async (credential) => {\n const [swap, spot, superMargin] = await Promise.all([\n getSwapAccountInfo(credential),\n getSpotAccountInfo(credential, 'spot'),\n getSuperMarginAccountInfo(credential, 'super-margin'),\n ]);\n return [...swap, ...spot, ...superMargin];\n },\n getOrders: async (credential) => {\n const swapOrders = await listSwapOrders(credential);\n return swapOrders;\n },\n submitOrder,\n cancelOrder: async (credential, order) => {\n throw new Error('Not Implemented');\n },\n modifyOrder: async (credential, order) => {\n throw new Error('Not Implemented');\n },\n getPositionsByProductId: async (credential, product_id) => {\n const [, instType] = decodePath(product_id);\n if (instType === 'SPOT') {\n const positions = await getSpotAccountInfo(credential, product_id);\n return positions.filter((pos) => pos.product_id === product_id);\n }\n if (instType === 'SWAP') {\n const positions = await getSwapAccountInfo(credential);\n return positions.filter((pos) => pos.product_id === product_id);\n }\n if (instType === 'SUPER-MARGIN') {\n const positions = await getSuperMarginAccountInfo(credential, product_id);\n return positions.filter((pos) => pos.product_id === product_id);\n }\n throw newError('UnsupportedProductId', { product_id });\n },\n getOrdersByProductId: async (credential: ICredential, product_id: string): Promise<IOrder[]> => {\n const [, instType] = decodePath(product_id);\n // if (instType === 'SPOT') {\n // const orders = await listSpotOrders(credential, product_id);\n // return orders.filter((order) => order.product_id === product_id);\n // }\n if (instType === 'SWAP') {\n const orders = await listSwapOrders(credential);\n return orders.filter((order) => order.product_id === product_id);\n }\n throw newError('UnsupportedProductId', { product_id });\n },\n});\n"]}
1
+ {"version":3,"file":"exchange.js","sourceRoot":"","sources":["../../src/services/exchange.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,uBAAuB,EAAE,MAAM,kBAAkB,CAAC;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\nimport { provideExchangeServices } from '@yuants/exchange';\nimport { Terminal } from '@yuants/protocol';\nimport { decodePath, encodePath, newError } from '@yuants/utils';\nimport { ICredential, getAccountAssetsMode, getUid } from '../api/private-api';\nimport { getSpotAccountInfo } from './accounts/spot';\nimport { getSuperMarginAccountInfo } from './accounts/super-margin';\nimport { getSwapAccountInfo, getUnionAccountInfo } from './accounts/swap';\nimport { listSwapOrders } from './orders/listOrders';\nimport { submitOrder } from './orders/submitOrder';\nimport { listProducts } from './product';\n\nconst terminal = Terminal.fromNodeEnv();\n\nprovideExchangeServices<ICredential>(terminal, {\n name: 'HTX',\n credentialSchema: {\n type: 'object',\n required: ['access_key', 'secret_key'],\n properties: {\n access_key: { type: 'string' },\n secret_key: { type: 'string' },\n },\n },\n getCredentialId: async (credential) => {\n const res = await getUid(credential);\n return encodePath('HTX', res.data);\n },\n listProducts,\n getPositions: async (credential) => {\n const accountMode = await getAccountAssetsMode(credential);\n if (accountMode.data.asset_mode === 1) {\n const [swap, spot, superMargin] = await Promise.all([\n getUnionAccountInfo(credential),\n getSpotAccountInfo(credential, 'spot'),\n getSuperMarginAccountInfo(credential, 'super-margin'),\n ]);\n return [...swap, ...spot, ...superMargin];\n } else {\n const [swap, spot, superMargin] = await Promise.all([\n getSwapAccountInfo(credential),\n getSpotAccountInfo(credential, 'spot'),\n getSuperMarginAccountInfo(credential, 'super-margin'),\n ]);\n return [...swap, ...spot, ...superMargin];\n }\n },\n getOrders: async (credential) => {\n const swapOrders = await listSwapOrders(credential);\n return swapOrders;\n },\n submitOrder,\n cancelOrder: async (credential, order) => {\n throw new Error('Not Implemented');\n },\n modifyOrder: async (credential, order) => {\n throw new Error('Not Implemented');\n },\n getPositionsByProductId: async (credential, product_id) => {\n const [, instType] = decodePath(product_id);\n if (instType === 'SPOT') {\n const positions = await getSpotAccountInfo(credential, product_id);\n return positions.filter((pos) => pos.product_id === product_id);\n }\n if (instType === 'SWAP') {\n const positions = await getSwapAccountInfo(credential);\n return positions.filter((pos) => pos.product_id === product_id);\n }\n if (instType === 'SUPER-MARGIN') {\n const positions = await getSuperMarginAccountInfo(credential, product_id);\n return positions.filter((pos) => pos.product_id === product_id);\n }\n throw newError('UnsupportedProductId', { product_id });\n },\n getOrdersByProductId: async (credential: ICredential, product_id: string): Promise<IOrder[]> => {\n const [, instType] = decodePath(product_id);\n // if (instType === 'SPOT') {\n // const orders = await listSpotOrders(credential, product_id);\n // return orders.filter((order) => order.product_id === product_id);\n // }\n if (instType === 'SWAP') {\n const orders = await listSwapOrders(credential);\n return orders.filter((order) => order.product_id === product_id);\n }\n throw newError('UnsupportedProductId', { product_id });\n },\n});\n"]}
@@ -1,8 +1,31 @@
1
1
  import { decodePath, formatTime, newError, roundToStep } from '@yuants/utils';
2
- import { getCrossMarginLoanInfo, getSpotAccountBalance, getSwapCrossPositionInfo, postSpotOrder, postSwapOrder, } from '../../api/private-api';
2
+ import { getAccountAssetsMode, getCrossMarginLoanInfo, getSpotAccountBalance, getSwapCrossPositionInfo, postSpotOrder, postSwapOrder, postUnionAccountSwapOrder, } from '../../api/private-api';
3
3
  import { getSpotTick } from '../../api/public-api';
4
4
  import { productCache } from '../product';
5
5
  import { superMarginAccountUidCache } from '../uid';
6
+ /**
7
+ * 处理 swap 账户订单提交
8
+ */
9
+ async function handleUnionAccountSwapOrder(order, credential) {
10
+ const [, instType, contractCode] = decodePath(order.product_id);
11
+ const params = {
12
+ contract_code: contractCode,
13
+ margin_mode: 'cross',
14
+ price: order.price,
15
+ volume: order.volume,
16
+ position_side: 'both',
17
+ side: order.order_direction === 'OPEN_LONG' || order.order_direction === 'CLOSE_SHORT' ? 'buy' : 'sell',
18
+ type: order.order_type === 'MARKET' ? 'market' : 'limit',
19
+ channel_code: process.env.BROKER_ID,
20
+ reduce_only: order.is_close ? 1 : 0,
21
+ };
22
+ const result = await postUnionAccountSwapOrder(credential, params);
23
+ console.info(formatTime(Date.now()), 'SubmitOrder', JSON.stringify(result), JSON.stringify(params));
24
+ if (result.code !== 200) {
25
+ throw newError(`HTX_SUBMIT_ORDER_FAILED`, { result });
26
+ }
27
+ return { order_id: result.data.order_id_str };
28
+ }
6
29
  /**
7
30
  * 处理 swap 账户订单提交
8
31
  */
@@ -84,9 +107,13 @@ async function handleSuperMarginOrder(order, credential) {
84
107
  }
85
108
  return { order_id: result.data.orderId.toString() };
86
109
  }
87
- export const submitOrder = (credential, order) => {
110
+ export const submitOrder = async (credential, order) => {
88
111
  const [, instType] = decodePath(order.product_id);
89
112
  if (instType === 'SWAP') {
113
+ const accountMode = await getAccountAssetsMode(credential);
114
+ if (accountMode.data.asset_mode === 1) {
115
+ return handleUnionAccountSwapOrder(order, credential);
116
+ }
90
117
  return handleSwapOrder(order, credential);
91
118
  }
92
119
  if (instType === 'SUPER-MARGIN') {
@@ -1 +1 @@
1
- {"version":3,"file":"submitOrder.js","sourceRoot":"","sources":["../../../src/services/orders/submitOrder.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,UAAU,EAAE,UAAU,EAAE,QAAQ,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC;AAC9E,OAAO,EAEL,sBAAsB,EACtB,qBAAqB,EACrB,wBAAwB,EACxB,aAAa,EACb,aAAa,GACd,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EAAE,WAAW,EAAE,MAAM,sBAAsB,CAAC;AACnD,OAAO,EAAE,YAAY,EAAE,MAAM,YAAY,CAAC;AAC1C,OAAO,EAAE,0BAA0B,EAAE,MAAM,QAAQ,CAAC;AAEpD;;GAEG;AACH,KAAK,UAAU,eAAe,CAAC,KAAa,EAAE,UAAuB;;IACnE,SAAS;IACT,MAAM,YAAY,GAAG,MAAM,wBAAwB,CAAC,UAAU,CAAC,CAAC;IAChE,MAAM,qBAAqB,GAAG,MAAM,CAAC,WAAW,CAC9C,YAAY,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,CAAC,aAAa,EAAE,CAAC,CAAC,UAAU,CAAC,C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} from '@yuants/data-order';\nimport { decodePath, formatTime, newError, roundToStep } from '@yuants/utils';\nimport {\n ICredential,\n getCrossMarginLoanInfo,\n getSpotAccountBalance,\n getSwapCrossPositionInfo,\n postSpotOrder,\n postSwapOrder,\n} from '../../api/private-api';\nimport { getSpotTick } from '../../api/public-api';\nimport { productCache } from '../product';\nimport { superMarginAccountUidCache } from '../uid';\n\n/**\n * 处理 swap 账户订单提交\n */\nasync function handleSwapOrder(order: IOrder, credential: ICredential): Promise<{ order_id: string }> {\n // 获取仓位信息\n const positionInfo = await getSwapCrossPositionInfo(credential);\n const mapContractCodeToRate = Object.fromEntries(\n positionInfo.data.map((v) => [v.contract_code, v.lever_rate]),\n );\n\n const [, instType, contractCode] = decodePath(order.product_id);\n const lever_rate = mapContractCodeToRate[contractCode] ?? 20;\n const params = {\n contract_code: contractCode,\n contract_type: 'swap',\n price: order.price,\n volume: order.volume,\n offset:\n order.order_direction === 'OPEN_LONG' || order.order_direction === 'OPEN_SHORT' ? 'open' : 'close',\n direction:\n order.order_direction === 'OPEN_LONG' || order.order_direction === 'CLOSE_SHORT' ? 'buy' : 'sell',\n // dynamically adjust the leverage\n lever_rate,\n order_price_type: order.order_type === 'MARKET' ? 'market' : 'limit',\n channel_code: process.env.BROKER_ID,\n };\n\n const result = await postSwapOrder(credential, params);\n console.info(formatTime(Date.now()), 'SubmitOrder', JSON.stringify(result), JSON.stringify(params));\n\n if (result.status !== 'ok') {\n throw newError(`HTX_SUBMIT_ORDER_FAILED`, { result });\n }\n return { order_id: result.data.order_id_str };\n}\n\n/**\n * 处理 super-margin 账户订单提交\n */\nasync function handleSuperMarginOrder(order: IOrder, credential: ICredential): Promise<{ order_id: string }> {\n // 获取可贷款金额\n const superMarginAccountUid = await superMarginAccountUidCache.query(JSON.stringify(credential));\n if (!superMarginAccountUid) throw new Error('Super margin account UID not found');\n const loanInfo = await getCrossMarginLoanInfo(credential);\n const usdtLoanable = loanInfo.data.find((v) => v.currency === 'usdt');\n if (!usdtLoanable) throw new Error('USDT loanable amount not found');\n const loanable = +usdtLoanable['loanable-amt'];\n\n const [, instType, contractCode] = decodePath(order.product_id);\n\n // 获取账户余额, 产品信息和价格\n const [balanceRes, theProduct, priceRes] = await Promise.all([\n getSpotAccountBalance(credential, superMarginAccountUid),\n productCache.query(order.product_id),\n getSpotTick({ symbol: contractCode }),\n ]);\n\n const balance = balanceRes.data.list\n .filter((v) => v.currency === 'usdt' && v.type === 'trade')\n .reduce((acc, cur) => acc + +cur.balance, 0);\n\n if (!theProduct) throw newError('HUOBI_SUBMIT_ORDER_PRODUCT_NOT_FOUND', { product_id: order.product_id });\n\n const price = priceRes.tick.close;\n const borrow_amount =\n order.order_direction === 'OPEN_LONG' || order.order_direction === 'CLOSE_SHORT'\n ? Math.max(Math.min(loanable, order.volume * price - balance), 0)\n : undefined;\n\n const params = {\n symbol: contractCode,\n 'account-id': '' + superMarginAccountUid,\n amount:\n '' +\n (order.order_direction === 'OPEN_LONG' || order.order_direction === 'CLOSE_SHORT'\n ? roundToStep(order.volume * price, theProduct?.volume_step!)\n : order.volume),\n 'borrow-amount': '' + borrow_amount,\n type: `${\n order.order_direction === 'OPEN_LONG' || order.order_direction === 'CLOSE_SHORT' ? 'buy' : 'sell'\n }-${'LIMIT' === order.order_type ? 'limit' : 'market'}`,\n 'trade-purpose':\n order.order_direction === 'OPEN_LONG' || order.order_direction === 'CLOSE_SHORT'\n ? '1' // auto borrow\n : '2', // auto repay\n price: order.order_type === 'MARKET' ? undefined : '' + order.price,\n source: 'super-margin-api',\n 'client-order-id': process.env.BROKER_ID,\n };\n\n const result = await postSpotOrder(credential, params);\n console.info(formatTime(Date.now()), 'SubmitOrder', JSON.stringify(result), JSON.stringify(params));\n\n if (result.success === false) {\n throw new Error(`Failed to submit super margin order: code=${result.code} message=${result.message}`);\n }\n\n return { order_id: result.data.orderId.toString() };\n}\n\nexport const submitOrder = (credential: ICredential, order: IOrder): Promise<{ order_id: string }> => {\n const [, instType] = decodePath(order.product_id);\n if (instType === 'SWAP') {\n return handleSwapOrder(order, credential);\n }\n if (instType === 'SUPER-MARGIN') {\n return handleSuperMarginOrder(order, credential);\n }\n throw newError('UNSUPPORTED_INST_TYPE', { order_type: instType });\n};\n"]}
1
+ {"version":3,"file":"submitOrder.js","sourceRoot":"","sources":["../../../src/services/orders/submitOrder.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,UAAU,EAAE,UAAU,EAAE,QAAQ,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC;AAC9E,OAAO,EAEL,oBAAoB,EACpB,sBAAsB,EACtB,qBAAqB,EACrB,wBAAwB,EACxB,aAAa,EACb,aAAa,EACb,yBAAyB,GAC1B,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EAAE,WAAW,EAAE,MAAM,sBAAsB,CAAC;AACnD,OAAO,EAAE,YAAY,EAAE,MAAM,YAAY,CAAC;AAC1C,OAAO,EAAE,0BAA0B,EAAE,MAAM,QAAQ,CAAC;AAEpD;;GAEG;AACH,KAAK,UAAU,2BAA2B,CACxC,KAAa,EACb,UAAuB;IAEvB,MAAM,CAAC,EAAE,QAAQ,EAAE,YAAY,CAAC,GAAG,UAAU,CAAC,KAAK,CAAC,UAAU,CAAC,CAAC;IAChE,MAAM,MAAM,GAAG;QACb,aAAa,EAAE,YAAY;QAC3B,WAAW,EAAE,OAAO;QACpB,KAAK,EAAE,KAAK,CAAC,KAAK;QAClB,MAAM,EAAE,KAAK,CAAC,MAAM;QACpB,aAAa,EAAE,MAAM;QACrB,IAAI,EAAE,KAAK,CAAC,eAAe,KAAK,WAAW,IAAI,KAAK,CAAC,eAAe,KAAK,aAAa,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,MAAM;QACvG,IAAI,EAAE,KAAK,CAAC,UAAU,KAAK,QAAQ,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC,OAAO;QACxD,YAAY,EAAE,OAAO,CAAC,GAAG,CAAC,SAAS;QACnC,WAAW,EAAE,KAAK,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AC,EAAE,aAAa,EAAE,IAAI,CAAC,SAAS,CAAC,MAAM,CAAC,EAAE,IAAI,CAAC,SAAS,CAAC,MAAM,CAAC,CAAC,CAAC;IAEpG,IAAI,MAAM,CAAC,OAAO,KAAK,KAAK,EAAE;QAC5B,MAAM,IAAI,KAAK,CAAC,6CAA6C,MAAM,CAAC,IAAI,YAAY,MAAM,CAAC,OAAO,EAAE,CAAC,CAAC;KACvG;IAED,OAAO,EAAE,QAAQ,EAAE,MAAM,CAAC,IAAI,CAAC,OAAO,CAAC,QAAQ,EAAE,EAAE,CAAC;AACtD,CAAC;AAED,MAAM,CAAC,MAAM,WAAW,GAAG,KAAK,EAAE,UAAuB,EAAE,KAAa,EAAiC,EAAE;IACzG,MAAM,CAAC,EAAE,QAAQ,CAAC,GAAG,UAAU,CAAC,KAAK,CAAC,UAAU,CAAC,CAAC;IAClD,IAAI,QAAQ,KAAK,MAAM,EAAE;QACvB,MAAM,WAAW,GAAG,MAAM,oBAAoB,CAAC,UAAU,CAAC,CAAC;QAC3D,IAAI,WAAW,CAAC,IAAI,CAAC,UAAU,KAAK,CAAC,EAAE;YACrC,OAAO,2BAA2B,CAAC,KAAK,EAAE,UAAU,CAAC,CAAC;SACvD;QACD,OAAO,eAAe,CAAC,KAAK,EAAE,UAAU,CAAC,CAAC;KAC3C;IACD,IAAI,QAAQ,KAAK,cAAc,EAAE;QAC/B,OAAO,sBAAsB,CAAC,KAAK,EAAE,UAAU,CAAC,CAAC;KAClD;IACD,MAAM,QAAQ,CAAC,uBAAuB,EAAE,EAAE,UAAU,EAAE,QAAQ,EAAE,CAAC,CAAC;AACpE,CAAC,CAAC","sourcesContent":["import { IOrder } from '@yuants/data-order';\nimport { decodePath, formatTime, newError, roundToStep } from '@yuants/utils';\nimport {\n ICredential,\n getAccountAssetsMode,\n getCrossMarginLoanInfo,\n getSpotAccountBalance,\n getSwapCrossPositionInfo,\n postSpotOrder,\n postSwapOrder,\n postUnionAccountSwapOrder,\n} from '../../api/private-api';\nimport { getSpotTick } from '../../api/public-api';\nimport { productCache } from '../product';\nimport { superMarginAccountUidCache } from '../uid';\n\n/**\n * 处理 swap 账户订单提交\n */\nasync function handleUnionAccountSwapOrder(\n order: IOrder,\n credential: ICredential,\n): Promise<{ order_id: string }> {\n const [, instType, contractCode] = decodePath(order.product_id);\n const params = {\n contract_code: contractCode,\n margin_mode: 'cross',\n price: order.price,\n volume: order.volume,\n position_side: 'both',\n side: order.order_direction === 'OPEN_LONG' || order.order_direction === 'CLOSE_SHORT' ? 'buy' : 'sell',\n type: order.order_type === 'MARKET' ? 'market' : 'limit',\n channel_code: process.env.BROKER_ID,\n reduce_only: order.is_close ? 1 : 0,\n };\n const result = await postUnionAccountSwapOrder(credential, params);\n console.info(formatTime(Date.now()), 'SubmitOrder', JSON.stringify(result), JSON.stringify(params));\n\n if (result.code !== 200) {\n throw newError(`HTX_SUBMIT_ORDER_FAILED`, { result });\n }\n return { order_id: result.data.order_id_str };\n}\n\n/**\n * 处理 swap 账户订单提交\n */\nasync function handleSwapOrder(order: IOrder, credential: ICredential): Promise<{ order_id: string }> {\n // 获取仓位信息\n const positionInfo = await getSwapCrossPositionInfo(credential);\n const mapContractCodeToRate = Object.fromEntries(\n positionInfo.data.map((v) => [v.contract_code, v.lever_rate]),\n );\n\n const [, instType, contractCode] = decodePath(order.product_id);\n const lever_rate = mapContractCodeToRate[contractCode] ?? 20;\n const params = {\n contract_code: contractCode,\n contract_type: 'swap',\n price: order.price,\n volume: order.volume,\n offset:\n order.order_direction === 'OPEN_LONG' || order.order_direction === 'OPEN_SHORT' ? 'open' : 'close',\n direction:\n order.order_direction === 'OPEN_LONG' || order.order_direction === 'CLOSE_SHORT' ? 'buy' : 'sell',\n // dynamically adjust the leverage\n lever_rate,\n order_price_type: order.order_type === 'MARKET' ? 'market' : 'limit',\n channel_code: process.env.BROKER_ID,\n };\n\n const result = await postSwapOrder(credential, params);\n console.info(formatTime(Date.now()), 'SubmitOrder', JSON.stringify(result), JSON.stringify(params));\n\n if (result.status !== 'ok') {\n throw newError(`HTX_SUBMIT_ORDER_FAILED`, { result });\n }\n return { order_id: result.data.order_id_str };\n}\n\n/**\n * 处理 super-margin 账户订单提交\n */\nasync function handleSuperMarginOrder(order: IOrder, credential: ICredential): Promise<{ order_id: string }> {\n // 获取可贷款金额\n const superMarginAccountUid = await superMarginAccountUidCache.query(JSON.stringify(credential));\n if (!superMarginAccountUid) throw new Error('Super margin account UID not found');\n const loanInfo = await getCrossMarginLoanInfo(credential);\n const usdtLoanable = loanInfo.data.find((v) => v.currency === 'usdt');\n if (!usdtLoanable) throw new Error('USDT loanable amount not found');\n const loanable = +usdtLoanable['loanable-amt'];\n\n const [, instType, contractCode] = decodePath(order.product_id);\n\n // 获取账户余额, 产品信息和价格\n const [balanceRes, theProduct, priceRes] = await Promise.all([\n getSpotAccountBalance(credential, superMarginAccountUid),\n productCache.query(order.product_id),\n getSpotTick({ symbol: contractCode }),\n ]);\n\n const balance = balanceRes.data.list\n .filter((v) => v.currency === 'usdt' && v.type === 'trade')\n .reduce((acc, cur) => acc + +cur.balance, 0);\n\n if (!theProduct) throw newError('HUOBI_SUBMIT_ORDER_PRODUCT_NOT_FOUND', { product_id: order.product_id });\n\n const price = priceRes.tick.close;\n const borrow_amount =\n order.order_direction === 'OPEN_LONG' || order.order_direction === 'CLOSE_SHORT'\n ? Math.max(Math.min(loanable, order.volume * price - balance), 0)\n : undefined;\n\n const params = {\n symbol: contractCode,\n 'account-id': '' + superMarginAccountUid,\n amount:\n '' +\n (order.order_direction === 'OPEN_LONG' || order.order_direction === 'CLOSE_SHORT'\n ? roundToStep(order.volume * price, theProduct?.volume_step!)\n : order.volume),\n 'borrow-amount': '' + borrow_amount,\n type: `${\n order.order_direction === 'OPEN_LONG' || order.order_direction === 'CLOSE_SHORT' ? 'buy' : 'sell'\n }-${'LIMIT' === order.order_type ? 'limit' : 'market'}`,\n 'trade-purpose':\n order.order_direction === 'OPEN_LONG' || order.order_direction === 'CLOSE_SHORT'\n ? '1' // auto borrow\n : '2', // auto repay\n price: order.order_type === 'MARKET' ? undefined : '' + order.price,\n source: 'super-margin-api',\n 'client-order-id': process.env.BROKER_ID,\n };\n\n const result = await postSpotOrder(credential, params);\n console.info(formatTime(Date.now()), 'SubmitOrder', JSON.stringify(result), JSON.stringify(params));\n\n if (result.success === false) {\n throw new Error(`Failed to submit super margin order: code=${result.code} message=${result.message}`);\n }\n\n return { order_id: result.data.orderId.toString() };\n}\n\nexport const submitOrder = async (credential: ICredential, order: IOrder): Promise<{ order_id: string }> => {\n const [, instType] = decodePath(order.product_id);\n if (instType === 'SWAP') {\n const accountMode = await getAccountAssetsMode(credential);\n if (accountMode.data.asset_mode === 1) {\n return handleUnionAccountSwapOrder(order, credential);\n }\n return handleSwapOrder(order, credential);\n }\n if (instType === 'SUPER-MARGIN') {\n return handleSuperMarginOrder(order, credential);\n }\n throw newError('UNSUPPORTED_INST_TYPE', { order_type: instType });\n};\n"]}