@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
@@ -1,10 +1,10 @@
1
1
  import { Terminal } from '@yuants/protocol';
2
- import { decodePath, formatTime, roundToStep } from '@yuants/utils';
3
- import { defer, firstValueFrom, map } from 'rxjs';
2
+ import { defer, firstValueFrom } from 'rxjs';
4
3
  import { tradingAccountId$ } from './account';
5
- import { getDefaultCredential, postTradeAmendOrder, postTradeCancelOrder, postTradeOrder } from './api';
6
- import { productService } from './product';
7
- import { spotMarketTickers$ } from './quote';
4
+ import { getDefaultCredential } from './api';
5
+ import { cancelOrder } from './orders/cancelOrder';
6
+ import { modifyOrder } from './orders/modifyOrder';
7
+ import { submitOrder } from './orders/submitOrder';
8
8
  const terminal = Terminal.fromNodeEnv();
9
9
  const credential = getDefaultCredential();
10
10
  defer(async () => {
@@ -15,115 +15,7 @@ defer(async () => {
15
15
  account_id: { const: tradingAccountId },
16
16
  },
17
17
  }, async (msg) => {
18
- var _a, _b, _c;
19
- console.info(formatTime(Date.now()), 'SubmitOrder', JSON.stringify(msg));
20
- const order = msg.req;
21
- const [instType, instId] = decodePath(order.product_id);
22
- const mapOrderDirectionToSide = (direction) => {
23
- switch (direction) {
24
- case 'OPEN_LONG':
25
- case 'CLOSE_SHORT':
26
- return 'buy';
27
- case 'OPEN_SHORT':
28
- case 'CLOSE_LONG':
29
- return 'sell';
30
- }
31
- throw new Error(`Unknown direction: ${direction}`);
32
- };
33
- const mapOrderDirectionToPosSide = (direction) => {
34
- switch (direction) {
35
- case 'OPEN_LONG':
36
- case 'CLOSE_LONG':
37
- return 'long';
38
- case 'CLOSE_SHORT':
39
- case 'OPEN_SHORT':
40
- return 'short';
41
- }
42
- throw new Error(`Unknown direction: ${direction}`);
43
- };
44
- const mapOrderTypeToOrdType = (order_type) => {
45
- switch (order_type) {
46
- case 'LIMIT':
47
- return 'limit';
48
- case 'MARKET':
49
- return 'market';
50
- case 'MAKER':
51
- return 'post_only';
52
- }
53
- throw new Error(`Unknown order type: ${order_type}`);
54
- };
55
- // 交易数量,表示要购买或者出售的数量。
56
- // 当币币/币币杠杆以限价买入和卖出时,指交易货币数量。
57
- // 当币币杠杆以市价买入时,指计价货币的数量。
58
- // 当币币杠杆以市价卖出时,指交易货币的数量。
59
- // 对于币币市价单,单位由 tgtCcy 决定
60
- // 当交割、永续、期权买入和卖出时,指合约张数。
61
- const mapOrderVolumeToSz = async (order) => {
62
- if (instType === 'SWAP') {
63
- return order.volume;
64
- }
65
- if (instType === 'MARGIN') {
66
- if (order.order_type === 'LIMIT') {
67
- return order.volume;
68
- }
69
- if (order.order_type === 'MAKER') {
70
- return order.volume;
71
- }
72
- if (order.order_type === 'MARKET') {
73
- if (order.order_direction === 'OPEN_SHORT' || order.order_direction === 'CLOSE_LONG') {
74
- return order.volume;
75
- }
76
- //
77
- const price = await firstValueFrom(spotMarketTickers$.pipe(map((x) => mapOrderDirectionToPosSide(order.order_direction) === 'long'
78
- ? +x[instId].askPx
79
- : +x[instId].bidPx)));
80
- if (!price) {
81
- throw new Error(`invalid tick: ${price}`);
82
- }
83
- console.info(formatTime(Date.now()), 'SubmitOrder', 'price', price);
84
- const theProduct = await firstValueFrom(productService.mapProductIdToProduct$.pipe(map((x) => x.get(order.product_id))));
85
- if (!theProduct) {
86
- throw new Error(`Unknown product: ${order.position_id}`);
87
- }
88
- return roundToStep(order.volume * price, theProduct.volume_step);
89
- }
90
- return 0;
91
- }
92
- if (instType === 'SPOT') {
93
- return order.volume;
94
- }
95
- throw new Error(`Unknown instType: ${instType}`);
96
- };
97
- const params = {
98
- instId,
99
- tdMode: instType === 'SPOT' ? 'cash' : 'cross',
100
- side: mapOrderDirectionToSide(order.order_direction),
101
- posSide: instType === 'MARGIN' || instType === 'SPOT'
102
- ? 'net'
103
- : mapOrderDirectionToPosSide(order.order_direction),
104
- ordType: mapOrderTypeToOrdType(order.order_type),
105
- sz: (await mapOrderVolumeToSz(order)).toString(),
106
- tgtCcy: instType === 'SPOT' && order.order_type === 'MARKET' ? 'base_ccy' : undefined,
107
- reduceOnly: instType === 'MARGIN' && ['CLOSE_LONG', 'CLOSE_SHORT'].includes((_a = order.order_direction) !== null && _a !== void 0 ? _a : '')
108
- ? 'true'
109
- : undefined,
110
- px: order.order_type === 'LIMIT' || order.order_type === 'MAKER' ? order.price.toString() : undefined,
111
- ccy: instType === 'MARGIN' ? 'USDT' : undefined,
112
- };
113
- console.info(formatTime(Date.now()), 'SubmitOrder', 'params', JSON.stringify(params));
114
- const res = await postTradeOrder(credential, params);
115
- if (res.code === '0' && ((_c = (_b = res.data) === null || _b === void 0 ? void 0 : _b[0]) === null || _c === void 0 ? void 0 : _c.ordId)) {
116
- return {
117
- res: {
118
- code: 0,
119
- message: 'OK',
120
- data: {
121
- order_id: res.data[0].ordId,
122
- },
123
- },
124
- };
125
- }
126
- return { res: { code: +res.code, message: res.msg } };
18
+ return { res: { code: 0, message: 'OK', data: { order_id: await submitOrder(credential, msg.req) } } };
127
19
  });
128
20
  terminal.server.provideService('ModifyOrder', {
129
21
  required: ['account_id'],
@@ -131,63 +23,7 @@ defer(async () => {
131
23
  account_id: { const: tradingAccountId },
132
24
  },
133
25
  }, async (msg) => {
134
- console.info(formatTime(Date.now()), 'ModifyOrder', JSON.stringify(msg));
135
- const order = msg.req;
136
- const [instType, instId] = decodePath(order.product_id);
137
- const params = {
138
- instId,
139
- ordId: order.order_id, // 使用现有订单ID
140
- };
141
- // 如果需要修改价格
142
- if (order.price !== undefined) {
143
- params.newPx = order.price.toString();
144
- }
145
- // 如果需要修改数量
146
- if (order.volume !== undefined) {
147
- // 处理数量修改,类似于 SubmitOrder 中的逻辑
148
- if (instType === 'SWAP') {
149
- params.newSz = order.volume.toString();
150
- }
151
- else if (instType === 'SPOT') {
152
- params.newSz = order.volume.toString();
153
- }
154
- else if (instType === 'MARGIN') {
155
- if (order.order_type === 'LIMIT') {
156
- params.newSz = order.volume.toString();
157
- }
158
- if (order.order_type === 'MAKER') {
159
- params.newSz = order.volume.toString();
160
- }
161
- if (order.order_type === 'MARKET') {
162
- // 对于市价单,可能需要根据当前价格计算新的数量
163
- const price = await firstValueFrom(spotMarketTickers$.pipe(map((x) => order.order_direction === 'OPEN_LONG' || order.order_direction === 'CLOSE_SHORT'
164
- ? +x[instId].askPx
165
- : +x[instId].bidPx)));
166
- if (!price) {
167
- throw new Error(`invalid tick: ${price}`);
168
- }
169
- console.info(formatTime(Date.now()), 'ModifyOrder', 'price', price);
170
- const theProduct = await firstValueFrom(productService.mapProductIdToProduct$.pipe(map((x) => x.get(order.product_id))));
171
- if (!theProduct) {
172
- throw new Error(`Unknown product: ${order.position_id}`);
173
- }
174
- params.newSz = roundToStep(order.volume * price, theProduct.volume_step).toString();
175
- }
176
- }
177
- else {
178
- throw new Error(`Unknown instType: ${instType}`);
179
- }
180
- }
181
- console.info(formatTime(Date.now()), 'ModifyOrder', 'params', JSON.stringify(params));
182
- const res = await postTradeAmendOrder(credential, params);
183
- if (res.code !== '0') {
184
- return {
185
- res: {
186
- code: +res.code,
187
- message: res.msg,
188
- },
189
- };
190
- }
26
+ await modifyOrder(credential, msg.req);
191
27
  return { res: { code: 0, message: 'OK' } };
192
28
  });
193
29
  terminal.server.provideService('CancelOrder', {
@@ -195,17 +31,9 @@ defer(async () => {
195
31
  properties: {
196
32
  account_id: { const: tradingAccountId },
197
33
  },
198
- }, (msg) => defer(async () => {
199
- const order = msg.req;
200
- const [instType, instId] = decodePath(order.product_id);
201
- const res = await postTradeCancelOrder(credential, {
202
- instId,
203
- ordId: order.order_id,
204
- });
205
- if (res.code !== '0') {
206
- return { res: { code: +res.code, message: res.msg } };
207
- }
34
+ }, async (msg) => {
35
+ await cancelOrder(credential, msg.req);
208
36
  return { res: { code: 0, message: 'OK' } };
209
- }));
37
+ });
210
38
  }).subscribe();
211
39
  //# sourceMappingURL=order-actions.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"order-actions.js","sourceRoot":"","sources":["../src/order-actions.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,QAAQ,EAAE,M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xC;KACF,EACD,CAAC,GAAG,EAAE,EAAE,CACN,KAAK,CAAC,KAAK,IAAI,EAAE;QACf,MAAM,KAAK,GAAG,GAAG,CAAC,GAAG,CAAC;QACtB,MAAM,CAAC,QAAQ,EAAE,MAAM,CAAC,GAAG,UAAU,CAAC,KAAK,CAAC,UAAU,CAAC,CAAC;QACxD,MAAM,GAAG,GAAG,MAAM,oBAAoB,CAAC,UAAU,EAAE;YACjD,MAAM;YACN,KAAK,EAAE,KAAK,CAAC,QAAS;SACvB,CAAC,CAAC;QACH,IAAI,GAAG,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,OAAO,EAAE,QAAQ,EAAE,MAAM,kBAAkB,CAAC;AAC5C,OAAO,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AE,IAAI,EAAE,CAAC,EAAE,OAAO,EAAE,IAAI,EAAE,EAAE,CAAC;IAC7C,CAAC,CACF,CAAC;IAEF,QAAQ,CAAC,MAAM,CAAC,cAAc,CAC5B,aAAa,EACb;QACE,QAAQ,EAAE,CAAC,YAAY,CAAC;QACxB,UAAU,EAAE;YACV,UAAU,EAAE,EAAE,KAAK,EAAE,gBAAgB,EAAE;SACxC;KACF,EACD,KAAK,EAAE,GAAG,EAAE,EAAE;QACZ,MAAM,WAAW,CAAC,UAAU,EAAE,GAAG,CAAC,GAAG,CAAC,CAAC;QACvC,OAAO,EAAE,GAAG,EAAE,EAAE,IAAI,EAAE,CAAC,EAAE,OAAO,EAAE,IAAI,EAAE,EAAE,CAAC;IAC7C,CAAC,CACF,CAAC;AACJ,CAAC,CAAC,CAAC,SAAS,EAAE,CAAC","sourcesContent":["import { IOrder } from '@yuants/data-order';\nimport { Terminal } from '@yuants/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,13 @@
1
+ import { decodePath } from '@yuants/utils';
2
+ import { postTradeCancelOrder } from '../api';
3
+ export const cancelOrder = async (credential, order) => {
4
+ const [, instId] = decodePath(order.product_id);
5
+ const res = await postTradeCancelOrder(credential, {
6
+ instId,
7
+ ordId: order.order_id,
8
+ });
9
+ if (res.code !== '0') {
10
+ throw new Error(`Cancel order failed: code=${res.code} msg=${res.msg}`);
11
+ }
12
+ };
13
+ //# sourceMappingURL=cancelOrder.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cancelOrder.js","sourceRoot":"","sources":["../../src/orders/cancelOrder.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,UAAU,EAAE,MAAM,eAAe,CAAC;AAC3C,OAAO,EAAe,oBAAoB,EAAE,MAAM,QAAQ,CAAC;AAE3D,MAAM,CAAC,MAAM,WAAW,GAAG,KAAK,EAAE,UAAuB,EAAE,KAAa,EAAE,EAAE;IAC1E,MAAM,CAAC,EAAE,MAAM,CAAC,GAAG,UAAU,CAAC,KAAK,CAAC,UAAU,CAAC,CAAC;IAChD,MAAM,GAAG,GAAG,MAAM,oBAAoB,CAAC,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","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,58 @@
1
+ import { formatTime, decodePath, roundToStep } from '@yuants/utils';
2
+ import { firstValueFrom, map } from 'rxjs';
3
+ import { postTradeAmendOrder } from '../api';
4
+ import { productService } from '../product';
5
+ import { spotMarketTickers$ } from '../quote';
6
+ export const modifyOrder = async (credential, order) => {
7
+ const [instType, instId] = decodePath(order.product_id);
8
+ const params = {
9
+ instId,
10
+ ordId: order.order_id, // 使用现有订单ID
11
+ };
12
+ // 如果需要修改价格
13
+ if (order.price !== undefined) {
14
+ params.newPx = order.price.toString();
15
+ }
16
+ // 如果需要修改数量
17
+ if (order.volume !== undefined) {
18
+ // 处理数量修改,类似于 SubmitOrder 中的逻辑
19
+ if (instType === 'SWAP') {
20
+ params.newSz = order.volume.toString();
21
+ }
22
+ else if (instType === 'SPOT') {
23
+ params.newSz = order.volume.toString();
24
+ }
25
+ else if (instType === 'MARGIN') {
26
+ if (order.order_type === 'LIMIT') {
27
+ params.newSz = order.volume.toString();
28
+ }
29
+ if (order.order_type === 'MAKER') {
30
+ params.newSz = order.volume.toString();
31
+ }
32
+ if (order.order_type === 'MARKET') {
33
+ // 对于市价单,可能需要根据当前价格计算新的数量
34
+ const price = await firstValueFrom(spotMarketTickers$.pipe(map((x) => order.order_direction === 'OPEN_LONG' || order.order_direction === 'CLOSE_SHORT'
35
+ ? +x[instId].askPx
36
+ : +x[instId].bidPx)));
37
+ if (!price) {
38
+ throw new Error(`invalid tick: ${price}`);
39
+ }
40
+ console.info(formatTime(Date.now()), 'ModifyOrder', 'price', price);
41
+ const theProduct = await firstValueFrom(productService.mapProductIdToProduct$.pipe(map((x) => x.get(order.product_id))));
42
+ if (!theProduct) {
43
+ throw new Error(`Unknown product: ${order.position_id}`);
44
+ }
45
+ params.newSz = roundToStep(order.volume * price, theProduct.volume_step).toString();
46
+ }
47
+ }
48
+ else {
49
+ throw new Error(`Unknown instType: ${instType}`);
50
+ }
51
+ }
52
+ console.info(formatTime(Date.now()), 'ModifyOrder', 'params', JSON.stringify(params));
53
+ const res = await postTradeAmendOrder(credential, params);
54
+ if (res.code !== '0') {
55
+ throw new Error(`ModifyOrder failed: code=${res.code}, msg=${res.msg}`);
56
+ }
57
+ };
58
+ //# sourceMappingURL=modifyOrder.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"modifyOrder.js","sourceRoot":"","sources":["../../src/orders/modifyOrder.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,mBAAmB,EAAE,MAAM,QAAQ,CAAC;AAC1D,OAAO,EAAE,cAAc,EAAE,MAAM,YAAY,CAAC;AAC5C,OAAO,EAAE,kBAAkB,EAAE,MAAM,UAAU,CAAC;AAE9C,MAAM,CAAC,MAAM,WAAW,GAAG,KAAK,EAAE,UAAuB,EAAE,KAAa,EAAE,EAAE;IAC1E,MAAM,CAAC,QAAQ,EAAE,MAAM,CAAC,GAAG,UAAU,CAAC,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,SAAS,EAAE;QAC7B,MAAM,CAAC,KAAK,GAAG,KAAK,CAAC,KAAK,CAAC,QAAQ,EAAE,CAAC;KACvC;IAED,WAAW;IACX,IAAI,KAAK,CAAC,MAAM,KAAK,SAAS,EAAE;QAC9B,8BAA8B;QAC9B,IAAI,QAAQ,KAAK,MAAM,EAAE;YACvB,MAAM,CAAC,KAAK,GAAG,KAAK,CAAC,MAAM,CAAC,QAAQ,EAAE,CAAC;SACxC;aAAM,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U,EAAE;oBACf,MAAM,IAAI,KAAK,CAAC,oBAAoB,KAAK,CAAC,WAAW,EAAE,CAAC,CAAC;iBAC1D;gBACD,MAAM,CAAC,KAAK,GAAG,WAAW,CAAC,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,UAAU,CAAC,IAAI,CAAC,GAAG,EAAE,CAAC,EAAE,aAAa,EAAE,QAAQ,EAAE,IAAI,CAAC,SAAS,CAAC,MAAM,CAAC,CAAC,CAAC;IAEtF,MAAM,GAAG,GAAG,MAAM,mBAAmB,CAAC,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","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,107 @@
1
+ import { decodePath, formatTime, roundToStep } from '@yuants/utils';
2
+ import { firstValueFrom, map } from 'rxjs';
3
+ import { postTradeOrder } from '../api';
4
+ import { productService } from '../product';
5
+ import { spotMarketTickers$ } from '../quote';
6
+ const mapOrderDirectionToSide = (direction) => {
7
+ switch (direction) {
8
+ case 'OPEN_LONG':
9
+ case 'CLOSE_SHORT':
10
+ return 'buy';
11
+ case 'OPEN_SHORT':
12
+ case 'CLOSE_LONG':
13
+ return 'sell';
14
+ }
15
+ throw new Error(`Unknown direction: ${direction}`);
16
+ };
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
+ const mapOrderTypeToOrdType = (order_type) => {
29
+ switch (order_type) {
30
+ case 'LIMIT':
31
+ return 'limit';
32
+ case 'MARKET':
33
+ return 'market';
34
+ case 'MAKER':
35
+ return 'post_only';
36
+ }
37
+ throw new Error(`Unknown order type: ${order_type}`);
38
+ };
39
+ export const submitOrder = async (credential, order) => {
40
+ var _a, _b, _c;
41
+ const [instType, instId] = decodePath(order.product_id);
42
+ // 交易数量,表示要购买或者出售的数量。
43
+ // 当币币/币币杠杆以限价买入和卖出时,指交易货币数量。
44
+ // 当币币杠杆以市价买入时,指计价货币的数量。
45
+ // 当币币杠杆以市价卖出时,指交易货币的数量。
46
+ // 对于币币市价单,单位由 tgtCcy 决定
47
+ // 当交割、永续、期权买入和卖出时,指合约张数。
48
+ const mapOrderVolumeToSz = async (order) => {
49
+ if (instType === 'SWAP') {
50
+ return order.volume;
51
+ }
52
+ if (instType === 'MARGIN') {
53
+ if (order.order_type === 'LIMIT') {
54
+ return order.volume;
55
+ }
56
+ if (order.order_type === 'MAKER') {
57
+ return order.volume;
58
+ }
59
+ if (order.order_type === 'MARKET') {
60
+ if (order.order_direction === 'OPEN_SHORT' || order.order_direction === 'CLOSE_LONG') {
61
+ return order.volume;
62
+ }
63
+ //
64
+ const price = await firstValueFrom(spotMarketTickers$.pipe(map((x) => mapOrderDirectionToPosSide(order.order_direction) === 'long'
65
+ ? +x[instId].askPx
66
+ : +x[instId].bidPx)));
67
+ if (!price) {
68
+ throw new Error(`invalid tick: ${price}`);
69
+ }
70
+ console.info(formatTime(Date.now()), 'SubmitOrder', 'price', price);
71
+ const theProduct = await firstValueFrom(productService.mapProductIdToProduct$.pipe(map((x) => x.get(order.product_id))));
72
+ if (!theProduct) {
73
+ throw new Error(`Unknown product: ${order.position_id}`);
74
+ }
75
+ return roundToStep(order.volume * price, theProduct.volume_step);
76
+ }
77
+ return 0;
78
+ }
79
+ if (instType === 'SPOT') {
80
+ return order.volume;
81
+ }
82
+ throw new Error(`Unknown instType: ${instType}`);
83
+ };
84
+ const params = {
85
+ instId,
86
+ tdMode: instType === 'SPOT' ? 'cash' : 'cross',
87
+ side: mapOrderDirectionToSide(order.order_direction),
88
+ posSide: instType === 'MARGIN' || instType === 'SPOT'
89
+ ? 'net'
90
+ : mapOrderDirectionToPosSide(order.order_direction),
91
+ ordType: mapOrderTypeToOrdType(order.order_type),
92
+ sz: (await mapOrderVolumeToSz(order)).toString(),
93
+ 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 : '')
95
+ ? 'true'
96
+ : undefined,
97
+ px: order.order_type === 'LIMIT' || order.order_type === 'MAKER' ? order.price.toString() : undefined,
98
+ ccy: instType === 'MARGIN' ? 'USDT' : undefined,
99
+ };
100
+ console.info(formatTime(Date.now()), 'SubmitOrder', 'params', JSON.stringify(params));
101
+ const res = await postTradeOrder(credential, params);
102
+ if (res.code === '0' && ((_c = (_b = res.data) === null || _b === void 0 ? void 0 : _b[0]) === null || _c === void 0 ? void 0 : _c.ordId)) {
103
+ return res.data[0].ordId;
104
+ }
105
+ throw `Failed to submit order: ${res.code} ${res.msg}`;
106
+ };
107
+ //# sourceMappingURL=submitOrder.js.map
@@ -0,0 +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,QAAQ,CAAC;AACrD,OAAO,EAAE,cAAc,EAAE,MAAM,YAAY,CAAC;AAC5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AAC,CAAC,CAAC,KAAK,CAAC,KAAM,CAAC,QAAQ,EAAE,CAAC,CAAC,CAAC,SAAS;QACtG,GAAG,EAAE,QAAQ,KAAK,QAAQ,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,SAAS;KAChD,CAAC;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,GAAG,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC;KAC1B;IACD,MAAM,2BAA2B,GAAG,CAAC,IAAI,IAAI,GAAG,CAAC,GAAG,EAAE,CAAC;AACzD,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';\nimport { productService } from '../product';\nimport { spotMarketTickers$ } from '../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<string> => {\n const [instType, instId] = decodePath(order.product_id);\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 };\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 res.data[0].ordId;\n }\n throw `Failed to submit order: ${res.code} ${res.msg}`;\n};\n"]}
@@ -1,8 +1,8 @@
1
1
  import { addAccountMarket, provideAccountInfoService } from '@yuants/data-account';
2
2
  import { Terminal } from '@yuants/protocol';
3
- import { encodePath } from '@yuants/utils';
4
3
  import { defer, filter, first, firstValueFrom, map, repeat, retry, shareReplay } from 'rxjs';
5
- import { getAccountConfig, getDefaultCredential, getGridOrdersAlgoPending, getGridPositions } from './api';
4
+ import { getAccountConfig, getDefaultCredential, getGridPositions } from './api';
5
+ import { getStrategyAccountInfo } from './accountInfos';
6
6
  const terminal = Terminal.fromNodeEnv();
7
7
  const credential = getDefaultCredential();
8
8
  export const accountConfig$ = defer(() => getAccountConfig(credential)).pipe(repeat({ delay: 10000 }), retry({ delay: 10000 }), shareReplay(1));
@@ -29,63 +29,9 @@ defer(async () => {
29
29
  egress_token_capacity: 20,
30
30
  egress_token_refill_interval: 4000, // 每 4 秒恢复 20 个令牌 (双倍冗余限流)
31
31
  });
32
- provideAccountInfoService(terminal, strategyAccountId, async () => {
33
- // TODO: 需要分页获取所有的网格订单 (每页 100 条)
34
- const [gridAlgoOrders] = await Promise.all([
35
- getGridOrdersAlgoPending(credential, {
36
- algoOrdType: 'contract_grid',
37
- }),
38
- ]);
39
- let totalEquity = 0;
40
- const positions = [];
41
- const gridPositionsRes = await Promise.all(gridAlgoOrders.data.map((item) => terminal.client.requestForResponseData('OKX/QueryGridPositions', {
42
- account_id: strategyAccountId,
43
- algoId: item.algoId,
44
- })));
45
- gridPositionsRes.forEach((gridPositions, index) => {
46
- var _a, _b, _c, _d;
47
- let positionValuation = 0;
48
- const leverage = +((_a = gridAlgoOrders.data) === null || _a === void 0 ? void 0 : _a[index].actualLever);
49
- (_b = gridPositions === null || gridPositions === void 0 ? void 0 : gridPositions.data) === null || _b === void 0 ? void 0 : _b.forEach((position) => {
50
- var _a, _b, _c;
51
- if (+position.pos !== 0) {
52
- const directionRaw = (_c = (_b = (_a = gridAlgoOrders.data) === null || _a === void 0 ? void 0 : _a[index]) === null || _b === void 0 ? void 0 : _b.direction) !== null && _c !== void 0 ? _c : '';
53
- const direction = directionRaw ? directionRaw.toUpperCase() : 'LONG';
54
- positions.push({
55
- position_id: encodePath(position.algoId, position.instId),
56
- datasource_id: 'OKX',
57
- product_id: encodePath(position.instType, position.instId),
58
- direction,
59
- volume: Math.abs(+position.pos),
60
- free_volume: +position.pos,
61
- position_price: +position.avgPx,
62
- floating_profit: +position.upl,
63
- closable_price: +position.last,
64
- valuation: +position.notionalUsd,
65
- });
66
- positionValuation += +position.notionalUsd;
67
- }
68
- });
69
- if (leverage === 0) {
70
- // 实际杠杆为 0,说明没有持仓,直接把投资金额和累计盈亏算到净值里
71
- totalEquity += +((_c = gridAlgoOrders.data) === null || _c === void 0 ? void 0 : _c[index].investment) + +((_d = gridAlgoOrders.data) === null || _d === void 0 ? void 0 : _d[index].totalPnl);
72
- }
73
- else {
74
- // 历史提取金额不会从 investment, totalPnl 扣减
75
- // 计算净值需要通过仓位的名义价值和实际杠杆计算
76
- totalEquity += positionValuation / leverage;
77
- }
78
- });
79
- return {
80
- money: {
81
- currency: 'USDT',
82
- equity: totalEquity,
83
- // TODO: 累计策略的可提取资金作为 free
84
- free: 0,
85
- },
86
- positions,
87
- };
88
- }, { auto_refresh_interval: 5000 });
32
+ provideAccountInfoService(terminal, strategyAccountId, () => getStrategyAccountInfo(credential), {
33
+ auto_refresh_interval: 5000,
34
+ });
89
35
  }).subscribe();
90
36
  const sub = defer(() => accountUid$)
91
37
  .pipe(first())
@@ -1 +1 @@
1
- {"version":3,"file":"strategy-account.js","sourceRoot":"","sources":["../src/strategy-account.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,gBAAgB,EAAa,yBAAyB,EAAE,MAAM,sBAAsB,CAAC;AAC9F,OAAO,EAAE,QAAQ,EAAE,MAAM,kBAAkB,CAAC;AAC5C,OAAO,EAAE,UAAU,EAAE,MAAM,eAAe,CAAC;AAC3C,OAAO,EAAE,KAAK,EAAE,MAAM,EAAE,KAAK,EAAE,cAAc,EAAE,GAAG,EAAE,MAAM,EAAE,KAAK,EAAE,WAAW,EAAE,MAAM,MAAM,CAAC;AAC7F,OAAO,EAAE,gBAAgB,EAAE,oBAAoB,EAAE,wBAAwB,EAAE,gBAAgB,EAAE,MAAM,OAAO,CAAC;AAE3G,MAAM,QAAQ,GAAG,QAAQ,CAAC,WAAW,EAAE,CAAC;AACxC,MAAM,UAAU,GAAG,oBAAoB,EAAE,CAAC;AAE1C,MAAM,CAAC,MAAM,cAAc,GAAG,KAAK,CAAC,GAAG,EAAE,CAAC,gBAAgB,CAAC,UAAU,CAAC,CAAC,CAAC,IAAI,CAC1E,MAAM,CAAC,EAAE,KAAK,EAAE,KAAM,EAAE,CAAC,EACzB,KAAK,CAAC,EAAE,KAAK,EAAE,KAAM,EAAE,CAAC,EACxB,WAAW,CAAC,CAAC,CAAC,CACf,CAAC;AAEF,MAAM,CAAC,MAAM,WAAW,GAAG,cAAc,CAAC,IAAI,CAC5C,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,EACzB,MAAM,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC,EAClB,WAAW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E,CAAC,GAAG,CAAC,WAAW,EAAE,CAAC,CAAC","sourcesContent":["import { addAccountMarket, IPosition, provideAccountInfoService } from '@yuants/data-account';\nimport { Terminal } from '@yuants/protocol';\nimport { encodePath } from '@yuants/utils';\nimport { defer, filter, first, firstValueFrom, map, repeat, retry, shareReplay } from 'rxjs';\nimport { getAccountConfig, getDefaultCredential, getGridOrdersAlgoPending, getGridPositions } from './api';\n\nconst terminal = Terminal.fromNodeEnv();\nconst credential = getDefaultCredential();\n\nexport const accountConfig$ = defer(() => getAccountConfig(credential)).pipe(\n repeat({ delay: 10_000 }),\n retry({ delay: 10_000 }),\n shareReplay(1),\n);\n\nexport const accountUid$ = accountConfig$.pipe(\n map((x) => x.data[0].uid),\n filter((x) => !!x),\n shareReplay(1),\n);\n\nexport const strategyAccountId$ = accountUid$.pipe(\n map((uid) => `okx/${uid}/strategy`),\n shareReplay(1),\n);\n\ndefer(async () => {\n const strategyAccountId = await firstValueFrom(strategyAccountId$);\n\n type InferPromise<T> = T extends Promise<infer U> ? U : T;\n\n terminal.server.provideService<\n { account_id: string; algoId: string },\n InferPromise<ReturnType<typeof getGridPositions>>\n >(\n `OKX/QueryGridPositions`,\n {\n required: ['account_id', 'algoId'],\n properties: {\n account_id: { type: 'string', const: strategyAccountId },\n algoId: { type: 'string' },\n },\n },\n async (msg) => {\n //\n return {\n res: {\n code: 0,\n message: 'OK',\n data: await getGridPositions(credential, { algoOrdType: 'contract_grid', algoId: msg.req.algoId }),\n },\n };\n },\n {\n egress_token_capacity: 20,\n egress_token_refill_interval: 4000, // 每 4 秒恢复 20 个令牌 (双倍冗余限流)\n },\n );\n\n provideAccountInfoService(\n terminal,\n strategyAccountId,\n async () => {\n // TODO: 需要分页获取所有的网格订单 (每页 100 条)\n const [gridAlgoOrders] = await Promise.all([\n getGridOrdersAlgoPending(credential, {\n algoOrdType: 'contract_grid',\n }),\n ]);\n\n let totalEquity = 0;\n const positions: IPosition[] = [];\n\n const gridPositionsRes = await Promise.all(\n gridAlgoOrders.data.map((item) =>\n terminal.client.requestForResponseData<\n { account_id: string; algoId: string },\n InferPromise<ReturnType<typeof getGridPositions>>\n >('OKX/QueryGridPositions', {\n account_id: strategyAccountId,\n algoId: item.algoId,\n }),\n ),\n );\n\n gridPositionsRes.forEach((gridPositions, index) => {\n let positionValuation = 0;\n const leverage = +gridAlgoOrders.data?.[index].actualLever;\n gridPositions?.data?.forEach((position) => {\n if (+position.pos !== 0) {\n const directionRaw = gridAlgoOrders.data?.[index]?.direction ?? '';\n const direction = directionRaw ? directionRaw.toUpperCase() : 'LONG';\n positions.push({\n position_id: encodePath(position.algoId, position.instId),\n datasource_id: 'OKX',\n product_id: encodePath(position.instType, position.instId),\n direction,\n volume: Math.abs(+position.pos),\n free_volume: +position.pos,\n position_price: +position.avgPx,\n floating_profit: +position.upl,\n closable_price: +position.last,\n valuation: +position.notionalUsd,\n });\n positionValuation += +position.notionalUsd;\n }\n });\n if (leverage === 0) {\n // 实际杠杆为 0,说明没有持仓,直接把投资金额和累计盈亏算到净值里\n totalEquity += +gridAlgoOrders.data?.[index].investment + +gridAlgoOrders.data?.[index].totalPnl;\n } else {\n // 历史提取金额不会从 investment, totalPnl 扣减\n // 计算净值需要通过仓位的名义价值和实际杠杆计算\n totalEquity += positionValuation / leverage;\n }\n });\n\n return {\n money: {\n currency: 'USDT',\n equity: totalEquity,\n // TODO: 累计策略的可提取资金作为 free\n free: 0,\n },\n positions,\n };\n },\n { auto_refresh_interval: 5000 },\n );\n}).subscribe();\n\nconst sub = defer(() => accountUid$)\n .pipe(first())\n .subscribe((uid) => {\n addAccountMarket(terminal, { account_id: `okx/${uid}/strategy`, market_id: 'OKX' });\n });\ndefer(() => terminal.dispose$).subscribe(() => sub.unsubscribe());\n"]}
1
+ {"version":3,"file":"strategy-account.js","sourceRoot":"","sources":["../src/strategy-account.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,gBAAgB,EAAE,yBAAyB,EAAE,MAAM,sBAAsB,CAAC;AACnF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import { addAccountMarket, provideAccountInfoService } from '@yuants/data-account';\nimport { Terminal } from '@yuants/protocol';\nimport { defer, filter, first, firstValueFrom, map, repeat, retry, shareReplay } from 'rxjs';\nimport { getAccountConfig, getDefaultCredential, getGridPositions } from './api';\nimport { getStrategyAccountInfo } from './accountInfos';\n\nconst terminal = Terminal.fromNodeEnv();\nconst credential = getDefaultCredential();\n\nexport const accountConfig$ = defer(() => getAccountConfig(credential)).pipe(\n repeat({ delay: 10_000 }),\n retry({ delay: 10_000 }),\n shareReplay(1),\n);\n\nexport const accountUid$ = accountConfig$.pipe(\n map((x) => x.data[0].uid),\n filter((x) => !!x),\n shareReplay(1),\n);\n\nexport const strategyAccountId$ = accountUid$.pipe(\n map((uid) => `okx/${uid}/strategy`),\n shareReplay(1),\n);\n\ndefer(async () => {\n const strategyAccountId = await firstValueFrom(strategyAccountId$);\n\n type InferPromise<T> = T extends Promise<infer U> ? U : T;\n\n terminal.server.provideService<\n { account_id: string; algoId: string },\n InferPromise<ReturnType<typeof getGridPositions>>\n >(\n `OKX/QueryGridPositions`,\n {\n required: ['account_id', 'algoId'],\n properties: {\n account_id: { type: 'string', const: strategyAccountId },\n algoId: { type: 'string' },\n },\n },\n async (msg) => {\n //\n return {\n res: {\n code: 0,\n message: 'OK',\n data: await getGridPositions(credential, { algoOrdType: 'contract_grid', algoId: msg.req.algoId }),\n },\n };\n },\n {\n egress_token_capacity: 20,\n egress_token_refill_interval: 4000, // 每 4 秒恢复 20 个令牌 (双倍冗余限流)\n },\n );\n\n provideAccountInfoService(terminal, strategyAccountId, () => getStrategyAccountInfo(credential), {\n auto_refresh_interval: 5000,\n });\n}).subscribe();\n\nconst sub = defer(() => accountUid$)\n .pipe(first())\n .subscribe((uid) => {\n addAccountMarket(terminal, { account_id: `okx/${uid}/strategy`, market_id: 'OKX' });\n });\ndefer(() => terminal.dispose$).subscribe(() => sub.unsubscribe());\n"]}
package/lib/account.d.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import { marketIndexTickerUSDT$ } from './accountInfos';
1
2
  export declare const accountConfig$: import("rxjs").Observable<{
2
3
  code: string;
3
4
  data: {
@@ -26,4 +27,5 @@ export declare const accountConfig$: import("rxjs").Observable<{
26
27
  }>;
27
28
  export declare const accountUid$: import("rxjs").Observable<string>;
28
29
  export declare const tradingAccountId$: import("rxjs").Observable<string>;
30
+ export { marketIndexTickerUSDT$ };
29
31
  //# sourceMappingURL=account.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"account.d.ts","sourceRoot":"","sources":["../src/account.ts"],"names":[],"mappings":"AAsBA,eAAO,MAAM,cAAc;;;;;;;;;;;;;;;;;;;;;;;;;EAI1B,CAAC;AAQF,eAAO,MAAM,WAAW,mCAIvB,CAAC;AAmDF,eAAO,MAAM,iBAAiB,mCAG7B,CAAC"}
1
+ {"version":3,"file":"account.d.ts","sourceRoot":"","sources":["../src/account.ts"],"names":[],"mappings":"AAMA,OAAO,EAIL,sBAAsB,EACvB,MAAM,gBAAgB,CAAC;AAMxB,eAAO,MAAM,cAAc;;;;;;;;;;;;;;;;;;;;;;;;;EAI1B,CAAC;AAEF,eAAO,MAAM,WAAW,mCAIvB,CAAC;AAwCF,eAAO,MAAM,iBAAiB,mCAG7B,CAAC;AA8BF,OAAO,EAAE,sBAAsB,EAAE,CAAC"}