@yuants/vendor-okx 0.29.6 → 0.29.8

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.
@@ -1,8 +1,8 @@
1
1
  import { createCache } from '@yuants/cache';
2
2
  import { getAccountConfig } from '../api/private-api';
3
- const accountConfigCache = createCache((key) => getAccountConfig(JSON.parse(key)), {
4
- expire: 100000,
5
- swrAfter: 10000,
3
+ export const accountConfigCache = createCache((key) => getAccountConfig(JSON.parse(key)), {
4
+ expire: 1000000,
5
+ swrAfter: 100000, // 100 秒后后台刷新
6
6
  });
7
7
  const accountUidCache = createCache(async (key) => {
8
8
  const config = await accountConfigCache.query(key);
@@ -1 +1 @@
1
- {"version":3,"file":"uid.js","sourceRoot":"","sources":["../../src/accountInfos/uid.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC;AAC5C,OAAO,EAAE,gBAAgB,EAAe,MAAM,oBAAoB,CAAC;AAEnE,MAAM,kBAAkB,GAAG,WAAW,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,gBAAgB,CAAC,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,EAAE;IACjF,MAAM,EAAE,MAAO;IACf,QAAQ,EAAE,KAAM;CACjB,CAAC,CAAC;AAEH,MAAM,eAAe,GAAG,WAAW,CAAC,KAAK,EAAE,GAAG,EAAE,EAAE;IAChD,MAAM,MAAM,GAAG,MAAM,kBAAkB,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;IACnD,OAAO,MAAM,aAAN,MAAM,uBAAN,MAAM,CAAE,IAAI,CAAC,CAAC,EAAE,GAAG,CAAC;AAC7B,CAAC,CAAC,CAAC;AAEH,MAAM,cAAc,GAAG,WAAW,CAAC,KAAK,EAAE,GAAG,EAAE,EAAE;IAC/C,MAAM,GAAG,GAAG,MAAM,eAAe,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;IAC7C,IAAI,CAAC,GAAG;Q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,CACnE,aAAa,CAAC,UAAU,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAE,CAAC,OAAO,CAAC,CAAC;AAEpD,MAAM,CAAC,MAAM,mBAAmB,GAAG,KAAK,EAAE,UAAuB,EAAE,EAAE,CACnE,aAAa,CAAC,UAAU,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAE,CAAC,OAAO,CAAC,CAAC","sourcesContent":["import { createCache } from '@yuants/cache';\nimport { getAccountConfig, ICredential } from '../api/private-api';\n\nconst accountConfigCache = createCache((key) => getAccountConfig(JSON.parse(key)), {\n expire: 100_000,\n swrAfter: 10_000,\n});\n\nconst accountUidCache = createCache(async (key) => {\n const config = await accountConfigCache.query(key);\n return config?.data[0].uid;\n});\n\nconst accountIdCache = createCache(async (key) => {\n const uid = await accountUidCache.query(key);\n if (!uid) throw new Error('Failed to get UID');\n return {\n trading: `okx/${uid}/trading`,\n strategy: `okx/${uid}/strategy`,\n loan: `okx/${uid}/loan/USDT`,\n earning: `okx/${uid}/earning/USDT`,\n funding: `okx/${uid}/funding/USDT`,\n };\n});\n\nexport const getUid = async (credential: ICredential) => {\n return accountUidCache.query(JSON.stringify(credential));\n};\n\nexport const getAccountIds = async (credential: ICredential) => {\n return accountIdCache.query(JSON.stringify(credential));\n};\n\nexport const getTradingAccountId = async (credential: ICredential) =>\n getAccountIds(credential).then((x) => x!.trading);\n\nexport const getStrategyAccountId = async (credential: ICredential) =>\n getAccountIds(credential).then((x) => x!.strategy);\n\nexport const getLoanAccountId = async (credential: ICredential) =>\n getAccountIds(credential).then((x) => x!.loan);\n\nexport const getEarningAccountId = async (credential: ICredential) =>\n getAccountIds(credential).then((x) => x!.earning);\n\nexport const getFundingAccountId = async (credential: ICredential) =>\n getAccountIds(credential).then((x) => x!.funding);\n"]}
1
+ {"version":3,"file":"uid.js","sourceRoot":"","sources":["../../src/accountInfos/uid.ts"],"names":[],"mappings":"AAAA,OAAO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AE,UAAuB,EAAE,EAAE;IAC7D,OAAO,cAAc,CAAC,KAAK,CAAC,IAAI,CAAC,SAAS,CAAC,UAAU,CAAC,CAAC,CAAC;AAC1D,CAAC,CAAC;AAEF,MAAM,CAAC,MAAM,mBAAmB,GAAG,KAAK,EAAE,UAAuB,EAAE,EAAE,CACnE,aAAa,CAAC,UAAU,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAE,CAAC,OAAO,CAAC,CAAC;AAEpD,MAAM,CAAC,MAAM,oBAAoB,GAAG,KAAK,EAAE,UAAuB,EAAE,EAAE,CACpE,aAAa,CAAC,UAAU,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAE,CAAC,QAAQ,CAAC,CAAC;AAErD,MAAM,CAAC,MAAM,gBAAgB,GAAG,KAAK,EAAE,UAAuB,EAAE,EAAE,CAChE,aAAa,CAAC,UAAU,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAE,CAAC,IAAI,CAAC,CAAC;AAEjD,MAAM,CAAC,MAAM,mBAAmB,GAAG,KAAK,EAAE,UAAuB,EAAE,EAAE,CACnE,aAAa,CAAC,UAAU,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAE,CAAC,OAAO,CAAC,CAAC;AAEpD,MAAM,CAAC,MAAM,mBAAmB,GAAG,KAAK,EAAE,UAAuB,EAAE,EAAE,CACnE,aAAa,CAAC,UAAU,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAE,CAAC,OAAO,CAAC,CAAC","sourcesContent":["import { createCache } from '@yuants/cache';\nimport { getAccountConfig, ICredential } from '../api/private-api';\n\nexport const accountConfigCache = createCache((key) => getAccountConfig(JSON.parse(key)), {\n expire: 1000_000, // 缓存 1000 秒\n swrAfter: 100_000, // 100 秒后后台刷新\n});\n\nconst accountUidCache = createCache(async (key) => {\n const config = await accountConfigCache.query(key);\n return config?.data[0].uid;\n});\n\nconst accountIdCache = createCache(async (key) => {\n const uid = await accountUidCache.query(key);\n if (!uid) throw new Error('Failed to get UID');\n return {\n trading: `okx/${uid}/trading`,\n strategy: `okx/${uid}/strategy`,\n loan: `okx/${uid}/loan/USDT`,\n earning: `okx/${uid}/earning/USDT`,\n funding: `okx/${uid}/funding/USDT`,\n };\n});\n\nexport const getUid = async (credential: ICredential) => {\n return accountUidCache.query(JSON.stringify(credential));\n};\n\nexport const getAccountIds = async (credential: ICredential) => {\n return accountIdCache.query(JSON.stringify(credential));\n};\n\nexport const getTradingAccountId = async (credential: ICredential) =>\n getAccountIds(credential).then((x) => x!.trading);\n\nexport const getStrategyAccountId = async (credential: ICredential) =>\n getAccountIds(credential).then((x) => x!.strategy);\n\nexport const getLoanAccountId = async (credential: ICredential) =>\n getAccountIds(credential).then((x) => x!.loan);\n\nexport const getEarningAccountId = async (credential: ICredential) =>\n getAccountIds(credential).then((x) => x!.earning);\n\nexport const getFundingAccountId = async (credential: ICredential) =>\n getAccountIds(credential).then((x) => x!.funding);\n"]}
@@ -1,5 +1,6 @@
1
- import { decodePath, formatTime, roundToStep } from '@yuants/utils';
1
+ import { decodePath, formatTime, newError, roundToStep } from '@yuants/utils';
2
2
  import { firstValueFrom, map } from 'rxjs';
3
+ import { accountConfigCache } from '../accountInfos/uid';
3
4
  import { postTradeOrder } from '../api/private-api';
4
5
  import { productService } from '../public-data/product';
5
6
  import { spotMarketTickers$ } from '../public-data/quote';
@@ -14,17 +15,6 @@ const mapOrderDirectionToSide = (direction) => {
14
15
  }
15
16
  throw new Error(`Unknown direction: ${direction}`);
16
17
  };
17
- const mapOrderDirectionToPosSide = (direction) => {
18
- switch (direction) {
19
- case 'OPEN_LONG':
20
- case 'CLOSE_LONG':
21
- return 'long';
22
- case 'CLOSE_SHORT':
23
- case 'OPEN_SHORT':
24
- return 'short';
25
- }
26
- throw new Error(`Unknown direction: ${direction}`);
27
- };
28
18
  const mapOrderTypeToOrdType = (order_type) => {
29
19
  switch (order_type) {
30
20
  case 'LIMIT':
@@ -37,7 +27,16 @@ const mapOrderTypeToOrdType = (order_type) => {
37
27
  throw new Error(`Unknown order type: ${order_type}`);
38
28
  };
39
29
  export const submitOrder = async (credential, order) => {
40
- var _a, _b, _c;
30
+ var _a, _b, _c, _d;
31
+ const accountConfigRes = await accountConfigCache.query(JSON.stringify(credential));
32
+ if (!accountConfigRes)
33
+ throw newError('ACCOUNT_CONFIG_FETCH_ERROR', { accountConfigRes });
34
+ if (!((_a = accountConfigRes.data) === null || _a === void 0 ? void 0 : _a[0]))
35
+ throw newError('ACCOUNT_CONFIG_FETCH_ERROR', { accountConfigRes });
36
+ /**
37
+ * 是否为组合保证金模式
38
+ */
39
+ const isPortfolioMarginMode = accountConfigRes.data[0].acctLv === '4';
41
40
  const [instType, instId] = decodePath(order.product_id).slice(-2);
42
41
  // 交易数量,表示要购买或者出售的数量。
43
42
  // 当币币/币币杠杆以限价买入和卖出时,指交易货币数量。
@@ -81,6 +80,19 @@ export const submitOrder = async (credential, order) => {
81
80
  }
82
81
  throw new Error(`Unknown instType: ${instType}`);
83
82
  };
83
+ const mapOrderDirectionToPosSide = (direction) => {
84
+ if (isPortfolioMarginMode)
85
+ return undefined;
86
+ switch (direction) {
87
+ case 'OPEN_LONG':
88
+ case 'CLOSE_LONG':
89
+ return 'long';
90
+ case 'CLOSE_SHORT':
91
+ case 'OPEN_SHORT':
92
+ return 'short';
93
+ }
94
+ throw new Error(`Unknown direction: ${direction}`);
95
+ };
84
96
  const params = {
85
97
  instId,
86
98
  tdMode: instType === 'SPOT' ? 'cash' : 'cross',
@@ -91,7 +103,7 @@ export const submitOrder = async (credential, order) => {
91
103
  ordType: mapOrderTypeToOrdType(order.order_type),
92
104
  sz: (await mapOrderVolumeToSz(order)).toString(),
93
105
  tgtCcy: instType === 'SPOT' && order.order_type === 'MARKET' ? 'base_ccy' : undefined,
94
- reduceOnly: instType === 'MARGIN' && ['CLOSE_LONG', 'CLOSE_SHORT'].includes((_a = order.order_direction) !== null && _a !== void 0 ? _a : '')
106
+ reduceOnly: instType === 'MARGIN' && ['CLOSE_LONG', 'CLOSE_SHORT'].includes((_b = order.order_direction) !== null && _b !== void 0 ? _b : '')
95
107
  ? 'true'
96
108
  : undefined,
97
109
  px: order.order_type === 'LIMIT' || order.order_type === 'MAKER' ? order.price.toString() : undefined,
@@ -100,7 +112,7 @@ export const submitOrder = async (credential, order) => {
100
112
  };
101
113
  console.info(formatTime(Date.now()), 'SubmitOrder', 'params', JSON.stringify(params));
102
114
  const res = await postTradeOrder(credential, params);
103
- if (res.code === '0' && ((_c = (_b = res.data) === null || _b === void 0 ? void 0 : _b[0]) === null || _c === void 0 ? void 0 : _c.ordId)) {
115
+ if (res.code === '0' && ((_d = (_c = res.data) === null || _c === void 0 ? void 0 : _c[0]) === null || _d === void 0 ? void 0 : _d.ordId)) {
104
116
  return { order_id: res.data[0].ordId };
105
117
  }
106
118
  throw `Failed to submit order: ${res.code} ${res.msg}: ${res.data
@@ -1 +1 @@
1
- {"version":3,"file":"submitOrder.js","sourceRoot":"","sources":["../../src/orders/submitOrder.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,UAAU,EAAE,UAAU,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC;AACpE,OAAO,EAAE,cAAc,EAAE,GAAG,EAAE,MAAM,MAAM,CAAC;AAC3C,OAAO,EAAe,cAAc,EAAE,MAAM,oBAAoB,CAAC;AACjE,OAAO,EAAE,cAAc,EAAE,MAAM,wBAAwB,CAAC;AACxD,OAAO,EAAE,kBAAkB,EAAE,MAAM,sBAAsB,CAAC;AAE1D,MAAM,uBAAuB,GAAG,CAAC,SAAkB,EAAE,EAAE;IACrD,QAAQ,SAAS,EAAE;QACjB,KAAK,WAAW,CAAC;QACjB,KAAK,aAAa;YAChB,OAAO,KAAK,CAAC;QACf,KAAK,YAAY,CAAC;QAClB,KAAK,YAAY;YACf,OAAO,MAAM,CAAC;KACjB;I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IACF,OAAO,CAAC,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC,GAAG,EAAE,CAAC,EAAE,aAAa,EAAE,QAAQ,EAAE,IAAI,CAAC,SAAS,CAAC,MAAM,CAAC,CAAC,CAAC;IACtF,MAAM,GAAG,GAAG,MAAM,cAAc,CAAC,UAAU,EAAE,MAAM,CAAC,CAAC;IACrD,IAAI,GAAG,CAAC,IAAI,KAAK,GAAG,KAAI,MAAA,MAAA,GAAG,CAAC,IAAI,0CAAG,CAAC,CAAC,0CAAE,KAAK,CAAA,EAAE;QAC5C,OAAO,EAAE,QAAQ,EAAE,GAAG,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,KAAK,EAAE,CAAC;KACxC;IACD,MAAM,2BAA2B,GAAG,CAAC,IAAI,IAAI,GAAG,CAAC,GAAG,KAAK,GAAG,CAAC,IAAI;SAC9D,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,GAAG,CAAC,CAAC,KAAK,IAAI,CAAC,CAAC,IAAI,EAAE,CAAC;SAClC,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC;AAClB,CAAC,CAAC","sourcesContent":["import { IOrder } from '@yuants/data-order';\nimport { decodePath, formatTime, roundToStep } from '@yuants/utils';\nimport { firstValueFrom, map } from 'rxjs';\nimport { ICredential, postTradeOrder } from '../api/private-api';\nimport { productService } from '../public-data/product';\nimport { spotMarketTickers$ } from '../public-data/quote';\n\nconst mapOrderDirectionToSide = (direction?: string) => {\n switch (direction) {\n case 'OPEN_LONG':\n case 'CLOSE_SHORT':\n return 'buy';\n case 'OPEN_SHORT':\n case 'CLOSE_LONG':\n return 'sell';\n }\n throw new Error(`Unknown direction: ${direction}`);\n};\n\nconst mapOrderDirectionToPosSide = (direction?: string) => {\n switch (direction) {\n case 'OPEN_LONG':\n case 'CLOSE_LONG':\n return 'long';\n case 'CLOSE_SHORT':\n case 'OPEN_SHORT':\n return 'short';\n }\n throw new Error(`Unknown direction: ${direction}`);\n};\n\nconst mapOrderTypeToOrdType = (order_type?: string) => {\n switch (order_type) {\n case 'LIMIT':\n return 'limit';\n case 'MARKET':\n return 'market';\n case 'MAKER':\n return 'post_only';\n }\n throw new Error(`Unknown order type: ${order_type}`);\n};\n\nexport const submitOrder = async (credential: ICredential, order: IOrder): Promise<{ order_id: string }> => {\n const [instType, instId] = decodePath(order.product_id).slice(-2);\n\n // 交易数量,表示要购买或者出售的数量。\n // 当币币/币币杠杆以限价买入和卖出时,指交易货币数量。\n // 当币币杠杆以市价买入时,指计价货币的数量。\n // 当币币杠杆以市价卖出时,指交易货币的数量。\n // 对于币币市价单,单位由 tgtCcy 决定\n // 当交割、永续、期权买入和卖出时,指合约张数。\n const mapOrderVolumeToSz = async (order: IOrder) => {\n if (instType === 'SWAP') {\n return order.volume;\n }\n if (instType === 'MARGIN') {\n if (order.order_type === 'LIMIT') {\n return order.volume;\n }\n if (order.order_type === 'MAKER') {\n return order.volume;\n }\n if (order.order_type === 'MARKET') {\n if (order.order_direction === 'OPEN_SHORT' || order.order_direction === 'CLOSE_LONG') {\n return order.volume;\n }\n //\n const price = await firstValueFrom(\n spotMarketTickers$.pipe(\n map((x) =>\n mapOrderDirectionToPosSide(order.order_direction) === 'long'\n ? +x[instId].askPx\n : +x[instId].bidPx,\n ),\n ),\n );\n if (!price) {\n throw new Error(`invalid tick: ${price}`);\n }\n console.info(formatTime(Date.now()), 'SubmitOrder', 'price', price);\n const theProduct = await firstValueFrom(\n productService.mapProductIdToProduct$.pipe(map((x) => x.get(order.product_id))),\n );\n if (!theProduct) {\n throw new Error(`Unknown product: ${order.position_id}`);\n }\n return roundToStep(order.volume * price, theProduct.volume_step!);\n }\n\n return 0;\n }\n\n if (instType === 'SPOT') {\n return order.volume;\n }\n\n throw new Error(`Unknown instType: ${instType}`);\n };\n\n const params = {\n instId,\n tdMode: instType === 'SPOT' ? 'cash' : 'cross',\n side: mapOrderDirectionToSide(order.order_direction),\n posSide:\n instType === 'MARGIN' || instType === 'SPOT'\n ? 'net'\n : mapOrderDirectionToPosSide(order.order_direction),\n ordType: mapOrderTypeToOrdType(order.order_type),\n sz: (await mapOrderVolumeToSz(order)).toString(),\n tgtCcy: instType === 'SPOT' && order.order_type === 'MARKET' ? 'base_ccy' : undefined,\n reduceOnly:\n instType === 'MARGIN' && ['CLOSE_LONG', 'CLOSE_SHORT'].includes(order.order_direction ?? '')\n ? 'true'\n : undefined,\n px: order.order_type === 'LIMIT' || order.order_type === 'MAKER' ? order.price!.toString() : undefined,\n ccy: instType === 'MARGIN' ? 'USDT' : undefined,\n tag: process.env.BROKER_CODE,\n };\n console.info(formatTime(Date.now()), 'SubmitOrder', 'params', JSON.stringify(params));\n const res = await postTradeOrder(credential, params);\n if (res.code === '0' && res.data?.[0]?.ordId) {\n return { order_id: res.data[0].ordId };\n }\n throw `Failed to submit order: ${res.code} ${res.msg}: ${res.data\n .map((x) => `${x.sCode} ${x.sMsg}`)\n .join('; ')}`;\n};\n"]}
1
+ {"version":3,"file":"submitOrder.js","sourceRoot":"","sources":["../../src/orders/submitOrder.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,UAAU,EAAE,UAAU,EAAE,QAAQ,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC;AAC9E,OAAO,EAAE,cAAc,EAAE,GAAG,EAAE,MAAM,MAAM,CAAC;AAC3C,OAAO,EAAE,kBAAkB,EAAE,MAAM,qBAAqB,CAAC;AACzD,OAAO,EAAe,cAAc,EAAE,MAAM,oBAAoB,CAAC;AACjE,OAAO,EAAE,cAAc,EAAE,MAAM,wBAAwB,CAAC;AACxD,OAAO,EAAE,kBAAkB,EAAE,MAAM,sBAAsB,CAAC;AAE1D,MAAM,uBAAuB,GAAG,CAAC,SAAkB,EAAE,EAAE;IACrD,QAAQ,SAAS,EAAE;QACjB,KAAK,WAAW,CAAC;QACjB,KAAK,aAAa;YAChB,OAAO,KAAK,CAAC;QACf,KAAK,YAAY,CAAC;QAClB,KAAK,YAAY;YACf,OAAO,MAAM,CAAC;KACjB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from '@yuants/data-order';\nimport { decodePath, formatTime, newError, roundToStep } from '@yuants/utils';\nimport { firstValueFrom, map } from 'rxjs';\nimport { accountConfigCache } from '../accountInfos/uid';\nimport { ICredential, postTradeOrder } from '../api/private-api';\nimport { productService } from '../public-data/product';\nimport { spotMarketTickers$ } from '../public-data/quote';\n\nconst mapOrderDirectionToSide = (direction?: string) => {\n switch (direction) {\n case 'OPEN_LONG':\n case 'CLOSE_SHORT':\n return 'buy';\n case 'OPEN_SHORT':\n case 'CLOSE_LONG':\n return 'sell';\n }\n throw new Error(`Unknown direction: ${direction}`);\n};\n\nconst mapOrderTypeToOrdType = (order_type?: string) => {\n switch (order_type) {\n case 'LIMIT':\n return 'limit';\n case 'MARKET':\n return 'market';\n case 'MAKER':\n return 'post_only';\n }\n throw new Error(`Unknown order type: ${order_type}`);\n};\n\nexport const submitOrder = async (credential: ICredential, order: IOrder): Promise<{ order_id: string }> => {\n const accountConfigRes = await accountConfigCache.query(JSON.stringify(credential));\n if (!accountConfigRes) throw newError('ACCOUNT_CONFIG_FETCH_ERROR', { accountConfigRes });\n if (!accountConfigRes.data?.[0]) throw newError('ACCOUNT_CONFIG_FETCH_ERROR', { accountConfigRes });\n\n /**\n * 是否为组合保证金模式\n */\n const isPortfolioMarginMode = accountConfigRes.data[0].acctLv === '4';\n\n const [instType, instId] = decodePath(order.product_id).slice(-2);\n\n // 交易数量,表示要购买或者出售的数量。\n // 当币币/币币杠杆以限价买入和卖出时,指交易货币数量。\n // 当币币杠杆以市价买入时,指计价货币的数量。\n // 当币币杠杆以市价卖出时,指交易货币的数量。\n // 对于币币市价单,单位由 tgtCcy 决定\n // 当交割、永续、期权买入和卖出时,指合约张数。\n const mapOrderVolumeToSz = async (order: IOrder) => {\n if (instType === 'SWAP') {\n return order.volume;\n }\n if (instType === 'MARGIN') {\n if (order.order_type === 'LIMIT') {\n return order.volume;\n }\n if (order.order_type === 'MAKER') {\n return order.volume;\n }\n if (order.order_type === 'MARKET') {\n if (order.order_direction === 'OPEN_SHORT' || order.order_direction === 'CLOSE_LONG') {\n return order.volume;\n }\n //\n const price = await firstValueFrom(\n spotMarketTickers$.pipe(\n map((x) =>\n mapOrderDirectionToPosSide(order.order_direction) === 'long'\n ? +x[instId].askPx\n : +x[instId].bidPx,\n ),\n ),\n );\n if (!price) {\n throw new Error(`invalid tick: ${price}`);\n }\n console.info(formatTime(Date.now()), 'SubmitOrder', 'price', price);\n const theProduct = await firstValueFrom(\n productService.mapProductIdToProduct$.pipe(map((x) => x.get(order.product_id))),\n );\n if (!theProduct) {\n throw new Error(`Unknown product: ${order.position_id}`);\n }\n return roundToStep(order.volume * price, theProduct.volume_step!);\n }\n\n return 0;\n }\n\n if (instType === 'SPOT') {\n return order.volume;\n }\n\n throw new Error(`Unknown instType: ${instType}`);\n };\n\n const mapOrderDirectionToPosSide = (direction?: string) => {\n if (isPortfolioMarginMode) return undefined;\n switch (direction) {\n case 'OPEN_LONG':\n case 'CLOSE_LONG':\n return 'long';\n case 'CLOSE_SHORT':\n case 'OPEN_SHORT':\n return 'short';\n }\n throw new Error(`Unknown direction: ${direction}`);\n };\n\n const params = {\n instId,\n tdMode: instType === 'SPOT' ? 'cash' : 'cross',\n side: mapOrderDirectionToSide(order.order_direction),\n posSide:\n instType === 'MARGIN' || instType === 'SPOT'\n ? 'net'\n : mapOrderDirectionToPosSide(order.order_direction),\n ordType: mapOrderTypeToOrdType(order.order_type),\n sz: (await mapOrderVolumeToSz(order)).toString(),\n tgtCcy: instType === 'SPOT' && order.order_type === 'MARKET' ? 'base_ccy' : undefined,\n reduceOnly:\n instType === 'MARGIN' && ['CLOSE_LONG', 'CLOSE_SHORT'].includes(order.order_direction ?? '')\n ? 'true'\n : undefined,\n px: order.order_type === 'LIMIT' || order.order_type === 'MAKER' ? order.price!.toString() : undefined,\n ccy: instType === 'MARGIN' ? 'USDT' : undefined,\n tag: process.env.BROKER_CODE,\n };\n console.info(formatTime(Date.now()), 'SubmitOrder', 'params', JSON.stringify(params));\n const res = await postTradeOrder(credential, params);\n if (res.code === '0' && res.data?.[0]?.ordId) {\n return { order_id: res.data[0].ordId };\n }\n throw `Failed to submit order: ${res.code} ${res.msg}: ${res.data\n .map((x) => `${x.sCode} ${x.sMsg}`)\n .join('; ')}`;\n};\n"]}
package/dist/trade.js CHANGED
@@ -47,7 +47,7 @@ const tradeParser = async (accountId, params) => {
47
47
  };
48
48
  v.forEach((bill) => {
49
49
  trade.created_at = Math.max(Number(trade.created_at), Number(bill.ts)).toString();
50
- trade.product_id = encodePath(bill.instType, bill.instId);
50
+ trade.product_id = encodePath('OKX', bill.instType, bill.instId);
51
51
  trade.traded_price = bill.px;
52
52
  if (bill.instType === 'SWAP') {
53
53
  if (bill.subType === '1')
package/dist/trade.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"trade.js","sourceRoot":"","sources":["../src/trade.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,QAAQ,EAAE,MAAM,kBAAkB,CAAC;AAC5C,OAAO,EAAE,2BAA2B,EAAE,SAAS,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACjF,OAAO,EAAE,UAAU,EAAE,UAAU,EAAE,MAAM,eAAe,CAAC;AACvD,OAAO,EAAE,KAAK,EAAE,MAAM,EAAE,KAAK,EAAE,GAAG,EAAE,OAAO,EAAE,MAAM,MAAM,CAAC;AAC1D,OAAO,EAAE,sBAAsB,EAAE,oBAAoB,EAAE,MAAM,mBAAmB,CAAC;AACjF,OAAO,EAAE,mBAAmB,EAAE,MAAM,oBAAoB,CAAC;AAEzD,MAAM,UAAU,GAAG,oBAAoB,EAAE,CAAC;AAE1C,MAAM,WAAW,GAAG,KAAK,EAAE,SAAiB,EAAE,MAA8B,EAAqB,EAAE;;IACjG,MAAM,SAAS,GAAa,EAAE,CAAC;IAC/B,MAAM,MAAM,GAAG,MAAM,sBAAsB,CAAC,UAAU,EAAE,MAAM,CAAC,CAAC;IAChE,MAAM,kBAAkB,GAAG,IAAI,GAAG,EAAoB,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\nimport { ITrade } from '@yuants/data-trade';\nimport { Terminal } from '@yuants/protocol';\nimport { buildInsertManyIntoTableSQL, escapeSQL, requestSQL } from '@yuants/sql';\nimport { encodePath, formatTime } from '@yuants/utils';\nimport { defer, repeat, retry, tap, timeout } from 'rxjs';\nimport { getAccountBillsArchive, getDefaultCredential } from './api/private-api';\nimport { getTradingAccountId } from './accountInfos/uid';\n\nconst credential = getDefaultCredential();\n\nconst tradeParser = async (accountId: string, params: Record<string, string>): Promise<ITrade[]> => {\n const tradeList: ITrade[] = [];\n const result = await getAccountBillsArchive(credential, params);\n const productIdToProduct = new Map<string, IProduct>();\n const productIdSet = new Set<string>();\n if (result.code === '0' && result.data) {\n const data = result.data;\n const mapTradeIdToBillList = new Map<string, typeof data>();\n data.forEach((item) => {\n productIdSet.add(encodePath(item.instType, item.instId));\n mapTradeIdToBillList.set(item.tradeId, [...(mapTradeIdToBillList.get(item.tradeId) ?? []), item]);\n });\n if (productIdSet.size > 0) {\n const productList = await requestSQL<IProduct[]>(\n Terminal.fromNodeEnv(),\n `\n select * from product where product_id in (${Array.from(productIdSet)\n .map((productId) => escapeSQL(productId))\n .join(',')})\n `,\n );\n if (productList.length > 0) {\n productList.forEach((p) => productIdToProduct.set(p.product_id, p));\n }\n }\n for (const [tradeId, v] of mapTradeIdToBillList) {\n if (!((v[0].instType === 'SPOT' && v.length === 2) || v[0].instType === 'SWAP')) continue;\n\n const trade: ITrade = {\n id: tradeId,\n account_id: accountId,\n product_id: '',\n direction: '',\n traded_volume: '',\n traded_price: '',\n traded_value: '',\n post_volume: '',\n fee: '',\n fee_currency: '',\n created_at: '0',\n };\n\n v.forEach((bill) => {\n trade.created_at = Math.max(Number(trade.created_at), Number(bill.ts)).toString();\n trade.product_id = encodePath(bill.instType, bill.instId);\n trade.traded_price = bill.px;\n if (bill.instType === 'SWAP') {\n if (bill.subType === '1') trade.direction = 'OPEN_LONG';\n if (bill.subType === '2') trade.direction = 'CLOSE_LONG';\n if (bill.subType === '3') trade.direction = 'OPEN_LONG';\n if (bill.subType === '4') trade.direction = 'OPEN_SHORT';\n if (bill.subType === '5') trade.direction = 'CLOSE_LONG';\n if (bill.subType === '6') trade.direction = 'CLOSE_SHORT';\n trade.traded_volume = bill.sz;\n trade.traded_value = (Number(bill.sz) * Number(bill.px)).toString();\n }\n if (bill.instType === 'SPOT') {\n if (bill.subType === '1') {\n if (bill.ccy !== 'USDT') {\n trade.direction = 'OPEN_LONG';\n } else {\n trade.direction = 'CLOSE_LONG';\n }\n }\n\n if (bill.ccy !== 'USDT') {\n trade.traded_volume = bill.sz;\n }\n if (bill.ccy === 'USDT') {\n trade.traded_value = bill.sz;\n }\n }\n // fee\n if (bill.fee !== '0') {\n trade.fee = Math.abs(Number(bill.fee)).toString();\n trade.fee_currency = bill.ccy;\n }\n });\n trade.created_at = formatTime(Number(trade.created_at));\n if (productIdToProduct.has(trade.product_id)) {\n trade.traded_value = (\n +trade.traded_value * +(productIdToProduct.get(trade.product_id)?.value_scale ?? 1)\n ).toString();\n } else {\n throw new Error(`Not Found Product With Product Id: ${trade.product_id}`);\n }\n tradeList.push(trade);\n }\n }\n return tradeList;\n};\n\nconst getAccountTradeWithAccountId = async (accountId: string) => {\n const currentTrade = await requestSQL<ITrade[]>(\n Terminal.fromNodeEnv(),\n `\n select * from trade where account_id=${escapeSQL(accountId)} order by created_at desc limit 1;\n `,\n );\n const params: Record<string, string> = {\n type: '2',\n begin: (new Date().getTime() - 1000 * 60 * 60 * 24 * 30 * 3).toString(),\n };\n if (currentTrade.length === 1) {\n params['begin'] = new Date(currentTrade[0].created_at ?? 0).getTime().toString();\n }\n console.log(formatTime(Date.now()), 'getAccountTrade', `params: ${JSON.stringify(params)}`);\n const tradeList = await tradeParser(accountId, params);\n console.log(formatTime(Date.now()), 'getAccountTrade', `tradeList: ${JSON.stringify(tradeList)}`);\n await requestSQL(\n Terminal.fromNodeEnv(),\n buildInsertManyIntoTableSQL(tradeList, 'trade', {\n columns: [\n 'id',\n 'account_id',\n 'product_id',\n 'traded_volume',\n 'traded_value',\n 'traded_price',\n 'direction',\n 'fee',\n 'fee_currency',\n 'created_at',\n ],\n conflictKeys: ['id'],\n }),\n );\n};\n\n(async () => {\n const account_id = await getTradingAccountId(credential);\n console.log(formatTime(Date.now()), 'getAccountTrade', `AccountID: ${account_id}`);\n defer(() => getAccountTradeWithAccountId(account_id))\n .pipe(\n //\n timeout(10_000), // 超时设定:10 秒\n tap({\n error: (err) => {\n console.error(formatTime(Date.now()), 'getAccountTradeError', err);\n },\n }),\n repeat({ delay: 30_000 }),\n retry({ delay: 5000 }),\n )\n .subscribe();\n})();\n"]}
1
+ {"version":3,"file":"trade.js","sourceRoot":"","sources":["../src/trade.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,QAAQ,EAAE,MAAM,kBAAkB,CAAC;AAC5C,OAAO,EAAE,2BAA2B,EAAE,SAAS,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACjF,OAAO,EAAE,UAAU,EAAE,UAAU,EAAE,MAAM,eAAe,CAAC;AACvD,OAAO,EAAE,KAAK,EAAE,MAAM,EAAE,KAAK,EAAE,GAAG,EAAE,OAAO,EAAE,MAAM,MAAM,CAAC;AAC1D,OAAO,EAAE,sBAAsB,EAAE,oBAAoB,EAAE,MAAM,mBAAmB,CAAC;AACjF,OAAO,EAAE,mBAAmB,EAAE,MAAM,oBAAoB,CAAC;AAEzD,MAAM,UAAU,GAAG,oBAAoB,EAAE,CAAC;AAE1C,MAAM,WAAW,GAAG,KAAK,EAAE,SAAiB,EAAE,MAA8B,EAAqB,EAAE;;IACjG,MAAM,SAAS,GAAa,EAAE,CAAC;IAC/B,MAAM,MAAM,GAAG,MAAM,sBAAsB,CAAC,UAAU,EAAE,MAAM,CAAC,CAAC;IAChE,MAAM,kBAAkB,GAAG,IAAI,GAAG,EAAoB,CAAC;IACvD,MAAM,YAAY,GAAG,IAAI,GAAG,EAAU,CAAC;IACvC,IAAI,MAAM,CAAC,IAAI,KAAK,GA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AAI,CAAC,GAAG,EAAE,CAAC,EAAE,iBAAiB,EAAE,cAAc,IAAI,CAAC,SAAS,CAAC,SAAS,CAAC,EAAE,CAAC,CAAC;IAClG,MAAM,UAAU,CACd,QAAQ,CAAC,WAAW,EAAE,EACtB,2BAA2B,CAAC,SAAS,EAAE,OAAO,EAAE;QAC9C,OAAO,EAAE;YACP,IAAI;YACJ,YAAY;YACZ,YAAY;YACZ,eAAe;YACf,cAAc;YACd,cAAc;YACd,WAAW;YACX,KAAK;YACL,cAAc;YACd,YAAY;SACb;QACD,YAAY,EAAE,CAAC,IAAI,CAAC;KACrB,CAAC,CACH,CAAC;AACJ,CAAC,CAAC;AAEF,CAAC,KAAK,IAAI,EAAE;IACV,MAAM,UAAU,GAAG,MAAM,mBAAmB,CAAC,UAAU,CAAC,CAAC;IACzD,OAAO,CAAC,GAAG,CAAC,UAAU,CAAC,IAAI,CAAC,GAAG,EAAE,CAAC,EAAE,iBAAiB,EAAE,cAAc,UAAU,EAAE,CAAC,CAAC;IACnF,KAAK,CAAC,GAAG,EAAE,CAAC,4BAA4B,CAAC,UAAU,CAAC,CAAC;SAClD,IAAI;IACH,EAAE;IACF,OAAO,CAAC,KAAM,CAAC,EAAE,aAAa;IAC9B,GAAG,CAAC;QACF,KAAK,EAAE,CAAC,GAAG,EAAE,EAAE;YACb,OAAO,CAAC,KAAK,CAAC,UAAU,CAAC,IAAI,CAAC,GAAG,EAAE,CAAC,EAAE,sBAAsB,EAAE,GAAG,CAAC,CAAC;QACrE,CAAC;KACF,CAAC,EACF,MAAM,CAAC,EAAE,KAAK,EAAE,KAAM,EAAE,CAAC,EACzB,KAAK,CAAC,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC,CACvB;SACA,SAAS,EAAE,CAAC;AACjB,CAAC,CAAC,EAAE,CAAC","sourcesContent":["import { IProduct } from '@yuants/data-product';\nimport { ITrade } from '@yuants/data-trade';\nimport { Terminal } from '@yuants/protocol';\nimport { buildInsertManyIntoTableSQL, escapeSQL, requestSQL } from '@yuants/sql';\nimport { encodePath, formatTime } from '@yuants/utils';\nimport { defer, repeat, retry, tap, timeout } from 'rxjs';\nimport { getAccountBillsArchive, getDefaultCredential } from './api/private-api';\nimport { getTradingAccountId } from './accountInfos/uid';\n\nconst credential = getDefaultCredential();\n\nconst tradeParser = async (accountId: string, params: Record<string, string>): Promise<ITrade[]> => {\n const tradeList: ITrade[] = [];\n const result = await getAccountBillsArchive(credential, params);\n const productIdToProduct = new Map<string, IProduct>();\n const productIdSet = new Set<string>();\n if (result.code === '0' && result.data) {\n const data = result.data;\n const mapTradeIdToBillList = new Map<string, typeof data>();\n data.forEach((item) => {\n productIdSet.add(encodePath(item.instType, item.instId));\n mapTradeIdToBillList.set(item.tradeId, [...(mapTradeIdToBillList.get(item.tradeId) ?? []), item]);\n });\n if (productIdSet.size > 0) {\n const productList = await requestSQL<IProduct[]>(\n Terminal.fromNodeEnv(),\n `\n select * from product where product_id in (${Array.from(productIdSet)\n .map((productId) => escapeSQL(productId))\n .join(',')})\n `,\n );\n if (productList.length > 0) {\n productList.forEach((p) => productIdToProduct.set(p.product_id, p));\n }\n }\n for (const [tradeId, v] of mapTradeIdToBillList) {\n if (!((v[0].instType === 'SPOT' && v.length === 2) || v[0].instType === 'SWAP')) continue;\n\n const trade: ITrade = {\n id: tradeId,\n account_id: accountId,\n product_id: '',\n direction: '',\n traded_volume: '',\n traded_price: '',\n traded_value: '',\n post_volume: '',\n fee: '',\n fee_currency: '',\n created_at: '0',\n };\n\n v.forEach((bill) => {\n trade.created_at = Math.max(Number(trade.created_at), Number(bill.ts)).toString();\n trade.product_id = encodePath('OKX', bill.instType, bill.instId);\n trade.traded_price = bill.px;\n if (bill.instType === 'SWAP') {\n if (bill.subType === '1') trade.direction = 'OPEN_LONG';\n if (bill.subType === '2') trade.direction = 'CLOSE_LONG';\n if (bill.subType === '3') trade.direction = 'OPEN_LONG';\n if (bill.subType === '4') trade.direction = 'OPEN_SHORT';\n if (bill.subType === '5') trade.direction = 'CLOSE_LONG';\n if (bill.subType === '6') trade.direction = 'CLOSE_SHORT';\n trade.traded_volume = bill.sz;\n trade.traded_value = (Number(bill.sz) * Number(bill.px)).toString();\n }\n if (bill.instType === 'SPOT') {\n if (bill.subType === '1') {\n if (bill.ccy !== 'USDT') {\n trade.direction = 'OPEN_LONG';\n } else {\n trade.direction = 'CLOSE_LONG';\n }\n }\n\n if (bill.ccy !== 'USDT') {\n trade.traded_volume = bill.sz;\n }\n if (bill.ccy === 'USDT') {\n trade.traded_value = bill.sz;\n }\n }\n // fee\n if (bill.fee !== '0') {\n trade.fee = Math.abs(Number(bill.fee)).toString();\n trade.fee_currency = bill.ccy;\n }\n });\n trade.created_at = formatTime(Number(trade.created_at));\n if (productIdToProduct.has(trade.product_id)) {\n trade.traded_value = (\n +trade.traded_value * +(productIdToProduct.get(trade.product_id)?.value_scale ?? 1)\n ).toString();\n } else {\n throw new Error(`Not Found Product With Product Id: ${trade.product_id}`);\n }\n tradeList.push(trade);\n }\n }\n return tradeList;\n};\n\nconst getAccountTradeWithAccountId = async (accountId: string) => {\n const currentTrade = await requestSQL<ITrade[]>(\n Terminal.fromNodeEnv(),\n `\n select * from trade where account_id=${escapeSQL(accountId)} order by created_at desc limit 1;\n `,\n );\n const params: Record<string, string> = {\n type: '2',\n begin: (new Date().getTime() - 1000 * 60 * 60 * 24 * 30 * 3).toString(),\n };\n if (currentTrade.length === 1) {\n params['begin'] = new Date(currentTrade[0].created_at ?? 0).getTime().toString();\n }\n console.log(formatTime(Date.now()), 'getAccountTrade', `params: ${JSON.stringify(params)}`);\n const tradeList = await tradeParser(accountId, params);\n console.log(formatTime(Date.now()), 'getAccountTrade', `tradeList: ${JSON.stringify(tradeList)}`);\n await requestSQL(\n Terminal.fromNodeEnv(),\n buildInsertManyIntoTableSQL(tradeList, 'trade', {\n columns: [\n 'id',\n 'account_id',\n 'product_id',\n 'traded_volume',\n 'traded_value',\n 'traded_price',\n 'direction',\n 'fee',\n 'fee_currency',\n 'created_at',\n ],\n conflictKeys: ['id'],\n }),\n );\n};\n\n(async () => {\n const account_id = await getTradingAccountId(credential);\n console.log(formatTime(Date.now()), 'getAccountTrade', `AccountID: ${account_id}`);\n defer(() => getAccountTradeWithAccountId(account_id))\n .pipe(\n //\n timeout(10_000), // 超时设定:10 秒\n tap({\n error: (err) => {\n console.error(formatTime(Date.now()), 'getAccountTradeError', err);\n },\n }),\n repeat({ delay: 30_000 }),\n retry({ delay: 5000 }),\n )\n .subscribe();\n})();\n"]}
@@ -1,4 +1,30 @@
1
1
  import { ICredential } from '../api/private-api';
2
+ export declare const accountConfigCache: import("@yuants/cache").ICache<{
3
+ code: string;
4
+ data: {
5
+ acctLv: string;
6
+ autoLoan: boolean;
7
+ ctIsoMode: string;
8
+ greeksType: string;
9
+ level: string;
10
+ levelTmp: string;
11
+ mgnIsoMode: string;
12
+ posMode: string;
13
+ spotOffsetType: string;
14
+ uid: string;
15
+ label: string;
16
+ roleType: string;
17
+ traderInsts: unknown[];
18
+ spotRoleType: string;
19
+ spotTraderInsts: unknown[];
20
+ opAuth: string;
21
+ kycLv: string;
22
+ ip: string;
23
+ perm: string;
24
+ mainUid: string;
25
+ }[];
26
+ msg: string;
27
+ }>;
2
28
  export declare const getUid: (credential: ICredential) => Promise<string | undefined>;
3
29
  export declare const getAccountIds: (credential: ICredential) => Promise<{
4
30
  trading: string;
@@ -1 +1 @@
1
- {"version":3,"file":"uid.d.ts","sourceRoot":"","sources":["../../src/accountInfos/uid.ts"],"names":[],"mappings":"AACA,OAAO,EAAoB,WAAW,EAAE,MAAM,oBAAoB,CAAC;AAwBnE,eAAO,MAAM,MAAM,eAAsB,WAAW,gCAEnD,CAAC;AAEF,eAAO,MAAM,aAAa,eAAsB,WAAW;;;;;;cAE1D,CAAC;AAEF,eAAO,MAAM,mBAAmB,eAAsB,WAAW,oBACd,CAAC;AAEpD,eAAO,MAAM,oBAAoB,eAAsB,WAAW,oBACd,CAAC;AAErD,eAAO,MAAM,gBAAgB,eAAsB,WAAW,oBACd,CAAC;AAEjD,eAAO,MAAM,mBAAmB,eAAsB,WAAW,oBACd,CAAC;AAEpD,eAAO,MAAM,mBAAmB,eAAsB,WAAW,oBACd,CAAC"}
1
+ {"version":3,"file":"uid.d.ts","sourceRoot":"","sources":["../../src/accountInfos/uid.ts"],"names":[],"mappings":"AACA,OAAO,EAAoB,WAAW,EAAE,MAAM,oBAAoB,CAAC;AAEnE,eAAO,MAAM,kBAAkB;;;;;;;;;;;;;;;;;;;;;;;;;EAG7B,CAAC;AAmBH,eAAO,MAAM,MAAM,eAAsB,WAAW,gCAEnD,CAAC;AAEF,eAAO,MAAM,aAAa,eAAsB,WAAW;;;;;;cAE1D,CAAC;AAEF,eAAO,MAAM,mBAAmB,eAAsB,WAAW,oBACd,CAAC;AAEpD,eAAO,MAAM,oBAAoB,eAAsB,WAAW,oBACd,CAAC;AAErD,eAAO,MAAM,gBAAgB,eAAsB,WAAW,oBACd,CAAC;AAEjD,eAAO,MAAM,mBAAmB,eAAsB,WAAW,oBACd,CAAC;AAEpD,eAAO,MAAM,mBAAmB,eAAsB,WAAW,oBACd,CAAC"}
@@ -1,14 +1,14 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.getFundingAccountId = exports.getEarningAccountId = exports.getLoanAccountId = exports.getStrategyAccountId = exports.getTradingAccountId = exports.getAccountIds = exports.getUid = void 0;
3
+ exports.getFundingAccountId = exports.getEarningAccountId = exports.getLoanAccountId = exports.getStrategyAccountId = exports.getTradingAccountId = exports.getAccountIds = exports.getUid = exports.accountConfigCache = void 0;
4
4
  const cache_1 = require("@yuants/cache");
5
5
  const private_api_1 = require("../api/private-api");
6
- const accountConfigCache = (0, cache_1.createCache)((key) => (0, private_api_1.getAccountConfig)(JSON.parse(key)), {
7
- expire: 100000,
8
- swrAfter: 10000,
6
+ exports.accountConfigCache = (0, cache_1.createCache)((key) => (0, private_api_1.getAccountConfig)(JSON.parse(key)), {
7
+ expire: 1000000,
8
+ swrAfter: 100000, // 100 秒后后台刷新
9
9
  });
10
10
  const accountUidCache = (0, cache_1.createCache)(async (key) => {
11
- const config = await accountConfigCache.query(key);
11
+ const config = await exports.accountConfigCache.query(key);
12
12
  return config === null || config === void 0 ? void 0 : config.data[0].uid;
13
13
  });
14
14
  const accountIdCache = (0, cache_1.createCache)(async (key) => {
@@ -1 +1 @@
1
- {"version":3,"file":"uid.js","sourceRoot":"","sources":["../../src/accountInfos/uid.ts"],"names":[],"mappings":";;;AAAA,yCAA4C;AAC5C,oDAAmE;AAEnE,MAAM,kBAAkB,GAAG,IAAA,mBAAW,EAAC,CAAC,GAAG,EAAE,EAAE,CAAC,IAAA,8BAAgB,EAAC,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,EAAE;IACjF,MAAM,EAAE,MAAO;IACf,QAAQ,EAAE,KAAM;CACjB,CAAC,CAAC;AAEH,MAAM,eAAe,GAAG,IAAA,mBAAW,EAAC,KAAK,EAAE,GAAG,EAAE,EAAE;IAChD,MAAM,MAAM,GAAG,MAAM,kBAAkB,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;IACnD,OAAO,MAAM,aAAN,MAAM,uBAAN,MAAM,CAAE,IAAI,CAAC,CAAC,EAAE,GAAG,CAAC;AAC7B,CAAC,CAAC,CAAC;AAEH,MAAM,cAAc,GAAG,IAAA,mBAAW,EAAC,KAAK,EAAE,GAAG,EAAE,EAAE;IAC/C,MAAM,GAAG,GAAG,MAAM,eAAe,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;IAC7C,IAAI,CAAC,GAAG;QAAE,MAAM,IAAI,KAAK,CAAC,mBAAmB,CAAC,CAAC;IAC/C,OAAO;QACL,OAAO,EAAE,OAAO,GAAG,UAAU;QAC7B,QAAQ,EAAE,OAAO,GAAG,WAAW;QAC/B,IAAI,EAAE,OAAO,GAAG,YAAY;QAC5B,OAAO,EAAE,OAAO,GAAG,eAAe;QAClC,OAAO,EAAE,OAAO,GAAG,eA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BAAmB,GAAG,KAAK,EAAE,UAAuB,EAAE,EAAE,CACnE,IAAA,qBAAa,EAAC,UAAU,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAE,CAAC,OAAO,CAAC,CAAC;AADvC,QAAA,mBAAmB,uBACoB","sourcesContent":["import { createCache } from '@yuants/cache';\nimport { getAccountConfig, ICredential } from '../api/private-api';\n\nconst accountConfigCache = createCache((key) => getAccountConfig(JSON.parse(key)), {\n expire: 100_000,\n swrAfter: 10_000,\n});\n\nconst accountUidCache = createCache(async (key) => {\n const config = await accountConfigCache.query(key);\n return config?.data[0].uid;\n});\n\nconst accountIdCache = createCache(async (key) => {\n const uid = await accountUidCache.query(key);\n if (!uid) throw new Error('Failed to get UID');\n return {\n trading: `okx/${uid}/trading`,\n strategy: `okx/${uid}/strategy`,\n loan: `okx/${uid}/loan/USDT`,\n earning: `okx/${uid}/earning/USDT`,\n funding: `okx/${uid}/funding/USDT`,\n };\n});\n\nexport const getUid = async (credential: ICredential) => {\n return accountUidCache.query(JSON.stringify(credential));\n};\n\nexport const getAccountIds = async (credential: ICredential) => {\n return accountIdCache.query(JSON.stringify(credential));\n};\n\nexport const getTradingAccountId = async (credential: ICredential) =>\n getAccountIds(credential).then((x) => x!.trading);\n\nexport const getStrategyAccountId = async (credential: ICredential) =>\n getAccountIds(credential).then((x) => x!.strategy);\n\nexport const getLoanAccountId = async (credential: ICredential) =>\n getAccountIds(credential).then((x) => x!.loan);\n\nexport const getEarningAccountId = async (credential: ICredential) =>\n getAccountIds(credential).then((x) => x!.earning);\n\nexport const getFundingAccountId = async (credential: ICredential) =>\n getAccountIds(credential).then((x) => x!.funding);\n"]}
1
+ {"version":3,"file":"uid.js","sourceRoot":"","sources":["../../src/accountInfos/uid.ts"],"names":[],"mappings":";;;AAAA,yCAA4C;AAC5C,oDAAmE;AAEtD,QAAA,kBAAkB,GAAG,IAAA,mBAAW,EAAC,CAAC,GAAG,EAAE,EAAE,CAAC,IA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AEK,MAAM,mBAAmB,GAAG,KAAK,EAAE,UAAuB,EAAE,EAAE,CACnE,IAAA,qBAAa,EAAC,UAAU,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAE,CAAC,OAAO,CAAC,CAAC;AADvC,QAAA,mBAAmB,uBACoB;AAE7C,MAAM,oBAAoB,GAAG,KAAK,EAAE,UAAuB,EAAE,EAAE,CACpE,IAAA,qBAAa,EAAC,UAAU,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAE,CAAC,QAAQ,CAAC,CAAC;AADxC,QAAA,oBAAoB,wBACoB;AAE9C,MAAM,gBAAgB,GAAG,KAAK,EAAE,UAAuB,EAAE,EAAE,CAChE,IAAA,qBAAa,EAAC,UAAU,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAE,CAAC,IAAI,CAAC,CAAC;AADpC,QAAA,gBAAgB,oBACoB;AAE1C,MAAM,mBAAmB,GAAG,KAAK,EAAE,UAAuB,EAAE,EAAE,CACnE,IAAA,qBAAa,EAAC,UAAU,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAE,CAAC,OAAO,CAAC,CAAC;AADvC,QAAA,mBAAmB,uBACoB;AAE7C,MAAM,mBAAmB,GAAG,KAAK,EAAE,UAAuB,EAAE,EAAE,CACnE,IAAA,qBAAa,EAAC,UAAU,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAE,CAAC,OAAO,CAAC,CAAC;AADvC,QAAA,mBAAmB,uBACoB","sourcesContent":["import { createCache } from '@yuants/cache';\nimport { getAccountConfig, ICredential } from '../api/private-api';\n\nexport const accountConfigCache = createCache((key) => getAccountConfig(JSON.parse(key)), {\n expire: 1000_000, // 缓存 1000 秒\n swrAfter: 100_000, // 100 秒后后台刷新\n});\n\nconst accountUidCache = createCache(async (key) => {\n const config = await accountConfigCache.query(key);\n return config?.data[0].uid;\n});\n\nconst accountIdCache = createCache(async (key) => {\n const uid = await accountUidCache.query(key);\n if (!uid) throw new Error('Failed to get UID');\n return {\n trading: `okx/${uid}/trading`,\n strategy: `okx/${uid}/strategy`,\n loan: `okx/${uid}/loan/USDT`,\n earning: `okx/${uid}/earning/USDT`,\n funding: `okx/${uid}/funding/USDT`,\n };\n});\n\nexport const getUid = async (credential: ICredential) => {\n return accountUidCache.query(JSON.stringify(credential));\n};\n\nexport const getAccountIds = async (credential: ICredential) => {\n return accountIdCache.query(JSON.stringify(credential));\n};\n\nexport const getTradingAccountId = async (credential: ICredential) =>\n getAccountIds(credential).then((x) => x!.trading);\n\nexport const getStrategyAccountId = async (credential: ICredential) =>\n getAccountIds(credential).then((x) => x!.strategy);\n\nexport const getLoanAccountId = async (credential: ICredential) =>\n getAccountIds(credential).then((x) => x!.loan);\n\nexport const getEarningAccountId = async (credential: ICredential) =>\n getAccountIds(credential).then((x) => x!.earning);\n\nexport const getFundingAccountId = async (credential: ICredential) =>\n getAccountIds(credential).then((x) => x!.funding);\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"submitOrder.d.ts","sourceRoot":"","sources":["../../src/orders/submitOrder.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,oBAAoB,CAAC;AAG5C,OAAO,EAAE,WAAW,EAAkB,MAAM,oBAAoB,CAAC;AAwCjE,eAAO,MAAM,WAAW,eAAsB,WAAW,SAAS,MAAM,KAAG,QAAQ;IAAE,QAAQ,EAAE,MAAM,CAAA;CAAE,CAoFtG,CAAC"}
1
+ {"version":3,"file":"submitOrder.d.ts","sourceRoot":"","sources":["../../src/orders/submitOrder.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,oBAAoB,CAAC;AAI5C,OAAO,EAAE,WAAW,EAAkB,MAAM,oBAAoB,CAAC;AA4BjE,eAAO,MAAM,WAAW,eAAsB,WAAW,SAAS,MAAM,KAAG,QAAQ;IAAE,QAAQ,EAAE,MAAM,CAAA;CAAE,CA0GtG,CAAC"}
@@ -3,6 +3,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.submitOrder = void 0;
4
4
  const utils_1 = require("@yuants/utils");
5
5
  const rxjs_1 = require("rxjs");
6
+ const uid_1 = require("../accountInfos/uid");
6
7
  const private_api_1 = require("../api/private-api");
7
8
  const product_1 = require("../public-data/product");
8
9
  const quote_1 = require("../public-data/quote");
@@ -17,17 +18,6 @@ const mapOrderDirectionToSide = (direction) => {
17
18
  }
18
19
  throw new Error(`Unknown direction: ${direction}`);
19
20
  };
20
- const mapOrderDirectionToPosSide = (direction) => {
21
- switch (direction) {
22
- case 'OPEN_LONG':
23
- case 'CLOSE_LONG':
24
- return 'long';
25
- case 'CLOSE_SHORT':
26
- case 'OPEN_SHORT':
27
- return 'short';
28
- }
29
- throw new Error(`Unknown direction: ${direction}`);
30
- };
31
21
  const mapOrderTypeToOrdType = (order_type) => {
32
22
  switch (order_type) {
33
23
  case 'LIMIT':
@@ -40,7 +30,16 @@ const mapOrderTypeToOrdType = (order_type) => {
40
30
  throw new Error(`Unknown order type: ${order_type}`);
41
31
  };
42
32
  const submitOrder = async (credential, order) => {
43
- var _a, _b, _c;
33
+ var _a, _b, _c, _d;
34
+ const accountConfigRes = await uid_1.accountConfigCache.query(JSON.stringify(credential));
35
+ if (!accountConfigRes)
36
+ throw (0, utils_1.newError)('ACCOUNT_CONFIG_FETCH_ERROR', { accountConfigRes });
37
+ if (!((_a = accountConfigRes.data) === null || _a === void 0 ? void 0 : _a[0]))
38
+ throw (0, utils_1.newError)('ACCOUNT_CONFIG_FETCH_ERROR', { accountConfigRes });
39
+ /**
40
+ * 是否为组合保证金模式
41
+ */
42
+ const isPortfolioMarginMode = accountConfigRes.data[0].acctLv === '4';
44
43
  const [instType, instId] = (0, utils_1.decodePath)(order.product_id).slice(-2);
45
44
  // 交易数量,表示要购买或者出售的数量。
46
45
  // 当币币/币币杠杆以限价买入和卖出时,指交易货币数量。
@@ -84,6 +83,19 @@ const submitOrder = async (credential, order) => {
84
83
  }
85
84
  throw new Error(`Unknown instType: ${instType}`);
86
85
  };
86
+ const mapOrderDirectionToPosSide = (direction) => {
87
+ if (isPortfolioMarginMode)
88
+ return undefined;
89
+ switch (direction) {
90
+ case 'OPEN_LONG':
91
+ case 'CLOSE_LONG':
92
+ return 'long';
93
+ case 'CLOSE_SHORT':
94
+ case 'OPEN_SHORT':
95
+ return 'short';
96
+ }
97
+ throw new Error(`Unknown direction: ${direction}`);
98
+ };
87
99
  const params = {
88
100
  instId,
89
101
  tdMode: instType === 'SPOT' ? 'cash' : 'cross',
@@ -94,7 +106,7 @@ const submitOrder = async (credential, order) => {
94
106
  ordType: mapOrderTypeToOrdType(order.order_type),
95
107
  sz: (await mapOrderVolumeToSz(order)).toString(),
96
108
  tgtCcy: instType === 'SPOT' && order.order_type === 'MARKET' ? 'base_ccy' : undefined,
97
- reduceOnly: instType === 'MARGIN' && ['CLOSE_LONG', 'CLOSE_SHORT'].includes((_a = order.order_direction) !== null && _a !== void 0 ? _a : '')
109
+ reduceOnly: instType === 'MARGIN' && ['CLOSE_LONG', 'CLOSE_SHORT'].includes((_b = order.order_direction) !== null && _b !== void 0 ? _b : '')
98
110
  ? 'true'
99
111
  : undefined,
100
112
  px: order.order_type === 'LIMIT' || order.order_type === 'MAKER' ? order.price.toString() : undefined,
@@ -103,7 +115,7 @@ const submitOrder = async (credential, order) => {
103
115
  };
104
116
  console.info((0, utils_1.formatTime)(Date.now()), 'SubmitOrder', 'params', JSON.stringify(params));
105
117
  const res = await (0, private_api_1.postTradeOrder)(credential, params);
106
- if (res.code === '0' && ((_c = (_b = res.data) === null || _b === void 0 ? void 0 : _b[0]) === null || _c === void 0 ? void 0 : _c.ordId)) {
118
+ if (res.code === '0' && ((_d = (_c = res.data) === null || _c === void 0 ? void 0 : _c[0]) === null || _d === void 0 ? void 0 : _d.ordId)) {
107
119
  return { order_id: res.data[0].ordId };
108
120
  }
109
121
  throw `Failed to submit order: ${res.code} ${res.msg}: ${res.data
@@ -1 +1 @@
1
- {"version":3,"file":"submitOrder.js","sourceRoot":"","sources":["../../src/orders/submitOrder.ts"],"names":[],"mappings":";;;AACA,yCAAoE;AACpE,+BAA2C;AAC3C,oDAAiE;AACjE,oDAAwD;AACxD,gDAA0D;AAE1D,MAAM,uBAAuB,GAAG,CAAC,SAAkB,EAAE,EAAE;IACrD,QAAQ,SAAS,EAAE;QACjB,KAAK,WAAW,CAAC;QACjB,KAAK,aAAa;YAChB,OAAO,KAAK,CAAC;QACf,KAAK,YAAY,CAAC;QAClB,KAAK,YAAY;YACf,OAAO,MAAM,CAAC;KACjB;IACD,MAAM,IAAI,KAAK,CAAC,sBAAsB,SAAS,EAAE,CAAC,CAAC;AACrD,CAAC,CAAC;AAEF,MAAM,0BAA0B,GAAG,CAAC,SAAkB,EAAE,EAAE;IACxD,QAAQ,SAAS,EAAE;QACjB,KAAK,WAAW,CAAC;QACjB,KAAK,YAAY;YACf,OAAO,MAAM,CAAC;QAChB,KAAK,aAAa,CAAC;QACnB,KAAK,YAAY;YACf,OAAO,OAAO,CAAC;KAClB;IACD,MAAM,IAAI,KAAK,CAAC,sBAAsB,SAAS,EAAE,CAAC,CAAC;AACrD,CAAC,CAAC;AAEF,MAAM,qBAAqB,GAAG,CAAC,UAAmB,EAAE,EAAE;IACpD,QAAQ,UAAU,EAAE;QAClB,KAAK,OAAO;YACV,OAAO,OAAO,CAAC;QACjB,KAAK,QAAQ;YACX,OAAO,QAAQ,CAAC;QAClB,KAAK,OAAO;YACV,OAAO,WAAW,CAAC;KACtB;IACD,MAAM,IAAI,KAAK,CAAC,uBAAuB,UAAU,EAAE,CAAC,CAAC;AACvD,CAAC,CAAC;AAEK,MAAM,WAAW,GAAG,KAAK,EAAE,UAAuB,EAAE,KAAa,EAAiC,EAAE;;IACzG,MAAM,CAAC,QAAQ,EAAE,MAAM,CAAC,GAAG,IAAA,kBAAU,EAAC,KAAK,C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data-order';\nimport { decodePath, formatTime, roundToStep } from '@yuants/utils';\nimport { firstValueFrom, map } from 'rxjs';\nimport { ICredential, postTradeOrder } from '../api/private-api';\nimport { productService } from '../public-data/product';\nimport { spotMarketTickers$ } from '../public-data/quote';\n\nconst mapOrderDirectionToSide = (direction?: string) => {\n switch (direction) {\n case 'OPEN_LONG':\n case 'CLOSE_SHORT':\n return 'buy';\n case 'OPEN_SHORT':\n case 'CLOSE_LONG':\n return 'sell';\n }\n throw new Error(`Unknown direction: ${direction}`);\n};\n\nconst mapOrderDirectionToPosSide = (direction?: string) => {\n switch (direction) {\n case 'OPEN_LONG':\n case 'CLOSE_LONG':\n return 'long';\n case 'CLOSE_SHORT':\n case 'OPEN_SHORT':\n return 'short';\n }\n throw new Error(`Unknown direction: ${direction}`);\n};\n\nconst mapOrderTypeToOrdType = (order_type?: string) => {\n switch (order_type) {\n case 'LIMIT':\n return 'limit';\n case 'MARKET':\n return 'market';\n case 'MAKER':\n return 'post_only';\n }\n throw new Error(`Unknown order type: ${order_type}`);\n};\n\nexport const submitOrder = async (credential: ICredential, order: IOrder): Promise<{ order_id: string }> => {\n const [instType, instId] = decodePath(order.product_id).slice(-2);\n\n // 交易数量,表示要购买或者出售的数量。\n // 当币币/币币杠杆以限价买入和卖出时,指交易货币数量。\n // 当币币杠杆以市价买入时,指计价货币的数量。\n // 当币币杠杆以市价卖出时,指交易货币的数量。\n // 对于币币市价单,单位由 tgtCcy 决定\n // 当交割、永续、期权买入和卖出时,指合约张数。\n const mapOrderVolumeToSz = async (order: IOrder) => {\n if (instType === 'SWAP') {\n return order.volume;\n }\n if (instType === 'MARGIN') {\n if (order.order_type === 'LIMIT') {\n return order.volume;\n }\n if (order.order_type === 'MAKER') {\n return order.volume;\n }\n if (order.order_type === 'MARKET') {\n if (order.order_direction === 'OPEN_SHORT' || order.order_direction === 'CLOSE_LONG') {\n return order.volume;\n }\n //\n const price = await firstValueFrom(\n spotMarketTickers$.pipe(\n map((x) =>\n mapOrderDirectionToPosSide(order.order_direction) === 'long'\n ? +x[instId].askPx\n : +x[instId].bidPx,\n ),\n ),\n );\n if (!price) {\n throw new Error(`invalid tick: ${price}`);\n }\n console.info(formatTime(Date.now()), 'SubmitOrder', 'price', price);\n const theProduct = await firstValueFrom(\n productService.mapProductIdToProduct$.pipe(map((x) => x.get(order.product_id))),\n );\n if (!theProduct) {\n throw new Error(`Unknown product: ${order.position_id}`);\n }\n return roundToStep(order.volume * price, theProduct.volume_step!);\n }\n\n return 0;\n }\n\n if (instType === 'SPOT') {\n return order.volume;\n }\n\n throw new Error(`Unknown instType: ${instType}`);\n };\n\n const params = {\n instId,\n tdMode: instType === 'SPOT' ? 'cash' : 'cross',\n side: mapOrderDirectionToSide(order.order_direction),\n posSide:\n instType === 'MARGIN' || instType === 'SPOT'\n ? 'net'\n : mapOrderDirectionToPosSide(order.order_direction),\n ordType: mapOrderTypeToOrdType(order.order_type),\n sz: (await mapOrderVolumeToSz(order)).toString(),\n tgtCcy: instType === 'SPOT' && order.order_type === 'MARKET' ? 'base_ccy' : undefined,\n reduceOnly:\n instType === 'MARGIN' && ['CLOSE_LONG', 'CLOSE_SHORT'].includes(order.order_direction ?? '')\n ? 'true'\n : undefined,\n px: order.order_type === 'LIMIT' || order.order_type === 'MAKER' ? order.price!.toString() : undefined,\n ccy: instType === 'MARGIN' ? 'USDT' : undefined,\n tag: process.env.BROKER_CODE,\n };\n console.info(formatTime(Date.now()), 'SubmitOrder', 'params', JSON.stringify(params));\n const res = await postTradeOrder(credential, params);\n if (res.code === '0' && res.data?.[0]?.ordId) {\n return { order_id: res.data[0].ordId };\n }\n throw `Failed to submit order: ${res.code} ${res.msg}: ${res.data\n .map((x) => `${x.sCode} ${x.sMsg}`)\n .join('; ')}`;\n};\n"]}
1
+ {"version":3,"file":"submitOrder.js","sourceRoot":"","sources":["../../src/orders/submitOrder.ts"],"names":[],"mappings":";;;AACA,yCAA8E;AAC9E,+BAA2C;AAC3C,6CAAyD;AACzD,oDAAiE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CAAC,CAAC,KAAK,EAAE,CAAC;KACxC;IACD,MAAM,2BAA2B,GAAG,CAAC,IAAI,IAAI,GAAG,CAAC,GAAG,KAAK,GAAG,CAAC,IAAI;SAC9D,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,GAAG,CAAC,CAAC,KAAK,IAAI,CAAC,CAAC,IAAI,EAAE,CAAC;SAClC,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC;AAClB,CAAC,CAAC;AA1GW,QAAA,WAAW,eA0GtB","sourcesContent":["import { IOrder } from '@yuants/data-order';\nimport { decodePath, formatTime, newError, roundToStep } from '@yuants/utils';\nimport { firstValueFrom, map } from 'rxjs';\nimport { accountConfigCache } from '../accountInfos/uid';\nimport { ICredential, postTradeOrder } from '../api/private-api';\nimport { productService } from '../public-data/product';\nimport { spotMarketTickers$ } from '../public-data/quote';\n\nconst mapOrderDirectionToSide = (direction?: string) => {\n switch (direction) {\n case 'OPEN_LONG':\n case 'CLOSE_SHORT':\n return 'buy';\n case 'OPEN_SHORT':\n case 'CLOSE_LONG':\n return 'sell';\n }\n throw new Error(`Unknown direction: ${direction}`);\n};\n\nconst mapOrderTypeToOrdType = (order_type?: string) => {\n switch (order_type) {\n case 'LIMIT':\n return 'limit';\n case 'MARKET':\n return 'market';\n case 'MAKER':\n return 'post_only';\n }\n throw new Error(`Unknown order type: ${order_type}`);\n};\n\nexport const submitOrder = async (credential: ICredential, order: IOrder): Promise<{ order_id: string }> => {\n const accountConfigRes = await accountConfigCache.query(JSON.stringify(credential));\n if (!accountConfigRes) throw newError('ACCOUNT_CONFIG_FETCH_ERROR', { accountConfigRes });\n if (!accountConfigRes.data?.[0]) throw newError('ACCOUNT_CONFIG_FETCH_ERROR', { accountConfigRes });\n\n /**\n * 是否为组合保证金模式\n */\n const isPortfolioMarginMode = accountConfigRes.data[0].acctLv === '4';\n\n const [instType, instId] = decodePath(order.product_id).slice(-2);\n\n // 交易数量,表示要购买或者出售的数量。\n // 当币币/币币杠杆以限价买入和卖出时,指交易货币数量。\n // 当币币杠杆以市价买入时,指计价货币的数量。\n // 当币币杠杆以市价卖出时,指交易货币的数量。\n // 对于币币市价单,单位由 tgtCcy 决定\n // 当交割、永续、期权买入和卖出时,指合约张数。\n const mapOrderVolumeToSz = async (order: IOrder) => {\n if (instType === 'SWAP') {\n return order.volume;\n }\n if (instType === 'MARGIN') {\n if (order.order_type === 'LIMIT') {\n return order.volume;\n }\n if (order.order_type === 'MAKER') {\n return order.volume;\n }\n if (order.order_type === 'MARKET') {\n if (order.order_direction === 'OPEN_SHORT' || order.order_direction === 'CLOSE_LONG') {\n return order.volume;\n }\n //\n const price = await firstValueFrom(\n spotMarketTickers$.pipe(\n map((x) =>\n mapOrderDirectionToPosSide(order.order_direction) === 'long'\n ? +x[instId].askPx\n : +x[instId].bidPx,\n ),\n ),\n );\n if (!price) {\n throw new Error(`invalid tick: ${price}`);\n }\n console.info(formatTime(Date.now()), 'SubmitOrder', 'price', price);\n const theProduct = await firstValueFrom(\n productService.mapProductIdToProduct$.pipe(map((x) => x.get(order.product_id))),\n );\n if (!theProduct) {\n throw new Error(`Unknown product: ${order.position_id}`);\n }\n return roundToStep(order.volume * price, theProduct.volume_step!);\n }\n\n return 0;\n }\n\n if (instType === 'SPOT') {\n return order.volume;\n }\n\n throw new Error(`Unknown instType: ${instType}`);\n };\n\n const mapOrderDirectionToPosSide = (direction?: string) => {\n if (isPortfolioMarginMode) return undefined;\n switch (direction) {\n case 'OPEN_LONG':\n case 'CLOSE_LONG':\n return 'long';\n case 'CLOSE_SHORT':\n case 'OPEN_SHORT':\n return 'short';\n }\n throw new Error(`Unknown direction: ${direction}`);\n };\n\n const params = {\n instId,\n tdMode: instType === 'SPOT' ? 'cash' : 'cross',\n side: mapOrderDirectionToSide(order.order_direction),\n posSide:\n instType === 'MARGIN' || instType === 'SPOT'\n ? 'net'\n : mapOrderDirectionToPosSide(order.order_direction),\n ordType: mapOrderTypeToOrdType(order.order_type),\n sz: (await mapOrderVolumeToSz(order)).toString(),\n tgtCcy: instType === 'SPOT' && order.order_type === 'MARKET' ? 'base_ccy' : undefined,\n reduceOnly:\n instType === 'MARGIN' && ['CLOSE_LONG', 'CLOSE_SHORT'].includes(order.order_direction ?? '')\n ? 'true'\n : undefined,\n px: order.order_type === 'LIMIT' || order.order_type === 'MAKER' ? order.price!.toString() : undefined,\n ccy: instType === 'MARGIN' ? 'USDT' : undefined,\n tag: process.env.BROKER_CODE,\n };\n console.info(formatTime(Date.now()), 'SubmitOrder', 'params', JSON.stringify(params));\n const res = await postTradeOrder(credential, params);\n if (res.code === '0' && res.data?.[0]?.ordId) {\n return { order_id: res.data[0].ordId };\n }\n throw `Failed to submit order: ${res.code} ${res.msg}: ${res.data\n .map((x) => `${x.sCode} ${x.sMsg}`)\n .join('; ')}`;\n};\n"]}
package/lib/trade.js CHANGED
@@ -49,7 +49,7 @@ const tradeParser = async (accountId, params) => {
49
49
  };
50
50
  v.forEach((bill) => {
51
51
  trade.created_at = Math.max(Number(trade.created_at), Number(bill.ts)).toString();
52
- trade.product_id = (0, utils_1.encodePath)(bill.instType, bill.instId);
52
+ trade.product_id = (0, utils_1.encodePath)('OKX', bill.instType, bill.instId);
53
53
  trade.traded_price = bill.px;
54
54
  if (bill.instType === 'SWAP') {
55
55
  if (bill.subType === '1')
package/lib/trade.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"trade.js","sourceRoot":"","sources":["../src/trade.ts"],"names":[],"mappings":";;AAEA,+CAA4C;AAC5C,qCAAiF;AACjF,yCAAuD;AACvD,+BAA0D;AAC1D,mDAAiF;AACjF,4CAAyD;AAEzD,MAAM,UAAU,GAAG,IAAA,kCAAoB,GAAE,CAAC;AAE1C,MAAM,WAAW,GAAG,KAAK,EAAE,SAAiB,EAAE,MAA8B,EAAqB,EAAE;;IACjG,MAAM,SAAS,GAAa,EAAE,CAAC;IAC/B,MAAM,MAAM,GAAG,MAAM,IAAA,oCAAsB,EAAC,UAAU,EAAE,MAAM,CA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AAE,KAAK,EAAE,KAAM,EAAE,CAAC,EACzB,IAAA,YAAK,EAAC,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC,CACvB;SACA,SAAS,EAAE,CAAC;AACjB,CAAC,CAAC,EAAE,CAAC","sourcesContent":["import { IProduct } from '@yuants/data-product';\nimport { ITrade } from '@yuants/data-trade';\nimport { Terminal } from '@yuants/protocol';\nimport { buildInsertManyIntoTableSQL, escapeSQL, requestSQL } from '@yuants/sql';\nimport { encodePath, formatTime } from '@yuants/utils';\nimport { defer, repeat, retry, tap, timeout } from 'rxjs';\nimport { getAccountBillsArchive, getDefaultCredential } from './api/private-api';\nimport { getTradingAccountId } from './accountInfos/uid';\n\nconst credential = getDefaultCredential();\n\nconst tradeParser = async (accountId: string, params: Record<string, string>): Promise<ITrade[]> => {\n const tradeList: ITrade[] = [];\n const result = await getAccountBillsArchive(credential, params);\n const productIdToProduct = new Map<string, IProduct>();\n const productIdSet = new Set<string>();\n if (result.code === '0' && result.data) {\n const data = result.data;\n const mapTradeIdToBillList = new Map<string, typeof data>();\n data.forEach((item) => {\n productIdSet.add(encodePath(item.instType, item.instId));\n mapTradeIdToBillList.set(item.tradeId, [...(mapTradeIdToBillList.get(item.tradeId) ?? []), item]);\n });\n if (productIdSet.size > 0) {\n const productList = await requestSQL<IProduct[]>(\n Terminal.fromNodeEnv(),\n `\n select * from product where product_id in (${Array.from(productIdSet)\n .map((productId) => escapeSQL(productId))\n .join(',')})\n `,\n );\n if (productList.length > 0) {\n productList.forEach((p) => productIdToProduct.set(p.product_id, p));\n }\n }\n for (const [tradeId, v] of mapTradeIdToBillList) {\n if (!((v[0].instType === 'SPOT' && v.length === 2) || v[0].instType === 'SWAP')) continue;\n\n const trade: ITrade = {\n id: tradeId,\n account_id: accountId,\n product_id: '',\n direction: '',\n traded_volume: '',\n traded_price: '',\n traded_value: '',\n post_volume: '',\n fee: '',\n fee_currency: '',\n created_at: '0',\n };\n\n v.forEach((bill) => {\n trade.created_at = Math.max(Number(trade.created_at), Number(bill.ts)).toString();\n trade.product_id = encodePath(bill.instType, bill.instId);\n trade.traded_price = bill.px;\n if (bill.instType === 'SWAP') {\n if (bill.subType === '1') trade.direction = 'OPEN_LONG';\n if (bill.subType === '2') trade.direction = 'CLOSE_LONG';\n if (bill.subType === '3') trade.direction = 'OPEN_LONG';\n if (bill.subType === '4') trade.direction = 'OPEN_SHORT';\n if (bill.subType === '5') trade.direction = 'CLOSE_LONG';\n if (bill.subType === '6') trade.direction = 'CLOSE_SHORT';\n trade.traded_volume = bill.sz;\n trade.traded_value = (Number(bill.sz) * Number(bill.px)).toString();\n }\n if (bill.instType === 'SPOT') {\n if (bill.subType === '1') {\n if (bill.ccy !== 'USDT') {\n trade.direction = 'OPEN_LONG';\n } else {\n trade.direction = 'CLOSE_LONG';\n }\n }\n\n if (bill.ccy !== 'USDT') {\n trade.traded_volume = bill.sz;\n }\n if (bill.ccy === 'USDT') {\n trade.traded_value = bill.sz;\n }\n }\n // fee\n if (bill.fee !== '0') {\n trade.fee = Math.abs(Number(bill.fee)).toString();\n trade.fee_currency = bill.ccy;\n }\n });\n trade.created_at = formatTime(Number(trade.created_at));\n if (productIdToProduct.has(trade.product_id)) {\n trade.traded_value = (\n +trade.traded_value * +(productIdToProduct.get(trade.product_id)?.value_scale ?? 1)\n ).toString();\n } else {\n throw new Error(`Not Found Product With Product Id: ${trade.product_id}`);\n }\n tradeList.push(trade);\n }\n }\n return tradeList;\n};\n\nconst getAccountTradeWithAccountId = async (accountId: string) => {\n const currentTrade = await requestSQL<ITrade[]>(\n Terminal.fromNodeEnv(),\n `\n select * from trade where account_id=${escapeSQL(accountId)} order by created_at desc limit 1;\n `,\n );\n const params: Record<string, string> = {\n type: '2',\n begin: (new Date().getTime() - 1000 * 60 * 60 * 24 * 30 * 3).toString(),\n };\n if (currentTrade.length === 1) {\n params['begin'] = new Date(currentTrade[0].created_at ?? 0).getTime().toString();\n }\n console.log(formatTime(Date.now()), 'getAccountTrade', `params: ${JSON.stringify(params)}`);\n const tradeList = await tradeParser(accountId, params);\n console.log(formatTime(Date.now()), 'getAccountTrade', `tradeList: ${JSON.stringify(tradeList)}`);\n await requestSQL(\n Terminal.fromNodeEnv(),\n buildInsertManyIntoTableSQL(tradeList, 'trade', {\n columns: [\n 'id',\n 'account_id',\n 'product_id',\n 'traded_volume',\n 'traded_value',\n 'traded_price',\n 'direction',\n 'fee',\n 'fee_currency',\n 'created_at',\n ],\n conflictKeys: ['id'],\n }),\n );\n};\n\n(async () => {\n const account_id = await getTradingAccountId(credential);\n console.log(formatTime(Date.now()), 'getAccountTrade', `AccountID: ${account_id}`);\n defer(() => getAccountTradeWithAccountId(account_id))\n .pipe(\n //\n timeout(10_000), // 超时设定:10 秒\n tap({\n error: (err) => {\n console.error(formatTime(Date.now()), 'getAccountTradeError', err);\n },\n }),\n repeat({ delay: 30_000 }),\n retry({ delay: 5000 }),\n )\n .subscribe();\n})();\n"]}
1
+ {"version":3,"file":"trade.js","sourceRoot":"","sources":["../src/trade.ts"],"names":[],"mappings":";;AAEA,+CAA4C;AAC5C,qCAAiF;AACjF,yCAAuD;AACvD,+BAA0D;AAC1D,mDAAiF;AACjF,4CAAyD;AAEzD,MAAM,UAAU,GAAG,IAAA,kCAAoB,GAAE,CAAC;AAE1C,MAAM,WAAW,GAAG,KAAK,EAAE,SAAiB,EAAE,MAA8B,EAAqB,EAAE;;IACjG,MAAM,SAAS,GAAa,EAAE,CAAC;IAC/B,MAAM,MAAM,GAAG,MAAM,IAAA,oCAAsB,EAAC,UAAU,EAAE,MAAM,CAAC,CAAC;IAChE,MAAM,kBAAkB,GAAG,IAAI,GAAG,EAAoB,CAAC;IACvD,MAAM,YAAY,GAAG,IAAI,GAAG,EAAU,CAAC;IACvC,IAAI,MAAM,CAAC,IAAI,KAAK,GAAG,IAAI,MAAM,CAAC,IAAI,EAAE;QACtC,MAAM,IAAI,GAAG,MAAM,CAAC,IAAI,CAAC;QACzB,MAAM,oBAAoB,GAAG,IAAI,GAA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c,IAAI,CAAC,SAAS,CAAC,SAAS,CAAC,EAAE,CAAC,CAAC;IAClG,MAAM,IAAA,gBAAU,EACd,mBAAQ,CAAC,WAAW,EAAE,EACtB,IAAA,iCAA2B,EAAC,SAAS,EAAE,OAAO,EAAE;QAC9C,OAAO,EAAE;YACP,IAAI;YACJ,YAAY;YACZ,YAAY;YACZ,eAAe;YACf,cAAc;YACd,cAAc;YACd,WAAW;YACX,KAAK;YACL,cAAc;YACd,YAAY;SACb;QACD,YAAY,EAAE,CAAC,IAAI,CAAC;KACrB,CAAC,CACH,CAAC;AACJ,CAAC,CAAC;AAEF,CAAC,KAAK,IAAI,EAAE;IACV,MAAM,UAAU,GAAG,MAAM,IAAA,yBAAmB,EAAC,UAAU,CAAC,CAAC;IACzD,OAAO,CAAC,GAAG,CAAC,IAAA,kBAAU,EAAC,IAAI,CAAC,GAAG,EAAE,CAAC,EAAE,iBAAiB,EAAE,cAAc,UAAU,EAAE,CAAC,CAAC;IACnF,IAAA,YAAK,EAAC,GAAG,EAAE,CAAC,4BAA4B,CAAC,UAAU,CAAC,CAAC;SAClD,IAAI;IACH,EAAE;IACF,IAAA,cAAO,EAAC,KAAM,CAAC,EAAE,aAAa;IAC9B,IAAA,UAAG,EAAC;QACF,KAAK,EAAE,CAAC,GAAG,EAAE,EAAE;YACb,OAAO,CAAC,KAAK,CAAC,IAAA,kBAAU,EAAC,IAAI,CAAC,GAAG,EAAE,CAAC,EAAE,sBAAsB,EAAE,GAAG,CAAC,CAAC;QACrE,CAAC;KACF,CAAC,EACF,IAAA,aAAM,EAAC,EAAE,KAAK,EAAE,KAAM,EAAE,CAAC,EACzB,IAAA,YAAK,EAAC,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC,CACvB;SACA,SAAS,EAAE,CAAC;AACjB,CAAC,CAAC,EAAE,CAAC","sourcesContent":["import { IProduct } from '@yuants/data-product';\nimport { ITrade } from '@yuants/data-trade';\nimport { Terminal } from '@yuants/protocol';\nimport { buildInsertManyIntoTableSQL, escapeSQL, requestSQL } from '@yuants/sql';\nimport { encodePath, formatTime } from '@yuants/utils';\nimport { defer, repeat, retry, tap, timeout } from 'rxjs';\nimport { getAccountBillsArchive, getDefaultCredential } from './api/private-api';\nimport { getTradingAccountId } from './accountInfos/uid';\n\nconst credential = getDefaultCredential();\n\nconst tradeParser = async (accountId: string, params: Record<string, string>): Promise<ITrade[]> => {\n const tradeList: ITrade[] = [];\n const result = await getAccountBillsArchive(credential, params);\n const productIdToProduct = new Map<string, IProduct>();\n const productIdSet = new Set<string>();\n if (result.code === '0' && result.data) {\n const data = result.data;\n const mapTradeIdToBillList = new Map<string, typeof data>();\n data.forEach((item) => {\n productIdSet.add(encodePath(item.instType, item.instId));\n mapTradeIdToBillList.set(item.tradeId, [...(mapTradeIdToBillList.get(item.tradeId) ?? []), item]);\n });\n if (productIdSet.size > 0) {\n const productList = await requestSQL<IProduct[]>(\n Terminal.fromNodeEnv(),\n `\n select * from product where product_id in (${Array.from(productIdSet)\n .map((productId) => escapeSQL(productId))\n .join(',')})\n `,\n );\n if (productList.length > 0) {\n productList.forEach((p) => productIdToProduct.set(p.product_id, p));\n }\n }\n for (const [tradeId, v] of mapTradeIdToBillList) {\n if (!((v[0].instType === 'SPOT' && v.length === 2) || v[0].instType === 'SWAP')) continue;\n\n const trade: ITrade = {\n id: tradeId,\n account_id: accountId,\n product_id: '',\n direction: '',\n traded_volume: '',\n traded_price: '',\n traded_value: '',\n post_volume: '',\n fee: '',\n fee_currency: '',\n created_at: '0',\n };\n\n v.forEach((bill) => {\n trade.created_at = Math.max(Number(trade.created_at), Number(bill.ts)).toString();\n trade.product_id = encodePath('OKX', bill.instType, bill.instId);\n trade.traded_price = bill.px;\n if (bill.instType === 'SWAP') {\n if (bill.subType === '1') trade.direction = 'OPEN_LONG';\n if (bill.subType === '2') trade.direction = 'CLOSE_LONG';\n if (bill.subType === '3') trade.direction = 'OPEN_LONG';\n if (bill.subType === '4') trade.direction = 'OPEN_SHORT';\n if (bill.subType === '5') trade.direction = 'CLOSE_LONG';\n if (bill.subType === '6') trade.direction = 'CLOSE_SHORT';\n trade.traded_volume = bill.sz;\n trade.traded_value = (Number(bill.sz) * Number(bill.px)).toString();\n }\n if (bill.instType === 'SPOT') {\n if (bill.subType === '1') {\n if (bill.ccy !== 'USDT') {\n trade.direction = 'OPEN_LONG';\n } else {\n trade.direction = 'CLOSE_LONG';\n }\n }\n\n if (bill.ccy !== 'USDT') {\n trade.traded_volume = bill.sz;\n }\n if (bill.ccy === 'USDT') {\n trade.traded_value = bill.sz;\n }\n }\n // fee\n if (bill.fee !== '0') {\n trade.fee = Math.abs(Number(bill.fee)).toString();\n trade.fee_currency = bill.ccy;\n }\n });\n trade.created_at = formatTime(Number(trade.created_at));\n if (productIdToProduct.has(trade.product_id)) {\n trade.traded_value = (\n +trade.traded_value * +(productIdToProduct.get(trade.product_id)?.value_scale ?? 1)\n ).toString();\n } else {\n throw new Error(`Not Found Product With Product Id: ${trade.product_id}`);\n }\n tradeList.push(trade);\n }\n }\n return tradeList;\n};\n\nconst getAccountTradeWithAccountId = async (accountId: string) => {\n const currentTrade = await requestSQL<ITrade[]>(\n Terminal.fromNodeEnv(),\n `\n select * from trade where account_id=${escapeSQL(accountId)} order by created_at desc limit 1;\n `,\n );\n const params: Record<string, string> = {\n type: '2',\n begin: (new Date().getTime() - 1000 * 60 * 60 * 24 * 30 * 3).toString(),\n };\n if (currentTrade.length === 1) {\n params['begin'] = new Date(currentTrade[0].created_at ?? 0).getTime().toString();\n }\n console.log(formatTime(Date.now()), 'getAccountTrade', `params: ${JSON.stringify(params)}`);\n const tradeList = await tradeParser(accountId, params);\n console.log(formatTime(Date.now()), 'getAccountTrade', `tradeList: ${JSON.stringify(tradeList)}`);\n await requestSQL(\n Terminal.fromNodeEnv(),\n buildInsertManyIntoTableSQL(tradeList, 'trade', {\n columns: [\n 'id',\n 'account_id',\n 'product_id',\n 'traded_volume',\n 'traded_value',\n 'traded_price',\n 'direction',\n 'fee',\n 'fee_currency',\n 'created_at',\n ],\n conflictKeys: ['id'],\n }),\n );\n};\n\n(async () => {\n const account_id = await getTradingAccountId(credential);\n console.log(formatTime(Date.now()), 'getAccountTrade', `AccountID: ${account_id}`);\n defer(() => getAccountTradeWithAccountId(account_id))\n .pipe(\n //\n timeout(10_000), // 超时设定:10 秒\n tap({\n error: (err) => {\n console.error(formatTime(Date.now()), 'getAccountTradeError', err);\n },\n }),\n repeat({ delay: 30_000 }),\n retry({ delay: 5000 }),\n )\n .subscribe();\n})();\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@yuants/vendor-okx",
3
- "version": "0.29.6",
3
+ "version": "0.29.8",
4
4
  "main": "lib/index.js",
5
5
  "files": [
6
6
  "dist",
@@ -1,13 +1,13 @@
1
1
  {
2
- "apps/vendor-okx/CHANGELOG.json": "347053c59e46dd97f7ef46447997cc049e2b7979",
3
- "apps/vendor-okx/CHANGELOG.md": "f82f60a78c4430fce22899f4a97f6c50b7051f09",
2
+ "apps/vendor-okx/CHANGELOG.json": "476462034b7370c0df35543839908a6dbfa43910",
3
+ "apps/vendor-okx/CHANGELOG.md": "3f789dccc780be0adf05c97490aa5c8492b6e6e2",
4
4
  "apps/vendor-okx/README.md": "68caeb8e383d77ece973cd70f4b167b86abb54c3",
5
5
  "apps/vendor-okx/api-extractor.json": "62f4fd324425b9a235f0c117975967aab09ced0c",
6
6
  "apps/vendor-okx/config/jest.config.json": "4bb17bde3ee911163a3edb36a6eb71491d80b1bd",
7
7
  "apps/vendor-okx/config/rig.json": "f6c7b5537dc77a3170ba9f008bae3b6c3ee11956",
8
8
  "apps/vendor-okx/config/typescript.json": "854907e8a821f2050f6533368db160c649c25348",
9
9
  "apps/vendor-okx/etc/vendor-okx.api.md": "92c54ccd547d2ad81ca6088158ca193e85c208df",
10
- "apps/vendor-okx/package.json": "1a8de4f66a4d81584513977126f2bf04d74ac068",
10
+ "apps/vendor-okx/package.json": "f44b810af2547cc6ce35946cd6dcec67f08f84fe",
11
11
  "apps/vendor-okx/src/account-actions-with-credential.ts": "1a2de787b588e98ceef60b3ffb951f298504bf12",
12
12
  "apps/vendor-okx/src/account.ts": "672014c974457b438cf026f763d6eecfe585c82b",
13
13
  "apps/vendor-okx/src/accountInfos/earning.ts": "62aaeb3b62fa9197d07ee14155625530cdb9b1cd",
@@ -17,7 +17,7 @@
17
17
  "apps/vendor-okx/src/accountInfos/strategy.ts": "176add92022ad1fb43bad61880c5053aaa9fd5be",
18
18
  "apps/vendor-okx/src/accountInfos/trading.ts": "60ded8fdeb5c448fea467d3eb10aa9dab752f903",
19
19
  "apps/vendor-okx/src/accountInfos/types.ts": "c3c1096c3ad6849f6f679f1dfe0badb3ae876e41",
20
- "apps/vendor-okx/src/accountInfos/uid.ts": "348b64b205771143974e5ac5f5a7d06e9391a9f9",
20
+ "apps/vendor-okx/src/accountInfos/uid.ts": "6dd95c14f0493ef3f7d2dcbf4f01a1c181817999",
21
21
  "apps/vendor-okx/src/api-service.ts": "f1d977b144b1096965c5990260d9e6c81b08cb8c",
22
22
  "apps/vendor-okx/src/api/private-api.ts": "73ab6b99249ebb73769e903cc356627eaf19b433",
23
23
  "apps/vendor-okx/src/api/public-api.ts": "05b9cddafd09b5c9f65ce4eaeab42832e7d60449",
@@ -32,7 +32,7 @@
32
32
  "apps/vendor-okx/src/orders/cancelOrder.ts": "9a6c6d976caddd896ce08afac1dd2e4e24879b54",
33
33
  "apps/vendor-okx/src/orders/listOrders.ts": "c4739eb4c0f54391164a7d8e6c7fde44b41cb268",
34
34
  "apps/vendor-okx/src/orders/modifyOrder.ts": "9101b5049743f302b0f0ad84f929ed8a88040bad",
35
- "apps/vendor-okx/src/orders/submitOrder.ts": "564c8a659091dfb9676de753f0fceef1ec8ee168",
35
+ "apps/vendor-okx/src/orders/submitOrder.ts": "626ff6d2f14d22e0b3a3ffa447d33a78d9d0a38b",
36
36
  "apps/vendor-okx/src/public-data/interest_rate.ts": "f3171f2753955d500ae00ce7e263ea26e05e5421",
37
37
  "apps/vendor-okx/src/public-data/market-order.ts": "c7269e9fe1f339b320e8b4cd98652854446a245c",
38
38
  "apps/vendor-okx/src/public-data/new-quote.ts": "c184aae2008fcbceabc32fbc944b05d3dfb9b2a3",
@@ -41,7 +41,7 @@
41
41
  "apps/vendor-okx/src/public-data/quote.ts": "84db94c5af399e03b630037eb13382eb38b8c1e4",
42
42
  "apps/vendor-okx/src/services.ts": "aeaf5f9d0a87347be6150b28961c5a7c0886b1d8",
43
43
  "apps/vendor-okx/src/strategy-account.ts": "2d8f913e19c4402eab249291aaab0b77bc4d9ff8",
44
- "apps/vendor-okx/src/trade.ts": "cbb88bc535b8377ecd54a18e39082923fd5a4fda",
44
+ "apps/vendor-okx/src/trade.ts": "dac18a969af0b92bb474b9e1b6ff3b6598f8ae0a",
45
45
  "apps/vendor-okx/src/transfer.ts": "381e4bf18846c8f79d3e970277d8800a2f94dacd",
46
46
  "apps/vendor-okx/src/utils/provideOHLCFromTimeBackwardService.ts": "3a44206410b5b73683f2395d6c551549b553d7bd",
47
47
  "apps/vendor-okx/src/utils/provideSeriesFromTimeBackwardService.ts": "daf3c793eb4fc20e59a740bb69e50fadab5f62f0",