@yuants/vendor-okx 0.23.25 → 0.23.26

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (80) hide show
  1. package/dist/account.js +13 -136
  2. package/dist/account.js.map +1 -1
  3. package/dist/accountInfos/earning.js +15 -0
  4. package/dist/accountInfos/earning.js.map +1 -0
  5. package/dist/accountInfos/funding.js +46 -0
  6. package/dist/accountInfos/funding.js.map +1 -0
  7. package/dist/accountInfos/index.js +7 -0
  8. package/dist/accountInfos/index.js.map +1 -0
  9. package/dist/accountInfos/loan.js +46 -0
  10. package/dist/accountInfos/loan.js.map +1 -0
  11. package/dist/accountInfos/strategy.js +56 -0
  12. package/dist/accountInfos/strategy.js.map +1 -0
  13. package/dist/accountInfos/trading.js +84 -0
  14. package/dist/accountInfos/trading.js.map +1 -0
  15. package/dist/accountInfos/types.js +2 -0
  16. package/dist/accountInfos/types.js.map +1 -0
  17. package/dist/loan-account.js +3 -45
  18. package/dist/loan-account.js.map +1 -1
  19. package/dist/order-actions.js +10 -182
  20. package/dist/order-actions.js.map +1 -1
  21. package/dist/orders/cancelOrder.js +13 -0
  22. package/dist/orders/cancelOrder.js.map +1 -0
  23. package/dist/orders/modifyOrder.js +58 -0
  24. package/dist/orders/modifyOrder.js.map +1 -0
  25. package/dist/orders/submitOrder.js +107 -0
  26. package/dist/orders/submitOrder.js.map +1 -0
  27. package/dist/strategy-account.js +5 -59
  28. package/dist/strategy-account.js.map +1 -1
  29. package/lib/account.d.ts +2 -0
  30. package/lib/account.d.ts.map +1 -1
  31. package/lib/account.js +12 -136
  32. package/lib/account.js.map +1 -1
  33. package/lib/accountInfos/earning.d.ts +4 -0
  34. package/lib/accountInfos/earning.d.ts.map +1 -0
  35. package/lib/accountInfos/earning.js +19 -0
  36. package/lib/accountInfos/earning.js.map +1 -0
  37. package/lib/accountInfos/funding.d.ts +4 -0
  38. package/lib/accountInfos/funding.d.ts.map +1 -0
  39. package/lib/accountInfos/funding.js +50 -0
  40. package/lib/accountInfos/funding.js.map +1 -0
  41. package/lib/accountInfos/index.d.ts +8 -0
  42. package/lib/accountInfos/index.d.ts.map +1 -0
  43. package/lib/accountInfos/index.js +16 -0
  44. package/lib/accountInfos/index.js.map +1 -0
  45. package/lib/accountInfos/loan.d.ts +4 -0
  46. package/lib/accountInfos/loan.d.ts.map +1 -0
  47. package/lib/accountInfos/loan.js +50 -0
  48. package/lib/accountInfos/loan.js.map +1 -0
  49. package/lib/accountInfos/strategy.d.ts +4 -0
  50. package/lib/accountInfos/strategy.d.ts.map +1 -0
  51. package/lib/accountInfos/strategy.js +60 -0
  52. package/lib/accountInfos/strategy.js.map +1 -0
  53. package/lib/accountInfos/trading.d.ts +5 -0
  54. package/lib/accountInfos/trading.d.ts.map +1 -0
  55. package/lib/accountInfos/trading.js +88 -0
  56. package/lib/accountInfos/trading.js.map +1 -0
  57. package/lib/accountInfos/types.d.ts +6 -0
  58. package/lib/accountInfos/types.d.ts.map +1 -0
  59. package/lib/accountInfos/types.js +3 -0
  60. package/lib/accountInfos/types.js.map +1 -0
  61. package/lib/loan-account.js +2 -44
  62. package/lib/loan-account.js.map +1 -1
  63. package/lib/order-actions.js +8 -180
  64. package/lib/order-actions.js.map +1 -1
  65. package/lib/orders/cancelOrder.d.ts +4 -0
  66. package/lib/orders/cancelOrder.d.ts.map +1 -0
  67. package/lib/orders/cancelOrder.js +17 -0
  68. package/lib/orders/cancelOrder.js.map +1 -0
  69. package/lib/orders/modifyOrder.d.ts +4 -0
  70. package/lib/orders/modifyOrder.d.ts.map +1 -0
  71. package/lib/orders/modifyOrder.js +62 -0
  72. package/lib/orders/modifyOrder.js.map +1 -0
  73. package/lib/orders/submitOrder.d.ts +4 -0
  74. package/lib/orders/submitOrder.d.ts.map +1 -0
  75. package/lib/orders/submitOrder.js +111 -0
  76. package/lib/orders/submitOrder.js.map +1 -0
  77. package/lib/strategy-account.js +4 -58
  78. package/lib/strategy-account.js.map +1 -1
  79. package/package.json +13 -13
  80. package/temp/package-deps.json +29 -19
@@ -0,0 +1 @@
1
+ {"version":3,"file":"trading.js","sourceRoot":"","sources":["../../src/accountInfos/trading.ts"],"names":[],"mappings":";;;AACA,yCAA2C;AAC3C,+BAA8E;AAC9E,gCAA6E;AAC7E,wCAA4C;AAC5C,8CAAqD;AAGxC,QAAA,sBAAsB,GAAG,IAAA,YAAK,EAAC,GAAG,EAAE,CAAC,IAAA,iCAAoB,EAAC,EAAE,QAAQ,EAAE,MAAM,EAAE,CAAC,CAAC,CAAC,IAAI,CAChG,IAAA,UAAG,EAAC,CAAC,CAAC,EAAE,EAAE;IACR,MAAM,gBAAgB,GAAG,IAAI,GAAG,EAAkB,CAAC;IACnD,CAAC,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC,IAAS,EAAE,EAAE,CAAC,gBAAgB,CAAC,GAAG,CAAC,IAAI,CAAC,MAAM,EAAE,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;IACrF,OAAO,gBAAgB,CAAC;AAC1B,CAAC,CAAC,EACF,IAAA,aAAM,EAAC,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC,EACvB,IAAA,YAAK,EAAC,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC,EACtB,IAAA,kBAAW,EAAC,CAAC,CAAC,CACf,CAAC;AAEK,MAAM,qBAAqB,GAAG,KAAK,EAAE,UAAuB,EAA6B,EAAE;;IAChG,MAAM,CAAC,YAAY,EAAE,UAAU,EAAE,qBAAqB,EAAE,qBAAqB,CAAC,GAAG,MAAM,OAAO,CAAC,GAAG,CAAC;QACjG,IAAA,yBAAmB,EAAC,UAAU,EAAE,EAAE,CAAC;QACnC,IAAA,uBAAiB,EAAC,UAAU,EAAE,EAAE,CAAC;QACjC,IAAA,qBAAc,EAAC,wBAAc,CAAC,sBAAsB,CAAC;QACrD,IAAA,qBAAc,EAAC,8BAAsB,CAAC;KACvC,CAAC,CAAC;IAEH,IAAI,WAAW,GAAG,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,EAAE,MAAM;YACd,WAAW,EAAE,CAAC,CAAC,CAAC,QAAQ;YACxB,cAAc;YACd,cAAc,EAAE,CAAC,CAAC,CAAC,KAAK;YACxB,eAAe,EAAE,CAAC,CAAC,CAAC,GAAG;YACvB,SAAS;SACV,CAAC,CAAC;IACL,CAAC,CAAC,CAAC;IACH,OAAO;QACL,KAAK,EAAE;YACL,QAAQ,EAAE,MAAM;YAChB,MAAM,EAAE,WAAW;YACnB,IAAI,EAAE,SAAS;SAChB;QACD,SAAS,EAAE,SAAS;KACrB,CAAC;AACJ,CAAC,CAAC;AA/EW,QAAA,qBAAqB,yBA+EhC","sourcesContent":["import { IAccountMoney, IPosition } from '@yuants/data-account';\nimport { encodePath } from '@yuants/utils';\nimport { defer, firstValueFrom, map, repeat, retry, shareReplay } from 'rxjs';\nimport { ICredential, getAccountBalance, getAccountPositions } from '../api';\nimport { productService } from '../product';\nimport { getMarketIndexTicker } from '../public-api';\nimport { IAccountInfoCore } from './types';\n\nexport const marketIndexTickerUSDT$ = defer(() => getMarketIndexTicker({ quoteCcy: 'USDT' })).pipe(\n map((x) => {\n const mapInstIdToPrice = new Map<string, number>();\n x.data.forEach((inst: any) => mapInstIdToPrice.set(inst.instId, Number(inst.idxPx)));\n return mapInstIdToPrice;\n }),\n repeat({ delay: 1000 }),\n retry({ delay: 5000 }),\n shareReplay(1),\n);\n\nexport const getTradingAccountInfo = async (credential: ICredential): Promise<IAccountInfoCore> => {\n const [positionsApi, balanceApi, mapProductIdToProduct, marketIndexTickerUSDT] = await Promise.all([\n getAccountPositions(credential, {}),\n getAccountBalance(credential, {}),\n firstValueFrom(productService.mapProductIdToProduct$),\n firstValueFrom(marketIndexTickerUSDT$),\n ]);\n\n let totalEquity = 0;\n let totalFree = 0;\n const positions: IPosition[] = [];\n\n balanceApi.data[0]?.details.forEach((detail) => {\n if (detail.ccy === 'USDT') {\n const balance = +(detail.cashBal ?? 0);\n const free = Math.min(\n balance, // free should no more than balance if there is much profits\n +(detail.availEq ?? 0),\n );\n const equity = +(detail.eq ?? 0) - +(detail.stgyEq ?? 0);\n totalEquity += equity;\n totalFree += free;\n } else {\n const volume = +(detail.cashBal ?? 0);\n const free_volume = Math.min(\n volume, // free should no more than balance if there is much profits\n +(detail.availEq ?? 0),\n );\n const closable_price = marketIndexTickerUSDT.get(detail.ccy + '-USDT') || 0;\n const delta_equity = volume * closable_price || 0;\n const delta_profit = +detail.totalPnl || 0;\n\n const product_id = encodePath('SPOT', `${detail.ccy}-USDT`);\n positions.push({\n position_id: product_id,\n datasource_id: 'OKX',\n product_id: product_id,\n direction: 'LONG',\n volume: volume,\n free_volume: free_volume,\n position_price: +detail.accAvgPx,\n floating_profit: delta_profit,\n closable_price: closable_price,\n valuation: delta_equity,\n });\n\n totalEquity += delta_equity;\n }\n });\n positionsApi.data.forEach((x) => {\n const direction =\n x.posSide === 'long' ? 'LONG' : x.posSide === 'short' ? 'SHORT' : +x.pos > 0 ? 'LONG' : 'SHORT';\n const volume = Math.abs(+x.pos);\n const product_id = encodePath(x.instType, x.instId);\n const closable_price = +x.last;\n const valuation =\n (mapProductIdToProduct.get(product_id)?.value_scale ?? 1) * volume * closable_price || 0;\n\n positions.push({\n position_id: x.posId,\n datasource_id: 'OKX',\n product_id,\n direction,\n volume: volume,\n free_volume: +x.availPos,\n closable_price,\n position_price: +x.avgPx,\n floating_profit: +x.upl,\n valuation,\n });\n });\n return {\n money: {\n currency: 'USDT',\n equity: totalEquity,\n free: totalFree,\n },\n positions: positions,\n };\n};\n"]}
@@ -0,0 +1,6 @@
1
+ import { IAccountMoney, IPosition } from '@yuants/data-account';
2
+ export interface IAccountInfoCore {
3
+ money: Pick<IAccountMoney, 'currency' | 'equity' | 'free'>;
4
+ positions: IPosition[];
5
+ }
6
+ //# sourceMappingURL=types.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/accountInfos/types.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,SAAS,EAAE,MAAM,sBAAsB,CAAC;AAEhE,MAAM,WAAW,gBAAgB;IAC/B,KAAK,EAAE,IAAI,CAAC,aAAa,EAAE,UAAU,GAAG,QAAQ,GAAG,MAAM,CAAC,CAAC;IAC3D,SAAS,EAAE,SAAS,EAAE,CAAC;CACxB"}
@@ -0,0 +1,3 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ //# sourceMappingURL=types.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/accountInfos/types.ts"],"names":[],"mappings":"","sourcesContent":["import { IAccountMoney, IPosition } from '@yuants/data-account';\n\nexport interface IAccountInfoCore {\n money: Pick<IAccountMoney, 'currency' | 'equity' | 'free'>;\n positions: IPosition[];\n}\n"]}
@@ -2,57 +2,15 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  const data_account_1 = require("@yuants/data-account");
4
4
  const protocol_1 = require("@yuants/protocol");
5
- const utils_1 = require("@yuants/utils");
6
5
  const rxjs_1 = require("rxjs");
7
6
  const account_1 = require("./account");
8
7
  const api_1 = require("./api");
8
+ const accountInfos_1 = require("./accountInfos");
9
9
  (0, rxjs_1.defer)(async () => {
10
10
  const uid = await (0, rxjs_1.firstValueFrom)(account_1.accountUid$);
11
11
  const loanAccountId = `okx/${uid}/loan/USDT`;
12
12
  const credential = (0, api_1.getDefaultCredential)();
13
- (0, data_account_1.provideAccountInfoService)(protocol_1.Terminal.fromNodeEnv(), loanAccountId, async () => {
14
- const res = await (0, api_1.getFlexibleLoanInfo)(credential);
15
- const data = res.data[0];
16
- const positions = [];
17
- for (const loan of data.loanData) {
18
- positions.push({
19
- datasource_id: 'OKX',
20
- product_id: `SPOT/${loan.ccy}-USDT`,
21
- volume: +loan.amt,
22
- free_volume: +loan.amt,
23
- position_id: (0, utils_1.encodePath)('loan', loan.ccy),
24
- direction: 'SHORT',
25
- position_price: 0,
26
- closable_price: 0,
27
- floating_profit: 0,
28
- valuation: 0,
29
- });
30
- }
31
- for (const collateral of data.collateralData) {
32
- positions.push({
33
- datasource_id: 'OKX',
34
- product_id: `SPOT/${collateral.ccy}-USDT`,
35
- volume: +collateral.amt,
36
- free_volume: +collateral.amt,
37
- position_id: (0, utils_1.encodePath)('collateral', collateral.ccy),
38
- direction: 'LONG',
39
- position_price: 0,
40
- closable_price: 0,
41
- floating_profit: 0,
42
- valuation: 0,
43
- });
44
- }
45
- const equity = +data.collateralNotionalUsd - +data.loanNotionalUsd;
46
- const free = equity - +data.collateralNotionalUsd;
47
- return {
48
- money: {
49
- currency: 'USDT',
50
- equity,
51
- free,
52
- },
53
- positions,
54
- };
55
- }, {
13
+ (0, data_account_1.provideAccountInfoService)(protocol_1.Terminal.fromNodeEnv(), loanAccountId, () => (0, accountInfos_1.getLoanAccountInfo)(credential), {
56
14
  auto_refresh_interval: 1000,
57
15
  });
58
16
  }).subscribe();
@@ -1 +1 @@
1
- {"version":3,"file":"loan-account.js","sourceRoot":"","sources":["../src/loan-account.ts"],"names":[],"mappings":";;AAAA,uDAA4E;AAC5E,+CAA4C;AAC5C,yCAA2C;AAC3C,+BAA6C;AAC7C,uCAAwC;AACxC,+BAAkE;AAElE,IAAA,YAAK,EAAC,KAAK,IAAI,EAAE;IACf,MAAM,GAAG,GAAG,MAAM,IAAA,qBAAc,EAAC,qBAAW,CAAC,CAAC;IAC9C,MAAM,aAAa,GAAG,OAAO,GAAG,YAAY,CAAC;IAC7C,MAAM,UAAU,GAAG,IAAA,0BAAoB,GAAE,CAAC;IAE1C,IAAA,wCAAyB,EACvB,mBAAQ,CAAC,WAAW,EAAE,EACtB,aAAa,EACb,KAAK,IAAI,EAAE;QACT,MAAM,GAAG,GAAG,MAAM,IAAA,yBAAmB,EAAC,UAAU,CAAC,CAAC;QAClD,MAAM,IAAI,GAAG,GAAG,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;QAEzB,MAAM,SAAS,GAAgB,EAAE,CAAC;QAClC,KA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I;KAC5B,CACF,CAAC;AACJ,CAAC,CAAC,CAAC,SAAS,EAAE,CAAC","sourcesContent":["import { IPosition, provideAccountInfoService } from '@yuants/data-account';\nimport { Terminal } from '@yuants/protocol';\nimport { encodePath } from '@yuants/utils';\nimport { defer, firstValueFrom } from 'rxjs';\nimport { accountUid$ } from './account';\nimport { getDefaultCredential, getFlexibleLoanInfo } from './api';\n\ndefer(async () => {\n const uid = await firstValueFrom(accountUid$);\n const loanAccountId = `okx/${uid}/loan/USDT`;\n const credential = getDefaultCredential();\n\n provideAccountInfoService(\n Terminal.fromNodeEnv(),\n loanAccountId,\n async () => {\n const res = await getFlexibleLoanInfo(credential);\n const data = res.data[0];\n\n const positions: IPosition[] = [];\n for (const loan of data.loanData) {\n positions.push({\n datasource_id: 'OKX',\n product_id: `SPOT/${loan.ccy}-USDT`,\n volume: +loan.amt,\n free_volume: +loan.amt,\n position_id: encodePath('loan', loan.ccy),\n direction: 'SHORT',\n position_price: 0,\n closable_price: 0,\n floating_profit: 0,\n valuation: 0,\n });\n }\n for (const collateral of data.collateralData) {\n positions.push({\n datasource_id: 'OKX',\n product_id: `SPOT/${collateral.ccy}-USDT`,\n volume: +collateral.amt,\n free_volume: +collateral.amt,\n position_id: encodePath('collateral', collateral.ccy),\n direction: 'LONG',\n position_price: 0,\n closable_price: 0,\n floating_profit: 0,\n valuation: 0,\n });\n }\n const equity = +data.collateralNotionalUsd - +data.loanNotionalUsd;\n const free = equity - +data.collateralNotionalUsd;\n return {\n money: {\n currency: 'USDT',\n equity,\n free,\n },\n positions,\n };\n },\n {\n auto_refresh_interval: 1000,\n },\n );\n}).subscribe();\n"]}
1
+ {"version":3,"file":"loan-account.js","sourceRoot":"","sources":["../src/loan-account.ts"],"names":[],"mappings":";;AAAA,uDAAiE;AACjE,+CAA4C;AAC5C,+BAA6C;AAC7C,uCAAwC;AACxC,+BAA6C;AAC7C,iDAAoD;AAEpD,IAAA,YAAK,EAAC,KAAK,IAAI,EAAE;IACf,MAAM,GAAG,GAAG,MAAM,IAAA,qBAAc,EAAC,qBAAW,CAAC,CAAC;IAC9C,MAAM,aAAa,GAAG,OAAO,GAAG,YAAY,CAAC;IAC7C,MAAM,UAAU,GAAG,IAAA,0BAAoB,GAAE,CAAC;IAE1C,IAAA,wCAAyB,EAAC,mBAAQ,CAAC,WAAW,EAAE,EAAE,aAAa,EAAE,GAAG,EAAE,CAAC,IAAA,iCAAkB,EAAC,UAAU,CAAC,EAAE;QACrG,qBAAqB,EAAE,IAAI;KAC5B,CAAC,CAAC;AACL,CAAC,CAAC,CAAC,SAAS,EAAE,CAAC","sourcesContent":["import { provideAccountInfoService } from '@yuants/data-account';\nimport { Terminal } from '@yuants/protocol';\nimport { defer, firstValueFrom } from 'rxjs';\nimport { accountUid$ } from './account';\nimport { getDefaultCredential } from './api';\nimport { getLoanAccountInfo } from './accountInfos';\n\ndefer(async () => {\n const uid = await firstValueFrom(accountUid$);\n const loanAccountId = `okx/${uid}/loan/USDT`;\n const credential = getDefaultCredential();\n\n provideAccountInfoService(Terminal.fromNodeEnv(), loanAccountId, () => getLoanAccountInfo(credential), {\n auto_refresh_interval: 1000,\n });\n}).subscribe();\n"]}
@@ -1,12 +1,12 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  const protocol_1 = require("@yuants/protocol");
4
- const utils_1 = require("@yuants/utils");
5
4
  const rxjs_1 = require("rxjs");
6
5
  const account_1 = require("./account");
7
6
  const api_1 = require("./api");
8
- const product_1 = require("./product");
9
- const quote_1 = require("./quote");
7
+ const cancelOrder_1 = require("./orders/cancelOrder");
8
+ const modifyOrder_1 = require("./orders/modifyOrder");
9
+ const submitOrder_1 = require("./orders/submitOrder");
10
10
  const terminal = protocol_1.Terminal.fromNodeEnv();
11
11
  const credential = (0, api_1.getDefaultCredential)();
12
12
  (0, rxjs_1.defer)(async () => {
@@ -17,115 +17,7 @@ const credential = (0, api_1.getDefaultCredential)();
17
17
  account_id: { const: tradingAccountId },
18
18
  },
19
19
  }, async (msg) => {
20
- var _a, _b, _c;
21
- console.info((0, utils_1.formatTime)(Date.now()), 'SubmitOrder', JSON.stringify(msg));
22
- const order = msg.req;
23
- const [instType, instId] = (0, utils_1.decodePath)(order.product_id);
24
- const mapOrderDirectionToSide = (direction) => {
25
- switch (direction) {
26
- case 'OPEN_LONG':
27
- case 'CLOSE_SHORT':
28
- return 'buy';
29
- case 'OPEN_SHORT':
30
- case 'CLOSE_LONG':
31
- return 'sell';
32
- }
33
- throw new Error(`Unknown direction: ${direction}`);
34
- };
35
- const mapOrderDirectionToPosSide = (direction) => {
36
- switch (direction) {
37
- case 'OPEN_LONG':
38
- case 'CLOSE_LONG':
39
- return 'long';
40
- case 'CLOSE_SHORT':
41
- case 'OPEN_SHORT':
42
- return 'short';
43
- }
44
- throw new Error(`Unknown direction: ${direction}`);
45
- };
46
- const mapOrderTypeToOrdType = (order_type) => {
47
- switch (order_type) {
48
- case 'LIMIT':
49
- return 'limit';
50
- case 'MARKET':
51
- return 'market';
52
- case 'MAKER':
53
- return 'post_only';
54
- }
55
- throw new Error(`Unknown order type: ${order_type}`);
56
- };
57
- // 交易数量,表示要购买或者出售的数量。
58
- // 当币币/币币杠杆以限价买入和卖出时,指交易货币数量。
59
- // 当币币杠杆以市价买入时,指计价货币的数量。
60
- // 当币币杠杆以市价卖出时,指交易货币的数量。
61
- // 对于币币市价单,单位由 tgtCcy 决定
62
- // 当交割、永续、期权买入和卖出时,指合约张数。
63
- const mapOrderVolumeToSz = async (order) => {
64
- if (instType === 'SWAP') {
65
- return order.volume;
66
- }
67
- if (instType === 'MARGIN') {
68
- if (order.order_type === 'LIMIT') {
69
- return order.volume;
70
- }
71
- if (order.order_type === 'MAKER') {
72
- return order.volume;
73
- }
74
- if (order.order_type === 'MARKET') {
75
- if (order.order_direction === 'OPEN_SHORT' || order.order_direction === 'CLOSE_LONG') {
76
- return order.volume;
77
- }
78
- //
79
- const price = await (0, rxjs_1.firstValueFrom)(quote_1.spotMarketTickers$.pipe((0, rxjs_1.map)((x) => mapOrderDirectionToPosSide(order.order_direction) === 'long'
80
- ? +x[instId].askPx
81
- : +x[instId].bidPx)));
82
- if (!price) {
83
- throw new Error(`invalid tick: ${price}`);
84
- }
85
- console.info((0, utils_1.formatTime)(Date.now()), 'SubmitOrder', 'price', price);
86
- const theProduct = await (0, rxjs_1.firstValueFrom)(product_1.productService.mapProductIdToProduct$.pipe((0, rxjs_1.map)((x) => x.get(order.product_id))));
87
- if (!theProduct) {
88
- throw new Error(`Unknown product: ${order.position_id}`);
89
- }
90
- return (0, utils_1.roundToStep)(order.volume * price, theProduct.volume_step);
91
- }
92
- return 0;
93
- }
94
- if (instType === 'SPOT') {
95
- return order.volume;
96
- }
97
- throw new Error(`Unknown instType: ${instType}`);
98
- };
99
- const params = {
100
- instId,
101
- tdMode: instType === 'SPOT' ? 'cash' : 'cross',
102
- side: mapOrderDirectionToSide(order.order_direction),
103
- posSide: instType === 'MARGIN' || instType === 'SPOT'
104
- ? 'net'
105
- : mapOrderDirectionToPosSide(order.order_direction),
106
- ordType: mapOrderTypeToOrdType(order.order_type),
107
- sz: (await mapOrderVolumeToSz(order)).toString(),
108
- tgtCcy: instType === 'SPOT' && order.order_type === 'MARKET' ? 'base_ccy' : undefined,
109
- reduceOnly: instType === 'MARGIN' && ['CLOSE_LONG', 'CLOSE_SHORT'].includes((_a = order.order_direction) !== null && _a !== void 0 ? _a : '')
110
- ? 'true'
111
- : undefined,
112
- px: order.order_type === 'LIMIT' || order.order_type === 'MAKER' ? order.price.toString() : undefined,
113
- ccy: instType === 'MARGIN' ? 'USDT' : undefined,
114
- };
115
- console.info((0, utils_1.formatTime)(Date.now()), 'SubmitOrder', 'params', JSON.stringify(params));
116
- const res = await (0, api_1.postTradeOrder)(credential, params);
117
- 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
- return {
119
- res: {
120
- code: 0,
121
- message: 'OK',
122
- data: {
123
- order_id: res.data[0].ordId,
124
- },
125
- },
126
- };
127
- }
128
- return { res: { code: +res.code, message: res.msg } };
20
+ return { res: { code: 0, message: 'OK', data: { order_id: await (0, submitOrder_1.submitOrder)(credential, msg.req) } } };
129
21
  });
130
22
  terminal.server.provideService('ModifyOrder', {
131
23
  required: ['account_id'],
@@ -133,63 +25,7 @@ const credential = (0, api_1.getDefaultCredential)();
133
25
  account_id: { const: tradingAccountId },
134
26
  },
135
27
  }, async (msg) => {
136
- console.info((0, utils_1.formatTime)(Date.now()), 'ModifyOrder', JSON.stringify(msg));
137
- const order = msg.req;
138
- const [instType, instId] = (0, utils_1.decodePath)(order.product_id);
139
- const params = {
140
- instId,
141
- ordId: order.order_id, // 使用现有订单ID
142
- };
143
- // 如果需要修改价格
144
- if (order.price !== undefined) {
145
- params.newPx = order.price.toString();
146
- }
147
- // 如果需要修改数量
148
- if (order.volume !== undefined) {
149
- // 处理数量修改,类似于 SubmitOrder 中的逻辑
150
- if (instType === 'SWAP') {
151
- params.newSz = order.volume.toString();
152
- }
153
- else if (instType === 'SPOT') {
154
- params.newSz = order.volume.toString();
155
- }
156
- else if (instType === 'MARGIN') {
157
- if (order.order_type === 'LIMIT') {
158
- params.newSz = order.volume.toString();
159
- }
160
- if (order.order_type === 'MAKER') {
161
- params.newSz = order.volume.toString();
162
- }
163
- if (order.order_type === 'MARKET') {
164
- // 对于市价单,可能需要根据当前价格计算新的数量
165
- const price = await (0, rxjs_1.firstValueFrom)(quote_1.spotMarketTickers$.pipe((0, rxjs_1.map)((x) => order.order_direction === 'OPEN_LONG' || order.order_direction === 'CLOSE_SHORT'
166
- ? +x[instId].askPx
167
- : +x[instId].bidPx)));
168
- if (!price) {
169
- throw new Error(`invalid tick: ${price}`);
170
- }
171
- console.info((0, utils_1.formatTime)(Date.now()), 'ModifyOrder', 'price', price);
172
- const theProduct = await (0, rxjs_1.firstValueFrom)(product_1.productService.mapProductIdToProduct$.pipe((0, rxjs_1.map)((x) => x.get(order.product_id))));
173
- if (!theProduct) {
174
- throw new Error(`Unknown product: ${order.position_id}`);
175
- }
176
- params.newSz = (0, utils_1.roundToStep)(order.volume * price, theProduct.volume_step).toString();
177
- }
178
- }
179
- else {
180
- throw new Error(`Unknown instType: ${instType}`);
181
- }
182
- }
183
- console.info((0, utils_1.formatTime)(Date.now()), 'ModifyOrder', 'params', JSON.stringify(params));
184
- const res = await (0, api_1.postTradeAmendOrder)(credential, params);
185
- if (res.code !== '0') {
186
- return {
187
- res: {
188
- code: +res.code,
189
- message: res.msg,
190
- },
191
- };
192
- }
28
+ await (0, modifyOrder_1.modifyOrder)(credential, msg.req);
193
29
  return { res: { code: 0, message: 'OK' } };
194
30
  });
195
31
  terminal.server.provideService('CancelOrder', {
@@ -197,17 +33,9 @@ const credential = (0, api_1.getDefaultCredential)();
197
33
  properties: {
198
34
  account_id: { const: tradingAccountId },
199
35
  },
200
- }, (msg) => (0, rxjs_1.defer)(async () => {
201
- const order = msg.req;
202
- const [instType, instId] = (0, utils_1.decodePath)(order.product_id);
203
- const res = await (0, api_1.postTradeCancelOrder)(credential, {
204
- instId,
205
- ordId: order.order_id,
206
- });
207
- if (res.code !== '0') {
208
- return { res: { code: +res.code, message: res.msg } };
209
- }
36
+ }, async (msg) => {
37
+ await (0, cancelOrder_1.cancelOrder)(credential, msg.req);
210
38
  return { res: { code: 0, message: 'OK' } };
211
- }));
39
+ });
212
40
  }).subscribe();
213
41
  //# sourceMappingURL=order-actions.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"order-actions.js","sourceRoot":"","sources":["../src/order-actions.ts"],"names":[],"mappings":";;AACA,+CAA4C;AAC5C,yCAAoE;AACpE,+BAAkD;AAClD,uCAA8C;AAC9C,+BAAwG;AACxG,uCAA2C;AAC3C,mCAA6C;AAE7C,MAAM,QAAQ,GAAG,mBAAQ,CAAC,WAAW,EAAE,CAAC;AAExC,MAAM,UAAU,GAAG,IAAA,0BAAoB,GAAE,CAAC;AAE1C,IAAA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CAAC,IAAI,KAAK,GAAG,EAAE;YACpB,OAAO,EAAE,GAAG,EAAE,EAAE,IAAI,EAAE,CAAC,GAAG,CAAC,IAAI,EAAE,OAAO,EAAE,GAAG,CAAC,GAAG,EAAE,EAAE,CAAC;SACvD;QACD,OAAO,EAAE,GAAG,EAAE,EAAE,IAAI,EAAE,CAAC,EAAE,OAAO,EAAE,IAAI,EAAE,EAAE,CAAC;IAC7C,CAAC,CAAC,CACL,CAAC;AACJ,CAAC,CAAC,CAAC,SAAS,EAAE,CAAC","sourcesContent":["import { IOrder } from '@yuants/data-order';\nimport { Terminal } from '@yuants/protocol';\nimport { decodePath, formatTime, roundToStep } from '@yuants/utils';\nimport { defer, firstValueFrom, map } from 'rxjs';\nimport { tradingAccountId$ } from './account';\nimport { getDefaultCredential, postTradeAmendOrder, postTradeCancelOrder, postTradeOrder } from './api';\nimport { productService } from './product';\nimport { spotMarketTickers$ } from './quote';\n\nconst terminal = Terminal.fromNodeEnv();\n\nconst credential = getDefaultCredential();\n\ndefer(async () => {\n const tradingAccountId = await firstValueFrom(tradingAccountId$);\n terminal.server.provideService<IOrder, { order_id?: string }>(\n 'SubmitOrder',\n {\n required: ['account_id'],\n properties: {\n account_id: { const: tradingAccountId },\n },\n },\n async (msg) => {\n console.info(formatTime(Date.now()), 'SubmitOrder', JSON.stringify(msg));\n const order = msg.req;\n const [instType, instId] = decodePath(order.product_id);\n\n const 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 const 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 const 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\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:\n order.order_type === 'LIMIT' || order.order_type === 'MAKER' ? order.price!.toString() : undefined,\n ccy: instType === 'MARGIN' ? 'USDT' : undefined,\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 {\n res: {\n code: 0,\n message: 'OK',\n data: {\n order_id: res.data[0].ordId,\n },\n },\n };\n }\n return { res: { code: +res.code, message: res.msg } };\n },\n );\n\n terminal.server.provideService<IOrder>(\n 'ModifyOrder',\n {\n required: ['account_id'],\n properties: {\n account_id: { const: tradingAccountId },\n },\n },\n async (msg) => {\n console.info(formatTime(Date.now()), 'ModifyOrder', JSON.stringify(msg));\n const order = msg.req;\n const [instType, instId] = decodePath(order.product_id);\n\n const params: {\n instId: string;\n ordId: string;\n newPx?: string;\n newSz?: string;\n } = {\n instId,\n ordId: order.order_id!, // 使用现有订单ID\n };\n\n // 如果需要修改价格\n if (order.price !== undefined) {\n params.newPx = order.price.toString();\n }\n\n // 如果需要修改数量\n if (order.volume !== undefined) {\n // 处理数量修改,类似于 SubmitOrder 中的逻辑\n if (instType === 'SWAP') {\n params.newSz = order.volume.toString();\n } else if (instType === 'SPOT') {\n params.newSz = order.volume.toString();\n } else if (instType === 'MARGIN') {\n if (order.order_type === 'LIMIT') {\n params.newSz = order.volume.toString();\n }\n if (order.order_type === 'MAKER') {\n params.newSz = order.volume.toString();\n }\n if (order.order_type === 'MARKET') {\n // 对于市价单,可能需要根据当前价格计算新的数量\n const price = await firstValueFrom(\n spotMarketTickers$.pipe(\n map((x) =>\n order.order_direction === 'OPEN_LONG' || order.order_direction === 'CLOSE_SHORT'\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()), 'ModifyOrder', '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 params.newSz = roundToStep(order.volume * price, theProduct.volume_step!).toString();\n }\n } else {\n throw new Error(`Unknown instType: ${instType}`);\n }\n }\n\n console.info(formatTime(Date.now()), 'ModifyOrder', 'params', JSON.stringify(params));\n\n const res = await postTradeAmendOrder(credential, params);\n if (res.code !== '0') {\n return {\n res: {\n code: +res.code,\n message: res.msg,\n },\n };\n }\n\n return { res: { code: 0, message: 'OK' } };\n },\n );\n\n terminal.server.provideService<IOrder>(\n 'CancelOrder',\n {\n required: ['account_id'],\n properties: {\n account_id: { const: tradingAccountId },\n },\n },\n (msg) =>\n defer(async () => {\n const order = msg.req;\n const [instType, instId] = decodePath(order.product_id);\n const res = await postTradeCancelOrder(credential, {\n instId,\n ordId: order.order_id!,\n });\n if (res.code !== '0') {\n return { res: { code: +res.code, message: res.msg } };\n }\n return { res: { code: 0, message: 'OK' } };\n }),\n );\n}).subscribe();\n"]}
1
+ {"version":3,"file":"order-actions.js","sourceRoot":"","sources":["../src/order-actions.ts"],"names":[],"mappings":";;AACA,+CAA4C;AAC5C,+BAA6C;AAC7C,uCAA8C;AAC9C,+BAA6C;AAC7C,sDAAmD;AACnD,sDAAmD;AACnD,sDAAmD;AAEnD,MAAM,QAAQ,GAAG,mBAAQ,CAAC,WAAW,EAAE,CAAC;AAExC,MAAM,UAAU,GAAG,IAAA,0BAAoB,GAAE,CAAC;AAE1C,IAAA,YAAK,EAAC,KAAK,IAAI,EAAE;IACf,MAAM,gBAAgB,GAAG,MAAM,IAAA,qBAAc,EAAC,2BAAiB,CAAC,CAAC;IACjE,QAAQ,CAAC,MAAM,CAAC,cAAc,CAC5B,aAAa,EACb;QACE,QAAQ,EAAE,CAAC,YAA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uants/protocol';\nimport { defer, firstValueFrom } from 'rxjs';\nimport { tradingAccountId$ } from './account';\nimport { getDefaultCredential } from './api';\nimport { cancelOrder } from './orders/cancelOrder';\nimport { modifyOrder } from './orders/modifyOrder';\nimport { submitOrder } from './orders/submitOrder';\n\nconst terminal = Terminal.fromNodeEnv();\n\nconst credential = getDefaultCredential();\n\ndefer(async () => {\n const tradingAccountId = await firstValueFrom(tradingAccountId$);\n terminal.server.provideService<IOrder, { order_id?: string }>(\n 'SubmitOrder',\n {\n required: ['account_id'],\n properties: {\n account_id: { const: tradingAccountId },\n },\n },\n async (msg) => {\n return { res: { code: 0, message: 'OK', data: { order_id: await submitOrder(credential, msg.req) } } };\n },\n );\n\n terminal.server.provideService<IOrder>(\n 'ModifyOrder',\n {\n required: ['account_id'],\n properties: {\n account_id: { const: tradingAccountId },\n },\n },\n async (msg) => {\n await modifyOrder(credential, msg.req);\n return { res: { code: 0, message: 'OK' } };\n },\n );\n\n terminal.server.provideService<IOrder>(\n 'CancelOrder',\n {\n required: ['account_id'],\n properties: {\n account_id: { const: tradingAccountId },\n },\n },\n async (msg) => {\n await cancelOrder(credential, msg.req);\n return { res: { code: 0, message: 'OK' } };\n },\n );\n}).subscribe();\n"]}
@@ -0,0 +1,4 @@
1
+ import { IOrder } from '@yuants/data-order';
2
+ import { ICredential } from '../api';
3
+ export declare const cancelOrder: (credential: ICredential, order: IOrder) => Promise<void>;
4
+ //# sourceMappingURL=cancelOrder.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cancelOrder.d.ts","sourceRoot":"","sources":["../../src/orders/cancelOrder.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,oBAAoB,CAAC;AAE5C,OAAO,EAAE,WAAW,EAAwB,MAAM,QAAQ,CAAC;AAE3D,eAAO,MAAM,WAAW,eAAsB,WAAW,SAAS,MAAM,kBASvE,CAAC"}
@@ -0,0 +1,17 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.cancelOrder = void 0;
4
+ const utils_1 = require("@yuants/utils");
5
+ const api_1 = require("../api");
6
+ const cancelOrder = async (credential, order) => {
7
+ const [, instId] = (0, utils_1.decodePath)(order.product_id);
8
+ const res = await (0, api_1.postTradeCancelOrder)(credential, {
9
+ instId,
10
+ ordId: order.order_id,
11
+ });
12
+ if (res.code !== '0') {
13
+ throw new Error(`Cancel order failed: code=${res.code} msg=${res.msg}`);
14
+ }
15
+ };
16
+ exports.cancelOrder = cancelOrder;
17
+ //# sourceMappingURL=cancelOrder.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cancelOrder.js","sourceRoot":"","sources":["../../src/orders/cancelOrder.ts"],"names":[],"mappings":";;;AACA,yCAA2C;AAC3C,gCAA2D;AAEpD,MAAM,WAAW,GAAG,KAAK,EAAE,UAAuB,EAAE,KAAa,EAAE,EAAE;IAC1E,MAAM,CAAC,EAAE,MAAM,CAAC,GAAG,IAAA,kBAAU,EAAC,KAAK,CAAC,UAAU,CAAC,CAAC;IAChD,MAAM,GAAG,GAAG,MAAM,IAAA,0BAAoB,EAAC,UAAU,EAAE;QACjD,MAAM;QACN,KAAK,EAAE,KAAK,CAAC,QAAS;KACvB,CAAC,CAAC;IACH,IAAI,GAAG,CAAC,IAAI,KAAK,GAAG,EAAE;QACpB,MAAM,IAAI,KAAK,CAAC,6BAA6B,GAAG,CAAC,IAAI,QAAQ,GAAG,CAAC,GAAG,EAAE,CAAC,CAAC;KACzE;AACH,CAAC,CAAC;AATW,QAAA,WAAW,eAStB","sourcesContent":["import { IOrder } from '@yuants/data-order';\nimport { decodePath } from '@yuants/utils';\nimport { ICredential, postTradeCancelOrder } from '../api';\n\nexport const cancelOrder = async (credential: ICredential, order: IOrder) => {\n const [, instId] = decodePath(order.product_id);\n const res = await postTradeCancelOrder(credential, {\n instId,\n ordId: order.order_id!,\n });\n if (res.code !== '0') {\n throw new Error(`Cancel order failed: code=${res.code} msg=${res.msg}`);\n }\n};\n"]}
@@ -0,0 +1,4 @@
1
+ import { IOrder } from '@yuants/data-order';
2
+ import { ICredential } from '../api';
3
+ export declare const modifyOrder: (credential: ICredential, order: IOrder) => Promise<void>;
4
+ //# sourceMappingURL=modifyOrder.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"modifyOrder.d.ts","sourceRoot":"","sources":["../../src/orders/modifyOrder.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,oBAAoB,CAAC;AAG5C,OAAO,EAAE,WAAW,EAAuB,MAAM,QAAQ,CAAC;AAI1D,eAAO,MAAM,WAAW,eAAsB,WAAW,SAAS,MAAM,kBAiEvE,CAAC"}
@@ -0,0 +1,62 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.modifyOrder = void 0;
4
+ const utils_1 = require("@yuants/utils");
5
+ const rxjs_1 = require("rxjs");
6
+ const api_1 = require("../api");
7
+ const product_1 = require("../product");
8
+ const quote_1 = require("../quote");
9
+ const modifyOrder = async (credential, order) => {
10
+ const [instType, instId] = (0, utils_1.decodePath)(order.product_id);
11
+ const params = {
12
+ instId,
13
+ ordId: order.order_id, // 使用现有订单ID
14
+ };
15
+ // 如果需要修改价格
16
+ if (order.price !== undefined) {
17
+ params.newPx = order.price.toString();
18
+ }
19
+ // 如果需要修改数量
20
+ if (order.volume !== undefined) {
21
+ // 处理数量修改,类似于 SubmitOrder 中的逻辑
22
+ if (instType === 'SWAP') {
23
+ params.newSz = order.volume.toString();
24
+ }
25
+ else if (instType === 'SPOT') {
26
+ params.newSz = order.volume.toString();
27
+ }
28
+ else if (instType === 'MARGIN') {
29
+ if (order.order_type === 'LIMIT') {
30
+ params.newSz = order.volume.toString();
31
+ }
32
+ if (order.order_type === 'MAKER') {
33
+ params.newSz = order.volume.toString();
34
+ }
35
+ if (order.order_type === 'MARKET') {
36
+ // 对于市价单,可能需要根据当前价格计算新的数量
37
+ const price = await (0, rxjs_1.firstValueFrom)(quote_1.spotMarketTickers$.pipe((0, rxjs_1.map)((x) => order.order_direction === 'OPEN_LONG' || order.order_direction === 'CLOSE_SHORT'
38
+ ? +x[instId].askPx
39
+ : +x[instId].bidPx)));
40
+ if (!price) {
41
+ throw new Error(`invalid tick: ${price}`);
42
+ }
43
+ console.info((0, utils_1.formatTime)(Date.now()), 'ModifyOrder', 'price', price);
44
+ const theProduct = await (0, rxjs_1.firstValueFrom)(product_1.productService.mapProductIdToProduct$.pipe((0, rxjs_1.map)((x) => x.get(order.product_id))));
45
+ if (!theProduct) {
46
+ throw new Error(`Unknown product: ${order.position_id}`);
47
+ }
48
+ params.newSz = (0, utils_1.roundToStep)(order.volume * price, theProduct.volume_step).toString();
49
+ }
50
+ }
51
+ else {
52
+ throw new Error(`Unknown instType: ${instType}`);
53
+ }
54
+ }
55
+ console.info((0, utils_1.formatTime)(Date.now()), 'ModifyOrder', 'params', JSON.stringify(params));
56
+ const res = await (0, api_1.postTradeAmendOrder)(credential, params);
57
+ if (res.code !== '0') {
58
+ throw new Error(`ModifyOrder failed: code=${res.code}, msg=${res.msg}`);
59
+ }
60
+ };
61
+ exports.modifyOrder = modifyOrder;
62
+ //# sourceMappingURL=modifyOrder.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"modifyOrder.js","sourceRoot":"","sources":["../../src/orders/modifyOrder.ts"],"names":[],"mappings":";;;AACA,yCAAoE;AACpE,+BAA2C;AAC3C,gCAA0D;AAC1D,wCAA4C;AAC5C,oCAA8C;AAEvC,MAAM,WAAW,GAAG,KAAK,EAAE,UAAuB,EAAE,KAAa,EAAE,EAAE;IAC1E,MAAM,CAAC,QAAQ,EAAE,MAAM,CAAC,GAAG,IAAA,kBAAU,EAAC,KAAK,CAAC,UAAU,CAAC,CAAC;IACxD,MAAM,MAAM,GAKR;QACF,MAAM;QACN,KAAK,EAAE,KAAK,CAAC,QAAS,EAAE,WAAW;KACpC,CAAC;IAEF,WAAW;IACX,IAAI,KAAK,CAAC,KAAK,KAAK,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,kBAAU,EAAC,IAAI,CAAC,GAAG,EAAE,CAAC,EAAE,aAAa,EAAE,OAAO,EAAE,KAAK,CAAC,CAAC;gBACpE,MAAM,UAAU,GAAG,MAAM,IAAA,qBAAc,EACrC,wBAAc,CAAC,sBAAsB,CAAC,IAAI,CAAC,IAAA,UAAG,EAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,GAAG,CAAC,KAAK,CAAC,UAAU,CAAC,CAAC,CAAC,CAChF,CAAC;gBACF,IAAI,CAAC,UAAU,EAAE;oBACf,MAAM,IAAI,KAAK,CAAC,oBAAoB,KAAK,CAAC,WAAW,EAAE,CAAC,CAAC;iBAC1D;gBACD,MAAM,CAAC,KAAK,GAAG,IAAA,mBAAW,EAAC,KAAK,CAAC,MAAM,GAAG,KAAK,EAAE,UAAU,CAAC,WAAY,CAAC,CAAC,QAAQ,EAAE,CAAC;aACtF;SACF;aAAM;YACL,MAAM,IAAI,KAAK,CAAC,qBAAqB,QAAQ,EAAE,CAAC,CAAC;SAClD;KACF;IAED,OAAO,CAAC,IAAI,CAAC,IAAA,kBAAU,EAAC,IAAI,CAAC,GAAG,EAAE,CAAC,EAAE,aAAa,EAAE,QAAQ,EAAE,IAAI,CAAC,SAAS,CAAC,MAAM,CAAC,CAAC,CAAC;IAEtF,MAAM,GAAG,GAAG,MAAM,IAAA,yBAAmB,EAAC,UAAU,EAAE,MAAM,CAAC,CAAC;IAC1D,IAAI,GAAG,CAAC,IAAI,KAAK,GAAG,EAAE;QACpB,MAAM,IAAI,KAAK,CAAC,4BAA4B,GAAG,CAAC,IAAI,SAAS,GAAG,CAAC,GAAG,EAAE,CAAC,CAAC;KACzE;AACH,CAAC,CAAC;AAjEW,QAAA,WAAW,eAiEtB","sourcesContent":["import { IOrder } from '@yuants/data-order';\nimport { formatTime, decodePath, roundToStep } from '@yuants/utils';\nimport { firstValueFrom, map } from 'rxjs';\nimport { ICredential, postTradeAmendOrder } from '../api';\nimport { productService } from '../product';\nimport { spotMarketTickers$ } from '../quote';\n\nexport const modifyOrder = async (credential: ICredential, order: IOrder) => {\n const [instType, instId] = decodePath(order.product_id);\n const params: {\n instId: string;\n ordId: string;\n newPx?: string;\n newSz?: string;\n } = {\n instId,\n ordId: order.order_id!, // 使用现有订单ID\n };\n\n // 如果需要修改价格\n if (order.price !== undefined) {\n params.newPx = order.price.toString();\n }\n\n // 如果需要修改数量\n if (order.volume !== undefined) {\n // 处理数量修改,类似于 SubmitOrder 中的逻辑\n if (instType === 'SWAP') {\n params.newSz = order.volume.toString();\n } else if (instType === 'SPOT') {\n params.newSz = order.volume.toString();\n } else if (instType === 'MARGIN') {\n if (order.order_type === 'LIMIT') {\n params.newSz = order.volume.toString();\n }\n if (order.order_type === 'MAKER') {\n params.newSz = order.volume.toString();\n }\n if (order.order_type === 'MARKET') {\n // 对于市价单,可能需要根据当前价格计算新的数量\n const price = await firstValueFrom(\n spotMarketTickers$.pipe(\n map((x) =>\n order.order_direction === 'OPEN_LONG' || order.order_direction === 'CLOSE_SHORT'\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()), 'ModifyOrder', '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 params.newSz = roundToStep(order.volume * price, theProduct.volume_step!).toString();\n }\n } else {\n throw new Error(`Unknown instType: ${instType}`);\n }\n }\n\n console.info(formatTime(Date.now()), 'ModifyOrder', 'params', JSON.stringify(params));\n\n const res = await postTradeAmendOrder(credential, params);\n if (res.code !== '0') {\n throw new Error(`ModifyOrder failed: code=${res.code}, msg=${res.msg}`);\n }\n};\n"]}
@@ -0,0 +1,4 @@
1
+ import { IOrder } from '@yuants/data-order';
2
+ import { ICredential } from '../api';
3
+ export declare const submitOrder: (credential: ICredential, order: IOrder) => Promise<string>;
4
+ //# sourceMappingURL=submitOrder.d.ts.map
@@ -0,0 +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,QAAQ,CAAC;AAwCrD,eAAO,MAAM,WAAW,eAAsB,WAAW,SAAS,MAAM,KAAG,QAAQ,MAAM,CAiFxF,CAAC"}
@@ -0,0 +1,111 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.submitOrder = void 0;
4
+ const utils_1 = require("@yuants/utils");
5
+ const rxjs_1 = require("rxjs");
6
+ const api_1 = require("../api");
7
+ const product_1 = require("../product");
8
+ const quote_1 = require("../quote");
9
+ const mapOrderDirectionToSide = (direction) => {
10
+ switch (direction) {
11
+ case 'OPEN_LONG':
12
+ case 'CLOSE_SHORT':
13
+ return 'buy';
14
+ case 'OPEN_SHORT':
15
+ case 'CLOSE_LONG':
16
+ return 'sell';
17
+ }
18
+ throw new Error(`Unknown direction: ${direction}`);
19
+ };
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
+ const mapOrderTypeToOrdType = (order_type) => {
32
+ switch (order_type) {
33
+ case 'LIMIT':
34
+ return 'limit';
35
+ case 'MARKET':
36
+ return 'market';
37
+ case 'MAKER':
38
+ return 'post_only';
39
+ }
40
+ throw new Error(`Unknown order type: ${order_type}`);
41
+ };
42
+ const submitOrder = async (credential, order) => {
43
+ var _a, _b, _c;
44
+ const [instType, instId] = (0, utils_1.decodePath)(order.product_id);
45
+ // 交易数量,表示要购买或者出售的数量。
46
+ // 当币币/币币杠杆以限价买入和卖出时,指交易货币数量。
47
+ // 当币币杠杆以市价买入时,指计价货币的数量。
48
+ // 当币币杠杆以市价卖出时,指交易货币的数量。
49
+ // 对于币币市价单,单位由 tgtCcy 决定
50
+ // 当交割、永续、期权买入和卖出时,指合约张数。
51
+ const mapOrderVolumeToSz = async (order) => {
52
+ if (instType === 'SWAP') {
53
+ return order.volume;
54
+ }
55
+ if (instType === 'MARGIN') {
56
+ if (order.order_type === 'LIMIT') {
57
+ return order.volume;
58
+ }
59
+ if (order.order_type === 'MAKER') {
60
+ return order.volume;
61
+ }
62
+ if (order.order_type === 'MARKET') {
63
+ if (order.order_direction === 'OPEN_SHORT' || order.order_direction === 'CLOSE_LONG') {
64
+ return order.volume;
65
+ }
66
+ //
67
+ const price = await (0, rxjs_1.firstValueFrom)(quote_1.spotMarketTickers$.pipe((0, rxjs_1.map)((x) => mapOrderDirectionToPosSide(order.order_direction) === 'long'
68
+ ? +x[instId].askPx
69
+ : +x[instId].bidPx)));
70
+ if (!price) {
71
+ throw new Error(`invalid tick: ${price}`);
72
+ }
73
+ console.info((0, utils_1.formatTime)(Date.now()), 'SubmitOrder', 'price', price);
74
+ const theProduct = await (0, rxjs_1.firstValueFrom)(product_1.productService.mapProductIdToProduct$.pipe((0, rxjs_1.map)((x) => x.get(order.product_id))));
75
+ if (!theProduct) {
76
+ throw new Error(`Unknown product: ${order.position_id}`);
77
+ }
78
+ return (0, utils_1.roundToStep)(order.volume * price, theProduct.volume_step);
79
+ }
80
+ return 0;
81
+ }
82
+ if (instType === 'SPOT') {
83
+ return order.volume;
84
+ }
85
+ throw new Error(`Unknown instType: ${instType}`);
86
+ };
87
+ const params = {
88
+ instId,
89
+ tdMode: instType === 'SPOT' ? 'cash' : 'cross',
90
+ side: mapOrderDirectionToSide(order.order_direction),
91
+ posSide: instType === 'MARGIN' || instType === 'SPOT'
92
+ ? 'net'
93
+ : mapOrderDirectionToPosSide(order.order_direction),
94
+ ordType: mapOrderTypeToOrdType(order.order_type),
95
+ sz: (await mapOrderVolumeToSz(order)).toString(),
96
+ 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 : '')
98
+ ? 'true'
99
+ : undefined,
100
+ px: order.order_type === 'LIMIT' || order.order_type === 'MAKER' ? order.price.toString() : undefined,
101
+ ccy: instType === 'MARGIN' ? 'USDT' : undefined,
102
+ };
103
+ console.info((0, utils_1.formatTime)(Date.now()), 'SubmitOrder', 'params', JSON.stringify(params));
104
+ const res = await (0, api_1.postTradeOrder)(credential, params);
105
+ if (res.code === '0' && ((_c = (_b = res.data) === null || _b === void 0 ? void 0 : _b[0]) === null || _c === void 0 ? void 0 : _c.ordId)) {
106
+ return res.data[0].ordId;
107
+ }
108
+ throw `Failed to submit order: ${res.code} ${res.msg}`;
109
+ };
110
+ exports.submitOrder = submitOrder;
111
+ //# sourceMappingURL=submitOrder.js.map