@yuants/vendor-huobi 0.18.7 → 0.18.9

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.
@@ -12,7 +12,7 @@ export const getSuperMarginAccountInfo = async (credential) => {
12
12
  // get account balance
13
13
  const superMarginAccountUid = await superMarginAccountUidCache.query(JSON.stringify(credential));
14
14
  if (!superMarginAccountUid)
15
- throw new Error('Failed to get Super Margin Account UID');
15
+ return [];
16
16
  const accountBalance = await getSpotAccountBalance(credential, superMarginAccountUid);
17
17
  const balanceList = ((_a = accountBalance.data) === null || _a === void 0 ? void 0 : _a.list) || [];
18
18
  // get prices and create 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,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
+ {"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,OAAO,EAAE,CAAC;IACtC,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) return [];\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"]}
@@ -8,7 +8,17 @@ 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';
11
+ import { createCache } from '@yuants/cache';
11
12
  const terminal = Terminal.fromNodeEnv();
13
+ export const accountModeCache = createCache(async (credentialKey) => {
14
+ const [access_key, secret_key] = decodePath(credentialKey);
15
+ const credential = { access_key, secret_key };
16
+ const res = await getAccountAssetsMode(credential);
17
+ return res.data.asset_mode;
18
+ }, {
19
+ expire: 600000,
20
+ swrAfter: 60000, // 1 minute
21
+ });
12
22
  provideExchangeServices(terminal, {
13
23
  name: 'HTX',
14
24
  credentialSchema: {
@@ -25,8 +35,8 @@ provideExchangeServices(terminal, {
25
35
  },
26
36
  listProducts,
27
37
  getPositions: async (credential) => {
28
- const accountMode = await getAccountAssetsMode(credential);
29
- if (accountMode.data.asset_mode === 1) {
38
+ const accountMode = await accountModeCache.query(encodePath(credential.access_key, credential.secret_key));
39
+ if (accountMode === 1) {
30
40
  const [swap, spot, superMargin] = await Promise.all([
31
41
  getUnionAccountInfo(credential),
32
42
  getSpotAccountInfo(credential, 'spot'),
@@ -1 +1 @@
1
- {"version":3,"file":"exchange.js","sourceRoot":"","sources":["../../src/services/exchange.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,uBAAuB,EAAE,MAAM,kBAAkB,CA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-order';\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
+ {"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,oBAAoB,EAAE,MAAM,EAAE,MAAM,oBAAoB,CAAC;AAC/E,OAAO,EAAE,kBAAkB,EAAE,MAAM,iBAAiB,CAAC;AACrD,OAAO,EAAE,yBAAyB,EAAE,MAAM,yBAAyB,CAAC;AACpE,OAAO,EAAE,kBAAkB,EAAE,mBAAmB,EAAE,MAAM,iBAAiB,CAAC;AAC1E,OAAO,EAAE,cAAc,EAAE,MAAM,qBAAqB,CAAC;AACrD,OAAO,EAAE,WAAW,EAAE,MAAM,sBAAsB,CAAC;AACnD,OAAO,EAAE,YAAY,EAAE,MAAM,WAAW,CAAC;AACzC,OAAO,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC;AAE5C,MAAM,QAAQ,GAAG,QAAQ,CAAC,WAAW,EAAE,CAAC;AAExC,MAAM,CAAC,MAAM,gBAAgB,GAAG,WAAW,CACzC,KAAK,EAAE,aAAqB,EAAE,EAA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QAAQ,KAAK,MAAM,EAAE;YACvB,MAAM,SAAS,GAAG,MAAM,kBAAkB,CAAC,UAAU,CAAC,CAAC;YACvD,OAAO,SAAS,CAAC,MAAM,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, 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';\nimport { createCache } from '@yuants/cache';\n\nconst terminal = Terminal.fromNodeEnv();\n\nexport const accountModeCache = createCache(\n async (credentialKey: string) => {\n const [access_key, secret_key] = decodePath(credentialKey);\n const credential = { access_key, secret_key };\n const res = await getAccountAssetsMode(credential);\n return res.data.asset_mode;\n },\n {\n expire: 600_000, // 10 minutes\n swrAfter: 60_000, // 1 minute\n },\n);\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 accountModeCache.query(\n encodePath(credential.access_key, credential.secret_key),\n );\n if (accountMode === 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,9 @@
1
- import { decodePath, formatTime, newError, roundToStep } from '@yuants/utils';
2
- import { getAccountAssetsMode, getCrossMarginLoanInfo, getSpotAccountBalance, getSwapCrossPositionInfo, postSpotOrder, postSwapOrder, postUnionAccountSwapOrder, } from '../../api/private-api';
1
+ import { decodePath, encodePath, formatTime, newError, roundToStep } from '@yuants/utils';
2
+ import { 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
+ import { accountModeCache } from '../exchange';
6
7
  /**
7
8
  * 处理 swap 账户订单提交
8
9
  */
@@ -110,8 +111,9 @@ async function handleSuperMarginOrder(order, credential) {
110
111
  export const submitOrder = async (credential, order) => {
111
112
  const [, instType] = decodePath(order.product_id);
112
113
  if (instType === 'SWAP') {
113
- const accountMode = await getAccountAssetsMode(credential);
114
- if (accountMode.data.asset_mode === 1) {
114
+ // const accountMode = await getAccountAssetsMode(credential);
115
+ const accountMode = await accountModeCache.query(encodePath(credential.access_key, credential.secret_key));
116
+ if (accountMode === 1) {
115
117
  return handleUnionAccountSwapOrder(order, credential);
116
118
  }
117
119
  return handleSwapOrder(order, credential);
@@ -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,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,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;KACpC,CAAC;IACF,MAAM,MAAM,GA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,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"]}
1
+ {"version":3,"file":"submitOrder.js","sourceRoot":"","sources":["../../../src/services/orders/submitOrder.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,QAAQ,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC;AAC1F,OAAO,EAGL,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;AACpD,OAAO,EAAE,gBAAgB,EAAE,MAAM,aAAa,CAAC;AAE/C;;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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,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, encodePath, 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';\nimport { accountModeCache } from '../exchange';\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 const accountMode = await accountModeCache.query(\n encodePath(credential.access_key, credential.secret_key),\n );\n if (accountMode === 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"]}
@@ -15,7 +15,7 @@ const getSuperMarginAccountInfo = async (credential) => {
15
15
  // get account balance
16
16
  const superMarginAccountUid = await uid_1.superMarginAccountUidCache.query(JSON.stringify(credential));
17
17
  if (!superMarginAccountUid)
18
- throw new Error('Failed to get Super Margin Account UID');
18
+ return [];
19
19
  const accountBalance = await (0, private_api_1.getSpotAccountBalance)(credential, superMarginAccountUid);
20
20
  const balanceList = ((_a = accountBalance.data) === null || _a === void 0 ? void 0 : _a.list) || [];
21
21
  // get prices and create positions
@@ -1 +1 @@
1
- {"version":3,"file":"super-margin.js","sourceRoot":"","sources":["../../../src/services/accounts/super-margin.ts"],"names":[],"mappings":";;;AAAA,uDAAmG;AACnG,yCAA2C;AAC3C,uDAA2E;AAC3E,gDAAkD;AAClD,gCAAoD;AAEpD;;GAEG;AACI,MAAM,yBAAyB,GAAgD,KAAK,EAAE,UAAU,EAAE,EAAE;;IACzG,MAAM,SAAS,GAAgB,EAAE,CAAC;IAClC,sBAAsB;IACtB,MAAM,qBAAqB,GAAG,MAAM,gCAA0B,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,IAAA,mCAAqB,EAAC,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,IAAA,kBAAU,EAAC,KAAK,EAAE,cAAc,EAAE,YAAY,CAAC,QAAQ,GAAG,MAAM,CAAC,CAAC;QACrF,MAAM,KAAK,GAAG,MAAM,kBAAU,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,IAAA,+BAAgB,EAAC;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;AA5BW,QAAA,yBAAyB,6BA4BpC","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
+ {"version":3,"file":"super-margin.js","sourceRoot":"","sources":["../../../src/services/accounts/super-margin.ts"],"names":[],"mappings":";;;AAAA,uDAAmG;AACnG,yCAA2C;AAC3C,uDAA2E;AAC3E,gDAAkD;AAClD,gCAAoD;AAEpD;;GAEG;AACI,MAAM,yBAAyB,GAAgD,KAAK,EAAE,UAAU,EAAE,EAAE;;IACzG,MAAM,SAAS,GAAgB,EAAE,CAAC;IAClC,sBAAsB;IACtB,MAAM,qBAAqB,GAAG,MAAM,gCAA0B,CAAC,KAAK,CAAC,IAAI,CAAC,SAAS,CAAC,UAAU,CAAC,CAAC,CAAC;IACjG,IAAI,CAAC,qBAAqB;QAAE,OAAO,EAAE,CAAC;IACtC,MAAM,cAAc,GAAG,MAAM,IAAA,mCAAqB,EAAC,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,IAAA,kBAAU,EAAC,KAAK,EAAE,cAAc,EAAE,YAAY,CAAC,QAAQ,GAAG,MAAM,CAAC,CAAC;QACrF,MAAM,KAAK,GAAG,MAAM,kBAAU,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,IAAA,+BAAgB,EAAC;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;AA5BW,QAAA,yBAAyB,6BA4BpC","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) return [];\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,2 +1,2 @@
1
- export {};
1
+ export declare const accountModeCache: import("@yuants/cache").ICache<number>;
2
2
  //# sourceMappingURL=exchange.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"exchange.d.ts","sourceRoot":"","sources":["../../src/services/exchange.ts"],"names":[],"mappings":""}
1
+ {"version":3,"file":"exchange.d.ts","sourceRoot":"","sources":["../../src/services/exchange.ts"],"names":[],"mappings":"AAeA,eAAO,MAAM,gBAAgB,wCAW5B,CAAC"}
@@ -1,5 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.accountModeCache = void 0;
3
4
  const exchange_1 = require("@yuants/exchange");
4
5
  const protocol_1 = require("@yuants/protocol");
5
6
  const utils_1 = require("@yuants/utils");
@@ -10,7 +11,17 @@ const swap_1 = require("./accounts/swap");
10
11
  const listOrders_1 = require("./orders/listOrders");
11
12
  const submitOrder_1 = require("./orders/submitOrder");
12
13
  const product_1 = require("./product");
14
+ const cache_1 = require("@yuants/cache");
13
15
  const terminal = protocol_1.Terminal.fromNodeEnv();
16
+ exports.accountModeCache = (0, cache_1.createCache)(async (credentialKey) => {
17
+ const [access_key, secret_key] = (0, utils_1.decodePath)(credentialKey);
18
+ const credential = { access_key, secret_key };
19
+ const res = await (0, private_api_1.getAccountAssetsMode)(credential);
20
+ return res.data.asset_mode;
21
+ }, {
22
+ expire: 600000,
23
+ swrAfter: 60000, // 1 minute
24
+ });
14
25
  (0, exchange_1.provideExchangeServices)(terminal, {
15
26
  name: 'HTX',
16
27
  credentialSchema: {
@@ -27,8 +38,8 @@ const terminal = protocol_1.Terminal.fromNodeEnv();
27
38
  },
28
39
  listProducts: product_1.listProducts,
29
40
  getPositions: async (credential) => {
30
- const accountMode = await (0, private_api_1.getAccountAssetsMode)(credential);
31
- if (accountMode.data.asset_mode === 1) {
41
+ const accountMode = await exports.accountModeCache.query((0, utils_1.encodePath)(credential.access_key, credential.secret_key));
42
+ if (accountMode === 1) {
32
43
  const [swap, spot, superMargin] = await Promise.all([
33
44
  (0, swap_1.getUnionAccountInfo)(credential),
34
45
  (0, spot_1.getSpotAccountInfo)(credential, 'spot'),
@@ -1 +1 @@
1
- {"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AK,MAAM,EAAE;YACvB,MAAM,SAAS,GAAG,MAAM,IAAA,yBAAkB,EAAC,UAAU,CAAC,CAAC;YACvD,OAAO,SAAS,CAAC,MAAM,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,IAAA,wCAAyB,EAAC,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,IAAA,gBAAQ,EAAC,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,IAAA,kBAAU,EAAC,UAAU,CAAC,CAAC;QAC5C,6BAA6B;QAC7B,iEAAiE;QACjE,sEAAsE;QACtE,IAAI;QACJ,IAAI,QAAQ,KAAK,MAAM,EAAE;YACvB,MAAM,MAAM,GAAG,MAAM,IAAA,2BAAc,EAAC,UAAU,CAAC,CAAC;YAChD,OAAO,MAAM,CAAC,MAAM,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,UAAU,KAAK,UAAU,CAAC,CAAC;SAClE;QACD,MAAM,IAAA,gBAAQ,EAAC,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, 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
+ {"version":3,"file":"exchange.js","sourceRoot":"","sources":["../../src/services/exchange.ts"],"names":[],"mappings":";;;AACA,+CAA2D;AAC3D,+CAA4C;AAC5C,yCAAiE;AACjE,oDAA+E;AAC/E,0CAAqD;AACrD,0DAAoE;AACpE,0CAA0E;AAC1E,oDAAqD;AACrD,sDAAmD;AACnD,uCAAyC;AACzC,yCAA4C;AAE5C,MAAM,QAAQ,GAAG,mBAAQ,CAAC,WAAW,EAAE,CAAC;AAE3B,QAAA,gBAAgB,GAAG,IAAA,mBAAW,EACzC,KAAK,EAAE,aAAqB,EAAE,EAAE;IAC9B,MAAM,CAAC,UAAU,EAAE,UAAU,CAAC,GAAG,IAAA,kBAAU,EAAC,aAAa,CAAC,CAAC;IAC3D,MAAM,UAAU,GAAG,EAAE,UAAU,EAAE,UAAU,EAAE,CAAC;IAC9C,MAAM,GAAG,GAAG,MAAM,IAAA,kCAAoB,EAAC,UAAU,CAAC,CAAC;IACnD,OAAO,GAAG,CAAC,IAAI,CAAC,UAAU,CAAC;AAC7B,CAAC,EACD;IACE,MAAM,EAAE,MAAO;IACf,QAAQ,EAAE,KAAM,EAAE,WAAW;CAC9B,CACF,CAAC;AAEF,IAAA,kCAAuB,EAAc,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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,EAAE,UAAU,EAAE,CAAC,CAAC;IACzD,CAAC;IACD,oBAAoB,EAAE,KAAK,EAAE,UAAuB,EAAE,UAAkB,EAAqB,EAAE;QAC7F,MAAM,CAAC,EAAE,QAAQ,CAAC,GAAG,IAAA,kBAAU,EAAC,UAAU,CAAC,CAAC;QAC5C,6BAA6B;QAC7B,iEAAiE;QACjE,sEAAsE;QACtE,IAAI;QACJ,IAAI,QAAQ,KAAK,MAAM,EAAE;YACvB,MAAM,MAAM,GAAG,MAAM,IAAA,2BAAc,EAAC,UAAU,CAAC,CAAC;YAChD,OAAO,MAAM,CAAC,MAAM,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,UAAU,KAAK,UAAU,CAAC,CAAC;SAClE;QACD,MAAM,IAAA,gBAAQ,EAAC,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, 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';\nimport { createCache } from '@yuants/cache';\n\nconst terminal = Terminal.fromNodeEnv();\n\nexport const accountModeCache = createCache(\n async (credentialKey: string) => {\n const [access_key, secret_key] = decodePath(credentialKey);\n const credential = { access_key, secret_key };\n const res = await getAccountAssetsMode(credential);\n return res.data.asset_mode;\n },\n {\n expire: 600_000, // 10 minutes\n swrAfter: 60_000, // 1 minute\n },\n);\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 accountModeCache.query(\n encodePath(credential.access_key, credential.secret_key),\n );\n if (accountMode === 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 +1 @@
1
- {"version":3,"file":"submitOrder.d.ts","sourceRoot":"","sources":["../../../src/services/orders/submitOrder.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,oBAAoB,CAAC;AAE5C,OAAO,EACL,WAAW,EAQZ,MAAM,uBAAuB,CAAC;AAqI/B,eAAO,MAAM,WAAW,eAAsB,WAAW,SAAS,MAAM,KAAG,QAAQ;IAAE,QAAQ,EAAE,MAAM,CAAA;CAAE,CAatG,CAAC"}
1
+ {"version":3,"file":"submitOrder.d.ts","sourceRoot":"","sources":["../../../src/services/orders/submitOrder.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,oBAAoB,CAAC;AAE5C,OAAO,EACL,WAAW,EAQZ,MAAM,uBAAuB,CAAC;AAsI/B,eAAO,MAAM,WAAW,eAAsB,WAAW,SAAS,MAAM,KAAG,QAAQ;IAAE,QAAQ,EAAE,MAAM,CAAA;CAAE,CAgBtG,CAAC"}
@@ -6,6 +6,7 @@ const private_api_1 = require("../../api/private-api");
6
6
  const public_api_1 = require("../../api/public-api");
7
7
  const product_1 = require("../product");
8
8
  const uid_1 = require("../uid");
9
+ const exchange_1 = require("../exchange");
9
10
  /**
10
11
  * 处理 swap 账户订单提交
11
12
  */
@@ -113,8 +114,9 @@ async function handleSuperMarginOrder(order, credential) {
113
114
  const submitOrder = async (credential, order) => {
114
115
  const [, instType] = (0, utils_1.decodePath)(order.product_id);
115
116
  if (instType === 'SWAP') {
116
- const accountMode = await (0, private_api_1.getAccountAssetsMode)(credential);
117
- if (accountMode.data.asset_mode === 1) {
117
+ // const accountMode = await getAccountAssetsMode(credential);
118
+ const accountMode = await exchange_1.accountModeCache.query((0, utils_1.encodePath)(credential.access_key, credential.secret_key));
119
+ if (accountMode === 1) {
118
120
  return handleUnionAccountSwapOrder(order, credential);
119
121
  }
120
122
  return handleSwapOrder(order, credential);
@@ -1 +1 @@
1
- {"version":3,"file":"submitOrder.js","sourceRoot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C;AACtD,CAAC;AAEM,MAAM,WAAW,GAAG,KAAK,EAAE,UAAuB,EAAE,KAAa,EAAiC,EAAE;IACzG,MAAM,CAAC,EAAE,QAAQ,CAAC,GAAG,IAAA,kBAAU,EAAC,KAAK,CAAC,UAAU,CAAC,CAAC;IAClD,IAAI,QAAQ,KAAK,MAAM,EAAE;QACvB,MAAM,WAAW,GAAG,MAAM,IAAA,kCAAoB,EAAC,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,IAAA,gBAAQ,EAAC,uBAAuB,EAAE,EAAE,UAAU,EAAE,QAAQ,EAAE,CAAC,CAAC;AACpE,CAAC,CAAC;AAbW,QAAA,WAAW,eAatB","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"]}
1
+ {"version":3,"file":"submitOrder.js","sourceRoot":"","sources":["../../../src/services/orders/submitOrder.ts"],"names":[],"mappings":";;;AACA,yCAA0F;AAC1F,uDAS+B;AAC/B,qDAAmD;AACnD,wCAA0C;AAC1C,gCAAoD;AACpD,0CAA+C;AAE/C;;GAEG;AACH,KAAK,UAAU,2BAA2B,CACxC,KAAa,EACb,UAAuB;IAEvB,MAAM,CAAC,EAAE,QAAQ,EAAE,YAAY,CAAC,GAAG,IAAA,kBAAU,EAAC,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,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;KACpC,CAAC;IACF,MAAM,MAAM,GAAG,MAAM,IAAA,uCAAyB,EAAC,UAAU,EAAE,MAAM,CAA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,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;AAEM,MAAM,WAAW,GAAG,KAAK,EAAE,UAAuB,EAAE,KAAa,EAAiC,EAAE;IACzG,MAAM,CAAC,EAAE,QAAQ,CAAC,GAAG,IAAA,kBAAU,EAAC,KAAK,CAAC,UAAU,CAAC,CAAC;IAClD,IAAI,QAAQ,KAAK,MAAM,EAAE;QACvB,8DAA8D;QAC9D,MAAM,WAAW,GAAG,MAAM,2BAAgB,CAAC,KAAK,CAC9C,IAAA,kBAAU,EAAC,UAAU,CAAC,UAAU,EAAE,UAAU,CAAC,UAAU,CAAC,CACzD,CAAC;QACF,IAAI,WAAW,KAAK,CAAC,EAAE;YACrB,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,IAAA,gBAAQ,EAAC,uBAAuB,EAAE,EAAE,UAAU,EAAE,QAAQ,EAAE,CAAC,CAAC;AACpE,CAAC,CAAC;AAhBW,QAAA,WAAW,eAgBtB","sourcesContent":["import { IOrder } from '@yuants/data-order';\nimport { decodePath, encodePath, 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';\nimport { accountModeCache } from '../exchange';\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 const accountMode = await accountModeCache.query(\n encodePath(credential.access_key, credential.secret_key),\n );\n if (accountMode === 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"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@yuants/vendor-huobi",
3
- "version": "0.18.7",
3
+ "version": "0.18.9",
4
4
  "main": "lib/index.js",
5
5
  "files": [
6
6
  "dist",
@@ -8,19 +8,19 @@
8
8
  "temp"
9
9
  ],
10
10
  "dependencies": {
11
- "@yuants/protocol": "0.53.7",
12
- "@yuants/data-account": "0.11.4",
13
- "@yuants/data-order": "0.7.5",
14
- "@yuants/data-ohlc": "0.6.0",
15
- "@yuants/transfer": "0.2.44",
16
- "@yuants/utils": "0.19.0",
17
- "@yuants/cache": "0.3.8",
18
- "@yuants/sql": "0.9.35",
19
- "@yuants/data-product": "0.5.5",
20
- "@yuants/data-series": "0.3.57",
21
- "@yuants/data-interest-rate": "0.2.3",
22
- "@yuants/data-quote": "0.4.4",
23
- "@yuants/exchange": "0.8.6",
11
+ "@yuants/protocol": "0.53.8",
12
+ "@yuants/data-account": "0.11.5",
13
+ "@yuants/data-order": "0.7.6",
14
+ "@yuants/data-ohlc": "0.6.1",
15
+ "@yuants/transfer": "0.2.45",
16
+ "@yuants/utils": "0.19.1",
17
+ "@yuants/cache": "0.3.9",
18
+ "@yuants/sql": "0.9.36",
19
+ "@yuants/data-product": "0.5.6",
20
+ "@yuants/data-series": "0.3.58",
21
+ "@yuants/data-interest-rate": "0.2.4",
22
+ "@yuants/data-quote": "0.4.5",
23
+ "@yuants/exchange": "0.8.7",
24
24
  "rxjs": "~7.5.6"
25
25
  },
26
26
  "devDependencies": {
@@ -30,7 +30,7 @@
30
30
  "@rushstack/heft-node-rig": "~1.10.7",
31
31
  "@types/heft-jest": "1.0.3",
32
32
  "@types/node": "22",
33
- "@yuants/extension": "0.2.36",
33
+ "@yuants/extension": "0.2.37",
34
34
  "@yuants/tool-kit": "0.2.1",
35
35
  "typescript": "~4.7.4"
36
36
  },
@@ -1,13 +1,13 @@
1
1
  {
2
- "apps/vendor-huobi/CHANGELOG.json": "3e2ffb56e766c1c3768eeeb350402eecc35371e1",
3
- "apps/vendor-huobi/CHANGELOG.md": "308a5508b85b5b183d30110bf14ab628dcf75f2e",
2
+ "apps/vendor-huobi/CHANGELOG.json": "66c2fafde69ebfd25ede0b9308e5319ac6a9cb70",
3
+ "apps/vendor-huobi/CHANGELOG.md": "f062fb8e9bb0a0d377675a54bffafc5b230ae4c5",
4
4
  "apps/vendor-huobi/README.md": "d7bf0149513114eab5500a6b5c9e7cba10565572",
5
5
  "apps/vendor-huobi/api-extractor.json": "62f4fd324425b9a235f0c117975967aab09ced0c",
6
6
  "apps/vendor-huobi/config/jest.config.json": "4bb17bde3ee911163a3edb36a6eb71491d80b1bd",
7
7
  "apps/vendor-huobi/config/rig.json": "f6c7b5537dc77a3170ba9f008bae3b6c3ee11956",
8
8
  "apps/vendor-huobi/config/typescript.json": "854907e8a821f2050f6533368db160c649c25348",
9
9
  "apps/vendor-huobi/etc/vendor-huobi.api.md": "dc8cbf2a044a227b30a4ee9701b0c97328244724",
10
- "apps/vendor-huobi/package.json": "08d5fbab311d4f923e90fa34e10a5375d66d3451",
10
+ "apps/vendor-huobi/package.json": "4908c9c4120ba03dee6c75876894e9968802f22e",
11
11
  "apps/vendor-huobi/src/__archived/account-info.ts": "5c325d3bb8839476c11f25693326ce05f3321ebd",
12
12
  "apps/vendor-huobi/src/__archived/api.ts": "8366151dc881b177d0478fb328a601a11e33cd35",
13
13
  "apps/vendor-huobi/src/__archived/transfer.ts": "fd299ad82ff31344460967f2a938b8f36c879259",
@@ -15,33 +15,33 @@
15
15
  "apps/vendor-huobi/src/api/public-api.ts": "7141d4c6369a59b062b2b0e5a475af9abb1ec31b",
16
16
  "apps/vendor-huobi/src/index.ts": "997283c933e2df8c6d35ce3d2f40d7d0c33c469b",
17
17
  "apps/vendor-huobi/src/services/accounts/spot.ts": "fb2e22203eecce2dbb246a0bf8d8c1caec4c5dff",
18
- "apps/vendor-huobi/src/services/accounts/super-margin.ts": "83b6012233458c4d4723971cb4f0342d876142ed",
18
+ "apps/vendor-huobi/src/services/accounts/super-margin.ts": "b8a97300664e25f512994813b2175f39a2d76508",
19
19
  "apps/vendor-huobi/src/services/accounts/swap.ts": "7ed0a7a6e927973b1c13dd156cd72607708e818b",
20
- "apps/vendor-huobi/src/services/exchange.ts": "00efd7d0b85e67d69bd4e01f21b16c48b41c6660",
20
+ "apps/vendor-huobi/src/services/exchange.ts": "6f704961de6dd03b2db3544da6b49c6dd8531f33",
21
21
  "apps/vendor-huobi/src/services/interest-rate-service.ts": "3180227cd8fe336e187ad7a90bf3ce1bb7dfc7f7",
22
22
  "apps/vendor-huobi/src/services/market-data/interest_rate.ts": "79aa362f9fa90e612f9813d0b45d357b96189f3e",
23
23
  "apps/vendor-huobi/src/services/market-data/quote.ts": "2f5883a95b11cf19c1a9a595567f9369b360cccf",
24
24
  "apps/vendor-huobi/src/services/ohlc-service.ts": "914f75705e0ad396b537e4b55334419206526160",
25
25
  "apps/vendor-huobi/src/services/orders/listOrders.ts": "1cf4621727fb290f8e5fd1439765fd73387bda7a",
26
- "apps/vendor-huobi/src/services/orders/submitOrder.ts": "1a2129b48496c546b9f7708d97c8bdbf9ad6d977",
26
+ "apps/vendor-huobi/src/services/orders/submitOrder.ts": "55c782b03c1f5acce3b8b9d09b1a626d673590e9",
27
27
  "apps/vendor-huobi/src/services/product.ts": "096feb6e1348910242e814ca45848afa3b5bff98",
28
28
  "apps/vendor-huobi/src/services/quotes.ts": "a99185c9d2e95da220919deef49357ec6280ee78",
29
29
  "apps/vendor-huobi/src/services/uid.ts": "b71c27a6a0debdd9365dea35306f4763327aca2f",
30
30
  "apps/vendor-huobi/tsconfig.json": "81da8f78196974b5d15da0edb6b2d9f48641063c",
31
31
  "apps/vendor-huobi/.rush/temp/shrinkwrap-deps.json": "237a816d6e825b5bd2a0fc742f5d055c19e37d3d",
32
- "libraries/protocol/temp/package-deps.json": "765a1ba74dfa437b95a8685a308a09df6de49706",
33
- "libraries/data-account/temp/package-deps.json": "ef7f802f6cec62965d3a5ea3365df131b9ed46a0",
34
- "libraries/data-order/temp/package-deps.json": "9940b4267bcaaba4f3e0db2d2e07f575ea8afa34",
35
- "libraries/data-ohlc/temp/package-deps.json": "1abde47d0c7112ca7871ec9243e38ea48f8eba79",
36
- "libraries/transfer/temp/package-deps.json": "f4c5d1fc1bed3061cee9e67381ab36749fb9118f",
37
- "libraries/utils/temp/package-deps.json": "ae24e0f28d8238425131202aa7e46e2fc6ba3ae2",
38
- "libraries/cache/temp/package-deps.json": "3fe087e264b56a7a72d25df93f942e69de6ab765",
39
- "libraries/sql/temp/package-deps.json": "35ac4d78347c54d6c247d31dd77a1d88cfaed20f",
40
- "libraries/data-product/temp/package-deps.json": "d527946b0136eb9ad0ee4451d31ea2c18eb88fa3",
41
- "libraries/data-series/temp/package-deps.json": "5148dcf1033142f34a1dff17076a7a031052cb21",
42
- "libraries/data-interest-rate/temp/package-deps.json": "82005a4c9b295c0eab9599127946dd8c915adc64",
43
- "libraries/data-quote/temp/package-deps.json": "1b8805efdca7fee957cf36c414a0c53d5faa454b",
44
- "libraries/exchange/temp/package-deps.json": "b00a11bc3628c9cbe8cea4eccd7b1f3d21d5b77d",
45
- "libraries/extension/temp/package-deps.json": "0655b86a4838124dba78913552adf2425484e900",
32
+ "libraries/protocol/temp/package-deps.json": "9da9005e6641248a130efd59cf3ecab59d38e439",
33
+ "libraries/data-account/temp/package-deps.json": "6c5c8d1a8978440a24088a8021ec8697e4f4f533",
34
+ "libraries/data-order/temp/package-deps.json": "99ffcda59f57c8df7335e0da889207f9fa5149db",
35
+ "libraries/data-ohlc/temp/package-deps.json": "7e7ac0f11ff026349ec065b464b26c2fa4947f74",
36
+ "libraries/transfer/temp/package-deps.json": "df82e243e9a7ee4355b5028ebb9b518531439f48",
37
+ "libraries/utils/temp/package-deps.json": "b5a9a3b10eb5327f65beb5f032945a3a319ceb8a",
38
+ "libraries/cache/temp/package-deps.json": "732005efe94c5ec2f26dcf7431bda6302f293a26",
39
+ "libraries/sql/temp/package-deps.json": "112e0f523cf3c672518f9cb970dc0e546a055e5d",
40
+ "libraries/data-product/temp/package-deps.json": "0e718a91c692c06681edd341b9abda24291f26a4",
41
+ "libraries/data-series/temp/package-deps.json": "129a2e45757cc68f8bb1f798dc1ffa8017b70720",
42
+ "libraries/data-interest-rate/temp/package-deps.json": "c76d04d57e4e37087103a33b9e2a1a9f3e1153aa",
43
+ "libraries/data-quote/temp/package-deps.json": "4b35a4ebec8793ed9b9f588fe1b2183866f4cfe6",
44
+ "libraries/exchange/temp/package-deps.json": "e788eb578ef4ff43c82e12b7916cb3a598528918",
45
+ "libraries/extension/temp/package-deps.json": "f4baba92c9074a6573eba5180a4d31f17c72b94f",
46
46
  "tools/toolkit/temp/package-deps.json": "23e053490eb8feade23e4d45de4e54883e322711"
47
47
  }