@yuants/vendor-okx 0.27.11 → 0.28.0

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 (50) hide show
  1. package/dist/experimental/cancelOrder.js +13 -0
  2. package/dist/experimental/cancelOrder.js.map +1 -0
  3. package/dist/experimental/exchange.js +46 -0
  4. package/dist/experimental/exchange.js.map +1 -0
  5. package/dist/experimental/getOrders.js +31 -0
  6. package/dist/experimental/getOrders.js.map +1 -0
  7. package/dist/experimental/getPositions.js +101 -0
  8. package/dist/experimental/getPositions.js.map +1 -0
  9. package/dist/experimental/modifyOrder.js +58 -0
  10. package/dist/experimental/modifyOrder.js.map +1 -0
  11. package/dist/experimental/product.js +90 -0
  12. package/dist/experimental/product.js.map +1 -0
  13. package/dist/experimental/submitOrder.js +109 -0
  14. package/dist/experimental/submitOrder.js.map +1 -0
  15. package/dist/index.js +1 -0
  16. package/dist/index.js.map +1 -1
  17. package/lib/experimental/cancelOrder.d.ts +4 -0
  18. package/lib/experimental/cancelOrder.d.ts.map +1 -0
  19. package/lib/experimental/cancelOrder.js +17 -0
  20. package/lib/experimental/cancelOrder.js.map +1 -0
  21. package/lib/experimental/exchange.d.ts +2 -0
  22. package/lib/experimental/exchange.d.ts.map +1 -0
  23. package/lib/experimental/exchange.js +48 -0
  24. package/lib/experimental/exchange.js.map +1 -0
  25. package/lib/experimental/getOrders.d.ts +4 -0
  26. package/lib/experimental/getOrders.d.ts.map +1 -0
  27. package/lib/experimental/getOrders.js +35 -0
  28. package/lib/experimental/getOrders.js.map +1 -0
  29. package/lib/experimental/getPositions.d.ts +4 -0
  30. package/lib/experimental/getPositions.d.ts.map +1 -0
  31. package/lib/experimental/getPositions.js +105 -0
  32. package/lib/experimental/getPositions.js.map +1 -0
  33. package/lib/experimental/modifyOrder.d.ts +4 -0
  34. package/lib/experimental/modifyOrder.d.ts.map +1 -0
  35. package/lib/experimental/modifyOrder.js +62 -0
  36. package/lib/experimental/modifyOrder.js.map +1 -0
  37. package/lib/experimental/product.d.ts +4 -0
  38. package/lib/experimental/product.d.ts.map +1 -0
  39. package/lib/experimental/product.js +94 -0
  40. package/lib/experimental/product.js.map +1 -0
  41. package/lib/experimental/submitOrder.d.ts +6 -0
  42. package/lib/experimental/submitOrder.d.ts.map +1 -0
  43. package/lib/experimental/submitOrder.js +113 -0
  44. package/lib/experimental/submitOrder.js.map +1 -0
  45. package/lib/index.d.ts +1 -0
  46. package/lib/index.d.ts.map +1 -1
  47. package/lib/index.js +1 -0
  48. package/lib/index.js.map +1 -1
  49. package/package.json +3 -3
  50. package/temp/package-deps.json +13 -6
@@ -0,0 +1,48 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const exchange_1 = require("@yuants/exchange");
4
+ const protocol_1 = require("@yuants/protocol");
5
+ const utils_1 = require("@yuants/utils");
6
+ const private_api_1 = require("../api/private-api");
7
+ const cancelOrder_1 = require("./cancelOrder");
8
+ const getOrders_1 = require("./getOrders");
9
+ const getPositions_1 = require("./getPositions");
10
+ const modifyOrder_1 = require("./modifyOrder");
11
+ const product_1 = require("./product");
12
+ const submitOrder_1 = require("./submitOrder");
13
+ const terminal = protocol_1.Terminal.fromNodeEnv();
14
+ (0, exchange_1.provideExchangeServices)(terminal, {
15
+ name: 'OKX',
16
+ credentialSchema: {
17
+ type: 'object',
18
+ required: ['access_key', 'secret_key', 'passphrase'],
19
+ properties: {
20
+ access_key: { type: 'string' },
21
+ secret_key: { type: 'string' },
22
+ passphrase: { type: 'string' },
23
+ },
24
+ },
25
+ getCredentialId: async function (credential) {
26
+ var _a, _b;
27
+ const accountConfig = await (0, private_api_1.getAccountConfig)(credential);
28
+ const uid = (_b = (_a = accountConfig.data) === null || _a === void 0 ? void 0 : _a[0]) === null || _b === void 0 ? void 0 : _b.uid;
29
+ if (!uid)
30
+ throw (0, utils_1.newError)('OKX_CREDENTIAL_INVALID', { credential });
31
+ return (0, utils_1.encodePath)('OKX', uid);
32
+ },
33
+ listProducts: product_1.listProducts,
34
+ getPositions: getPositions_1.getPositions,
35
+ getOrders: getOrders_1.getOrders,
36
+ getPositionsByProductId: async (credential, product_id) => {
37
+ const positions = await (0, getPositions_1.getPositions)(credential);
38
+ return positions.filter((x) => x.product_id === product_id);
39
+ },
40
+ getOrdersByProductId: async (credential, product_id) => {
41
+ const orders = await (0, getOrders_1.getOrders)(credential);
42
+ return orders.filter((x) => x.product_id === product_id);
43
+ },
44
+ submitOrder: submitOrder_1.submitOrder,
45
+ modifyOrder: modifyOrder_1.modifyOrder,
46
+ cancelOrder: cancelOrder_1.cancelOrder,
47
+ });
48
+ //# sourceMappingURL=exchange.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"exchange.js","sourceRoot":"","sources":["../../src/experimental/exchange.ts"],"names":[],"mappings":";;AAAA,+CAA2D;AAC3D,+CAA4C;AAC5C,yCAAqD;AACrD,oDAAmE;AACnE,+CAA4C;AAC5C,2CAAwC;AACxC,iDAA8C;AAC9C,+CAA4C;AAC5C,uCAAyC;AACzC,+CAA4C;AAE5C,MAAM,QAAQ,GAAG,mBAAQ,CAAC,WAAW,EAAE,CAAC;AAExC,IAAA,kCAAuB,EAAc,QAAQ,EAAE;IAC7C,IAAI,EAAE,KAAK;IACX,gBAAgB,EAAE;QAChB,IAAI,EAAE,QAAQ;QACd,QAAQ,EAAE,CAAC,YAAY,EAAE,YAAY,EAAE,YAAY,CAAC;QACpD,UAAU,EAAE;YACV,UAAU,EAAE,EAAE,IAAI,EAAE,QAAQ,EAAE;YAC9B,UAAU,EAAE,EAAE,IAAI,EAAE,QAAQ,EAAE;YAC9B,UAAU,EAAE,EAAE,IAAI,EAAE,QAAQ,EAAE;SAC/B;KACF;IACD,eAAe,EAAE,KAAK,WAAW,UAAuB;;QACtD,MAAM,aAAa,GAAG,MAAM,IAAA,8BAAgB,EAAC,UAAU,CAAC,CAAC;QACzD,MAAM,GAAG,GAAG,MAAA,MAAA,aAAa,CAAC,IAAI,0CAAG,CAAC,CAAC,0CAAE,GAAG,CAAC;QACzC,IAAI,CAAC,GAAG;YAAE,MAAM,IAAA,gBAAQ,EAAC,wBAAwB,EAAE,EAAE,UAAU,EAAE,CAAC,CAAC;QACnE,OAAO,IAAA,kBAAU,EAAC,KAAK,EAAE,GAAG,CAAC,CAAC;IAChC,CAAC;IACD,YAAY,EAAE,sBAAY;IAC1B,YAAY,EAAE,2BAAY;IAC1B,SAAS,EAAT,qBAAS;IACT,uBAAuB,EAAE,KAAK,EAAE,UAAU,EAAE,UAAU,EAAE,EAAE;QACxD,MAAM,SAAS,GAAG,MAAM,IAAA,2BAAY,EAAC,UAAU,CAAC,CAAC;QACjD,OAAO,SAAS,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,UAAU,KAAK,UAAU,CAAC,CAAC;IAC9D,CAAC;IACD,oBAAoB,EAAE,KAAK,EAAE,UAAU,EAAE,UAAU,EAAE,EAAE;QACrD,MAAM,MAAM,GAAG,MAAM,IAAA,qBAAS,EAAC,UAAU,CAAC,CAAC;QAC3C,OAAO,MAAM,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,UAAU,KAAK,UAAU,CAAC,CAAC;IAC3D,CAAC;IACD,WAAW,EAAE,yBAAW;IACxB,WAAW,EAAE,yBAAW;IACxB,WAAW,EAAE,yBAAW;CACzB,CAAC,CAAC","sourcesContent":["import { provideExchangeServices } from '@yuants/exchange';\nimport { Terminal } from '@yuants/protocol';\nimport { encodePath, newError } from '@yuants/utils';\nimport { getAccountConfig, ICredential } from '../api/private-api';\nimport { cancelOrder } from './cancelOrder';\nimport { getOrders } from './getOrders';\nimport { getPositions } from './getPositions';\nimport { modifyOrder } from './modifyOrder';\nimport { listProducts } from './product';\nimport { submitOrder } from './submitOrder';\n\nconst terminal = Terminal.fromNodeEnv();\n\nprovideExchangeServices<ICredential>(terminal, {\n name: 'OKX',\n credentialSchema: {\n type: 'object',\n required: ['access_key', 'secret_key', 'passphrase'],\n properties: {\n access_key: { type: 'string' },\n secret_key: { type: 'string' },\n passphrase: { type: 'string' },\n },\n },\n getCredentialId: async function (credential: ICredential): Promise<string> {\n const accountConfig = await getAccountConfig(credential);\n const uid = accountConfig.data?.[0]?.uid;\n if (!uid) throw newError('OKX_CREDENTIAL_INVALID', { credential });\n return encodePath('OKX', uid);\n },\n listProducts: listProducts,\n getPositions: getPositions,\n getOrders,\n getPositionsByProductId: async (credential, product_id) => {\n const positions = await getPositions(credential);\n return positions.filter((x) => x.product_id === product_id);\n },\n getOrdersByProductId: async (credential, product_id) => {\n const orders = await getOrders(credential);\n return orders.filter((x) => x.product_id === product_id);\n },\n submitOrder: submitOrder,\n modifyOrder: modifyOrder,\n cancelOrder: cancelOrder,\n});\n"]}
@@ -0,0 +1,4 @@
1
+ import { IOrder } from '@yuants/data-order';
2
+ import { ICredential } from '../api/private-api';
3
+ export declare const getOrders: (credential: ICredential) => Promise<IOrder[]>;
4
+ //# sourceMappingURL=getOrders.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"getOrders.d.ts","sourceRoot":"","sources":["../../src/experimental/getOrders.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,oBAAoB,CAAC;AAE5C,OAAO,EAAE,WAAW,EAAyB,MAAM,oBAAoB,CAAC;AAExE,eAAO,MAAM,SAAS,eAA+B,WAAW,KAAG,QAAQ,MAAM,EAAE,CA+BlF,CAAC"}
@@ -0,0 +1,35 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getOrders = void 0;
4
+ const utils_1 = require("@yuants/utils");
5
+ const private_api_1 = require("../api/private-api");
6
+ const getOrders = async function (credential) {
7
+ const orders = [];
8
+ const orderRes = await (0, private_api_1.getTradeOrdersPending)(credential, {});
9
+ for (const x of orderRes.data || []) {
10
+ const order_type = x.ordType === 'market' ? 'MARKET' : x.ordType === 'limit' ? 'LIMIT' : 'UNKNOWN';
11
+ const order_direction = x.side === 'buy'
12
+ ? x.posSide === 'long'
13
+ ? 'OPEN_LONG'
14
+ : 'CLOSE_SHORT'
15
+ : x.posSide === 'short'
16
+ ? 'OPEN_SHORT'
17
+ : 'CLOSE_LONG';
18
+ orders.push({
19
+ order_id: x.ordId,
20
+ account_id: '',
21
+ product_id: (0, utils_1.encodePath)('OKX', x.instType, x.instId),
22
+ submit_at: +x.cTime,
23
+ filled_at: +x.fillTime,
24
+ order_type,
25
+ order_direction,
26
+ volume: +x.sz,
27
+ traded_volume: +x.accFillSz,
28
+ price: +x.px,
29
+ traded_price: +x.avgPx,
30
+ });
31
+ }
32
+ return orders;
33
+ };
34
+ exports.getOrders = getOrders;
35
+ //# sourceMappingURL=getOrders.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"getOrders.js","sourceRoot":"","sources":["../../src/experimental/getOrders.ts"],"names":[],"mappings":";;;AACA,yCAA2C;AAC3C,oDAAwE;AAEjE,MAAM,SAAS,GAAG,KAAK,WAAW,UAAuB;IAC9D,MAAM,MAAM,GAAa,EAAE,CAAC;IAC5B,MAAM,QAAQ,GAAG,MAAM,IAAA,mCAAqB,EAAC,UAAU,EAAE,EAAE,CAAC,CAAC;IAE7D,KAAK,MAAM,CAAC,IAAI,QAAQ,CAAC,IAAI,IAAI,EAAE,EAAE;QACnC,MAAM,UAAU,GAAG,CAAC,CAAC,OAAO,KAAK,QAAQ,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC,CAAC,OAAO,KAAK,OAAO,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,SAAS,CAAC;QAEnG,MAAM,eAAe,GACnB,CAAC,CAAC,IAAI,KAAK,KAAK;YACd,CAAC,CAAC,CAAC,CAAC,OAAO,KAAK,MAAM;gBACpB,CAAC,CAAC,WAAW;gBACb,CAAC,CAAC,aAAa;YACjB,CAAC,CAAC,CAAC,CAAC,OAAO,KAAK,OAAO;gBACvB,CAAC,CAAC,YAAY;gBACd,CAAC,CAAC,YAAY,CAAC;QACnB,MAAM,CAAC,IAAI,CAAC;YACV,QAAQ,EAAE,CAAC,CAAC,KAAK;YACjB,UAAU,EAAE,EAAE;YACd,UAAU,EAAE,IAAA,kBAAU,EAAC,KAAK,EAAE,CAAC,CAAC,QAAQ,EAAE,CAAC,CAAC,MAAM,CAAC;YACnD,SAAS,EAAE,CAAC,CAAC,CAAC,KAAK;YACnB,SAAS,EAAE,CAAC,CAAC,CAAC,QAAQ;YACtB,UAAU;YACV,eAAe;YACf,MAAM,EAAE,CAAC,CAAC,CAAC,EAAE;YACb,aAAa,EAAE,CAAC,CAAC,CAAC,SAAS;YAC3B,KAAK,EAAE,CAAC,CAAC,CAAC,EAAE;YACZ,YAAY,EAAE,CAAC,CAAC,CAAC,KAAK;SACvB,CAAC,CAAC;KACJ;IAED,OAAO,MAAM,CAAC;AAChB,CAAC,CAAC;AA/BW,QAAA,SAAS,aA+BpB","sourcesContent":["import { IOrder } from '@yuants/data-order';\nimport { encodePath } from '@yuants/utils';\nimport { ICredential, getTradeOrdersPending } from '../api/private-api';\n\nexport const getOrders = async function (credential: ICredential): Promise<IOrder[]> {\n const orders: IOrder[] = [];\n const orderRes = await getTradeOrdersPending(credential, {});\n\n for (const x of orderRes.data || []) {\n const order_type = x.ordType === 'market' ? 'MARKET' : x.ordType === 'limit' ? 'LIMIT' : 'UNKNOWN';\n\n const order_direction =\n x.side === 'buy'\n ? x.posSide === 'long'\n ? 'OPEN_LONG'\n : 'CLOSE_SHORT'\n : x.posSide === 'short'\n ? 'OPEN_SHORT'\n : 'CLOSE_LONG';\n orders.push({\n order_id: x.ordId,\n account_id: '',\n product_id: encodePath('OKX', x.instType, x.instId),\n submit_at: +x.cTime,\n filled_at: +x.fillTime,\n order_type,\n order_direction,\n volume: +x.sz,\n traded_volume: +x.accFillSz,\n price: +x.px,\n traded_price: +x.avgPx,\n });\n }\n\n return orders;\n};\n"]}
@@ -0,0 +1,4 @@
1
+ import { IPosition } from '@yuants/data-account';
2
+ import { ICredential } from '../api/private-api';
3
+ export declare const getPositions: (credential: ICredential) => Promise<IPosition[]>;
4
+ //# sourceMappingURL=getPositions.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"getPositions.d.ts","sourceRoot":"","sources":["../../src/experimental/getPositions.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAoB,MAAM,sBAAsB,CAAC;AAGnE,OAAO,EAML,WAAW,EACZ,MAAM,oBAAoB,CAAC;AAG5B,eAAO,MAAM,YAAY,eAAsB,WAAW,KAAG,QAAQ,SAAS,EAAE,CAiH/E,CAAC"}
@@ -0,0 +1,105 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getPositions = void 0;
4
+ const data_account_1 = require("@yuants/data-account");
5
+ const utils_1 = require("@yuants/utils");
6
+ const trading_1 = require("../accountInfos/trading");
7
+ const private_api_1 = require("../api/private-api");
8
+ const product_1 = require("./product");
9
+ const getPositions = async (credential) => {
10
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j;
11
+ const positions = [];
12
+ const [positionsApi, balanceApi, assetBalancesApi, offersApi, flexibleLoanInfoApi] = await Promise.all([
13
+ // Trading Accounts
14
+ (0, private_api_1.getAccountPositions)(credential, {}),
15
+ (0, private_api_1.getAccountBalance)(credential, {}),
16
+ // Funding Accounts
17
+ (0, private_api_1.getAssetBalances)(credential, {}),
18
+ // Earning Accounts
19
+ (0, private_api_1.getFinanceSavingsBalance)(credential, {}),
20
+ // Loan Accounts
21
+ (0, private_api_1.getFlexibleLoanInfo)(credential),
22
+ ]);
23
+ // 现货头寸
24
+ for (const detail of ((_b = (_a = balanceApi.data) === null || _a === void 0 ? void 0 : _a[0]) === null || _b === void 0 ? void 0 : _b.details) || []) {
25
+ const volume = +((_c = detail.cashBal) !== null && _c !== void 0 ? _c : 0);
26
+ const free_volume = Math.min(volume, // free should no more than balance if there is much profits
27
+ +((_d = detail.availEq) !== null && _d !== void 0 ? _d : 0));
28
+ const product_id = (0, utils_1.encodePath)('OKX', 'SPOT', `${detail.ccy}-USDT`);
29
+ positions.push((0, data_account_1.makeSpotPosition)({
30
+ position_id: product_id,
31
+ datasource_id: 'OKX',
32
+ product_id: product_id,
33
+ volume: volume,
34
+ free_volume: free_volume,
35
+ closable_price: (0, trading_1.getSpotPrice)(detail.ccy),
36
+ }));
37
+ }
38
+ for (const x of positionsApi.data || []) {
39
+ const direction = x.posSide === 'long' ? 'LONG' : x.posSide === 'short' ? 'SHORT' : +x.pos > 0 ? 'LONG' : 'SHORT';
40
+ const volume = Math.abs(+x.pos);
41
+ const product_id = (0, utils_1.encodePath)('OKX', x.instType, x.instId);
42
+ const closable_price = +x.last;
43
+ const theProduct = await product_1.productCache.query(product_id);
44
+ const valuation = ((_e = theProduct === null || theProduct === void 0 ? void 0 : theProduct.value_scale) !== null && _e !== void 0 ? _e : 1) * volume * closable_price || 0;
45
+ positions.push({
46
+ position_id: x.posId,
47
+ datasource_id: 'OKX',
48
+ product_id,
49
+ direction,
50
+ volume: volume,
51
+ free_volume: +x.availPos,
52
+ closable_price,
53
+ position_price: +x.avgPx,
54
+ floating_profit: +x.upl,
55
+ valuation,
56
+ });
57
+ }
58
+ for (const x of assetBalancesApi.data || []) {
59
+ positions.push((0, data_account_1.makeSpotPosition)({
60
+ datasource_id: 'OKX',
61
+ position_id: (0, utils_1.encodePath)('OKX', 'FUNDING-ASSET', `${x.ccy}`),
62
+ product_id: (0, utils_1.encodePath)('OKX', 'FUNDING-ASSET', `${x.ccy}`),
63
+ volume: +x.bal,
64
+ free_volume: +x.bal,
65
+ closable_price: (0, trading_1.getSpotPrice)(x.ccy),
66
+ }));
67
+ }
68
+ for (const offer of offersApi.data || []) {
69
+ positions.push((0, data_account_1.makeSpotPosition)({
70
+ position_id: (0, utils_1.encodePath)('OKX', 'EARNING-ASSET', `${offer.ccy}`),
71
+ datasource_id: 'OKX',
72
+ product_id: (0, utils_1.encodePath)('OKX', 'EARNING-ASSET', `${offer.ccy}`),
73
+ volume: +offer.amt,
74
+ free_volume: +offer.amt,
75
+ closable_price: (0, trading_1.getSpotPrice)(offer.ccy),
76
+ }));
77
+ }
78
+ for (const loan of ((_g = (_f = flexibleLoanInfoApi.data) === null || _f === void 0 ? void 0 : _f[0]) === null || _g === void 0 ? void 0 : _g.loanData) || []) {
79
+ positions.push({
80
+ datasource_id: 'OKX',
81
+ position_id: (0, utils_1.encodePath)('OKX', 'LOAN', `${loan.ccy}`),
82
+ product_id: (0, utils_1.encodePath)('OKX', 'LOAN', `${loan.ccy}`),
83
+ volume: +loan.amt,
84
+ free_volume: +loan.amt,
85
+ direction: 'SHORT',
86
+ position_price: 0,
87
+ closable_price: (0, trading_1.getSpotPrice)(loan.ccy),
88
+ floating_profit: -(0, trading_1.getSpotPrice)(loan.ccy) * +loan.amt,
89
+ valuation: (0, trading_1.getSpotPrice)(loan.ccy) * +loan.amt,
90
+ });
91
+ }
92
+ for (const collateral of ((_j = (_h = flexibleLoanInfoApi.data) === null || _h === void 0 ? void 0 : _h[0]) === null || _j === void 0 ? void 0 : _j.collateralData) || []) {
93
+ positions.push((0, data_account_1.makeSpotPosition)({
94
+ position_id: (0, utils_1.encodePath)('OKX', 'COLLATERAL', `${collateral.ccy}`),
95
+ datasource_id: 'OKX',
96
+ product_id: (0, utils_1.encodePath)('OKX', 'COLLATERAL', `${collateral.ccy}`),
97
+ volume: +collateral.amt,
98
+ free_volume: +collateral.amt,
99
+ closable_price: (0, trading_1.getSpotPrice)(collateral.ccy),
100
+ }));
101
+ }
102
+ return positions;
103
+ };
104
+ exports.getPositions = getPositions;
105
+ //# sourceMappingURL=getPositions.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"getPositions.js","sourceRoot":"","sources":["../../src/experimental/getPositions.ts"],"names":[],"mappings":";;;AAAA,uDAAmE;AACnE,yCAA2C;AAC3C,qDAAuD;AACvD,oDAO4B;AAC5B,uCAAyC;AAElC,MAAM,YAAY,GAAG,K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AG,EAAE,CAAC;YACpD,MAAM,EAAE,CAAC,IAAI,CAAC,GAAG;YACjB,WAAW,EAAE,CAAC,IAAI,CAAC,GAAG;YACtB,SAAS,EAAE,OAAO;YAClB,cAAc,EAAE,CAAC;YACjB,cAAc,EAAE,IAAA,sBAAY,EAAC,IAAI,CAAC,GAAG,CAAC;YACtC,eAAe,EAAE,CAAC,IAAA,sBAAY,EAAC,IAAI,CAAC,GAAG,CAAC,GAAG,CAAC,IAAI,CAAC,GAAG;YACpD,SAAS,EAAE,IAAA,sBAAY,EAAC,IAAI,CAAC,GAAG,CAAC,GAAG,CAAC,IAAI,CAAC,GAAG;SAC9C,CAAC,CAAC;KACJ;IAED,KAAK,MAAM,UAAU,IAAI,CAAA,MAAA,MAAA,mBAAmB,CAAC,IAAI,0CAAG,CAAC,CAAC,0CAAE,cAAc,KAAI,EAAE,EAAE;QAC5E,SAAS,CAAC,IAAI,CACZ,IAAA,+BAAgB,EAAC;YACf,WAAW,EAAE,IAAA,kBAAU,EAAC,KAAK,EAAE,YAAY,EAAE,GAAG,UAAU,CAAC,GAAG,EAAE,CAAC;YACjE,aAAa,EAAE,KAAK;YACpB,UAAU,EAAE,IAAA,kBAAU,EAAC,KAAK,EAAE,YAAY,EAAE,GAAG,UAAU,CAAC,GAAG,EAAE,CAAC;YAChE,MAAM,EAAE,CAAC,UAAU,CAAC,GAAG;YACvB,WAAW,EAAE,CAAC,UAAU,CAAC,GAAG;YAC5B,cAAc,EAAE,IAAA,sBAAY,EAAC,UAAU,CAAC,GAAG,CAAC;SAC7C,CAAC,CACH,CAAC;KACH;IAED,OAAO,SAAS,CAAC;AACnB,CAAC,CAAC;AAjHW,QAAA,YAAY,gBAiHvB","sourcesContent":["import { IPosition, makeSpotPosition } from '@yuants/data-account';\nimport { encodePath } from '@yuants/utils';\nimport { getSpotPrice } from '../accountInfos/trading';\nimport {\n getAccountBalance,\n getAccountPositions,\n getAssetBalances,\n getFinanceSavingsBalance,\n getFlexibleLoanInfo,\n ICredential,\n} from '../api/private-api';\nimport { productCache } from './product';\n\nexport const getPositions = async (credential: ICredential): Promise<IPosition[]> => {\n const positions: IPosition[] = [];\n\n const [positionsApi, balanceApi, assetBalancesApi, offersApi, flexibleLoanInfoApi] = await Promise.all([\n // Trading Accounts\n getAccountPositions(credential, {}),\n getAccountBalance(credential, {}),\n // Funding Accounts\n getAssetBalances(credential, {}),\n // Earning Accounts\n getFinanceSavingsBalance(credential, {}),\n // Loan Accounts\n getFlexibleLoanInfo(credential),\n ]);\n\n // 现货头寸\n for (const detail of balanceApi.data?.[0]?.details || []) {\n const volume = +(detail.cashBal ?? 0);\n const free_volume = Math.min(\n volume, // free should no more than balance if there is much profits\n +(detail.availEq ?? 0),\n );\n\n const product_id = encodePath('OKX', 'SPOT', `${detail.ccy}-USDT`);\n positions.push(\n makeSpotPosition({\n position_id: product_id,\n datasource_id: 'OKX',\n product_id: product_id,\n volume: volume,\n free_volume: free_volume,\n closable_price: getSpotPrice(detail.ccy),\n }),\n );\n }\n for (const x of positionsApi.data || []) {\n const direction =\n x.posSide === 'long' ? 'LONG' : x.posSide === 'short' ? 'SHORT' : +x.pos > 0 ? 'LONG' : 'SHORT';\n const volume = Math.abs(+x.pos);\n const product_id = encodePath('OKX', x.instType, x.instId);\n const closable_price = +x.last;\n const theProduct = await productCache.query(product_id);\n const valuation = (theProduct?.value_scale ?? 1) * volume * closable_price || 0;\n\n positions.push({\n position_id: x.posId,\n datasource_id: 'OKX',\n product_id,\n direction,\n volume: volume,\n free_volume: +x.availPos,\n closable_price,\n position_price: +x.avgPx,\n floating_profit: +x.upl,\n valuation,\n });\n }\n\n for (const x of assetBalancesApi.data || []) {\n positions.push(\n makeSpotPosition({\n datasource_id: 'OKX',\n position_id: encodePath('OKX', 'FUNDING-ASSET', `${x.ccy}`),\n product_id: encodePath('OKX', 'FUNDING-ASSET', `${x.ccy}`),\n volume: +x.bal,\n free_volume: +x.bal,\n closable_price: getSpotPrice(x.ccy),\n }),\n );\n }\n\n for (const offer of offersApi.data || []) {\n positions.push(\n makeSpotPosition({\n position_id: encodePath('OKX', 'EARNING-ASSET', `${offer.ccy}`),\n datasource_id: 'OKX',\n product_id: encodePath('OKX', 'EARNING-ASSET', `${offer.ccy}`),\n volume: +offer.amt,\n free_volume: +offer.amt,\n closable_price: getSpotPrice(offer.ccy),\n }),\n );\n }\n\n for (const loan of flexibleLoanInfoApi.data?.[0]?.loanData || []) {\n positions.push({\n datasource_id: 'OKX',\n position_id: encodePath('OKX', 'LOAN', `${loan.ccy}`),\n product_id: encodePath('OKX', 'LOAN', `${loan.ccy}`),\n volume: +loan.amt,\n free_volume: +loan.amt,\n direction: 'SHORT',\n position_price: 0,\n closable_price: getSpotPrice(loan.ccy),\n floating_profit: -getSpotPrice(loan.ccy) * +loan.amt,\n valuation: getSpotPrice(loan.ccy) * +loan.amt,\n });\n }\n\n for (const collateral of flexibleLoanInfoApi.data?.[0]?.collateralData || []) {\n positions.push(\n makeSpotPosition({\n position_id: encodePath('OKX', 'COLLATERAL', `${collateral.ccy}`),\n datasource_id: 'OKX',\n product_id: encodePath('OKX', 'COLLATERAL', `${collateral.ccy}`),\n volume: +collateral.amt,\n free_volume: +collateral.amt,\n closable_price: getSpotPrice(collateral.ccy),\n }),\n );\n }\n\n return positions;\n};\n"]}
@@ -0,0 +1,4 @@
1
+ import { IOrder } from '@yuants/data-order';
2
+ import { ICredential } from '../api/private-api';
3
+ export declare const modifyOrder: (credential: ICredential, order: IOrder) => Promise<void>;
4
+ //# sourceMappingURL=modifyOrder.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"modifyOrder.d.ts","sourceRoot":"","sources":["../../src/experimental/modifyOrder.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,oBAAoB,CAAC;AAG5C,OAAO,EAAE,WAAW,EAAuB,MAAM,oBAAoB,CAAC;AAItE,eAAO,MAAM,WAAW,eAAsB,WAAW,SAAS,MAAM,kBAiEvE,CAAC"}
@@ -0,0 +1,62 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.modifyOrder = void 0;
4
+ const utils_1 = require("@yuants/utils");
5
+ const rxjs_1 = require("rxjs");
6
+ const private_api_1 = require("../api/private-api");
7
+ const product_1 = require("../public-data/product");
8
+ const quote_1 = require("../public-data/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, private_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/experimental/modifyOrder.ts"],"names":[],"mappings":";;;AACA,yCAAoE;AACpE,+BAA2C;AAC3C,oDAAsE;AACtE,oDAAwD;AACxD,gDAA0D;AAEnD,MAAM,WAAW,GAAG,KAAK,EAAE,UAAuB,EAAE,KAAa,EAAE,EAAE;IAC1E,MAAM,CAAC,EAAE,QAAQ,EAAE,MAAM,CAAC,GAAG,IAAA,kBAAU,EAAC,KAAK,CAAC,UAAU,CAAC,CAAC;IAC1D,MAAM,MAAM,GAKR;QACF,MAAM;QACN,KAAK,EAAE,KAAK,CAAC,QAAS,EAAE,WAAW;KACpC,CAAC;IAEF,WAAW;IACX,IAAI,KAAK,CAAC,KAAK,KAAK,SAAS,EAAE;QAC7B,MAAM,CAAC,KAAK,GAAG,KAAK,CAAC,KAAK,CAAC,QAAQ,EAAE,CAAC;KACvC;IAED,WAAW;IACX,IAAI,KAAK,CAAC,MAAM,KAAK,SAAS,EAAE;QAC9B,8BAA8B;QAC9B,IAAI,QAAQ,KAAK,MAAM,EAAE;YACvB,MAAM,CAAC,KAAK,GAAG,KAAK,CAAC,MAAM,CAAC,QAAQ,EAAE,CAAC;SACxC;aAAM,IAAI,QAAQ,KAAK,MAAM,EAAE;YAC9B,MAAM,CAAC,KAAK,GAAG,KAAK,CAAC,MAAM,CAAC,QAAQ,EAAE,CAAC;SACxC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,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,iCAAmB,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/private-api';\nimport { productService } from '../public-data/product';\nimport { spotMarketTickers$ } from '../public-data/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 { IProduct } from '@yuants/data-product';
2
+ export declare const productCache: import("@yuants/cache").ICache<IProduct>;
3
+ export declare const listProducts: () => Promise<IProduct[]>;
4
+ //# sourceMappingURL=product.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"product.d.ts","sourceRoot":"","sources":["../../src/experimental/product.ts"],"names":[],"mappings":"AAAA,OAAO,EAA4B,QAAQ,EAAE,MAAM,sBAAsB,CAAC;AAO1E,eAAO,MAAM,YAAY,0CAA2D,CAAC;AAErF,eAAO,MAAM,YAAY,QAAa,QAAQ,QAAQ,EAAE,CAsFvD,CAAC"}
@@ -0,0 +1,94 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.listProducts = exports.productCache = void 0;
4
+ const data_product_1 = require("@yuants/data-product");
5
+ const protocol_1 = require("@yuants/protocol");
6
+ const utils_1 = require("@yuants/utils");
7
+ const public_api_1 = require("../api/public-api");
8
+ const terminal = protocol_1.Terminal.fromNodeEnv();
9
+ exports.productCache = (0, data_product_1.createClientProductCache)(terminal, { expire: 3600000 });
10
+ const listProducts = async () => {
11
+ const products = [];
12
+ // Get all instrument types in parallel
13
+ const [swapInstruments, marginInstruments, spotInstruments] = await Promise.all([
14
+ (0, public_api_1.getInstruments)({ instType: 'SWAP' }),
15
+ (0, public_api_1.getInstruments)({ instType: 'MARGIN' }),
16
+ (0, public_api_1.getInstruments)({ instType: 'SPOT' }),
17
+ ]);
18
+ // Get USDT swap products
19
+ for (const instrument of swapInstruments.data || []) {
20
+ if (instrument.ctType === 'linear' && +instrument.lever > 0) {
21
+ products.push({
22
+ datasource_id: 'OKX',
23
+ product_id: (0, utils_1.encodePath)('OKX', instrument.instType, instrument.instId),
24
+ name: `${instrument.ctValCcy}-${instrument.settleCcy}-PERP`,
25
+ base_currency: instrument.ctValCcy,
26
+ quote_currency: instrument.settleCcy,
27
+ value_scale: +instrument.ctVal,
28
+ volume_step: +instrument.lotSz,
29
+ price_step: +instrument.tickSz,
30
+ margin_rate: 1 / +instrument.lever,
31
+ value_scale_unit: '',
32
+ value_based_cost: 0,
33
+ volume_based_cost: 0,
34
+ max_position: 0,
35
+ max_volume: 0,
36
+ allow_long: true,
37
+ allow_short: true,
38
+ market_id: 'OKX',
39
+ no_interest_rate: false,
40
+ });
41
+ }
42
+ }
43
+ // Get margin products
44
+ for (const instrument of marginInstruments.data || []) {
45
+ if (+instrument.lever > 0) {
46
+ products.push({
47
+ datasource_id: 'OKX',
48
+ product_id: (0, utils_1.encodePath)('OKX', instrument.instType, instrument.instId),
49
+ base_currency: instrument.baseCcy,
50
+ quote_currency: instrument.quoteCcy,
51
+ value_scale: 1,
52
+ volume_step: +instrument.lotSz,
53
+ price_step: +instrument.tickSz,
54
+ margin_rate: 1 / +instrument.lever,
55
+ name: `${instrument.baseCcy}-${instrument.quoteCcy}-MARGIN`,
56
+ value_scale_unit: '',
57
+ value_based_cost: 0,
58
+ volume_based_cost: 0,
59
+ max_position: 0,
60
+ max_volume: 0,
61
+ allow_long: true,
62
+ allow_short: true,
63
+ market_id: 'OKX',
64
+ no_interest_rate: false,
65
+ });
66
+ }
67
+ }
68
+ // Get spot products
69
+ for (const instrument of spotInstruments.data || []) {
70
+ products.push({
71
+ datasource_id: 'OKX',
72
+ product_id: (0, utils_1.encodePath)('OKX', instrument.instType, instrument.instId),
73
+ base_currency: instrument.baseCcy,
74
+ quote_currency: instrument.quoteCcy,
75
+ value_scale: 1,
76
+ volume_step: +instrument.lotSz,
77
+ price_step: +instrument.tickSz,
78
+ margin_rate: 1,
79
+ name: `${instrument.baseCcy}-${instrument.quoteCcy}-SPOT`,
80
+ value_scale_unit: '',
81
+ value_based_cost: 0,
82
+ volume_based_cost: 0,
83
+ max_position: 0,
84
+ max_volume: 0,
85
+ allow_long: true,
86
+ allow_short: true,
87
+ market_id: 'OKX',
88
+ no_interest_rate: true,
89
+ });
90
+ }
91
+ return products;
92
+ };
93
+ exports.listProducts = listProducts;
94
+ //# sourceMappingURL=product.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"product.js","sourceRoot":"","sources":["../../src/experimental/product.ts"],"names":[],"mappings":";;;AAAA,uDAA0E;AAC1E,+CAA4C;AAC5C,yCAA2C;AAC3C,kDAAmD;AAEnD,MAAM,QAAQ,GAAG,mBAAQ,CAAC,WAAW,EAAE,CAAC;AAE3B,QAAA,YAAY,GAAG,IAAA,uCAAwB,EAAC,QAAQ,EAAE,EAAE,MAAM,EAAE,OAAQ,EAAE,CAAC,CAAC;AAE9E,MAAM,YAAY,GAAG,KAAK,IAAyB,EAAE;IAC1D,MAAM,QAAQ,GAAe,EAAE,CAAC;IAEhC,uCAAuC;IACvC,MAAM,CAAC,eAAe,EAAE,iBAAiB,EAAE,eAAe,CAAC,GAAG,MAAM,O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AAW,EAAE,CAAC;YACd,IAAI,EAAE,GAAG,UAAU,CAAC,OAAO,IAAI,UAAU,CAAC,QAAQ,OAAO;YACzD,gBAAgB,EAAE,EAAE;YACpB,gBAAgB,EAAE,CAAC;YACnB,iBAAiB,EAAE,CAAC;YACpB,YAAY,EAAE,CAAC;YACf,UAAU,EAAE,CAAC;YACb,UAAU,EAAE,IAAI;YAChB,WAAW,EAAE,IAAI;YACjB,SAAS,EAAE,KAAK;YAChB,gBAAgB,EAAE,IAAI;SACvB,CAAC,CAAC;KACJ;IACD,OAAO,QAAQ,CAAC;AAClB,CAAC,CAAC;AAtFW,QAAA,YAAY,gBAsFvB","sourcesContent":["import { createClientProductCache, IProduct } from '@yuants/data-product';\nimport { Terminal } from '@yuants/protocol';\nimport { encodePath } from '@yuants/utils';\nimport { getInstruments } from '../api/public-api';\n\nconst terminal = Terminal.fromNodeEnv();\n\nexport const productCache = createClientProductCache(terminal, { expire: 3600_000 });\n\nexport const listProducts = async (): Promise<IProduct[]> => {\n const products: IProduct[] = [];\n\n // Get all instrument types in parallel\n const [swapInstruments, marginInstruments, spotInstruments] = await Promise.all([\n getInstruments({ instType: 'SWAP' }),\n getInstruments({ instType: 'MARGIN' }),\n getInstruments({ instType: 'SPOT' }),\n ]);\n\n // Get USDT swap products\n for (const instrument of swapInstruments.data || []) {\n if (instrument.ctType === 'linear' && +instrument.lever > 0) {\n products.push({\n datasource_id: 'OKX',\n product_id: encodePath('OKX', instrument.instType, instrument.instId),\n name: `${instrument.ctValCcy}-${instrument.settleCcy}-PERP`,\n base_currency: instrument.ctValCcy,\n quote_currency: instrument.settleCcy,\n value_scale: +instrument.ctVal,\n volume_step: +instrument.lotSz,\n price_step: +instrument.tickSz,\n margin_rate: 1 / +instrument.lever,\n value_scale_unit: '',\n value_based_cost: 0,\n volume_based_cost: 0,\n max_position: 0,\n max_volume: 0,\n allow_long: true,\n allow_short: true,\n market_id: 'OKX',\n no_interest_rate: false,\n });\n }\n }\n\n // Get margin products\n for (const instrument of marginInstruments.data || []) {\n if (+instrument.lever > 0) {\n products.push({\n datasource_id: 'OKX',\n product_id: encodePath('OKX', instrument.instType, instrument.instId),\n base_currency: instrument.baseCcy,\n quote_currency: instrument.quoteCcy,\n value_scale: 1,\n volume_step: +instrument.lotSz,\n price_step: +instrument.tickSz,\n margin_rate: 1 / +instrument.lever,\n name: `${instrument.baseCcy}-${instrument.quoteCcy}-MARGIN`,\n value_scale_unit: '',\n value_based_cost: 0,\n volume_based_cost: 0,\n max_position: 0,\n max_volume: 0,\n allow_long: true,\n allow_short: true,\n market_id: 'OKX',\n no_interest_rate: false,\n });\n }\n }\n\n // Get spot products\n for (const instrument of spotInstruments.data || []) {\n products.push({\n datasource_id: 'OKX',\n product_id: encodePath('OKX', instrument.instType, instrument.instId),\n base_currency: instrument.baseCcy,\n quote_currency: instrument.quoteCcy,\n value_scale: 1,\n volume_step: +instrument.lotSz,\n price_step: +instrument.tickSz,\n margin_rate: 1,\n name: `${instrument.baseCcy}-${instrument.quoteCcy}-SPOT`,\n value_scale_unit: '',\n value_based_cost: 0,\n volume_based_cost: 0,\n max_position: 0,\n max_volume: 0,\n allow_long: true,\n allow_short: true,\n market_id: 'OKX',\n no_interest_rate: true,\n });\n }\n return products;\n};\n"]}
@@ -0,0 +1,6 @@
1
+ import { IOrder } from '@yuants/data-order';
2
+ import { ICredential } from '../api/private-api';
3
+ export declare const submitOrder: (credential: ICredential, order: IOrder) => Promise<{
4
+ order_id: string;
5
+ }>;
6
+ //# sourceMappingURL=submitOrder.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"submitOrder.d.ts","sourceRoot":"","sources":["../../src/experimental/submitOrder.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,oBAAoB,CAAC;AAG5C,OAAO,EAAE,WAAW,EAAkB,MAAM,oBAAoB,CAAC;AAwCjE,eAAO,MAAM,WAAW,eAAsB,WAAW,SAAS,MAAM,KAAG,QAAQ;IAAE,QAAQ,EAAE,MAAM,CAAA;CAAE,CAmFtG,CAAC"}
@@ -0,0 +1,113 @@
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 private_api_1 = require("../api/private-api");
7
+ const product_1 = require("../public-data/product");
8
+ const quote_1 = require("../public-data/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, private_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 { order_id: res.data[0].ordId };
107
+ }
108
+ throw `Failed to submit order: ${res.code} ${res.msg}: ${res.data
109
+ .map((x) => `${x.sCode} ${x.sMsg}`)
110
+ .join('; ')}`;
111
+ };
112
+ exports.submitOrder = submitOrder;
113
+ //# sourceMappingURL=submitOrder.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"submitOrder.js","sourceRoot":"","sources":["../../src/experimental/submitOrder.ts"],"names":[],"mappings":";;;AACA,yCAAoE;AACpE,+BAA2C;AAC3C,oDAAiE;AACjE,oDAAwD;AACxD,gDAA0D;AAE1D,MAAM,uBAAuB,GAAG,CAAC,SAAkB,EAAE,EAAE;IACrD,QAAQ,SAAS,EAAE;QACjB,KAAK,WAAW,CAAC;QACjB,KAAK,aAAa;YAChB,OAAO,KAAK,CAAC;QACf,KAAK,YAAY,CAAC;QAClB,KAAK,YAAY;YACf,OAAO,MAAM,CAAC;KACjB;IACD,MAAM,IAAI,KAAK,CAAC,sBAAsB,SAAS,EAAE,CAAC,CAAC;AACrD,CAAC,CAAC;AAEF,MAAM,0BAA0B,GAAG,CAAC,SAAkB,EAAE,EAAE;IACxD,QAAQ,SAAS,EAAE;QACjB,KAAK,WAAW,CAAC;QACjB,KAAK,YAAY;YACf,OAAO,MAAM,CAAC;QAChB,KAAK,aAAa,CAAC;QACnB,KAAK,YAAY;YACf,OAAO,OAAO,CAAC;KAClB;IACD,MAAM,IAAI,KAAK,CAAC,sBAAsB,SAAS,EAAE,CAAC,CAAC;AACrD,CAAC,CAAC;AAEF,MAAM,qB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,CAAC,KAAK,EAAE,CAAC;KACxC;IACD,MAAM,2BAA2B,GAAG,CAAC,IAAI,IAAI,GAAG,CAAC,GAAG,KAAK,GAAG,CAAC,IAAI;SAC9D,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,GAAG,CAAC,CAAC,KAAK,IAAI,CAAC,CAAC,IAAI,EAAE,CAAC;SAClC,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC;AAClB,CAAC,CAAC;AAnFW,QAAA,WAAW,eAmFtB","sourcesContent":["import { IOrder } from '@yuants/data-order';\nimport { decodePath, formatTime, roundToStep } from '@yuants/utils';\nimport { firstValueFrom, map } from 'rxjs';\nimport { ICredential, postTradeOrder } from '../api/private-api';\nimport { productService } from '../public-data/product';\nimport { spotMarketTickers$ } from '../public-data/quote';\n\nconst mapOrderDirectionToSide = (direction?: string) => {\n switch (direction) {\n case 'OPEN_LONG':\n case 'CLOSE_SHORT':\n return 'buy';\n case 'OPEN_SHORT':\n case 'CLOSE_LONG':\n return 'sell';\n }\n throw new Error(`Unknown direction: ${direction}`);\n};\n\nconst mapOrderDirectionToPosSide = (direction?: string) => {\n switch (direction) {\n case 'OPEN_LONG':\n case 'CLOSE_LONG':\n return 'long';\n case 'CLOSE_SHORT':\n case 'OPEN_SHORT':\n return 'short';\n }\n throw new Error(`Unknown direction: ${direction}`);\n};\n\nconst mapOrderTypeToOrdType = (order_type?: string) => {\n switch (order_type) {\n case 'LIMIT':\n return 'limit';\n case 'MARKET':\n return 'market';\n case 'MAKER':\n return 'post_only';\n }\n throw new Error(`Unknown order type: ${order_type}`);\n};\n\nexport const submitOrder = async (credential: ICredential, order: IOrder): Promise<{ order_id: string }> => {\n const [, instType, instId] = decodePath(order.product_id);\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 { order_id: res.data[0].ordId };\n }\n throw `Failed to submit order: ${res.code} ${res.msg}: ${res.data\n .map((x) => `${x.sCode} ${x.sMsg}`)\n .join('; ')}`;\n};\n"]}
package/lib/index.d.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  import './account';
2
2
  import './account-actions-with-credential';
3
3
  import './api-service';
4
+ import './experimental/exchange';
4
5
  import './order';
5
6
  import './order-actions';
6
7
  import './order-actions-with-credential';
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,WAAW,CAAC;AACnB,OAAO,mCAAmC,CAAC;AAC3C,OAAO,eAAe,CAAC;AACvB,OAAO,SAAS,CAAC;AACjB,OAAO,iBAAiB,CAAC;AACzB,OAAO,iCAAiC,CAAC;AACzC,OAAO,6BAA6B,CAAC;AACrC,OAAO,4BAA4B,CAAC;AACpC,OAAO,oBAAoB,CAAC;AAC5B,OAAO,qBAAqB,CAAC;AAC7B,OAAO,YAAY,CAAC;AACpB,OAAO,oBAAoB,CAAC;AAC5B,OAAO,SAAS,CAAC;AACjB,OAAO,YAAY,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,WAAW,CAAC;AACnB,OAAO,mCAAmC,CAAC;AAC3C,OAAO,eAAe,CAAC;AACvB,OAAO,yBAAyB,CAAC;AACjC,OAAO,SAAS,CAAC;AACjB,OAAO,iBAAiB,CAAC;AACzB,OAAO,iCAAiC,CAAC;AACzC,OAAO,6BAA6B,CAAC;AACrC,OAAO,4BAA4B,CAAC;AACpC,OAAO,oBAAoB,CAAC;AAC5B,OAAO,qBAAqB,CAAC;AAC7B,OAAO,YAAY,CAAC;AACpB,OAAO,oBAAoB,CAAC;AAC5B,OAAO,SAAS,CAAC;AACjB,OAAO,YAAY,CAAC"}
package/lib/index.js CHANGED
@@ -3,6 +3,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  require("./account");
4
4
  require("./account-actions-with-credential");
5
5
  require("./api-service");
6
+ require("./experimental/exchange");
6
7
  require("./order");
7
8
  require("./order-actions");
8
9
  require("./order-actions-with-credential");