@yuants/vendor-okx 0.16.9 → 0.17.1

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 (90) hide show
  1. package/dist/account.js +198 -0
  2. package/dist/account.js.map +1 -0
  3. package/dist/api.js +463 -0
  4. package/dist/api.js.map +1 -0
  5. package/dist/cli.js +3 -0
  6. package/dist/cli.js.map +1 -0
  7. package/dist/cluster.js +80 -0
  8. package/dist/cluster.js.map +1 -0
  9. package/dist/extension.js +89 -0
  10. package/dist/extension.js.map +1 -0
  11. package/dist/index.js +7 -0
  12. package/dist/index.js.map +1 -0
  13. package/dist/interest_rate.js +133 -0
  14. package/dist/interest_rate.js.map +1 -0
  15. package/dist/legacy_index.js +554 -0
  16. package/dist/legacy_index.js.map +1 -0
  17. package/dist/logger.js +91 -0
  18. package/dist/logger.js.map +1 -0
  19. package/dist/ohlc.js +171 -0
  20. package/dist/ohlc.js.map +1 -0
  21. package/dist/order.js +96 -0
  22. package/dist/order.js.map +1 -0
  23. package/dist/product.js +85 -0
  24. package/dist/product.js.map +1 -0
  25. package/dist/quote.js +58 -0
  26. package/dist/quote.js.map +1 -0
  27. package/dist/vendor-okx.d.ts +1 -0
  28. package/dist/websocket.js +80 -0
  29. package/dist/websocket.js.map +1 -0
  30. package/lib/account.d.ts +102 -0
  31. package/lib/account.d.ts.map +1 -0
  32. package/lib/account.js +201 -0
  33. package/lib/account.js.map +1 -0
  34. package/lib/api.d.ts +1401 -0
  35. package/lib/api.d.ts.map +1 -0
  36. package/lib/api.js +470 -0
  37. package/lib/api.js.map +1 -0
  38. package/lib/cli.d.ts +3 -0
  39. package/lib/cli.d.ts.map +1 -0
  40. package/lib/cli.js +5 -0
  41. package/lib/cli.js.map +1 -0
  42. package/lib/cluster.d.ts +2 -0
  43. package/lib/cluster.d.ts.map +1 -0
  44. package/lib/cluster.js +108 -0
  45. package/lib/cluster.js.map +1 -0
  46. package/lib/extension.d.ts +4 -0
  47. package/lib/extension.d.ts.map +1 -0
  48. package/lib/extension.js +91 -0
  49. package/lib/extension.js.map +1 -0
  50. package/lib/index.d.ts +7 -0
  51. package/lib/index.d.ts.map +1 -0
  52. package/lib/index.js +9 -0
  53. package/lib/index.js.map +1 -0
  54. package/lib/interest_rate.d.ts +2 -0
  55. package/lib/interest_rate.d.ts.map +1 -0
  56. package/lib/interest_rate.js +135 -0
  57. package/lib/interest_rate.js.map +1 -0
  58. package/lib/legacy_index.d.ts +2 -0
  59. package/lib/legacy_index.d.ts.map +1 -0
  60. package/lib/legacy_index.js +556 -0
  61. package/lib/legacy_index.js.map +1 -0
  62. package/lib/logger.d.ts +21 -0
  63. package/lib/logger.d.ts.map +1 -0
  64. package/lib/logger.js +98 -0
  65. package/lib/logger.js.map +1 -0
  66. package/lib/ohlc.d.ts +2 -0
  67. package/lib/ohlc.d.ts.map +1 -0
  68. package/lib/ohlc.js +173 -0
  69. package/lib/ohlc.js.map +1 -0
  70. package/lib/order.d.ts +4 -0
  71. package/lib/order.d.ts.map +1 -0
  72. package/lib/order.js +99 -0
  73. package/lib/order.js.map +1 -0
  74. package/lib/product.d.ts +6 -0
  75. package/lib/product.d.ts.map +1 -0
  76. package/lib/product.js +88 -0
  77. package/lib/product.js.map +1 -0
  78. package/lib/quote.d.ts +42 -0
  79. package/lib/quote.d.ts.map +1 -0
  80. package/lib/quote.js +61 -0
  81. package/lib/quote.js.map +1 -0
  82. package/lib/websocket.d.ts +14 -0
  83. package/lib/websocket.d.ts.map +1 -0
  84. package/lib/websocket.js +83 -0
  85. package/lib/websocket.js.map +1 -0
  86. package/package.json +9 -4
  87. package/temp/image-tag +1 -0
  88. package/temp/package-deps.json +42 -0
  89. package/temp/vendor-okx.api.json +177 -0
  90. package/temp/vendor-okx.api.md +9 -0
@@ -0,0 +1,554 @@
1
+ import { Terminal } from '@yuants/protocol';
2
+ import { addAccountTransferAddress } from '@yuants/transfer';
3
+ import { decodePath, encodePath, formatTime, roundToStep } from '@yuants/utils';
4
+ import { defer, filter, firstValueFrom, from, map, mergeMap, repeat, retry, shareReplay } from 'rxjs';
5
+ import { accountConfig$, tradingAccountInfo$ } from './account';
6
+ import { client } from './api';
7
+ import { mapProductIdToMarginProduct$ } from './product';
8
+ import { spotMarketTickers$ } from './quote';
9
+ const terminal = Terminal.fromNodeEnv();
10
+ console.info(formatTime(Date.now()), 'Terminal', terminal.terminalInfo.terminal_id);
11
+ const resOfAssetCurrencies = defer(() => client.getAssetCurrencies()).pipe(repeat({ delay: 3600000 }), retry({ delay: 10000 }), shareReplay(1));
12
+ resOfAssetCurrencies.subscribe(); // make it hot
13
+ const memoizeMap = (fn) => {
14
+ const cache = {};
15
+ return ((...params) => { var _a; var _b; return ((_a = cache[_b = encodePath(params)]) !== null && _a !== void 0 ? _a : (cache[_b] = fn(...params))); });
16
+ };
17
+ const fundingRate$ = memoizeMap((product_id) => defer(() => client.getFundingRate({ instId: decodePath(product_id)[1] })).pipe(mergeMap((x) => x.data), repeat({ delay: 5000 }), retry({ delay: 5000 }), shareReplay(1)));
18
+ const interestRateLoanQuota$ = defer(() => client.getInterestRateLoanQuota()).pipe(repeat({ delay: 60000 }), retry({ delay: 60000 }), shareReplay(1));
19
+ const interestRateByCurrency$ = memoizeMap((currency) => interestRateLoanQuota$.pipe(mergeMap((x) => from(x.data || []).pipe(mergeMap((x) => x.basic), filter((x) => x.ccy === currency), map((x) => +x.rate))), shareReplay(1)));
20
+ // provideTicks(terminal, 'OKX', (product_id) => {
21
+ // const [instType, instId] = decodePath(product_id);
22
+ // if (instType === 'SWAP') {
23
+ // return defer(async () => {
24
+ // const products = await firstValueFrom(usdtSwapProducts$);
25
+ // const theProduct = products.find((x) => x.product_id === product_id);
26
+ // if (!theProduct) throw `No Found ProductID ${product_id}`;
27
+ // const theTicker$ = swapMarketTickers$.pipe(
28
+ // map((x) => x[instId]),
29
+ // shareReplay(1),
30
+ // );
31
+ // return [of(theProduct), theTicker$, fundingRate$(product_id), swapOpenInterest$] as const;
32
+ // }).pipe(
33
+ // catchError(() => EMPTY),
34
+ // mergeMap((x) =>
35
+ // combineLatest(x).pipe(
36
+ // map(([theProduct, ticker, fundingRate, swapOpenInterest]): ITick => {
37
+ // return {
38
+ // datasource_id: 'OKX',
39
+ // product_id,
40
+ // updated_at: Date.now(),
41
+ // settlement_scheduled_at: +fundingRate.fundingTime,
42
+ // price: +ticker.last,
43
+ // ask: +ticker.askPx,
44
+ // bid: +ticker.bidPx,
45
+ // volume: +ticker.lastSz,
46
+ // interest_rate_for_long: -+fundingRate.fundingRate,
47
+ // interest_rate_for_short: +fundingRate.fundingRate,
48
+ // open_interest: swapOpenInterest.get(instId),
49
+ // };
50
+ // }),
51
+ // ),
52
+ // ),
53
+ // );
54
+ // }
55
+ // if (instType === 'MARGIN') {
56
+ // return defer(async () => {
57
+ // const products = await firstValueFrom(marginProducts$);
58
+ // const theProduct = products.find((x) => x.product_id === product_id);
59
+ // if (!theProduct) throw `No Found ProductID ${product_id}`;
60
+ // const theTicker$ = spotMarketTickers$.pipe(
61
+ // map((x) => x[instId]),
62
+ // shareReplay(1),
63
+ // );
64
+ // return [
65
+ // of(theProduct),
66
+ // theTicker$,
67
+ // interestRateByCurrency$(theProduct.base_currency!),
68
+ // interestRateByCurrency$(theProduct.quote_currency!),
69
+ // ] as const;
70
+ // }).pipe(
71
+ // catchError(() => EMPTY),
72
+ // mergeMap((x) =>
73
+ // combineLatest(x).pipe(
74
+ // map(
75
+ // ([theProduct, ticker, interestRateForBase, interestRateForQuote]): ITick => ({
76
+ // datasource_id: 'OKX',
77
+ // product_id,
78
+ // updated_at: Date.now(),
79
+ // price: +ticker.last,
80
+ // volume: +ticker.lastSz,
81
+ // // 在下一个整点扣除利息 See 如何计算利息 https://www.okx.com/zh-hans/help/how-to-calculate-borrowing-interest
82
+ // settlement_scheduled_at: new Date().setMinutes(0, 0, 0) + 3600_000,
83
+ // interest_rate_for_long: -interestRateForQuote / 24,
84
+ // interest_rate_for_short: -interestRateForBase / 24,
85
+ // }),
86
+ // ),
87
+ // ),
88
+ // ),
89
+ // );
90
+ // }
91
+ // return EMPTY;
92
+ // });
93
+ defer(async () => {
94
+ const account_config = await firstValueFrom(accountConfig$);
95
+ console.info(formatTime(Date.now()), 'AccountConfig', JSON.stringify(account_config));
96
+ const { mainUid, uid } = account_config.data[0];
97
+ const isMainAccount = mainUid === uid;
98
+ const TRADING_ACCOUNT_ID = `okx/${uid}/trading`;
99
+ const FUNDING_ACCOUNT_ID = `okx/${uid}/funding/USDT`;
100
+ const EARNING_ACCOUNT_ID = `okx/${uid}/earning/USDT`;
101
+ // BLOCK_CHAIN: only available for main account
102
+ if (isMainAccount) {
103
+ const depositAddressRes = await client.getAssetDepositAddress({ ccy: 'USDT' });
104
+ console.info(formatTime(Date.now()), 'DepositAddress', JSON.stringify(depositAddressRes.data));
105
+ const addresses = depositAddressRes.data.filter((v) => v.chain === 'USDT-TRC20' && v.to === '6');
106
+ for (const address of addresses) {
107
+ addAccountTransferAddress({
108
+ terminal,
109
+ account_id: FUNDING_ACCOUNT_ID,
110
+ network_id: 'TRC20',
111
+ currency: 'USDT',
112
+ address: address.addr,
113
+ onApply: {
114
+ INIT: async (order) => {
115
+ var _a, _b;
116
+ if (!order.current_amount ||
117
+ order.current_amount < 3 // 最小提币额度
118
+ ) {
119
+ return { state: 'ERROR', message: 'Amount too small' };
120
+ }
121
+ const res = await firstValueFrom(resOfAssetCurrencies);
122
+ const theRes = (_a = res.data) === null || _a === void 0 ? void 0 : _a.find((x) => x.ccy === 'USDT' && x.chain === 'USDT-TRC20');
123
+ const _fee = theRes === null || theRes === void 0 ? void 0 : theRes.minFee;
124
+ if (!_fee)
125
+ return { state: 'ERROR', message: 'Currency Info not found, cannot get fee' };
126
+ const fee = +_fee;
127
+ const amt = Math.floor(order.current_amount - fee);
128
+ const transferResult = await client.postAssetWithdrawal({
129
+ amt: `${amt}`,
130
+ ccy: 'USDT',
131
+ chain: 'USDT-TRC20',
132
+ fee: `${fee}`,
133
+ dest: '4',
134
+ toAddr: order.current_rx_address,
135
+ });
136
+ if (transferResult.code !== '0') {
137
+ return { state: 'INIT', message: transferResult.msg };
138
+ }
139
+ const wdId = (_b = transferResult.data[0]) === null || _b === void 0 ? void 0 : _b.wdId;
140
+ return { state: 'AWAIT_TX_ID', context: wdId };
141
+ },
142
+ AWAIT_TX_ID: async (transferOrder) => {
143
+ var _a, _b;
144
+ const wdId = transferOrder.current_tx_context;
145
+ const withdrawalHistory = await client.getAssetWithdrawalHistory({ wdId });
146
+ const txId = (_b = (_a = withdrawalHistory.data) === null || _a === void 0 ? void 0 : _a[0]) === null || _b === void 0 ? void 0 : _b.txId;
147
+ if (!txId) {
148
+ return { state: 'AWAIT_TX_ID', context: wdId };
149
+ }
150
+ return { state: 'COMPLETE', transaction_id: txId };
151
+ },
152
+ },
153
+ onEval: async (transferOrder) => {
154
+ const checkResult = await client.getAssetDepositHistory({
155
+ ccy: 'USDT',
156
+ txId: transferOrder.current_transaction_id,
157
+ type: '4',
158
+ });
159
+ if (checkResult.code !== '0') {
160
+ return {
161
+ state: 'INIT',
162
+ };
163
+ }
164
+ if (checkResult.data[0].state !== '2') {
165
+ return { state: 'PENDING' };
166
+ }
167
+ const received_amount = +checkResult.data[0].amt;
168
+ return { state: 'COMPLETE', received_amount };
169
+ },
170
+ });
171
+ }
172
+ }
173
+ // Funding-Trading
174
+ {
175
+ const FUNDING_TRADING_NETWORK_ID = `OKX/${uid}/Funding-Trading`;
176
+ addAccountTransferAddress({
177
+ terminal,
178
+ account_id: FUNDING_ACCOUNT_ID,
179
+ network_id: FUNDING_TRADING_NETWORK_ID,
180
+ currency: 'USDT',
181
+ address: 'funding',
182
+ onApply: {
183
+ INIT: async (order) => {
184
+ const transferResult = await client.postAssetTransfer({
185
+ type: '0',
186
+ ccy: 'USDT',
187
+ amt: `${order.current_amount}`,
188
+ from: '6',
189
+ to: '18',
190
+ });
191
+ if (transferResult.code !== '0') {
192
+ return { state: 'INIT', message: transferResult.msg };
193
+ }
194
+ const transaction_id = transferResult.data[0].transId;
195
+ return { state: 'COMPLETE', transaction_id };
196
+ },
197
+ },
198
+ onEval: async (transferOrder) => {
199
+ return { state: 'COMPLETE', received_amount: transferOrder.current_amount };
200
+ },
201
+ });
202
+ addAccountTransferAddress({
203
+ terminal,
204
+ account_id: TRADING_ACCOUNT_ID,
205
+ network_id: FUNDING_TRADING_NETWORK_ID,
206
+ currency: 'USDT',
207
+ address: 'trading',
208
+ onApply: {
209
+ INIT: async (order) => {
210
+ const transferResult = await client.postAssetTransfer({
211
+ type: '0',
212
+ ccy: order.currency,
213
+ amt: `${order.current_amount}`,
214
+ from: '18',
215
+ to: '6',
216
+ });
217
+ if (transferResult.code !== '0') {
218
+ return { state: 'INIT', message: transferResult.msg };
219
+ }
220
+ const transaction_id = transferResult.data[0].transId;
221
+ return { state: 'COMPLETE', transaction_id };
222
+ },
223
+ },
224
+ onEval: async (transferOrder) => {
225
+ return { state: 'COMPLETE', received_amount: transferOrder.current_amount };
226
+ },
227
+ });
228
+ }
229
+ // Funding-Earning
230
+ {
231
+ const FUNDING_EARNING_NETWORK_ID = `OKX/${uid}/Funding-Earning`;
232
+ addAccountTransferAddress({
233
+ terminal,
234
+ account_id: FUNDING_ACCOUNT_ID,
235
+ network_id: FUNDING_EARNING_NETWORK_ID,
236
+ currency: 'USDT',
237
+ address: 'funding',
238
+ onApply: {
239
+ INIT: async (order) => {
240
+ const transferResult = await client.postFinanceSavingsPurchaseRedempt({
241
+ ccy: 'USDT',
242
+ amt: `${order.current_amount}`,
243
+ side: 'purchase',
244
+ rate: '0.01',
245
+ });
246
+ if (transferResult.code !== '0') {
247
+ return { state: 'INIT', message: transferResult.msg };
248
+ }
249
+ return { state: 'COMPLETE', transaction_id: 'ok' };
250
+ },
251
+ },
252
+ onEval: async (transferOrder) => {
253
+ return { state: 'COMPLETE', received_amount: transferOrder.current_amount };
254
+ },
255
+ });
256
+ addAccountTransferAddress({
257
+ terminal,
258
+ account_id: EARNING_ACCOUNT_ID,
259
+ network_id: FUNDING_EARNING_NETWORK_ID,
260
+ currency: 'USDT',
261
+ address: 'earning',
262
+ onApply: {
263
+ INIT: async (order) => {
264
+ const transferResult = await client.postFinanceSavingsPurchaseRedempt({
265
+ ccy: 'USDT',
266
+ amt: `${order.current_amount}`,
267
+ side: 'redempt',
268
+ rate: '0.01',
269
+ });
270
+ if (transferResult.code !== '0') {
271
+ return { state: 'INIT', message: transferResult.msg };
272
+ }
273
+ return { state: 'COMPLETE', transaction_id: 'ok' };
274
+ },
275
+ },
276
+ onEval: async (transferOrder) => {
277
+ return { state: 'COMPLETE', received_amount: transferOrder.current_amount };
278
+ },
279
+ });
280
+ }
281
+ // SubAccount
282
+ {
283
+ const getSubAccountNetworkId = (subUid) => `OKX/${mainUid}/SubAccount/${subUid}`;
284
+ if (isMainAccount) {
285
+ const subAcctsRes = await client.getSubAccountList();
286
+ for (const item of subAcctsRes.data || []) {
287
+ addAccountTransferAddress({
288
+ terminal,
289
+ account_id: FUNDING_ACCOUNT_ID,
290
+ network_id: getSubAccountNetworkId(item.uid),
291
+ currency: 'USDT',
292
+ address: 'main',
293
+ onApply: {
294
+ INIT: async (order) => {
295
+ const transferResult = await client.postAssetTransfer({
296
+ type: '1',
297
+ ccy: 'USDT',
298
+ amt: `${order.current_amount}`,
299
+ from: '6',
300
+ to: '6',
301
+ subAcct: item.subAcct,
302
+ });
303
+ if (transferResult.code !== '0') {
304
+ return { state: 'INIT', message: transferResult.msg };
305
+ }
306
+ const transaction_id = transferResult.data[0].transId;
307
+ return { state: 'COMPLETE', transaction_id };
308
+ },
309
+ },
310
+ onEval: async (order) => {
311
+ // ISSUE: OKX API Issue: transId is incorrect or transId does not match with ‘ type’
312
+ // const checkResult = await client.getAssetTransferState({ transId: order.current_transaction_id });
313
+ // const received_amount = checkResult?.data?.[0]?.amt;
314
+ // if (!received_amount) {
315
+ // return { state: 'INIT', message: checkResult.msg };
316
+ // }
317
+ // return { state: 'COMPLETE', received_amount: +received_amount };
318
+ return { state: 'COMPLETE', received_amount: order.current_amount };
319
+ },
320
+ });
321
+ }
322
+ }
323
+ // SubAccount API
324
+ else {
325
+ addAccountTransferAddress({
326
+ terminal,
327
+ account_id: FUNDING_ACCOUNT_ID,
328
+ network_id: getSubAccountNetworkId(uid),
329
+ currency: 'USDT',
330
+ address: 'sub',
331
+ onApply: {
332
+ INIT: async (order) => {
333
+ const transferResult = await client.postAssetTransfer({
334
+ type: '3',
335
+ ccy: 'USDT',
336
+ amt: `${order.current_amount}`,
337
+ from: '6',
338
+ to: '6',
339
+ });
340
+ if (transferResult.code !== '0') {
341
+ return { state: 'INIT', message: transferResult.msg };
342
+ }
343
+ const transaction_id = transferResult.data[0].transId;
344
+ return { state: 'COMPLETE', transaction_id };
345
+ },
346
+ },
347
+ onEval: async (order) => {
348
+ // ISSUE: OKX API Issue: transId is incorrect or transId does not match with ‘ type’
349
+ // const checkResult = await client.getAssetTransferState({ transId: order.current_transaction_id });
350
+ // const received_amount = checkResult?.data?.[0]?.amt;
351
+ // if (!received_amount) {
352
+ // return { state: 'INIT', message: checkResult.msg };
353
+ // }
354
+ // return { state: 'COMPLETE', received_amount: +received_amount };
355
+ return { state: 'COMPLETE', received_amount: order.current_amount };
356
+ },
357
+ });
358
+ }
359
+ }
360
+ }).subscribe();
361
+ defer(async () => {
362
+ const tradingAccountInfo = await firstValueFrom(tradingAccountInfo$);
363
+ terminal.provideService('SubmitOrder', {
364
+ required: ['account_id'],
365
+ properties: {
366
+ account_id: { const: tradingAccountInfo.account_id },
367
+ },
368
+ }, async (msg) => {
369
+ var _a, _b, _c;
370
+ console.info(formatTime(Date.now()), 'SubmitOrder', JSON.stringify(msg));
371
+ const order = msg.req;
372
+ const [instType, instId] = decodePath(order.product_id);
373
+ const mapOrderDirectionToSide = (direction) => {
374
+ switch (direction) {
375
+ case 'OPEN_LONG':
376
+ case 'CLOSE_SHORT':
377
+ return 'buy';
378
+ case 'OPEN_SHORT':
379
+ case 'CLOSE_LONG':
380
+ return 'sell';
381
+ }
382
+ throw new Error(`Unknown direction: ${direction}`);
383
+ };
384
+ const mapOrderDirectionToPosSide = (direction) => {
385
+ switch (direction) {
386
+ case 'OPEN_LONG':
387
+ case 'CLOSE_LONG':
388
+ return 'long';
389
+ case 'CLOSE_SHORT':
390
+ case 'OPEN_SHORT':
391
+ return 'short';
392
+ }
393
+ throw new Error(`Unknown direction: ${direction}`);
394
+ };
395
+ const mapOrderTypeToOrdType = (order_type) => {
396
+ switch (order_type) {
397
+ case 'LIMIT':
398
+ return 'limit';
399
+ case 'MARKET':
400
+ return 'market';
401
+ }
402
+ throw new Error(`Unknown order type: ${order_type}`);
403
+ };
404
+ // 交易数量,表示要购买或者出售的数量。
405
+ // 当币币/币币杠杆以限价买入和卖出时,指交易货币数量。
406
+ // 当币币杠杆以市价买入时,指计价货币的数量。
407
+ // 当币币杠杆以市价卖出时,指交易货币的数量。
408
+ // 对于币币市价单,单位由 tgtCcy 决定
409
+ // 当交割、永续、期权买入和卖出时,指合约张数。
410
+ const mapOrderVolumeToSz = async (order) => {
411
+ if (instType === 'SWAP') {
412
+ return order.volume;
413
+ }
414
+ if (instType === 'MARGIN') {
415
+ if (order.order_type === 'LIMIT') {
416
+ return order.volume;
417
+ }
418
+ if (order.order_type === 'MARKET') {
419
+ if (order.order_direction === 'OPEN_SHORT' || order.order_direction === 'CLOSE_LONG') {
420
+ return order.volume;
421
+ }
422
+ //
423
+ const price = await firstValueFrom(spotMarketTickers$.pipe(map((x) => mapOrderDirectionToPosSide(order.order_direction) === 'long'
424
+ ? +x[instId].askPx
425
+ : +x[instId].bidPx)));
426
+ if (!price) {
427
+ throw new Error(`invalid tick: ${price}`);
428
+ }
429
+ console.info(formatTime(Date.now()), 'SubmitOrder', 'price', price);
430
+ const theProduct = await firstValueFrom(mapProductIdToMarginProduct$.pipe(map((x) => x.get(order.product_id))));
431
+ if (!theProduct) {
432
+ throw new Error(`Unknown product: ${order.position_id}`);
433
+ }
434
+ return roundToStep(order.volume * price, theProduct.volume_step);
435
+ }
436
+ return 0;
437
+ }
438
+ if (instType === 'SPOT') {
439
+ return order.volume;
440
+ }
441
+ throw new Error(`Unknown instType: ${instType}`);
442
+ };
443
+ const params = {
444
+ instId,
445
+ tdMode: instType === 'SPOT' ? 'cash' : 'cross',
446
+ side: mapOrderDirectionToSide(order.order_direction),
447
+ posSide: instType === 'MARGIN' || instType === 'SPOT'
448
+ ? 'net'
449
+ : mapOrderDirectionToPosSide(order.order_direction),
450
+ ordType: mapOrderTypeToOrdType(order.order_type),
451
+ sz: (await mapOrderVolumeToSz(order)).toString(),
452
+ tgtCcy: instType === 'SPOT' && order.order_type === 'MARKET' ? 'base_ccy' : undefined,
453
+ reduceOnly: instType === 'MARGIN' && ['CLOSE_LONG', 'CLOSE_SHORT'].includes((_a = order.order_direction) !== null && _a !== void 0 ? _a : '')
454
+ ? 'true'
455
+ : undefined,
456
+ px: order.order_type === 'LIMIT' ? order.price.toString() : undefined,
457
+ ccy: instType === 'MARGIN' ? 'USDT' : undefined,
458
+ };
459
+ console.info(formatTime(Date.now()), 'SubmitOrder', 'params', JSON.stringify(params));
460
+ const res = await client.postTradeOrder(params);
461
+ if (res.code === '0' && ((_c = (_b = res.data) === null || _b === void 0 ? void 0 : _b[0]) === null || _c === void 0 ? void 0 : _c.ordId)) {
462
+ return {
463
+ res: {
464
+ code: 0,
465
+ message: 'OK',
466
+ data: {
467
+ order_id: res.data[0].ordId,
468
+ },
469
+ },
470
+ };
471
+ }
472
+ return { res: { code: +res.code, message: res.msg } };
473
+ });
474
+ terminal.provideService('ModifyOrder', {
475
+ required: ['account_id'],
476
+ properties: {
477
+ account_id: { const: tradingAccountInfo.account_id },
478
+ },
479
+ }, async (msg) => {
480
+ console.info(formatTime(Date.now()), 'ModifyOrder', JSON.stringify(msg));
481
+ const order = msg.req;
482
+ const [instType, instId] = decodePath(order.product_id);
483
+ const params = {
484
+ instId,
485
+ ordId: order.order_id, // 使用现有订单ID
486
+ };
487
+ // 如果需要修改价格
488
+ if (order.price !== undefined) {
489
+ params.newPx = order.price.toString();
490
+ }
491
+ // 如果需要修改数量
492
+ if (order.volume !== undefined) {
493
+ // 处理数量修改,类似于 SubmitOrder 中的逻辑
494
+ if (instType === 'SWAP') {
495
+ params.newSz = order.volume.toString();
496
+ }
497
+ else if (instType === 'SPOT') {
498
+ params.newSz = order.volume.toString();
499
+ }
500
+ else if (instType === 'MARGIN') {
501
+ if (order.order_type === 'LIMIT') {
502
+ params.newSz = order.volume.toString();
503
+ }
504
+ if (order.order_type === 'MARKET') {
505
+ // 对于市价单,可能需要根据当前价格计算新的数量
506
+ const price = await firstValueFrom(spotMarketTickers$.pipe(map((x) => order.order_direction === 'OPEN_LONG' || order.order_direction === 'CLOSE_SHORT'
507
+ ? +x[instId].askPx
508
+ : +x[instId].bidPx)));
509
+ if (!price) {
510
+ throw new Error(`invalid tick: ${price}`);
511
+ }
512
+ console.info(formatTime(Date.now()), 'ModifyOrder', 'price', price);
513
+ const theProduct = await firstValueFrom(mapProductIdToMarginProduct$.pipe(map((x) => x.get(order.product_id))));
514
+ if (!theProduct) {
515
+ throw new Error(`Unknown product: ${order.position_id}`);
516
+ }
517
+ params.newSz = roundToStep(order.volume * price, theProduct.volume_step).toString();
518
+ }
519
+ }
520
+ else {
521
+ throw new Error(`Unknown instType: ${instType}`);
522
+ }
523
+ }
524
+ console.info(formatTime(Date.now()), 'ModifyOrder', 'params', JSON.stringify(params));
525
+ const res = await client.postTradeAmendOrder(params);
526
+ if (res.code !== '0') {
527
+ return {
528
+ res: {
529
+ code: +res.code,
530
+ message: res.msg,
531
+ },
532
+ };
533
+ }
534
+ return { res: { code: 0, message: 'OK' } };
535
+ });
536
+ terminal.provideService('CancelOrder', {
537
+ required: ['account_id'],
538
+ properties: {
539
+ account_id: { const: tradingAccountInfo.account_id },
540
+ },
541
+ }, (msg) => defer(async () => {
542
+ const order = msg.req;
543
+ const [instType, instId] = decodePath(order.product_id);
544
+ const res = await client.postTradeCancelOrder({
545
+ instId,
546
+ ordId: order.order_id,
547
+ });
548
+ if (res.code !== '0') {
549
+ return { res: { code: +res.code, message: res.msg } };
550
+ }
551
+ return { res: { code: 0, message: 'OK' } };
552
+ }));
553
+ }).subscribe();
554
+ //# sourceMappingURL=legacy_index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"legacy_index.js","sourceRoot":"","sources":["../src/legacy_index.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,QAAQ,EAAE,MAAM,kBAAkB,CAAC;AAC5C,OAAO,EAAE,yBAAyB,EAAE,MAAM,kBAAkB,CAAC;AAC7D,OAAO,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC;AAChF,OAAO,EAAE,KAAK,EAAE,MAAM,EAAE,cAAc,EAAE,IAAI,EAAE,GAAG,EAAE,QAAQ,EAAE,MAAM,EAAE,KAAK,EAAE,WAAW,EAAE,MAAM,MAAM,CAAC;AACtG,OAAO,EAAE,cAAc,EAAE,mBAAmB,EAAE,MAAM,WAAW,CAAC;AAChE,OAAO,EAAE,MAAM,EAAE,MAAM,OAAO,CAAC;AAC/B,OAAO,EAAE,4BAA4B,EAAE,MAAM,WAAW,CAAC;AACzD,OAAO,EAAE,kBAAkB,EAAE,MAAM,SAAS,CAAC;AAE7C,MAAM,QAAQ,GAAG,QAAQ,CAAC,WAAW,EAAE,CAAC;AAExC,OAAO,CAAC,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC,GAAG,EAAE,CAAC,EAAE,UAAU,EAAE,QAAQ,CAAC,YAAY,CAAC,WAAW,CAAC,CAAC;AAEpF,MAAM,oBAAoB,GAAG,KAAK,CAAC,GAAG,EAAE,CAAC,MAAM,CAAC,kBAAkB,EAAE,CAAC,CAAC,IAAI,CACxE,MAAM,CAAC,EAAE,KAAK,EAAE,OAAQ,EAAE,CAAC,EAC3B,KAAK,CAAC,EAAE,KAAK,EAAE,KAAM,EAAE,CAAC,EACxB,WAAW,CAAC,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EAAE,GAAG,CAAC,GAAG;iBACjB;aACF,CAAC;SACH;QAED,OAAO,EAAE,GAAG,EAAE,EAAE,IAAI,EAAE,CAAC,EAAE,OAAO,EAAE,IAAI,EAAE,EAAE,CAAC;IAC7C,CAAC,CACF,CAAC;IAEF,QAAQ,CAAC,cAAc,CACrB,aAAa,EACb;QACE,QAAQ,EAAE,CAAC,YAAY,CAAC;QACxB,UAAU,EAAE;YACV,UAAU,EAAE,EAAE,KAAK,EAAE,kBAAkB,CAAC,UAAU,EAAE;SACrD;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,MAAM,CAAC,oBAAoB,CAAC;YAC5C,MAAM;YACN,KAAK,EAAE,KAAK,CAAC,QAAQ;SACtB,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 { addAccountTransferAddress } from '@yuants/transfer';\nimport { decodePath, encodePath, formatTime, roundToStep } from '@yuants/utils';\nimport { defer, filter, firstValueFrom, from, map, mergeMap, repeat, retry, shareReplay } from 'rxjs';\nimport { accountConfig$, tradingAccountInfo$ } from './account';\nimport { client } from './api';\nimport { mapProductIdToMarginProduct$ } from './product';\nimport { spotMarketTickers$ } from './quote';\n\nconst terminal = Terminal.fromNodeEnv();\n\nconsole.info(formatTime(Date.now()), 'Terminal', terminal.terminalInfo.terminal_id);\n\nconst resOfAssetCurrencies = defer(() => client.getAssetCurrencies()).pipe(\n repeat({ delay: 3600_000 }),\n retry({ delay: 10_000 }),\n shareReplay(1),\n);\n\nresOfAssetCurrencies.subscribe(); // make it hot\n\nconst memoizeMap = <T extends (...params: any[]) => any>(fn: T): T => {\n const cache: Record<string, any> = {};\n return ((...params: any[]) => (cache[encodePath(params)] ??= fn(...params))) as T;\n};\n\nconst fundingRate$ = memoizeMap((product_id: string) =>\n defer(() => client.getFundingRate({ instId: decodePath(product_id)[1] })).pipe(\n mergeMap((x) => x.data),\n repeat({ delay: 5000 }),\n retry({ delay: 5000 }),\n shareReplay(1),\n ),\n);\n\nconst interestRateLoanQuota$ = defer(() => client.getInterestRateLoanQuota()).pipe(\n repeat({ delay: 60_000 }),\n retry({ delay: 60_000 }),\n shareReplay(1),\n);\n\nconst interestRateByCurrency$ = memoizeMap((currency: string) =>\n interestRateLoanQuota$.pipe(\n mergeMap((x) =>\n from(x.data || []).pipe(\n mergeMap((x) => x.basic),\n filter((x) => x.ccy === currency),\n map((x) => +x.rate),\n ),\n ),\n shareReplay(1),\n ),\n);\n\n// provideTicks(terminal, 'OKX', (product_id) => {\n// const [instType, instId] = decodePath(product_id);\n// if (instType === 'SWAP') {\n// return defer(async () => {\n// const products = await firstValueFrom(usdtSwapProducts$);\n// const theProduct = products.find((x) => x.product_id === product_id);\n// if (!theProduct) throw `No Found ProductID ${product_id}`;\n// const theTicker$ = swapMarketTickers$.pipe(\n// map((x) => x[instId]),\n// shareReplay(1),\n// );\n// return [of(theProduct), theTicker$, fundingRate$(product_id), swapOpenInterest$] as const;\n// }).pipe(\n// catchError(() => EMPTY),\n// mergeMap((x) =>\n// combineLatest(x).pipe(\n// map(([theProduct, ticker, fundingRate, swapOpenInterest]): ITick => {\n// return {\n// datasource_id: 'OKX',\n// product_id,\n// updated_at: Date.now(),\n// settlement_scheduled_at: +fundingRate.fundingTime,\n// price: +ticker.last,\n// ask: +ticker.askPx,\n// bid: +ticker.bidPx,\n// volume: +ticker.lastSz,\n// interest_rate_for_long: -+fundingRate.fundingRate,\n// interest_rate_for_short: +fundingRate.fundingRate,\n// open_interest: swapOpenInterest.get(instId),\n// };\n// }),\n// ),\n// ),\n// );\n// }\n// if (instType === 'MARGIN') {\n// return defer(async () => {\n// const products = await firstValueFrom(marginProducts$);\n// const theProduct = products.find((x) => x.product_id === product_id);\n// if (!theProduct) throw `No Found ProductID ${product_id}`;\n// const theTicker$ = spotMarketTickers$.pipe(\n// map((x) => x[instId]),\n// shareReplay(1),\n// );\n// return [\n// of(theProduct),\n// theTicker$,\n// interestRateByCurrency$(theProduct.base_currency!),\n// interestRateByCurrency$(theProduct.quote_currency!),\n// ] as const;\n// }).pipe(\n// catchError(() => EMPTY),\n// mergeMap((x) =>\n// combineLatest(x).pipe(\n// map(\n// ([theProduct, ticker, interestRateForBase, interestRateForQuote]): ITick => ({\n// datasource_id: 'OKX',\n// product_id,\n// updated_at: Date.now(),\n// price: +ticker.last,\n// volume: +ticker.lastSz,\n// // 在下一个整点扣除利息 See 如何计算利息 https://www.okx.com/zh-hans/help/how-to-calculate-borrowing-interest\n// settlement_scheduled_at: new Date().setMinutes(0, 0, 0) + 3600_000,\n// interest_rate_for_long: -interestRateForQuote / 24,\n// interest_rate_for_short: -interestRateForBase / 24,\n// }),\n// ),\n// ),\n// ),\n// );\n// }\n// return EMPTY;\n// });\n\ndefer(async () => {\n const account_config = await firstValueFrom(accountConfig$);\n console.info(formatTime(Date.now()), 'AccountConfig', JSON.stringify(account_config));\n const { mainUid, uid } = account_config.data[0];\n const isMainAccount = mainUid === uid;\n\n const TRADING_ACCOUNT_ID = `okx/${uid}/trading`;\n const FUNDING_ACCOUNT_ID = `okx/${uid}/funding/USDT`;\n const EARNING_ACCOUNT_ID = `okx/${uid}/earning/USDT`;\n\n // BLOCK_CHAIN: only available for main account\n if (isMainAccount) {\n const depositAddressRes = await client.getAssetDepositAddress({ ccy: 'USDT' });\n console.info(formatTime(Date.now()), 'DepositAddress', JSON.stringify(depositAddressRes.data));\n const addresses = depositAddressRes.data.filter((v) => v.chain === 'USDT-TRC20' && v.to === '6');\n for (const address of addresses) {\n addAccountTransferAddress({\n terminal,\n account_id: FUNDING_ACCOUNT_ID,\n network_id: 'TRC20',\n currency: 'USDT',\n address: address.addr,\n onApply: {\n INIT: async (order) => {\n if (\n !order.current_amount ||\n order.current_amount < 3 // 最小提币额度\n ) {\n return { state: 'ERROR', message: 'Amount too small' };\n }\n const res = await firstValueFrom(resOfAssetCurrencies);\n const theRes = res.data?.find((x) => x.ccy === 'USDT' && x.chain === 'USDT-TRC20');\n const _fee = theRes?.minFee;\n if (!_fee) return { state: 'ERROR', message: 'Currency Info not found, cannot get fee' };\n const fee = +_fee;\n const amt = Math.floor(order.current_amount - fee);\n const transferResult = await client.postAssetWithdrawal({\n amt: `${amt}`,\n ccy: 'USDT',\n chain: 'USDT-TRC20',\n fee: `${fee}`,\n dest: '4', // 链上提币\n toAddr: order.current_rx_address!,\n });\n if (transferResult.code !== '0') {\n return { state: 'INIT', message: transferResult.msg };\n }\n const wdId = transferResult.data[0]?.wdId;\n return { state: 'AWAIT_TX_ID', context: wdId };\n },\n AWAIT_TX_ID: async (transferOrder) => {\n const wdId = transferOrder.current_tx_context;\n const withdrawalHistory = await client.getAssetWithdrawalHistory({ wdId });\n const txId = withdrawalHistory.data?.[0]?.txId;\n if (!txId) {\n return { state: 'AWAIT_TX_ID', context: wdId };\n }\n return { state: 'COMPLETE', transaction_id: txId };\n },\n },\n onEval: async (transferOrder) => {\n const checkResult = await client.getAssetDepositHistory({\n ccy: 'USDT',\n txId: transferOrder.current_transaction_id,\n type: '4',\n });\n\n if (checkResult.code !== '0') {\n return {\n state: 'INIT',\n };\n }\n\n if (checkResult.data[0].state !== '2') {\n return { state: 'PENDING' };\n }\n const received_amount = +checkResult.data[0].amt;\n return { state: 'COMPLETE', received_amount };\n },\n });\n }\n }\n\n // Funding-Trading\n {\n const FUNDING_TRADING_NETWORK_ID = `OKX/${uid}/Funding-Trading`;\n addAccountTransferAddress({\n terminal,\n account_id: FUNDING_ACCOUNT_ID,\n network_id: FUNDING_TRADING_NETWORK_ID,\n currency: 'USDT',\n address: 'funding',\n onApply: {\n INIT: async (order) => {\n const transferResult = await client.postAssetTransfer({\n type: '0',\n ccy: 'USDT',\n amt: `${order.current_amount}`,\n from: '6',\n to: '18',\n });\n if (transferResult.code !== '0') {\n return { state: 'INIT', message: transferResult.msg };\n }\n const transaction_id = transferResult.data[0].transId;\n return { state: 'COMPLETE', transaction_id };\n },\n },\n onEval: async (transferOrder) => {\n return { state: 'COMPLETE', received_amount: transferOrder.current_amount };\n },\n });\n addAccountTransferAddress({\n terminal,\n account_id: TRADING_ACCOUNT_ID,\n network_id: FUNDING_TRADING_NETWORK_ID,\n currency: 'USDT',\n address: 'trading',\n onApply: {\n INIT: async (order) => {\n const transferResult = await client.postAssetTransfer({\n type: '0',\n ccy: order.currency,\n amt: `${order.current_amount}`,\n from: '18',\n to: '6',\n });\n if (transferResult.code !== '0') {\n return { state: 'INIT', message: transferResult.msg };\n }\n const transaction_id = transferResult.data[0].transId;\n return { state: 'COMPLETE', transaction_id };\n },\n },\n onEval: async (transferOrder) => {\n return { state: 'COMPLETE', received_amount: transferOrder.current_amount };\n },\n });\n }\n // Funding-Earning\n {\n const FUNDING_EARNING_NETWORK_ID = `OKX/${uid}/Funding-Earning`;\n addAccountTransferAddress({\n terminal,\n account_id: FUNDING_ACCOUNT_ID,\n network_id: FUNDING_EARNING_NETWORK_ID,\n currency: 'USDT',\n address: 'funding',\n onApply: {\n INIT: async (order) => {\n const transferResult = await client.postFinanceSavingsPurchaseRedempt({\n ccy: 'USDT',\n amt: `${order.current_amount}`,\n side: 'purchase',\n rate: '0.01',\n });\n if (transferResult.code !== '0') {\n return { state: 'INIT', message: transferResult.msg };\n }\n return { state: 'COMPLETE', transaction_id: 'ok' };\n },\n },\n onEval: async (transferOrder) => {\n return { state: 'COMPLETE', received_amount: transferOrder.current_amount };\n },\n });\n addAccountTransferAddress({\n terminal,\n account_id: EARNING_ACCOUNT_ID,\n network_id: FUNDING_EARNING_NETWORK_ID,\n currency: 'USDT',\n address: 'earning',\n onApply: {\n INIT: async (order) => {\n const transferResult = await client.postFinanceSavingsPurchaseRedempt({\n ccy: 'USDT',\n amt: `${order.current_amount}`,\n side: 'redempt',\n rate: '0.01',\n });\n if (transferResult.code !== '0') {\n return { state: 'INIT', message: transferResult.msg };\n }\n return { state: 'COMPLETE', transaction_id: 'ok' };\n },\n },\n onEval: async (transferOrder) => {\n return { state: 'COMPLETE', received_amount: transferOrder.current_amount };\n },\n });\n }\n\n // SubAccount\n {\n const getSubAccountNetworkId = (subUid: string) => `OKX/${mainUid}/SubAccount/${subUid}`;\n if (isMainAccount) {\n const subAcctsRes = await client.getSubAccountList();\n for (const item of subAcctsRes.data || []) {\n addAccountTransferAddress({\n terminal,\n account_id: FUNDING_ACCOUNT_ID,\n network_id: getSubAccountNetworkId(item.uid),\n currency: 'USDT',\n address: 'main',\n onApply: {\n INIT: async (order) => {\n const transferResult = await client.postAssetTransfer({\n type: '1',\n ccy: 'USDT',\n amt: `${order.current_amount}`,\n from: '6',\n to: '6',\n subAcct: item.subAcct,\n });\n if (transferResult.code !== '0') {\n return { state: 'INIT', message: transferResult.msg };\n }\n const transaction_id = transferResult.data[0].transId;\n return { state: 'COMPLETE', transaction_id };\n },\n },\n onEval: async (order) => {\n // ISSUE: OKX API Issue: transId is incorrect or transId does not match with ‘ type’\n // const checkResult = await client.getAssetTransferState({ transId: order.current_transaction_id });\n // const received_amount = checkResult?.data?.[0]?.amt;\n // if (!received_amount) {\n // return { state: 'INIT', message: checkResult.msg };\n // }\n // return { state: 'COMPLETE', received_amount: +received_amount };\n\n return { state: 'COMPLETE', received_amount: order.current_amount };\n },\n });\n }\n }\n // SubAccount API\n else {\n addAccountTransferAddress({\n terminal,\n account_id: FUNDING_ACCOUNT_ID,\n network_id: getSubAccountNetworkId(uid),\n currency: 'USDT',\n address: 'sub',\n onApply: {\n INIT: async (order) => {\n const transferResult = await client.postAssetTransfer({\n type: '3',\n ccy: 'USDT',\n amt: `${order.current_amount}`,\n from: '6',\n to: '6',\n });\n if (transferResult.code !== '0') {\n return { state: 'INIT', message: transferResult.msg };\n }\n const transaction_id = transferResult.data[0].transId;\n return { state: 'COMPLETE', transaction_id };\n },\n },\n onEval: async (order) => {\n // ISSUE: OKX API Issue: transId is incorrect or transId does not match with ‘ type’\n // const checkResult = await client.getAssetTransferState({ transId: order.current_transaction_id });\n // const received_amount = checkResult?.data?.[0]?.amt;\n // if (!received_amount) {\n // return { state: 'INIT', message: checkResult.msg };\n // }\n // return { state: 'COMPLETE', received_amount: +received_amount };\n return { state: 'COMPLETE', received_amount: order.current_amount };\n },\n });\n }\n }\n}).subscribe();\n\ndefer(async () => {\n const tradingAccountInfo = await firstValueFrom(tradingAccountInfo$);\n terminal.provideService(\n 'SubmitOrder',\n {\n required: ['account_id'],\n properties: {\n account_id: { const: tradingAccountInfo.account_id },\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 }\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 === '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 mapProductIdToMarginProduct$.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.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 client.postTradeOrder(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.provideService(\n 'ModifyOrder',\n {\n required: ['account_id'],\n properties: {\n account_id: { const: tradingAccountInfo.account_id },\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: any = {\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 === '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 mapProductIdToMarginProduct$.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 client.postTradeAmendOrder(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.provideService(\n 'CancelOrder',\n {\n required: ['account_id'],\n properties: {\n account_id: { const: tradingAccountInfo.account_id },\n },\n },\n (msg) =>\n defer(async () => {\n const order = msg.req;\n const [instType, instId] = decodePath(order.product_id);\n const res = await client.postTradeCancelOrder({\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"]}