@yuants/vendor-okx 0.23.24 → 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 (139) hide show
  1. package/dist/account.js +16 -138
  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/api.js +444 -402
  18. package/dist/api.js.map +1 -1
  19. package/dist/index.js +5 -4
  20. package/dist/index.js.map +1 -1
  21. package/dist/loan-account.js +4 -45
  22. package/dist/loan-account.js.map +1 -1
  23. package/dist/market-order.js +1 -1
  24. package/dist/market-order.js.map +1 -1
  25. package/dist/order-actions.js +39 -0
  26. package/dist/order-actions.js.map +1 -0
  27. package/dist/order.js +3 -3
  28. package/dist/order.js.map +1 -1
  29. package/dist/orders/cancelOrder.js +13 -0
  30. package/dist/orders/cancelOrder.js.map +1 -0
  31. package/dist/orders/modifyOrder.js +58 -0
  32. package/dist/orders/modifyOrder.js.map +1 -0
  33. package/dist/orders/submitOrder.js +107 -0
  34. package/dist/orders/submitOrder.js.map +1 -0
  35. package/dist/public-api.js.map +1 -1
  36. package/dist/quote.js.map +1 -1
  37. package/dist/services.js +3 -2
  38. package/dist/services.js.map +1 -1
  39. package/dist/strategy-account.js +8 -61
  40. package/dist/strategy-account.js.map +1 -1
  41. package/dist/trade.js +6 -5
  42. package/dist/trade.js.map +1 -1
  43. package/dist/transfer.js +279 -0
  44. package/dist/transfer.js.map +1 -0
  45. package/dist/websocket.js.map +1 -1
  46. package/lib/account.d.ts +4 -2
  47. package/lib/account.d.ts.map +1 -1
  48. package/lib/account.js +15 -138
  49. package/lib/account.js.map +1 -1
  50. package/lib/accountInfos/earning.d.ts +4 -0
  51. package/lib/accountInfos/earning.d.ts.map +1 -0
  52. package/lib/accountInfos/earning.js +19 -0
  53. package/lib/accountInfos/earning.js.map +1 -0
  54. package/lib/accountInfos/funding.d.ts +4 -0
  55. package/lib/accountInfos/funding.d.ts.map +1 -0
  56. package/lib/accountInfos/funding.js +50 -0
  57. package/lib/accountInfos/funding.js.map +1 -0
  58. package/lib/accountInfos/index.d.ts +8 -0
  59. package/lib/accountInfos/index.d.ts.map +1 -0
  60. package/lib/accountInfos/index.js +16 -0
  61. package/lib/accountInfos/index.js.map +1 -0
  62. package/lib/accountInfos/loan.d.ts +4 -0
  63. package/lib/accountInfos/loan.d.ts.map +1 -0
  64. package/lib/accountInfos/loan.js +50 -0
  65. package/lib/accountInfos/loan.js.map +1 -0
  66. package/lib/accountInfos/strategy.d.ts +4 -0
  67. package/lib/accountInfos/strategy.d.ts.map +1 -0
  68. package/lib/accountInfos/strategy.js +60 -0
  69. package/lib/accountInfos/strategy.js.map +1 -0
  70. package/lib/accountInfos/trading.d.ts +5 -0
  71. package/lib/accountInfos/trading.d.ts.map +1 -0
  72. package/lib/accountInfos/trading.js +88 -0
  73. package/lib/accountInfos/trading.js.map +1 -0
  74. package/lib/accountInfos/types.d.ts +6 -0
  75. package/lib/accountInfos/types.d.ts.map +1 -0
  76. package/lib/accountInfos/types.js +3 -0
  77. package/lib/accountInfos/types.js.map +1 -0
  78. package/lib/api.d.ts +1252 -1264
  79. package/lib/api.d.ts.map +1 -1
  80. package/lib/api.js +477 -404
  81. package/lib/api.js.map +1 -1
  82. package/lib/index.d.ts +5 -4
  83. package/lib/index.d.ts.map +1 -1
  84. package/lib/index.js +5 -4
  85. package/lib/index.js.map +1 -1
  86. package/lib/loan-account.js +3 -44
  87. package/lib/loan-account.js.map +1 -1
  88. package/lib/market-order.d.ts.map +1 -1
  89. package/lib/market-order.js +1 -1
  90. package/lib/market-order.js.map +1 -1
  91. package/lib/order-actions.d.ts +2 -0
  92. package/lib/order-actions.d.ts.map +1 -0
  93. package/lib/order-actions.js +41 -0
  94. package/lib/order-actions.js.map +1 -0
  95. package/lib/order.js +2 -2
  96. package/lib/order.js.map +1 -1
  97. package/lib/orders/cancelOrder.d.ts +4 -0
  98. package/lib/orders/cancelOrder.d.ts.map +1 -0
  99. package/lib/orders/cancelOrder.js +17 -0
  100. package/lib/orders/cancelOrder.js.map +1 -0
  101. package/lib/orders/modifyOrder.d.ts +4 -0
  102. package/lib/orders/modifyOrder.d.ts.map +1 -0
  103. package/lib/orders/modifyOrder.js +62 -0
  104. package/lib/orders/modifyOrder.js.map +1 -0
  105. package/lib/orders/submitOrder.d.ts +4 -0
  106. package/lib/orders/submitOrder.d.ts.map +1 -0
  107. package/lib/orders/submitOrder.js +111 -0
  108. package/lib/orders/submitOrder.js.map +1 -0
  109. package/lib/public-api.js.map +1 -1
  110. package/lib/quote.d.ts +1 -1
  111. package/lib/quote.d.ts.map +1 -1
  112. package/lib/quote.js.map +1 -1
  113. package/lib/services.js +2 -1
  114. package/lib/services.js.map +1 -1
  115. package/lib/strategy-account.d.ts +2 -2
  116. package/lib/strategy-account.d.ts.map +1 -1
  117. package/lib/strategy-account.js +7 -60
  118. package/lib/strategy-account.js.map +1 -1
  119. package/lib/trade.js +6 -5
  120. package/lib/trade.js.map +1 -1
  121. package/lib/transfer.d.ts +2 -0
  122. package/lib/transfer.d.ts.map +1 -0
  123. package/lib/transfer.js +281 -0
  124. package/lib/transfer.js.map +1 -0
  125. package/lib/websocket.js.map +1 -1
  126. package/package.json +13 -12
  127. package/temp/package-deps.json +40 -29
  128. package/dist/legacy_index.js +0 -563
  129. package/dist/legacy_index.js.map +0 -1
  130. package/dist/logger.js +0 -91
  131. package/dist/logger.js.map +0 -1
  132. package/lib/legacy_index.d.ts +0 -2
  133. package/lib/legacy_index.d.ts.map +0 -1
  134. package/lib/legacy_index.js +0 -565
  135. package/lib/legacy_index.js.map +0 -1
  136. package/lib/logger.d.ts +0 -21
  137. package/lib/logger.d.ts.map +0 -1
  138. package/lib/logger.js +0 -98
  139. package/lib/logger.js.map +0 -1
@@ -0,0 +1,62 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.modifyOrder = void 0;
4
+ const utils_1 = require("@yuants/utils");
5
+ const rxjs_1 = require("rxjs");
6
+ const api_1 = require("../api");
7
+ const product_1 = require("../product");
8
+ const quote_1 = require("../quote");
9
+ const modifyOrder = async (credential, order) => {
10
+ const [instType, instId] = (0, utils_1.decodePath)(order.product_id);
11
+ const params = {
12
+ instId,
13
+ ordId: order.order_id, // 使用现有订单ID
14
+ };
15
+ // 如果需要修改价格
16
+ if (order.price !== undefined) {
17
+ params.newPx = order.price.toString();
18
+ }
19
+ // 如果需要修改数量
20
+ if (order.volume !== undefined) {
21
+ // 处理数量修改,类似于 SubmitOrder 中的逻辑
22
+ if (instType === 'SWAP') {
23
+ params.newSz = order.volume.toString();
24
+ }
25
+ else if (instType === 'SPOT') {
26
+ params.newSz = order.volume.toString();
27
+ }
28
+ else if (instType === 'MARGIN') {
29
+ if (order.order_type === 'LIMIT') {
30
+ params.newSz = order.volume.toString();
31
+ }
32
+ if (order.order_type === 'MAKER') {
33
+ params.newSz = order.volume.toString();
34
+ }
35
+ if (order.order_type === 'MARKET') {
36
+ // 对于市价单,可能需要根据当前价格计算新的数量
37
+ const price = await (0, rxjs_1.firstValueFrom)(quote_1.spotMarketTickers$.pipe((0, rxjs_1.map)((x) => order.order_direction === 'OPEN_LONG' || order.order_direction === 'CLOSE_SHORT'
38
+ ? +x[instId].askPx
39
+ : +x[instId].bidPx)));
40
+ if (!price) {
41
+ throw new Error(`invalid tick: ${price}`);
42
+ }
43
+ console.info((0, utils_1.formatTime)(Date.now()), 'ModifyOrder', 'price', price);
44
+ const theProduct = await (0, rxjs_1.firstValueFrom)(product_1.productService.mapProductIdToProduct$.pipe((0, rxjs_1.map)((x) => x.get(order.product_id))));
45
+ if (!theProduct) {
46
+ throw new Error(`Unknown product: ${order.position_id}`);
47
+ }
48
+ params.newSz = (0, utils_1.roundToStep)(order.volume * price, theProduct.volume_step).toString();
49
+ }
50
+ }
51
+ else {
52
+ throw new Error(`Unknown instType: ${instType}`);
53
+ }
54
+ }
55
+ console.info((0, utils_1.formatTime)(Date.now()), 'ModifyOrder', 'params', JSON.stringify(params));
56
+ const res = await (0, api_1.postTradeAmendOrder)(credential, params);
57
+ if (res.code !== '0') {
58
+ throw new Error(`ModifyOrder failed: code=${res.code}, msg=${res.msg}`);
59
+ }
60
+ };
61
+ exports.modifyOrder = modifyOrder;
62
+ //# sourceMappingURL=modifyOrder.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"modifyOrder.js","sourceRoot":"","sources":["../../src/orders/modifyOrder.ts"],"names":[],"mappings":";;;AACA,yCAAoE;AACpE,+BAA2C;AAC3C,gCAA0D;AAC1D,wCAA4C;AAC5C,oCAA8C;AAEvC,MAAM,WAAW,GAAG,KAAK,EAAE,UAAuB,EAAE,KAAa,EAAE,EAAE;IAC1E,MAAM,CAAC,QAAQ,EAAE,MAAM,CAAC,GAAG,IAAA,kBAAU,EAAC,KAAK,CAAC,UAAU,CAAC,CAAC;IACxD,MAAM,MAAM,GAKR;QACF,MAAM;QACN,KAAK,EAAE,KAAK,CAAC,QAAS,EAAE,WAAW;KACpC,CAAC;IAEF,WAAW;IACX,IAAI,KAAK,CAAC,KAAK,KAAK,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,IA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,CAAC,IAAA,UAAG,EAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,GAAG,CAAC,KAAK,CAAC,UAAU,CAAC,CAAC,CAAC,CAChF,CAAC;gBACF,IAAI,CAAC,UAAU,EAAE;oBACf,MAAM,IAAI,KAAK,CAAC,oBAAoB,KAAK,CAAC,WAAW,EAAE,CAAC,CAAC;iBAC1D;gBACD,MAAM,CAAC,KAAK,GAAG,IAAA,mBAAW,EAAC,KAAK,CAAC,MAAM,GAAG,KAAK,EAAE,UAAU,CAAC,WAAY,CAAC,CAAC,QAAQ,EAAE,CAAC;aACtF;SACF;aAAM;YACL,MAAM,IAAI,KAAK,CAAC,qBAAqB,QAAQ,EAAE,CAAC,CAAC;SAClD;KACF;IAED,OAAO,CAAC,IAAI,CAAC,IAAA,kBAAU,EAAC,IAAI,CAAC,GAAG,EAAE,CAAC,EAAE,aAAa,EAAE,QAAQ,EAAE,IAAI,CAAC,SAAS,CAAC,MAAM,CAAC,CAAC,CAAC;IAEtF,MAAM,GAAG,GAAG,MAAM,IAAA,yBAAmB,EAAC,UAAU,EAAE,MAAM,CAAC,CAAC;IAC1D,IAAI,GAAG,CAAC,IAAI,KAAK,GAAG,EAAE;QACpB,MAAM,IAAI,KAAK,CAAC,4BAA4B,GAAG,CAAC,IAAI,SAAS,GAAG,CAAC,GAAG,EAAE,CAAC,CAAC;KACzE;AACH,CAAC,CAAC;AAjEW,QAAA,WAAW,eAiEtB","sourcesContent":["import { IOrder } from '@yuants/data-order';\nimport { formatTime, decodePath, roundToStep } from '@yuants/utils';\nimport { firstValueFrom, map } from 'rxjs';\nimport { ICredential, postTradeAmendOrder } from '../api';\nimport { productService } from '../product';\nimport { spotMarketTickers$ } from '../quote';\n\nexport const modifyOrder = async (credential: ICredential, order: IOrder) => {\n const [instType, instId] = decodePath(order.product_id);\n const params: {\n instId: string;\n ordId: string;\n newPx?: string;\n newSz?: string;\n } = {\n instId,\n ordId: order.order_id!, // 使用现有订单ID\n };\n\n // 如果需要修改价格\n if (order.price !== undefined) {\n params.newPx = order.price.toString();\n }\n\n // 如果需要修改数量\n if (order.volume !== undefined) {\n // 处理数量修改,类似于 SubmitOrder 中的逻辑\n if (instType === 'SWAP') {\n params.newSz = order.volume.toString();\n } else if (instType === 'SPOT') {\n params.newSz = order.volume.toString();\n } else if (instType === 'MARGIN') {\n if (order.order_type === 'LIMIT') {\n params.newSz = order.volume.toString();\n }\n if (order.order_type === 'MAKER') {\n params.newSz = order.volume.toString();\n }\n if (order.order_type === 'MARKET') {\n // 对于市价单,可能需要根据当前价格计算新的数量\n const price = await firstValueFrom(\n spotMarketTickers$.pipe(\n map((x) =>\n order.order_direction === 'OPEN_LONG' || order.order_direction === 'CLOSE_SHORT'\n ? +x[instId].askPx\n : +x[instId].bidPx,\n ),\n ),\n );\n if (!price) {\n throw new Error(`invalid tick: ${price}`);\n }\n console.info(formatTime(Date.now()), 'ModifyOrder', 'price', price);\n const theProduct = await firstValueFrom(\n productService.mapProductIdToProduct$.pipe(map((x) => x.get(order.product_id))),\n );\n if (!theProduct) {\n throw new Error(`Unknown product: ${order.position_id}`);\n }\n params.newSz = roundToStep(order.volume * price, theProduct.volume_step!).toString();\n }\n } else {\n throw new Error(`Unknown instType: ${instType}`);\n }\n }\n\n console.info(formatTime(Date.now()), 'ModifyOrder', 'params', JSON.stringify(params));\n\n const res = await postTradeAmendOrder(credential, params);\n if (res.code !== '0') {\n throw new Error(`ModifyOrder failed: code=${res.code}, msg=${res.msg}`);\n }\n};\n"]}
@@ -0,0 +1,4 @@
1
+ import { IOrder } from '@yuants/data-order';
2
+ import { ICredential } from '../api';
3
+ export declare const submitOrder: (credential: ICredential, order: IOrder) => Promise<string>;
4
+ //# sourceMappingURL=submitOrder.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"submitOrder.d.ts","sourceRoot":"","sources":["../../src/orders/submitOrder.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,oBAAoB,CAAC;AAG5C,OAAO,EAAE,WAAW,EAAkB,MAAM,QAAQ,CAAC;AAwCrD,eAAO,MAAM,WAAW,eAAsB,WAAW,SAAS,MAAM,KAAG,QAAQ,MAAM,CAiFxF,CAAC"}
@@ -0,0 +1,111 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.submitOrder = void 0;
4
+ const utils_1 = require("@yuants/utils");
5
+ const rxjs_1 = require("rxjs");
6
+ const api_1 = require("../api");
7
+ const product_1 = require("../product");
8
+ const quote_1 = require("../quote");
9
+ const mapOrderDirectionToSide = (direction) => {
10
+ switch (direction) {
11
+ case 'OPEN_LONG':
12
+ case 'CLOSE_SHORT':
13
+ return 'buy';
14
+ case 'OPEN_SHORT':
15
+ case 'CLOSE_LONG':
16
+ return 'sell';
17
+ }
18
+ throw new Error(`Unknown direction: ${direction}`);
19
+ };
20
+ const mapOrderDirectionToPosSide = (direction) => {
21
+ switch (direction) {
22
+ case 'OPEN_LONG':
23
+ case 'CLOSE_LONG':
24
+ return 'long';
25
+ case 'CLOSE_SHORT':
26
+ case 'OPEN_SHORT':
27
+ return 'short';
28
+ }
29
+ throw new Error(`Unknown direction: ${direction}`);
30
+ };
31
+ const mapOrderTypeToOrdType = (order_type) => {
32
+ switch (order_type) {
33
+ case 'LIMIT':
34
+ return 'limit';
35
+ case 'MARKET':
36
+ return 'market';
37
+ case 'MAKER':
38
+ return 'post_only';
39
+ }
40
+ throw new Error(`Unknown order type: ${order_type}`);
41
+ };
42
+ const submitOrder = async (credential, order) => {
43
+ var _a, _b, _c;
44
+ const [instType, instId] = (0, utils_1.decodePath)(order.product_id);
45
+ // 交易数量,表示要购买或者出售的数量。
46
+ // 当币币/币币杠杆以限价买入和卖出时,指交易货币数量。
47
+ // 当币币杠杆以市价买入时,指计价货币的数量。
48
+ // 当币币杠杆以市价卖出时,指交易货币的数量。
49
+ // 对于币币市价单,单位由 tgtCcy 决定
50
+ // 当交割、永续、期权买入和卖出时,指合约张数。
51
+ const mapOrderVolumeToSz = async (order) => {
52
+ if (instType === 'SWAP') {
53
+ return order.volume;
54
+ }
55
+ if (instType === 'MARGIN') {
56
+ if (order.order_type === 'LIMIT') {
57
+ return order.volume;
58
+ }
59
+ if (order.order_type === 'MAKER') {
60
+ return order.volume;
61
+ }
62
+ if (order.order_type === 'MARKET') {
63
+ if (order.order_direction === 'OPEN_SHORT' || order.order_direction === 'CLOSE_LONG') {
64
+ return order.volume;
65
+ }
66
+ //
67
+ const price = await (0, rxjs_1.firstValueFrom)(quote_1.spotMarketTickers$.pipe((0, rxjs_1.map)((x) => mapOrderDirectionToPosSide(order.order_direction) === 'long'
68
+ ? +x[instId].askPx
69
+ : +x[instId].bidPx)));
70
+ if (!price) {
71
+ throw new Error(`invalid tick: ${price}`);
72
+ }
73
+ console.info((0, utils_1.formatTime)(Date.now()), 'SubmitOrder', 'price', price);
74
+ const theProduct = await (0, rxjs_1.firstValueFrom)(product_1.productService.mapProductIdToProduct$.pipe((0, rxjs_1.map)((x) => x.get(order.product_id))));
75
+ if (!theProduct) {
76
+ throw new Error(`Unknown product: ${order.position_id}`);
77
+ }
78
+ return (0, utils_1.roundToStep)(order.volume * price, theProduct.volume_step);
79
+ }
80
+ return 0;
81
+ }
82
+ if (instType === 'SPOT') {
83
+ return order.volume;
84
+ }
85
+ throw new Error(`Unknown instType: ${instType}`);
86
+ };
87
+ const params = {
88
+ instId,
89
+ tdMode: instType === 'SPOT' ? 'cash' : 'cross',
90
+ side: mapOrderDirectionToSide(order.order_direction),
91
+ posSide: instType === 'MARGIN' || instType === 'SPOT'
92
+ ? 'net'
93
+ : mapOrderDirectionToPosSide(order.order_direction),
94
+ ordType: mapOrderTypeToOrdType(order.order_type),
95
+ sz: (await mapOrderVolumeToSz(order)).toString(),
96
+ tgtCcy: instType === 'SPOT' && order.order_type === 'MARKET' ? 'base_ccy' : undefined,
97
+ reduceOnly: instType === 'MARGIN' && ['CLOSE_LONG', 'CLOSE_SHORT'].includes((_a = order.order_direction) !== null && _a !== void 0 ? _a : '')
98
+ ? 'true'
99
+ : undefined,
100
+ px: order.order_type === 'LIMIT' || order.order_type === 'MAKER' ? order.price.toString() : undefined,
101
+ ccy: instType === 'MARGIN' ? 'USDT' : undefined,
102
+ };
103
+ console.info((0, utils_1.formatTime)(Date.now()), 'SubmitOrder', 'params', JSON.stringify(params));
104
+ const res = await (0, api_1.postTradeOrder)(credential, params);
105
+ if (res.code === '0' && ((_c = (_b = res.data) === null || _b === void 0 ? void 0 : _b[0]) === null || _c === void 0 ? void 0 : _c.ordId)) {
106
+ return res.data[0].ordId;
107
+ }
108
+ throw `Failed to submit order: ${res.code} ${res.msg}`;
109
+ };
110
+ exports.submitOrder = submitOrder;
111
+ //# sourceMappingURL=submitOrder.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"submitOrder.js","sourceRoot":"","sources":["../../src/orders/submitOrder.ts"],"names":[],"mappings":";;;AACA,yCAAoE;AACpE,+BAA2C;AAC3C,gCAAqD;AACrD,wCAA4C;AAC5C,oCAA8C;AAE9C,MAAM,uBAAuB,GAAG,CAAC,SAAkB,EAAE,EAAE;IACrD,QAAQ,SAAS,EAAE;QACjB,KAAK,WAAW,CAAC;QACjB,KAAK,aAAa;YAChB,OAAO,KAAK,CAAC;QACf,KAAK,YAAY,CAAC;QAClB,KAAK,YAAY;YACf,OAAO,MAAM,CAAC;KACjB;IACD,MAAM,IAAI,KAAK,CAAC,sBAAsB,SAAS,EAAE,CAAC,CAAC;AACrD,CAAC,CAAC;AAEF,MAAM,0BAA0B,GAAG,CAAC,SAAkB,EAAE,EAAE;IACxD,QAAQ,SAAS,EAAE;QACjB,KAAK,WAAW,CAAC;QACjB,KAAK,YAAY;YACf,OAAO,MAAM,CAAC;QAChB,KAAK,aAAa,CAAC;QACnB,KAAK,YAAY;YACf,OAAO,OAAO,CAAC;KAClB;IACD,MAAM,IAAI,KAAK,CAAC,sBAAsB,SAAS,EAAE,CAAC,CAAC;AACrD,CAAC,CAAC;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K,CAAC;KAC1B;IACD,MAAM,2BAA2B,GAAG,CAAC,IAAI,IAAI,GAAG,CAAC,GAAG,EAAE,CAAC;AACzD,CAAC,CAAC;AAjFW,QAAA,WAAW,eAiFtB","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 +1 @@
1
- {"version":3,"file":"public-api.js","sourceRoot":"","sources":["../src/public-api.ts"],"names":[],"mappings":";;;A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AAM,gBAAgB,GAAG,CAAC,MAQhC,EAiBE,EAAE,CAAC,aAAa,CAAC,KAAK,EAAE,+BAA+B,EAAE,MAAM,CAAC,CAAC;AAzBvD,QAAA,gBAAgB,oBAyBuC","sourcesContent":["import { formatTime } from '@yuants/utils';\n\n/**\n * 基础公共请求函数\n */\nasync function publicRequest(method: string, path: string, params?: any) {\n const url = new URL('https://www.okx.com');\n url.pathname = path;\n if (method === 'GET') {\n for (const key in params) {\n url.searchParams.set(key, params[key]);\n }\n }\n\n console.info(formatTime(Date.now()), method, url.href);\n const res = await fetch(url.href, { method });\n return res.json();\n}\n\n/**\n * 获取所有产品行情信息\n *\n * 获取产品行情信息\n *\n * 限速:20次/2s\n * 限速规则:IP\n *\n * https://www.okx.com/docs-v5/zh/#order-book-trading-market-data-get-tickers\n */\nexport const getMarketTickers = (params: {\n instType: string;\n uly?: string;\n instFamily?: string;\n}): Promise<{\n code: string;\n msg: string;\n data: Array<{\n instType: string;\n instId: string;\n last: string;\n lastSz: string;\n askPx: string;\n askSz: string;\n bidPx: string;\n bidSz: string;\n open24h: string;\n high24h: string;\n low24h: string;\n volCcy24h: string;\n vol24h: string;\n sodUtc0: string;\n sodUtc8: string;\n ts: string;\n }>;\n}> => publicRequest('GET', '/api/v5/market/tickers', params);\n\n/**\n * 获取交易产品基础信息\n *\n * 获取所有可交易产品的信息列表。\n *\n * 限速:20次/2s\n * 限速规则:IP +instType\n *\n * https://www.okx.com/docs-v5/zh/#public-data-rest-api-get-instruments\n */\nexport const getInstruments = (params: {\n instType: string;\n uly?: string;\n instFamily?: string;\n instId?: string;\n}): Promise<{\n code: string;\n msg: string;\n data: Array<{\n alias: string;\n baseCcy: string;\n category: string;\n ctMult: string;\n ctType: string;\n ctVal: string;\n ctValCcy: string;\n expTime: string;\n instFamily: string;\n instId: string;\n instType: string;\n lever: string;\n listTime: string;\n lotSz: string;\n maxIcebergSz: string;\n maxLmtAmt: string;\n maxLmtSz: string;\n maxMktAmt: string;\n maxMktSz: string;\n maxStopSz: string;\n maxTriggerSz: string;\n maxTwapSz: string;\n minSz: string;\n optType: string;\n quoteCcy: string;\n settleCcy: string;\n state: string;\n stk: string;\n tickSz: string;\n uly: string;\n }>;\n}> => publicRequest('GET', '/api/v5/public/instruments', params);\n\n/**\n * 获取永续合约当前资金费率\n *\n * 获取当前资金费率\n *\n * 限速:20次/2s\n * 限速规则:IP +instrumentID\n *\n * https://www.okx.com/docs-v5/zh/#public-data-rest-api-get-funding-rate\n */\nexport const getFundingRate = (params: {\n instId: string;\n}): Promise<{\n code: string;\n data: Array<{\n fundingRate: string;\n fundingTime: string;\n instId: string;\n instType: string;\n method: string;\n maxFundingRate: string;\n minFundingRate: string;\n nextFundingRate: string;\n nextFundingTime: string;\n premium: string;\n settFundingRate: string;\n settState: string;\n ts: string;\n }>;\n msg: string;\n}> => publicRequest('GET', '/api/v5/public/funding-rate', params);\n\n/**\n * 获取永续合约历史资金费率\n *\n * 获取最近3个月的历史资金费率\n *\n * 限速:10次/2s\n * 限速规则:IP +instrumentID\n *\n * https://www.okx.com/docs-v5/zh/#public-data-rest-api-get-funding-rate-history\n */\nexport const getFundingRateHistory = (params: {\n instId: string;\n before?: string;\n after?: string;\n limit?: string;\n}): Promise<{\n code: string;\n msg: string;\n data: Array<{\n fundingRate: string;\n fundingTime: string;\n instId: string;\n instType: string;\n method: string;\n realizedRate: string;\n }>;\n}> => publicRequest('GET', '/api/v5/public/funding-rate-history', params);\n\n/**\n * 获取标记价格历史K线数据\n *\n * 获取最近几年的标记价格K线数据\n *\n * 限速:10次/2s\n * 限速规则:IP\n *\n * https://www.okx.com/docs-v5/zh/#public-data-rest-api-get-mark-price-candlesticks-history\n */\nexport const getHistoryMarkPriceCandles = (params: {\n instId: string;\n bar?: string;\n after?: string;\n before?: string;\n limit?: string;\n}): Promise<{\n code: string;\n msg: string;\n data: Array<[ts: string, o: string, h: string, l: string, c: string, confirm: string]>;\n}> => publicRequest('GET', '/api/v5/market/history-mark-price-candles', params);\n\n/**\n * 获取交易产品历史K线数据\n *\n * 获取最近几年的历史k线数据(1s k线支持查询最近3个月的数据)\n *\n * 限速:20次/2s\n * 限速规则:IP\n *\n * 期权不支持 1s K线, 其他业务线 (币币, 杠杆, 交割和永续)支持\n *\n * https://www.okx.com/docs-v5/zh/#order-book-trading-market-data-get-candlesticks-history\n */\nexport const getHistoryCandles = (params: {\n instId: string;\n bar?: string;\n after?: string;\n before?: string;\n limit?: string;\n}): Promise<{\n code: string;\n msg: string;\n data: Array<\n [\n ts: string,\n o: string,\n h: string,\n l: string,\n c: string,\n vol: string,\n volCcy: string,\n volCcyQuote: string,\n confirm: string,\n ]\n >;\n}> => publicRequest('GET', '/api/v5/market/history-candles', params);\n\n/**\n * 获取持仓总量\n *\n * 查询单个交易产品的市场的持仓总量\n *\n * 限速:20次/2s\n * 限速规则:IP + instrumentID\n *\n * https://www.okx.com/docs-v5/zh/#public-data-rest-api-get-open-interest\n */\nexport const getOpenInterest = (params: {\n instType: string;\n uly?: string;\n instFamily?: string;\n instId?: string;\n}): Promise<{\n code: string;\n msg: string;\n data: {\n instType: string;\n instId: string;\n oi: string;\n oiCcy: string;\n ts: string;\n }[];\n}> => publicRequest('GET', '/api/v5/public/open-interest', params);\n\n/**\n * 获取市场借币杠杆利率和借币限额\n *\n * 限速:2次/2s\n * 限速规则:IP\n *\n * https://www.okx.com/docs-v5/zh/#public-data-rest-api-get-interest-rate-and-loan-quota\n */\nexport const getInterestRateLoanQuota = (): Promise<{\n code: string;\n data?: Array<{\n basic: Array<{\n ccy: string;\n rate: string;\n quota: string;\n }>;\n vip: Array<{\n loanQuotaCoef: string;\n level: string;\n }>;\n regular: Array<{\n loanQuotaCoef: string;\n level: string;\n }>;\n }>;\n}> => publicRequest('GET', '/api/v5/public/interest-rate-loan-quota');\n\n/**\n * 获取市场借贷历史(公共)\n *\n * 公共接口无须鉴权\n *\n * 返回2021年12月14日后的记录\n *\n * 限速:6次/s\n * 限速规则:IP\n *\n * https://www.okx.com/docs-v5/zh/#financial-product-savings-get-public-borrow-history-public\n */\nexport const getLendingRateHistory = (params: {\n ccy?: string;\n after?: string;\n before?: string;\n limit?: string;\n}): Promise<{\n code: string;\n msg: string;\n data: Array<{\n ccy: string;\n amt: string;\n rate: string;\n ts: string;\n }>;\n}> => publicRequest('GET', '/api/v5/finance/savings/lending-rate-history', params);\n\n/**\n * 获取指数行情数据\n *\n * 限速:20次/2s\n *\n * https://www.okx.com/docs-v5/zh/#public-data-rest-api-get-index-tickers\n */\nexport const getMarketIndexTicker = (params?: {\n quoteCcy?: string;\n instId?: string;\n}): Promise<{\n code: string;\n msg: string;\n data: {\n instId: string;\n idxPx: string;\n high24h: string;\n sodUtc0: string;\n open24h: string;\n low24h: string;\n sodUtc8: string;\n ts: string;\n }[];\n}> => publicRequest('GET', '/api/v5/market/index-tickers', params);\n\n/**\n * 获取产品深度\n *\n * 限速:40次/2s\n * 限速规则:IP\n *\n * https://www.okx.com/docs-v5/zh/#order-book-trading-market-data-get-order-book\n */\nexport const getMarketBooks = (params: {\n sz?: string;\n instId: string;\n}): Promise<{\n code: string;\n data: {\n asks: [price: string, volume: string, abandon: string, order_number: string][];\n bids: [price: string, volume: string, abandon: string, order_number: string][];\n ts: string;\n }[];\n msg: string;\n}> => publicRequest('GET', '/api/v5/market/books', params);\n\n/**\n * 获取衍生品仓位档位\n *\n * 获取全部仓位档位对应信息\n *\n * 限速:10次/2s\n * 限速规则:IP\n *\n * https://www.okx.com/docs-v5/zh/#public-data-rest-api-get-position-tiers\n */\nexport const getPositionTiers = (params: {\n instType: string;\n tdMode: string;\n instFamily?: string;\n instId?: string;\n uly?: string;\n ccy?: string;\n tier?: string;\n}): Promise<{\n code: string;\n msg: string;\n data: Array<{\n uly: string;\n instFamily: string;\n instId: string;\n tier: string;\n minSz: string;\n maxSz: string;\n mmr: string;\n imr: string;\n maxLever: string;\n optMgnFactor: string;\n quoteMaxLoan: string;\n baseMaxLoan: string;\n }>;\n}> => publicRequest('GET', '/api/v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AAE,sBAAsB,EAAE,MAAM,CAAC,CAAC;AAX9C,QAAA,cAAc,kBAWgC;AAE3D;;;;;;;;;GASG;AACI,MAAM,gBAAgB,GAAG,CAAC,MAQhC,EAiBE,EAAE,CAAC,aAAa,CAAC,KAAK,EAAE,+BAA+B,EAAE,MAAM,CAAC,CAAC;AAzBvD,QAAA,gBAAgB,oBAyBuC","sourcesContent":["import { formatTime } from '@yuants/utils';\n\n/**\n * 基础公共请求函数\n */\nasync function publicRequest(method: string, path: string, params?: Record<string, string>) {\n const url = new URL('https://www.okx.com');\n url.pathname = path;\n if (method === 'GET') {\n for (const key in params) {\n url.searchParams.set(key, params[key]);\n }\n }\n\n console.info(formatTime(Date.now()), method, url.href);\n const res = await fetch(url.href, { method });\n return res.json();\n}\n\n/**\n * 获取所有产品行情信息\n *\n * 获取产品行情信息\n *\n * 限速:20次/2s\n * 限速规则:IP\n *\n * https://www.okx.com/docs-v5/zh/#order-book-trading-market-data-get-tickers\n */\nexport const getMarketTickers = (params: {\n instType: string;\n uly?: string;\n instFamily?: string;\n}): Promise<{\n code: string;\n msg: string;\n data: Array<{\n instType: string;\n instId: string;\n last: string;\n lastSz: string;\n askPx: string;\n askSz: string;\n bidPx: string;\n bidSz: string;\n open24h: string;\n high24h: string;\n low24h: string;\n volCcy24h: string;\n vol24h: string;\n sodUtc0: string;\n sodUtc8: string;\n ts: string;\n }>;\n}> => publicRequest('GET', '/api/v5/market/tickers', params);\n\n/**\n * 获取交易产品基础信息\n *\n * 获取所有可交易产品的信息列表。\n *\n * 限速:20次/2s\n * 限速规则:IP +instType\n *\n * https://www.okx.com/docs-v5/zh/#public-data-rest-api-get-instruments\n */\nexport const getInstruments = (params: {\n instType: string;\n uly?: string;\n instFamily?: string;\n instId?: string;\n}): Promise<{\n code: string;\n msg: string;\n data: Array<{\n alias: string;\n baseCcy: string;\n category: string;\n ctMult: string;\n ctType: string;\n ctVal: string;\n ctValCcy: string;\n expTime: string;\n instFamily: string;\n instId: string;\n instType: string;\n lever: string;\n listTime: string;\n lotSz: string;\n maxIcebergSz: string;\n maxLmtAmt: string;\n maxLmtSz: string;\n maxMktAmt: string;\n maxMktSz: string;\n maxStopSz: string;\n maxTriggerSz: string;\n maxTwapSz: string;\n minSz: string;\n optType: string;\n quoteCcy: string;\n settleCcy: string;\n state: string;\n stk: string;\n tickSz: string;\n uly: string;\n }>;\n}> => publicRequest('GET', '/api/v5/public/instruments', params);\n\n/**\n * 获取永续合约当前资金费率\n *\n * 获取当前资金费率\n *\n * 限速:20次/2s\n * 限速规则:IP +instrumentID\n *\n * https://www.okx.com/docs-v5/zh/#public-data-rest-api-get-funding-rate\n */\nexport const getFundingRate = (params: {\n instId: string;\n}): Promise<{\n code: string;\n data: Array<{\n fundingRate: string;\n fundingTime: string;\n instId: string;\n instType: string;\n method: string;\n maxFundingRate: string;\n minFundingRate: string;\n nextFundingRate: string;\n nextFundingTime: string;\n premium: string;\n settFundingRate: string;\n settState: string;\n ts: string;\n }>;\n msg: string;\n}> => publicRequest('GET', '/api/v5/public/funding-rate', params);\n\n/**\n * 获取永续合约历史资金费率\n *\n * 获取最近3个月的历史资金费率\n *\n * 限速:10次/2s\n * 限速规则:IP +instrumentID\n *\n * https://www.okx.com/docs-v5/zh/#public-data-rest-api-get-funding-rate-history\n */\nexport const getFundingRateHistory = (params: {\n instId: string;\n before?: string;\n after?: string;\n limit?: string;\n}): Promise<{\n code: string;\n msg: string;\n data: Array<{\n fundingRate: string;\n fundingTime: string;\n instId: string;\n instType: string;\n method: string;\n realizedRate: string;\n }>;\n}> => publicRequest('GET', '/api/v5/public/funding-rate-history', params);\n\n/**\n * 获取标记价格历史K线数据\n *\n * 获取最近几年的标记价格K线数据\n *\n * 限速:10次/2s\n * 限速规则:IP\n *\n * https://www.okx.com/docs-v5/zh/#public-data-rest-api-get-mark-price-candlesticks-history\n */\nexport const getHistoryMarkPriceCandles = (params: {\n instId: string;\n bar?: string;\n after?: string;\n before?: string;\n limit?: string;\n}): Promise<{\n code: string;\n msg: string;\n data: Array<[ts: string, o: string, h: string, l: string, c: string, confirm: string]>;\n}> => publicRequest('GET', '/api/v5/market/history-mark-price-candles', params);\n\n/**\n * 获取交易产品历史K线数据\n *\n * 获取最近几年的历史k线数据(1s k线支持查询最近3个月的数据)\n *\n * 限速:20次/2s\n * 限速规则:IP\n *\n * 期权不支持 1s K线, 其他业务线 (币币, 杠杆, 交割和永续)支持\n *\n * https://www.okx.com/docs-v5/zh/#order-book-trading-market-data-get-candlesticks-history\n */\nexport const getHistoryCandles = (params: {\n instId: string;\n bar?: string;\n after?: string;\n before?: string;\n limit?: string;\n}): Promise<{\n code: string;\n msg: string;\n data: Array<\n [\n ts: string,\n o: string,\n h: string,\n l: string,\n c: string,\n vol: string,\n volCcy: string,\n volCcyQuote: string,\n confirm: string,\n ]\n >;\n}> => publicRequest('GET', '/api/v5/market/history-candles', params);\n\n/**\n * 获取持仓总量\n *\n * 查询单个交易产品的市场的持仓总量\n *\n * 限速:20次/2s\n * 限速规则:IP + instrumentID\n *\n * https://www.okx.com/docs-v5/zh/#public-data-rest-api-get-open-interest\n */\nexport const getOpenInterest = (params: {\n instType: string;\n uly?: string;\n instFamily?: string;\n instId?: string;\n}): Promise<{\n code: string;\n msg: string;\n data: {\n instType: string;\n instId: string;\n oi: string;\n oiCcy: string;\n ts: string;\n }[];\n}> => publicRequest('GET', '/api/v5/public/open-interest', params);\n\n/**\n * 获取市场借币杠杆利率和借币限额\n *\n * 限速:2次/2s\n * 限速规则:IP\n *\n * https://www.okx.com/docs-v5/zh/#public-data-rest-api-get-interest-rate-and-loan-quota\n */\nexport const getInterestRateLoanQuota = (): Promise<{\n code: string;\n data?: Array<{\n basic: Array<{\n ccy: string;\n rate: string;\n quota: string;\n }>;\n vip: Array<{\n loanQuotaCoef: string;\n level: string;\n }>;\n regular: Array<{\n loanQuotaCoef: string;\n level: string;\n }>;\n }>;\n}> => publicRequest('GET', '/api/v5/public/interest-rate-loan-quota');\n\n/**\n * 获取市场借贷历史(公共)\n *\n * 公共接口无须鉴权\n *\n * 返回2021年12月14日后的记录\n *\n * 限速:6次/s\n * 限速规则:IP\n *\n * https://www.okx.com/docs-v5/zh/#financial-product-savings-get-public-borrow-history-public\n */\nexport const getLendingRateHistory = (params: {\n ccy?: string;\n after?: string;\n before?: string;\n limit?: string;\n}): Promise<{\n code: string;\n msg: string;\n data: Array<{\n ccy: string;\n amt: string;\n rate: string;\n ts: string;\n }>;\n}> => publicRequest('GET', '/api/v5/finance/savings/lending-rate-history', params);\n\n/**\n * 获取指数行情数据\n *\n * 限速:20次/2s\n *\n * https://www.okx.com/docs-v5/zh/#public-data-rest-api-get-index-tickers\n */\nexport const getMarketIndexTicker = (params?: {\n quoteCcy?: string;\n instId?: string;\n}): Promise<{\n code: string;\n msg: string;\n data: {\n instId: string;\n idxPx: string;\n high24h: string;\n sodUtc0: string;\n open24h: string;\n low24h: string;\n sodUtc8: string;\n ts: string;\n }[];\n}> => publicRequest('GET', '/api/v5/market/index-tickers', params);\n\n/**\n * 获取产品深度\n *\n * 限速:40次/2s\n * 限速规则:IP\n *\n * https://www.okx.com/docs-v5/zh/#order-book-trading-market-data-get-order-book\n */\nexport const getMarketBooks = (params: {\n sz?: string;\n instId: string;\n}): Promise<{\n code: string;\n data: {\n asks: [price: string, volume: string, abandon: string, order_number: string][];\n bids: [price: string, volume: string, abandon: string, order_number: string][];\n ts: string;\n }[];\n msg: string;\n}> => publicRequest('GET', '/api/v5/market/books', params);\n\n/**\n * 获取衍生品仓位档位\n *\n * 获取全部仓位档位对应信息\n *\n * 限速:10次/2s\n * 限速规则:IP\n *\n * https://www.okx.com/docs-v5/zh/#public-data-rest-api-get-position-tiers\n */\nexport const getPositionTiers = (params: {\n instType: string;\n tdMode: string;\n instFamily?: string;\n instId?: string;\n uly?: string;\n ccy?: string;\n tier?: string;\n}): Promise<{\n code: string;\n msg: string;\n data: Array<{\n uly: string;\n instFamily: string;\n instId: string;\n tier: string;\n minSz: string;\n maxSz: string;\n mmr: string;\n imr: string;\n maxLever: string;\n optMgnFactor: string;\n quoteMaxLoan: string;\n baseMaxLoan: string;\n }>;\n}> => publicRequest('GET', '/api/v5/public/position-tiers', params);\n"]}
package/lib/quote.d.ts CHANGED
@@ -18,5 +18,5 @@ export declare const spotMarketTickers$: import("rxjs").Observable<{
18
18
  ts: string;
19
19
  };
20
20
  }>;
21
- export declare const swapOpenInterest$: import("rxjs").Observable<Map<any, number>>;
21
+ export declare const swapOpenInterest$: import("rxjs").Observable<Map<string, number>>;
22
22
  //# sourceMappingURL=quote.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"quote.d.ts","sourceRoot":"","sources":["../src/quote.ts"],"names":[],"mappings":"AA8DA,eAAO,MAAM,kBAAkB;;;;;;;;;;;;;;;;;;;EAW9B,CAAC;AAsRF,eAAO,MAAM,iBAAiB,6CAG7B,CAAC"}
1
+ {"version":3,"file":"quote.d.ts","sourceRoot":"","sources":["../src/quote.ts"],"names":[],"mappings":"AA8DA,eAAO,MAAM,kBAAkB;;;;;;;;;;;;;;;;;;;EAW9B,CAAC;AAsRF,eAAO,MAAM,iBAAiB,gDAG7B,CAAC"}
package/lib/quote.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"quote.js","sourceRoot":"","sources":["../src/quote.ts"],"names":[],"mappings":";;;AACA,+CAA4C;AAC5C,qCAAyC;AACzC,yCAA8E;AAC9E,+BAuBc;AACd,6CAAmG;AACnG,6BAAkD;AAClD,4DAA4D;AAE5D,MAAM,QAAQ,GAAG,mBAAQ,CAAC,WAAW,EAAE,CAAC;AAExC,MAAM,gBAAgB,GAAG,IAAA,YAAK,EAAC,GAAG,EAAE,CAAC,IAAA,2BAAc,EAAC,EAAE,QAAQ,EAAE,MAAM,EAAE,CAAC,CAAC,CAAC,IAAI,CAC7E,IAAA,aAAM,EAAC,EAAE,KAAK,EAAE,OAAQ,EAAE,CAAC,EAC3B,IAAA,YAAK,EAAC,EAAE,KAAK,EAAE,KAAM,EAAE,CAA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AAA,YAAK,GAAE,CACR,CAAC;AAEF,sBAAsB;AACtB,IAAI,OAAO,CAAC,GAAG,CAAC,kBAAkB,KAAK,MAAM,EAAE;IAC7C,QAAQ,CAAC,OAAO,CAAC,cAAc,CAAC,OAAO,EAAE,EAAE,OAAO,EAAE,OAAO,EAAE,EAAE,CAAC,UAAU,EAAE,EAAE;QAC5E,MAAM,CAAC,aAAa,EAAE,UAAU,CAAC,GAAG,IAAA,kBAAU,EAAC,UAAU,CAAC,CAAC;QAC3D,IAAI,CAAC,aAAa,EAAE;YAClB,MAAM,2BAA2B,CAAC;SACnC;QACD,IAAI,CAAC,UAAU,EAAE;YACf,MAAM,wBAAwB,CAAC;SAChC;QACD,OAAO,MAAM,CAAC,IAAI,CAAC,IAAA,aAAM,EAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,UAAU,KAAK,UAAU,CAAC,CAAC,CAAC;IACjE,CAAC,CAAC,CAAC;IAEH,MAAM;SACH,IAAI,CACH,IAAA,gBAAU,EAAC;QACT,QAAQ;QACR,aAAa,EAAE,IAAI;QACnB,SAAS,EAAE,OAAO;QAClB,YAAY,EAAE,CAAC,eAAe,EAAE,YAAY,CAAC;KAC9C,CAAC,CACH;SACA,SAAS,EAAE,CAAC;CAChB;AAEY,QAAA,iBAAiB,GAAG,IAAA,YAAK,EAAC,GAAG,EAAE,CAAC,kBAAkB,CAAC,CAAC,IAAI,CACnE,IAAA,UAAG,EAAC,CAAC,CAAC,EAAE,EAAE,CAAC,IAAI,GAAG,CAAC,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,CAAM,EAAE,EAAE,CAAC,CAAC,CAAC,CAAC,MAAM,EAAE,CAAC,CAAC,CAAC,EAAE,CAAU,CAAC,CAAC,CAAC,EACvE,IAAA,kBAAW,EAAC,CAAC,CAAC,CACf,CAAC","sourcesContent":["import { IQuote } from '@yuants/data-quote';\nimport { Terminal } from '@yuants/protocol';\nimport { writeToSQL } from '@yuants/sql';\nimport { decodePath, encodePath, formatTime, listWatch } from '@yuants/utils';\nimport {\n catchError,\n concatMap,\n defer,\n distinctUntilChanged,\n EMPTY,\n filter,\n first,\n firstValueFrom,\n from,\n groupBy,\n map,\n merge,\n mergeMap,\n reduce,\n repeat,\n retry,\n scan,\n share,\n shareReplay,\n switchMap,\n tap,\n toArray,\n} from 'rxjs';\nimport { getInstruments, getMarketTickers, getOpenInterest, getPositionTiers } from './public-api';\nimport { useOpenInterest, useTicker } from './ws';\n// import { useOpenInterest, useTicker } from './websocket';\n\nconst terminal = Terminal.fromNodeEnv();\n\nconst swapInstruments$ = defer(() => getInstruments({ instType: 'SWAP' })).pipe(\n repeat({ delay: 3600_000 }),\n retry({ delay: 10_000 }),\n map((x) => x.data),\n shareReplay(1),\n);\nconst spotInstruments$ = defer(() => getInstruments({ instType: 'SPOT' })).pipe(\n repeat({ delay: 3600_000 }),\n retry({ delay: 10_000 }),\n map((x) => x.data),\n shareReplay(1),\n);\n\nconst shallowEqual = (a: string[], b: string[]) => a.length === b.length && a.every((v, i) => v === b[i]);\n\nconst spotInstIds$ = spotInstruments$.pipe(\n map((items) => items.map((item) => item.instId)),\n distinctUntilChanged(shallowEqual),\n shareReplay(1),\n);\n\nconst spotTickers$ = defer(() => getMarketTickers({ instType: 'SPOT' })).pipe(\n repeat({ delay: 5000 }),\n retry({ delay: 5000 }),\n shareReplay(1),\n);\n\n// depend by SubmitOrders\nexport const spotMarketTickers$ = defer(() => spotTickers$).pipe(\n mergeMap((x) =>\n from(x.data).pipe(\n map((x) => [x.instId, x] as const),\n toArray(),\n map((x) => Object.fromEntries(x)),\n ),\n ),\n repeat({ delay: 5000 }),\n retry({ delay: 5000 }),\n shareReplay(1),\n);\n\nconst spotTicker$ = spotInstruments$.pipe(\n tap((x) => {\n console.info('SPOT INSTRUMENTS', x.length);\n }),\n listWatch(\n (x) => x.instId,\n (x) => useTicker(x.instId),\n () => true,\n ),\n share(),\n);\n\nconst quoteOfSwapFromRest$ = defer(() => getMarketTickers({ instType: 'SWAP' })).pipe(\n mergeMap((x) => x.data || []),\n map(\n (x): Partial<IQuote> => ({\n datasource_id: 'OKX',\n product_id: encodePath(x.instType, x.instId),\n last_price: x.last,\n ask_price: x.askPx,\n bid_price: x.bidPx,\n ask_volume: x.askSz,\n bid_volume: x.bidSz,\n }),\n ),\n repeat({ delay: 1000 }),\n retry({ delay: 1000 }),\n);\n\nconst quoteOfSpotAndMarginFromRest$ = defer(() => getMarketTickers({ instType: 'SPOT' })).pipe(\n mergeMap((x) => x.data || []),\n mergeMap((x): Partial<IQuote>[] => [\n {\n datasource_id: 'OKX',\n product_id: encodePath('SPOT', x.instId),\n last_price: x.last,\n ask_price: x.askPx,\n bid_price: x.bidPx,\n ask_volume: x.askSz,\n bid_volume: x.bidSz,\n },\n {\n datasource_id: 'OKX',\n product_id: encodePath('MARGIN', x.instId),\n last_price: x.last,\n ask_price: x.askPx,\n bid_price: x.bidPx,\n ask_volume: x.askSz,\n bid_volume: x.bidSz,\n },\n ]),\n repeat({ delay: 1000 }),\n retry({ delay: 1000 }),\n);\n\nconst quoteOfSwapFromWs$ = swapInstruments$.pipe(\n listWatch(\n (x) => x.instId,\n (x) => useTicker(x.instId),\n () => true,\n ),\n map(\n (ticker): Partial<IQuote> => ({\n datasource_id: 'OKX',\n product_id: encodePath('SWAP', ticker[0].instId),\n last_price: ticker[0].last,\n ask_price: ticker[0].askPx,\n bid_price: ticker[0].bidPx,\n ask_volume: ticker[0].askSz,\n bid_volume: ticker[0].bidSz,\n }),\n ),\n);\n\nconst quoteOfSpotAndMarginFromWs$ = spotTicker$.pipe(\n mergeMap((ticker): Partial<IQuote>[] => [\n {\n datasource_id: 'OKX',\n product_id: encodePath('SPOT', ticker[0].instId),\n last_price: ticker[0].last,\n ask_price: ticker[0].askPx,\n bid_price: ticker[0].bidPx,\n ask_volume: ticker[0].askSz,\n bid_volume: ticker[0].bidSz,\n },\n {\n datasource_id: 'OKX',\n product_id: encodePath('MARGIN', ticker[0].instId),\n last_price: ticker[0].last,\n ask_price: ticker[0].askPx,\n bid_price: ticker[0].bidPx,\n ask_volume: ticker[0].askSz,\n bid_volume: ticker[0].bidSz,\n },\n ]),\n);\n\nconst swapOpenInterests$ = defer(() => getOpenInterest({ instType: 'SWAP' })).pipe(\n repeat({ delay: 10_000 }),\n retry({ delay: 10_000 }),\n shareReplay(1),\n);\n\nconst interestRateOfSwapFromWS$ = swapInstruments$.pipe(\n listWatch(\n (x) => x.instId,\n (x) => useOpenInterest(x.instId),\n () => true,\n ),\n map(\n (x): Partial<IQuote> => ({\n datasource_id: 'OKX',\n product_id: encodePath('SWAP', x[0].instId),\n open_interest: x[0].oi,\n }),\n ),\n share(),\n);\n\ntype PositionTiersResponse = Awaited<ReturnType<typeof getPositionTiers>>;\ntype PositionTiersEntry = PositionTiersResponse['data'];\n\nconst marginPositionTiersMap$ = defer(() =>\n spotInstIds$.pipe(\n first(),\n map((instIds) => instIds.filter((id) => id.endsWith('USDT') || id.endsWith('USDC'))),\n switchMap((instIds) => {\n const total = instIds.length;\n let processed = 0;\n return from(instIds).pipe(\n concatMap((instId) =>\n defer(async () => {\n const tiers = await terminal.client.requestForResponseData<\n { instType: string; tdMode: string; instId: string },\n PositionTiersResponse\n >('OKX/PositionTiers', {\n instType: 'MARGIN',\n tdMode: 'cross',\n instId,\n });\n if (!tiers?.data) {\n throw new Error(`Failed to load position tiers for ${instId}: ${tiers.msg}`);\n }\n return {\n instId,\n tiers,\n };\n }).pipe(retry({ delay: 2000 })),\n ),\n reduce((map, { instId, tiers }) => {\n processed += 1;\n console.info(\n formatTime(Date.now()),\n `Loaded margin position tiers ${processed}/${total} (${instId})`,\n );\n if (tiers?.data) {\n map.set(instId, tiers.data);\n }\n return map;\n }, new Map<string, PositionTiersEntry>()),\n );\n }),\n ),\n).pipe(\n //\n retry({ delay: 60_000 }),\n repeat({ delay: 86400_000 }),\n shareReplay(1),\n);\n\n// Margin 的 open interest 只依赖 position-tier:\n// 1) 启动时先拉全量 MARGIN 仓位档位并缓存,下次直接命中;\n// 2) 档位内只保留同 tier 杠杆最高的记录;\n// 3) 当前策略只使用 tier=1 的 quoteMaxLoan 作为持仓上限,不再混合 /account/max-size;\n// 4) 每个 instId 60 秒刷新一次,并在接口报错时 10 秒重试。\nconst marginOpenInterest$ = spotInstIds$.pipe(\n mergeMap((instIds) =>\n from(instIds).pipe(\n mergeMap((instId) =>\n defer(async () => {\n const tiersMap = await firstValueFrom(marginPositionTiersMap$);\n const tiers = tiersMap.get(instId);\n if (!tiers?.length) {\n return null;\n }\n\n const tierByLevel = tiers\n .filter((tier) => !tier.instId || tier.instId === instId)\n .reduce((mapTierToTierInfo, tierInfo) => {\n const existing = mapTierToTierInfo.get(tierInfo.tier);\n if (!existing || +tierInfo.maxLever > +existing.maxLever) {\n mapTierToTierInfo.set(tierInfo.tier, tierInfo);\n }\n return mapTierToTierInfo;\n }, new Map<string, (typeof tiers)[number]>());\n // 获取一级杠杆的最大可借贷额度作为持仓量\n const openInterest = +(tierByLevel.get('1')?.quoteMaxLoan || 0);\n\n return {\n instId,\n openInterest,\n };\n }).pipe(retry({ delay: 10_000 }), repeat({ delay: 60_000 })),\n ),\n ),\n ),\n filter((result): result is { instId: string; openInterest: number } => result !== null),\n map(({ instId, openInterest }) => {\n const partial: Partial<IQuote> = {\n datasource_id: 'OKX',\n product_id: encodePath('MARGIN', instId),\n };\n if (typeof openInterest === 'number' && Number.isFinite(openInterest)) {\n partial.open_interest = `${openInterest}`;\n }\n return partial;\n }),\n share(),\n);\n\nmarginOpenInterest$.subscribe();\n\nconst quoteSources$ = [\n quoteOfSwapFromWs$,\n interestRateOfSwapFromWS$,\n quoteOfSwapFromRest$,\n quoteOfSpotAndMarginFromWs$,\n quoteOfSpotAndMarginFromRest$,\n marginOpenInterest$,\n];\n\nconst quote$ = defer(() =>\n merge(\n ...quoteSources$.map((x$) =>\n defer(() => x$).pipe(\n // 防止单个流关闭导致整体关闭\n catchError(() => EMPTY),\n ),\n ),\n ),\n).pipe(\n groupBy((x) => encodePath(x.datasource_id, x.product_id)),\n mergeMap((group$) => {\n return group$.pipe(\n //\n scan((acc, cur) => Object.assign(acc, cur), {} as Partial<IQuote>),\n );\n }),\n share(),\n);\n\n// 合并不同来源的数据并进行合并,避免死锁\nif (process.env.WRITE_QUOTE_TO_SQL === 'true') {\n terminal.channel.publishChannel('quote', { pattern: `^OKX/` }, (channel_id) => {\n const [datasource_id, product_id] = decodePath(channel_id);\n if (!datasource_id) {\n throw 'datasource_id is required';\n }\n if (!product_id) {\n throw 'product_id is required';\n }\n return quote$.pipe(filter((x) => x.product_id === product_id));\n });\n\n quote$\n .pipe(\n writeToSQL({\n terminal,\n writeInterval: 1000,\n tableName: 'quote',\n conflictKeys: ['datasource_id', 'product_id'],\n }),\n )\n .subscribe();\n}\n\nexport const swapOpenInterest$ = defer(() => swapOpenInterests$).pipe(\n map((x) => new Map(x.data.map((x: any) => [x.instId, +x.oi] as const))),\n shareReplay(1),\n);\n"]}
1
+ {"version":3,"file":"quote.js","sourceRoot":"","sources":["../src/quote.ts"],"names":[],"mappings":";;;AACA,+CAA4C;AAC5C,qCAAyC;AACzC,yCAA8E;AAC9E,+BAuBc;AACd,6CAAmG;AACnG,6BAAkD;AAClD,4DAA4D;AAE5D,MAAM,QAAQ,GAAG,mBAAQ,CAAC,WAAW,EAAE,CAAC;AAExC,MAAM,gBAAgB,GAAG,IAAA,YAAK,EAAC,GAAG,EAAE,CAAC,IAAA,2BAAc,EAAC,EAAE,QAAQ,EAAE,MAAM,EAAE,CAAC,CAAC,CAAC,IAAI,CAC7E,IAAA,aAAM,EAAC,EAAE,KAAK,EAAE,OAAQ,EAAE,CAAC,EAC3B,IAAA,YAAK,EAAC,EAAE,KAAK,EAAE,KAAM,EAAE,CAAC,EACxB,IAAA,UAAG,EAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC,EAClB,IAAA,kBAAW,EAAC,CAAC,CAAC,CACf,CAAC;AACF,MAA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cAAc,CAAC,OAAO,EAAE,EAAE,OAAO,EAAE,OAAO,EAAE,EAAE,CAAC,UAAU,EAAE,EAAE;QAC5E,MAAM,CAAC,aAAa,EAAE,UAAU,CAAC,GAAG,IAAA,kBAAU,EAAC,UAAU,CAAC,CAAC;QAC3D,IAAI,CAAC,aAAa,EAAE;YAClB,MAAM,2BAA2B,CAAC;SACnC;QACD,IAAI,CAAC,UAAU,EAAE;YACf,MAAM,wBAAwB,CAAC;SAChC;QACD,OAAO,MAAM,CAAC,IAAI,CAAC,IAAA,aAAM,EAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,UAAU,KAAK,UAAU,CAAC,CAAC,CAAC;IACjE,CAAC,CAAC,CAAC;IAEH,MAAM;SACH,IAAI,CACH,IAAA,gBAAU,EAAC;QACT,QAAQ;QACR,aAAa,EAAE,IAAI;QACnB,SAAS,EAAE,OAAO;QAClB,YAAY,EAAE,CAAC,eAAe,EAAE,YAAY,CAAC;KAC9C,CAAC,CACH;SACA,SAAS,EAAE,CAAC;CAChB;AAEY,QAAA,iBAAiB,GAAG,IAAA,YAAK,EAAC,GAAG,EAAE,CAAC,kBAAkB,CAAC,CAAC,IAAI,CACnE,IAAA,UAAG,EAAC,CAAC,CAAC,EAAE,EAAE,CAAC,IAAI,GAAG,CAAC,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,CAAC,MAAM,EAAE,CAAC,CAAC,CAAC,EAAE,CAAU,CAAC,CAAC,CAAC,EAClE,IAAA,kBAAW,EAAC,CAAC,CAAC,CACf,CAAC","sourcesContent":["import { IQuote } from '@yuants/data-quote';\nimport { Terminal } from '@yuants/protocol';\nimport { writeToSQL } from '@yuants/sql';\nimport { decodePath, encodePath, formatTime, listWatch } from '@yuants/utils';\nimport {\n catchError,\n concatMap,\n defer,\n distinctUntilChanged,\n EMPTY,\n filter,\n first,\n firstValueFrom,\n from,\n groupBy,\n map,\n merge,\n mergeMap,\n reduce,\n repeat,\n retry,\n scan,\n share,\n shareReplay,\n switchMap,\n tap,\n toArray,\n} from 'rxjs';\nimport { getInstruments, getMarketTickers, getOpenInterest, getPositionTiers } from './public-api';\nimport { useOpenInterest, useTicker } from './ws';\n// import { useOpenInterest, useTicker } from './websocket';\n\nconst terminal = Terminal.fromNodeEnv();\n\nconst swapInstruments$ = defer(() => getInstruments({ instType: 'SWAP' })).pipe(\n repeat({ delay: 3600_000 }),\n retry({ delay: 10_000 }),\n map((x) => x.data),\n shareReplay(1),\n);\nconst spotInstruments$ = defer(() => getInstruments({ instType: 'SPOT' })).pipe(\n repeat({ delay: 3600_000 }),\n retry({ delay: 10_000 }),\n map((x) => x.data),\n shareReplay(1),\n);\n\nconst shallowEqual = (a: string[], b: string[]) => a.length === b.length && a.every((v, i) => v === b[i]);\n\nconst spotInstIds$ = spotInstruments$.pipe(\n map((items) => items.map((item) => item.instId)),\n distinctUntilChanged(shallowEqual),\n shareReplay(1),\n);\n\nconst spotTickers$ = defer(() => getMarketTickers({ instType: 'SPOT' })).pipe(\n repeat({ delay: 5000 }),\n retry({ delay: 5000 }),\n shareReplay(1),\n);\n\n// depend by SubmitOrders\nexport const spotMarketTickers$ = defer(() => spotTickers$).pipe(\n mergeMap((x) =>\n from(x.data).pipe(\n map((x) => [x.instId, x] as const),\n toArray(),\n map((x) => Object.fromEntries(x)),\n ),\n ),\n repeat({ delay: 5000 }),\n retry({ delay: 5000 }),\n shareReplay(1),\n);\n\nconst spotTicker$ = spotInstruments$.pipe(\n tap((x) => {\n console.info('SPOT INSTRUMENTS', x.length);\n }),\n listWatch(\n (x) => x.instId,\n (x) => useTicker(x.instId),\n () => true,\n ),\n share(),\n);\n\nconst quoteOfSwapFromRest$ = defer(() => getMarketTickers({ instType: 'SWAP' })).pipe(\n mergeMap((x) => x.data || []),\n map(\n (x): Partial<IQuote> => ({\n datasource_id: 'OKX',\n product_id: encodePath(x.instType, x.instId),\n last_price: x.last,\n ask_price: x.askPx,\n bid_price: x.bidPx,\n ask_volume: x.askSz,\n bid_volume: x.bidSz,\n }),\n ),\n repeat({ delay: 1000 }),\n retry({ delay: 1000 }),\n);\n\nconst quoteOfSpotAndMarginFromRest$ = defer(() => getMarketTickers({ instType: 'SPOT' })).pipe(\n mergeMap((x) => x.data || []),\n mergeMap((x): Partial<IQuote>[] => [\n {\n datasource_id: 'OKX',\n product_id: encodePath('SPOT', x.instId),\n last_price: x.last,\n ask_price: x.askPx,\n bid_price: x.bidPx,\n ask_volume: x.askSz,\n bid_volume: x.bidSz,\n },\n {\n datasource_id: 'OKX',\n product_id: encodePath('MARGIN', x.instId),\n last_price: x.last,\n ask_price: x.askPx,\n bid_price: x.bidPx,\n ask_volume: x.askSz,\n bid_volume: x.bidSz,\n },\n ]),\n repeat({ delay: 1000 }),\n retry({ delay: 1000 }),\n);\n\nconst quoteOfSwapFromWs$ = swapInstruments$.pipe(\n listWatch(\n (x) => x.instId,\n (x) => useTicker(x.instId),\n () => true,\n ),\n map(\n (ticker): Partial<IQuote> => ({\n datasource_id: 'OKX',\n product_id: encodePath('SWAP', ticker[0].instId),\n last_price: ticker[0].last,\n ask_price: ticker[0].askPx,\n bid_price: ticker[0].bidPx,\n ask_volume: ticker[0].askSz,\n bid_volume: ticker[0].bidSz,\n }),\n ),\n);\n\nconst quoteOfSpotAndMarginFromWs$ = spotTicker$.pipe(\n mergeMap((ticker): Partial<IQuote>[] => [\n {\n datasource_id: 'OKX',\n product_id: encodePath('SPOT', ticker[0].instId),\n last_price: ticker[0].last,\n ask_price: ticker[0].askPx,\n bid_price: ticker[0].bidPx,\n ask_volume: ticker[0].askSz,\n bid_volume: ticker[0].bidSz,\n },\n {\n datasource_id: 'OKX',\n product_id: encodePath('MARGIN', ticker[0].instId),\n last_price: ticker[0].last,\n ask_price: ticker[0].askPx,\n bid_price: ticker[0].bidPx,\n ask_volume: ticker[0].askSz,\n bid_volume: ticker[0].bidSz,\n },\n ]),\n);\n\nconst swapOpenInterests$ = defer(() => getOpenInterest({ instType: 'SWAP' })).pipe(\n repeat({ delay: 10_000 }),\n retry({ delay: 10_000 }),\n shareReplay(1),\n);\n\nconst interestRateOfSwapFromWS$ = swapInstruments$.pipe(\n listWatch(\n (x) => x.instId,\n (x) => useOpenInterest(x.instId),\n () => true,\n ),\n map(\n (x): Partial<IQuote> => ({\n datasource_id: 'OKX',\n product_id: encodePath('SWAP', x[0].instId),\n open_interest: x[0].oi,\n }),\n ),\n share(),\n);\n\ntype PositionTiersResponse = Awaited<ReturnType<typeof getPositionTiers>>;\ntype PositionTiersEntry = PositionTiersResponse['data'];\n\nconst marginPositionTiersMap$ = defer(() =>\n spotInstIds$.pipe(\n first(),\n map((instIds) => instIds.filter((id) => id.endsWith('USDT') || id.endsWith('USDC'))),\n switchMap((instIds) => {\n const total = instIds.length;\n let processed = 0;\n return from(instIds).pipe(\n concatMap((instId) =>\n defer(async () => {\n const tiers = await terminal.client.requestForResponseData<\n { instType: string; tdMode: string; instId: string },\n PositionTiersResponse\n >('OKX/PositionTiers', {\n instType: 'MARGIN',\n tdMode: 'cross',\n instId,\n });\n if (!tiers?.data) {\n throw new Error(`Failed to load position tiers for ${instId}: ${tiers.msg}`);\n }\n return {\n instId,\n tiers,\n };\n }).pipe(retry({ delay: 2000 })),\n ),\n reduce((map, { instId, tiers }) => {\n processed += 1;\n console.info(\n formatTime(Date.now()),\n `Loaded margin position tiers ${processed}/${total} (${instId})`,\n );\n if (tiers?.data) {\n map.set(instId, tiers.data);\n }\n return map;\n }, new Map<string, PositionTiersEntry>()),\n );\n }),\n ),\n).pipe(\n //\n retry({ delay: 60_000 }),\n repeat({ delay: 86400_000 }),\n shareReplay(1),\n);\n\n// Margin 的 open interest 只依赖 position-tier:\n// 1) 启动时先拉全量 MARGIN 仓位档位并缓存,下次直接命中;\n// 2) 档位内只保留同 tier 杠杆最高的记录;\n// 3) 当前策略只使用 tier=1 的 quoteMaxLoan 作为持仓上限,不再混合 /account/max-size;\n// 4) 每个 instId 60 秒刷新一次,并在接口报错时 10 秒重试。\nconst marginOpenInterest$ = spotInstIds$.pipe(\n mergeMap((instIds) =>\n from(instIds).pipe(\n mergeMap((instId) =>\n defer(async () => {\n const tiersMap = await firstValueFrom(marginPositionTiersMap$);\n const tiers = tiersMap.get(instId);\n if (!tiers?.length) {\n return null;\n }\n\n const tierByLevel = tiers\n .filter((tier) => !tier.instId || tier.instId === instId)\n .reduce((mapTierToTierInfo, tierInfo) => {\n const existing = mapTierToTierInfo.get(tierInfo.tier);\n if (!existing || +tierInfo.maxLever > +existing.maxLever) {\n mapTierToTierInfo.set(tierInfo.tier, tierInfo);\n }\n return mapTierToTierInfo;\n }, new Map<string, (typeof tiers)[number]>());\n // 获取一级杠杆的最大可借贷额度作为持仓量\n const openInterest = +(tierByLevel.get('1')?.quoteMaxLoan || 0);\n\n return {\n instId,\n openInterest,\n };\n }).pipe(retry({ delay: 10_000 }), repeat({ delay: 60_000 })),\n ),\n ),\n ),\n filter((result): result is { instId: string; openInterest: number } => result !== null),\n map(({ instId, openInterest }) => {\n const partial: Partial<IQuote> = {\n datasource_id: 'OKX',\n product_id: encodePath('MARGIN', instId),\n };\n if (typeof openInterest === 'number' && Number.isFinite(openInterest)) {\n partial.open_interest = `${openInterest}`;\n }\n return partial;\n }),\n share(),\n);\n\nmarginOpenInterest$.subscribe();\n\nconst quoteSources$ = [\n quoteOfSwapFromWs$,\n interestRateOfSwapFromWS$,\n quoteOfSwapFromRest$,\n quoteOfSpotAndMarginFromWs$,\n quoteOfSpotAndMarginFromRest$,\n marginOpenInterest$,\n];\n\nconst quote$ = defer(() =>\n merge(\n ...quoteSources$.map((x$) =>\n defer(() => x$).pipe(\n // 防止单个流关闭导致整体关闭\n catchError(() => EMPTY),\n ),\n ),\n ),\n).pipe(\n groupBy((x) => encodePath(x.datasource_id, x.product_id)),\n mergeMap((group$) => {\n return group$.pipe(\n //\n scan((acc, cur) => Object.assign(acc, cur), {} as Partial<IQuote>),\n );\n }),\n share(),\n);\n\n// 合并不同来源的数据并进行合并,避免死锁\nif (process.env.WRITE_QUOTE_TO_SQL === 'true') {\n terminal.channel.publishChannel('quote', { pattern: `^OKX/` }, (channel_id) => {\n const [datasource_id, product_id] = decodePath(channel_id);\n if (!datasource_id) {\n throw 'datasource_id is required';\n }\n if (!product_id) {\n throw 'product_id is required';\n }\n return quote$.pipe(filter((x) => x.product_id === product_id));\n });\n\n quote$\n .pipe(\n writeToSQL({\n terminal,\n writeInterval: 1000,\n tableName: 'quote',\n conflictKeys: ['datasource_id', 'product_id'],\n }),\n )\n .subscribe();\n}\n\nexport const swapOpenInterest$ = defer(() => swapOpenInterests$).pipe(\n map((x) => new Map(x.data.map((x) => [x.instId, +x.oi] as const))),\n shareReplay(1),\n);\n"]}
package/lib/services.js CHANGED
@@ -7,6 +7,7 @@ const api_1 = require("./api");
7
7
  const terminal = protocol_1.Terminal.fromNodeEnv();
8
8
  (0, rxjs_1.defer)(async () => {
9
9
  const tradingAccountId = await (0, rxjs_1.firstValueFrom)(account_1.tradingAccountId$);
10
+ const credential = (0, api_1.getDefaultCredential)();
10
11
  terminal.server.provideService('Grid/Algo-Order', {
11
12
  required: ['account_id'],
12
13
  properties: {
@@ -14,7 +15,7 @@ const terminal = protocol_1.Terminal.fromNodeEnv();
14
15
  },
15
16
  }, async (msg) => {
16
17
  if (msg.req) {
17
- const result = await api_1.client.postGridAlgoOrder(msg.req);
18
+ const result = await (0, api_1.postGridAlgoOrder)(credential, msg.req);
18
19
  return { res: { code: 0, message: 'OK', data: result } };
19
20
  }
20
21
  return { res: { code: 0, message: 'No Params' } };
@@ -1 +1 @@
1
- {"version":3,"file":"services.js","sourceRoot":"","sources":["../src/services.ts"],"names":[],"mappings":";;AAAA,+CAA4C;AAC5C,+BAA6C;AAC7C,uCAA8C;AAC9C,+BAA+B;AAE/B,MAAM,QAAQ,GAAG,mBAAQ,CAAC,WAAW,EAAE,CAAC;AAExC,IAAA,YAAK,EAAC,KAAK,IAAI,EAAE;IACf,MAAM,gBAAgB,GAAG,MAAM,IAAA,qBAAc,EAAC,2BAAiB,CAAC,CAAC;IACjE,QAAQ,CAAC,MAAM,CAAC,cAAc,CAC5B,iBAAiB,EACjB;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,IAAI,GAAG,CAAC,GAAG,EAAE;YACX,MAAM,MAAM,GAAG,MAAM,YAAM,CAAC,iBAAiB,CAAC,GAAG,CAAC,GAAU,CAAC,CAAC;YAC9D,OAAO,EAAE,GAAG,EAAE,EAAE,IAAI,EAAE,CAAC,EAAE,OAAO,EAAE,IAAI,EAAE,IAAI,EAAE,MAAM,EAAE,EAAE,CAAC;SAC1D;QACD,OAAO,EAAE,GAAG,EAAE,EAAE,IAAI,EAAE,CAAC,EAAE,OAAO,EAAE,WAAW,EAAE,EAAE,CAAC;IACpD,CAAC,CACF,CAAC;AACJ,CAAC,CAAC,CAAC,SAAS,EAAE,CAAC","sourcesContent":["import { Terminal } from '@yuants/protocol';\nimport { defer, firstValueFrom } from 'rxjs';\nimport { tradingAccountId$ } from './account';\nimport { client } from './api';\n\nconst terminal = Terminal.fromNodeEnv();\n\ndefer(async () => {\n const tradingAccountId = await firstValueFrom(tradingAccountId$);\n terminal.server.provideService(\n 'Grid/Algo-Order',\n {\n required: ['account_id'],\n properties: {\n account_id: { const: tradingAccountId },\n },\n },\n async (msg) => {\n if (msg.req) {\n const result = await client.postGridAlgoOrder(msg.req as any);\n return { res: { code: 0, message: 'OK', data: result } };\n }\n return { res: { code: 0, message: 'No Params' } };\n },\n );\n}).subscribe();\n"]}
1
+ {"version":3,"file":"services.js","sourceRoot":"","sources":["../src/services.ts"],"names":[],"mappings":";;AAAA,+CAA4C;AAC5C,+BAA6C;AAC7C,uCAA8C;AAC9C,+BAAgE;AAEhE,MAAM,QAAQ,GAAG,mBAAQ,CAAC,WAAW,EAAE,CAAC;AAExC,IAAA,YAAK,EAAC,KAAK,IAAI,EAAE;IACf,MAAM,gBAAgB,GAAG,MAAM,IAAA,qBAAc,EAAC,2BAAiB,CAAC,CAAC;IACjE,MAAM,UAAU,GAAG,IAAA,0BAAoB,GAAE,CAAC;IAE1C,QAAQ,CAAC,MAAM,CAAC,cAAc,CAC5B,iBAAiB,EACjB;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,IAAI,GAAG,CAAC,GAAG,EAAE;YACX,MAAM,MAAM,GAAG,MAAM,IAAA,uBAAiB,EAAC,UAAU,EAAE,GAAG,CAAC,GAAU,CAAC,CAAC;YACnE,OAAO,EAAE,GAAG,EAAE,EAAE,IAAI,EAAE,CAAC,EAAE,OAAO,EAAE,IAAI,EAAE,IAAI,EAAE,MAAM,EAAE,EAAE,CAAC;SAC1D;QACD,OAAO,EAAE,GAAG,EAAE,EAAE,IAAI,EAAE,CAAC,EAAE,OAAO,EAAE,WAAW,EAAE,EAAE,CAAC;IACpD,CAAC,CACF,CAAC;AACJ,CAAC,CAAC,CAAC,SAAS,EAAE,CAAC","sourcesContent":["import { Terminal } from '@yuants/protocol';\nimport { defer, firstValueFrom } from 'rxjs';\nimport { tradingAccountId$ } from './account';\nimport { getDefaultCredential, postGridAlgoOrder } from './api';\n\nconst terminal = Terminal.fromNodeEnv();\n\ndefer(async () => {\n const tradingAccountId = await firstValueFrom(tradingAccountId$);\n const credential = getDefaultCredential();\n\n terminal.server.provideService(\n 'Grid/Algo-Order',\n {\n required: ['account_id'],\n properties: {\n account_id: { const: tradingAccountId },\n },\n },\n async (msg) => {\n if (msg.req) {\n const result = await postGridAlgoOrder(credential, msg.req as any);\n return { res: { code: 0, message: 'OK', data: result } };\n }\n return { res: { code: 0, message: 'No Params' } };\n },\n );\n}).subscribe();\n"]}
@@ -13,9 +13,9 @@ export declare const accountConfig$: import("rxjs").Observable<{
13
13
  uid: string;
14
14
  label: string;
15
15
  roleType: string;
16
- traderInsts: any[];
16
+ traderInsts: unknown[];
17
17
  spotRoleType: string;
18
- spotTraderInsts: any[];
18
+ spotTraderInsts: unknown[];
19
19
  opAuth: string;
20
20
  kycLv: string;
21
21
  ip: string;
@@ -1 +1 @@
1
- {"version":3,"file":"strategy-account.d.ts","sourceRoot":"","sources":["../src/strategy-account.ts"],"names":[],"mappings":"AAQA,eAAO,MAAM,cAAc;;;;;;;;;;;;;;;;;;;;;;;;;EAI1B,CAAC;AAEF,eAAO,MAAM,WAAW,mCAIvB,CAAC;AAEF,eAAO,MAAM,kBAAkB,mCAG9B,CAAC"}
1
+ {"version":3,"file":"strategy-account.d.ts","sourceRoot":"","sources":["../src/strategy-account.ts"],"names":[],"mappings":"AASA,eAAO,MAAM,cAAc;;;;;;;;;;;;;;;;;;;;;;;;;EAI1B,CAAC;AAEF,eAAO,MAAM,WAAW,mCAIvB,CAAC;AAEF,eAAO,MAAM,kBAAkB,mCAG9B,CAAC"}
@@ -3,11 +3,12 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.strategyAccountId$ = exports.accountUid$ = exports.accountConfig$ = void 0;
4
4
  const data_account_1 = require("@yuants/data-account");
5
5
  const protocol_1 = require("@yuants/protocol");
6
- const utils_1 = require("@yuants/utils");
7
6
  const rxjs_1 = require("rxjs");
8
7
  const api_1 = require("./api");
8
+ const accountInfos_1 = require("./accountInfos");
9
9
  const terminal = protocol_1.Terminal.fromNodeEnv();
10
- exports.accountConfig$ = (0, rxjs_1.defer)(() => api_1.client.getAccountConfig()).pipe((0, rxjs_1.repeat)({ delay: 10000 }), (0, rxjs_1.retry)({ delay: 10000 }), (0, rxjs_1.shareReplay)(1));
10
+ const credential = (0, api_1.getDefaultCredential)();
11
+ exports.accountConfig$ = (0, rxjs_1.defer)(() => (0, api_1.getAccountConfig)(credential)).pipe((0, rxjs_1.repeat)({ delay: 10000 }), (0, rxjs_1.retry)({ delay: 10000 }), (0, rxjs_1.shareReplay)(1));
11
12
  exports.accountUid$ = exports.accountConfig$.pipe((0, rxjs_1.map)((x) => x.data[0].uid), (0, rxjs_1.filter)((x) => !!x), (0, rxjs_1.shareReplay)(1));
12
13
  exports.strategyAccountId$ = exports.accountUid$.pipe((0, rxjs_1.map)((uid) => `okx/${uid}/strategy`), (0, rxjs_1.shareReplay)(1));
13
14
  (0, rxjs_1.defer)(async () => {
@@ -24,70 +25,16 @@ exports.strategyAccountId$ = exports.accountUid$.pipe((0, rxjs_1.map)((uid) => `
24
25
  res: {
25
26
  code: 0,
26
27
  message: 'OK',
27
- data: await api_1.client.getGridPositions({ algoOrdType: 'contract_grid', algoId: msg.req.algoId }),
28
+ data: await (0, api_1.getGridPositions)(credential, { algoOrdType: 'contract_grid', algoId: msg.req.algoId }),
28
29
  },
29
30
  };
30
31
  }, {
31
32
  egress_token_capacity: 20,
32
33
  egress_token_refill_interval: 4000, // 每 4 秒恢复 20 个令牌 (双倍冗余限流)
33
34
  });
34
- (0, data_account_1.provideAccountInfoService)(terminal, strategyAccountId, async () => {
35
- // TODO: 需要分页获取所有的网格订单 (每页 100 条)
36
- const [gridAlgoOrders] = await Promise.all([
37
- api_1.client.getGridOrdersAlgoPending({
38
- algoOrdType: 'contract_grid',
39
- }),
40
- ]);
41
- let totalEquity = 0;
42
- const positions = [];
43
- const gridPositionsRes = await Promise.all(gridAlgoOrders.data.map((item) => terminal.client.requestForResponseData('OKX/QueryGridPositions', {
44
- account_id: strategyAccountId,
45
- algoId: item.algoId,
46
- })));
47
- gridPositionsRes.forEach((gridPositions, index) => {
48
- var _a, _b, _c, _d;
49
- let positionValuation = 0;
50
- const leverage = +((_a = gridAlgoOrders.data) === null || _a === void 0 ? void 0 : _a[index].actualLever);
51
- (_b = gridPositions === null || gridPositions === void 0 ? void 0 : gridPositions.data) === null || _b === void 0 ? void 0 : _b.forEach((position) => {
52
- var _a, _b, _c;
53
- if (+position.pos !== 0) {
54
- 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 : '';
55
- const direction = directionRaw ? directionRaw.toUpperCase() : 'LONG';
56
- positions.push({
57
- position_id: (0, utils_1.encodePath)(position.algoId, position.instId),
58
- datasource_id: 'OKX',
59
- product_id: (0, utils_1.encodePath)(position.instType, position.instId),
60
- direction,
61
- volume: Math.abs(+position.pos),
62
- free_volume: +position.pos,
63
- position_price: +position.avgPx,
64
- floating_profit: +position.upl,
65
- closable_price: +position.last,
66
- valuation: +position.notionalUsd,
67
- });
68
- positionValuation += +position.notionalUsd;
69
- }
70
- });
71
- if (leverage === 0) {
72
- // 实际杠杆为 0,说明没有持仓,直接把投资金额和累计盈亏算到净值里
73
- 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);
74
- }
75
- else {
76
- // 历史提取金额不会从 investment, totalPnl 扣减
77
- // 计算净值需要通过仓位的名义价值和实际杠杆计算
78
- totalEquity += positionValuation / leverage;
79
- }
80
- });
81
- return {
82
- money: {
83
- currency: 'USDT',
84
- equity: totalEquity,
85
- // TODO: 累计策略的可提取资金作为 free
86
- free: 0,
87
- },
88
- positions,
89
- };
90
- }, { auto_refresh_interval: 5000 });
35
+ (0, data_account_1.provideAccountInfoService)(terminal, strategyAccountId, () => (0, accountInfos_1.getStrategyAccountInfo)(credential), {
36
+ auto_refresh_interval: 5000,
37
+ });
91
38
  }).subscribe();
92
39
  const sub = (0, rxjs_1.defer)(() => exports.accountUid$)
93
40
  .pipe((0, rxjs_1.first)())
@@ -1 +1 @@
1
- {"version":3,"file":"strategy-account.js","sourceRoot":"","sources":["../src/strategy-account.ts"],"names":[],"mappings":";;;AAAA,uDAA8F;AAC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I,iBAAiB,GAAG,QAAQ,CAAC;aAC7C;QACH,CAAC,CAAC,CAAC;QAEH,OAAO;YACL,KAAK,EAAE;gBACL,QAAQ,EAAE,MAAM;gBAChB,MAAM,EAAE,WAAW;gBACnB,0BAA0B;gBAC1B,IAAI,EAAE,CAAC;aACR;YACD,SAAS;SACV,CAAC;IACJ,CAAC,EACD,EAAE,qBAAqB,EAAE,IAAI,EAAE,CAChC,CAAC;AACJ,CAAC,CAAC,CAAC,SAAS,EAAE,CAAC;AAEf,MAAM,GAAG,GAAG,IAAA,YAAK,EAAC,GAAG,EAAE,CAAC,mBAAW,CAAC;KACjC,IAAI,CAAC,IAAA,YAAK,GAAE,CAAC;KACb,SAAS,CAAC,CAAC,GAAG,EAAE,EAAE;IACjB,IAAA,+BAAgB,EAAC,QAAQ,EAAE,EAAE,UAAU,EAAE,OAAO,GAAG,WAAW,EAAE,SAAS,EAAE,KAAK,EAAE,CAAC,CAAC;AACtF,CAAC,CAAC,CAAC;AACL,IAAA,YAAK,EAAC,GAAG,EAAE,CAAC,QAAQ,CAAC,QAAQ,CAAC,CAAC,SAAS,CAAC,GAAG,EAAE,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 { client } from './api';\n\nconst terminal = Terminal.fromNodeEnv();\n\nexport const accountConfig$ = defer(() => client.getAccountConfig()).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 client.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 client.getGridPositions({ 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 client.getGridOrdersAlgoPending({\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 client.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,uDAAmF;AACnF,+CAA4C;AAC5C,+BAA6F;AAC7F,+BAAiF;AACjF,iDAAwD;AAExD,MAAM,QAAQ,GAAG,mBAAQ,CAAC,WAAW,EAAE,CAAC;AACxC,MAAM,UAAU,GAAG,IAAA,0BAAoB,GAAE,CAAC;AAE7B,QAAA,cAAc,GAAG,IAAA,YAAK,EAAC,GAAG,EAAE,CAAC,IAAA,sBAAgB,EAAC,UAAU,CAAC,CAAC,CAAC,IAAI,CAC1E,IAAA,aAAM,EAAC,EAAE,KAAK,EAAE,KAAM,EAAE,CAAC,EACzB,IAAA,YAAK,EAAC,EAAE,KAAK,EAAE,KAAM,EAAE,CAAC,EACxB,IAAA,kBAAW,EAAC,CAAC,CAAC,CACf,CAAC;AAEW,QAAA,WAAW,GAAG,sBAAc,CAAC,IAAI,CAC5C,IAAA,UAAG,EAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,EACzB,IAAA,aAAM,EAAC,CAAC,CAAC,EAAE,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AG,IAAA,YAAK,EAAC,GAAG,EAAE,CAAC,mBAAW,CAAC;KACjC,IAAI,CAAC,IAAA,YAAK,GAAE,CAAC;KACb,SAAS,CAAC,CAAC,GAAG,EAAE,EAAE;IACjB,IAAA,+BAAgB,EAAC,QAAQ,EAAE,EAAE,UAAU,EAAE,OAAO,GAAG,WAAW,EAAE,SAAS,EAAE,KAAK,EAAE,CAAC,CAAC;AACtF,CAAC,CAAC,CAAC;AACL,IAAA,YAAK,EAAC,GAAG,EAAE,CAAC,QAAQ,CAAC,QAAQ,CAAC,CAAC,SAAS,CAAC,GAAG,EAAE,CAAC,GAAG,CAAC,WAAW,EAAE,CAAC,CAAC","sourcesContent":["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/trade.js CHANGED
@@ -1,14 +1,15 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
+ const protocol_1 = require("@yuants/protocol");
4
+ const sql_1 = require("@yuants/sql");
5
+ const utils_1 = require("@yuants/utils");
3
6
  const rxjs_1 = require("rxjs");
4
- const api_1 = require("./api");
5
7
  const account_1 = require("./account");
6
- const utils_1 = require("@yuants/utils");
7
- const sql_1 = require("@yuants/sql");
8
- const protocol_1 = require("@yuants/protocol");
8
+ const api_1 = require("./api");
9
9
  const tradeParser = async (accountId, params) => {
10
10
  const tradeList = [];
11
- const result = await api_1.client.getAccountBillsArchive(params);
11
+ const credential = (0, api_1.getDefaultCredential)();
12
+ const result = await (0, api_1.getAccountBillsArchive)(credential, params);
12
13
  const productIdToProduct = new Map();
13
14
  const productIdSet = new Set();
14
15
  if (result.code === '0' && result.data) {