@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,13 @@
1
+ import { decodePath } from '@yuants/utils';
2
+ import { postTradeCancelOrder } from '../api/private-api';
3
+ export const cancelOrder = async (credential, order) => {
4
+ const [, , instId] = decodePath(order.product_id);
5
+ const res = await postTradeCancelOrder(credential, {
6
+ instId,
7
+ ordId: order.order_id,
8
+ });
9
+ if (res.code !== '0') {
10
+ throw new Error(`Cancel order failed: code=${res.code} msg=${res.msg}`);
11
+ }
12
+ };
13
+ //# sourceMappingURL=cancelOrder.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cancelOrder.js","sourceRoot":"","sources":["../../src/experimental/cancelOrder.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,UAAU,EAAE,MAAM,eAAe,CAAC;AAC3C,OAAO,EAAe,oBAAoB,EAAE,MAAM,oBAAoB,CAAC;AAEvE,MAAM,CAAC,MAAM,WAAW,GAAG,KAAK,EAAE,UAAuB,EAAE,KAAa,EAAE,EAAE;IAC1E,MAAM,CAAC,EAAE,AAAD,EAAG,MAAM,CAAC,GAAG,UAAU,CAAC,KAAK,CAAC,UAAU,CAAC,CAAC;IAClD,MAAM,GAAG,GAAG,MAAM,oBAAoB,CAAC,UAAU,EAAE;QACjD,MAAM;QACN,KAAK,EAAE,KAAK,CAAC,QAAS;KACvB,CAAC,CAAC;IACH,IAAI,GAAG,CAAC,IAAI,KAAK,GAAG,EAAE;QACpB,MAAM,IAAI,KAAK,CAAC,6BAA6B,GAAG,CAAC,IAAI,QAAQ,GAAG,CAAC,GAAG,EAAE,CAAC,CAAC;KACzE;AACH,CAAC,CAAC","sourcesContent":["import { IOrder } from '@yuants/data-order';\nimport { decodePath } from '@yuants/utils';\nimport { ICredential, postTradeCancelOrder } from '../api/private-api';\n\nexport const cancelOrder = async (credential: ICredential, order: IOrder) => {\n const [, , instId] = decodePath(order.product_id);\n const res = await postTradeCancelOrder(credential, {\n instId,\n ordId: order.order_id!,\n });\n if (res.code !== '0') {\n throw new Error(`Cancel order failed: code=${res.code} msg=${res.msg}`);\n }\n};\n"]}
@@ -0,0 +1,46 @@
1
+ import { provideExchangeServices } from '@yuants/exchange';
2
+ import { Terminal } from '@yuants/protocol';
3
+ import { encodePath, newError } from '@yuants/utils';
4
+ import { getAccountConfig } from '../api/private-api';
5
+ import { cancelOrder } from './cancelOrder';
6
+ import { getOrders } from './getOrders';
7
+ import { getPositions } from './getPositions';
8
+ import { modifyOrder } from './modifyOrder';
9
+ import { listProducts } from './product';
10
+ import { submitOrder } from './submitOrder';
11
+ const terminal = Terminal.fromNodeEnv();
12
+ provideExchangeServices(terminal, {
13
+ name: 'OKX',
14
+ credentialSchema: {
15
+ type: 'object',
16
+ required: ['access_key', 'secret_key', 'passphrase'],
17
+ properties: {
18
+ access_key: { type: 'string' },
19
+ secret_key: { type: 'string' },
20
+ passphrase: { type: 'string' },
21
+ },
22
+ },
23
+ getCredentialId: async function (credential) {
24
+ var _a, _b;
25
+ const accountConfig = await getAccountConfig(credential);
26
+ const uid = (_b = (_a = accountConfig.data) === null || _a === void 0 ? void 0 : _a[0]) === null || _b === void 0 ? void 0 : _b.uid;
27
+ if (!uid)
28
+ throw newError('OKX_CREDENTIAL_INVALID', { credential });
29
+ return encodePath('OKX', uid);
30
+ },
31
+ listProducts: listProducts,
32
+ getPositions: getPositions,
33
+ getOrders,
34
+ getPositionsByProductId: async (credential, product_id) => {
35
+ const positions = await getPositions(credential);
36
+ return positions.filter((x) => x.product_id === product_id);
37
+ },
38
+ getOrdersByProductId: async (credential, product_id) => {
39
+ const orders = await getOrders(credential);
40
+ return orders.filter((x) => x.product_id === product_id);
41
+ },
42
+ submitOrder: submitOrder,
43
+ modifyOrder: modifyOrder,
44
+ cancelOrder: cancelOrder,
45
+ });
46
+ //# sourceMappingURL=exchange.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"exchange.js","sourceRoot":"","sources":["../../src/experimental/exchange.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uBAAuB,EAAE,MAAM,kBAAkB,CAAC;AAC3D,OAAO,EAAE,QAAQ,EAAE,MAAM,kBAAkB,CAAC;AAC5C,OAAO,EAAE,UAAU,EAAE,QAAQ,EAAE,MAAM,eAAe,CAAC;AACrD,OAAO,EAAE,gBAAgB,EAAe,MAAM,oBAAoB,CAAC;AACnE,OAAO,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC;AAC5C,OAAO,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AACxC,OAAO,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;AAC9C,OAAO,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC;AAC5C,OAAO,EAAE,YAAY,EAAE,MAAM,WAAW,CAAC;AACzC,OAAO,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC;AAE5C,MAAM,QAAQ,GAAG,QAAQ,CAAC,WAAW,EAAE,CAAC;AAExC,uBAAuB,CAAc,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,gBAAgB,CAAC,UAAU,CAAC,CAAC;QACzD,MAAM,GAAG,GAAG,MAAA,MAAA,aAAa,CAAC,IAAI,0CAAG,CAAC,CAAC,0CAAE,GAAG,CAAC;QACzC,IAAI,CAAC,GAAG;YAAE,MAAM,QAAQ,CAAC,wBAAwB,EAAE,EAAE,UAAU,EAAE,CAAC,CAAC;QACnE,OAAO,UAAU,CAAC,KAAK,EAAE,GAAG,CAAC,CAAC;IAChC,CAAC;IACD,YAAY,EAAE,YAAY;IAC1B,YAAY,EAAE,YAAY;IAC1B,SAAS;IACT,uBAAuB,EAAE,KAAK,EAAE,UAAU,EAAE,UAAU,EAAE,EAAE;QACxD,MAAM,SAAS,GAAG,MAAM,YAAY,CAAC,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,SAAS,CAAC,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,WAAW;IACxB,WAAW,EAAE,WAAW;IACxB,WAAW,EAAE,WAAW;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,31 @@
1
+ import { encodePath } from '@yuants/utils';
2
+ import { getTradeOrdersPending } from '../api/private-api';
3
+ export const getOrders = async function (credential) {
4
+ const orders = [];
5
+ const orderRes = await getTradeOrdersPending(credential, {});
6
+ for (const x of orderRes.data || []) {
7
+ const order_type = x.ordType === 'market' ? 'MARKET' : x.ordType === 'limit' ? 'LIMIT' : 'UNKNOWN';
8
+ const order_direction = x.side === 'buy'
9
+ ? x.posSide === 'long'
10
+ ? 'OPEN_LONG'
11
+ : 'CLOSE_SHORT'
12
+ : x.posSide === 'short'
13
+ ? 'OPEN_SHORT'
14
+ : 'CLOSE_LONG';
15
+ orders.push({
16
+ order_id: x.ordId,
17
+ account_id: '',
18
+ product_id: encodePath('OKX', x.instType, x.instId),
19
+ submit_at: +x.cTime,
20
+ filled_at: +x.fillTime,
21
+ order_type,
22
+ order_direction,
23
+ volume: +x.sz,
24
+ traded_volume: +x.accFillSz,
25
+ price: +x.px,
26
+ traded_price: +x.avgPx,
27
+ });
28
+ }
29
+ return orders;
30
+ };
31
+ //# sourceMappingURL=getOrders.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"getOrders.js","sourceRoot":"","sources":["../../src/experimental/getOrders.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,UAAU,EAAE,MAAM,eAAe,CAAC;AAC3C,OAAO,EAAe,qBAAqB,EAAE,MAAM,oBAAoB,CAAC;AAExE,MAAM,CAAC,MAAM,SAAS,GAAG,KAAK,WAAW,UAAuB;IAC9D,MAAM,MAAM,GAAa,EAAE,CAAC;IAC5B,MAAM,QAAQ,GAAG,MAAM,qBAAqB,CAAC,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,UAAU,CAAC,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","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,101 @@
1
+ import { makeSpotPosition } from '@yuants/data-account';
2
+ import { encodePath } from '@yuants/utils';
3
+ import { getSpotPrice } from '../accountInfos/trading';
4
+ import { getAccountBalance, getAccountPositions, getAssetBalances, getFinanceSavingsBalance, getFlexibleLoanInfo, } from '../api/private-api';
5
+ import { productCache } from './product';
6
+ export const getPositions = async (credential) => {
7
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j;
8
+ const positions = [];
9
+ const [positionsApi, balanceApi, assetBalancesApi, offersApi, flexibleLoanInfoApi] = await Promise.all([
10
+ // Trading Accounts
11
+ getAccountPositions(credential, {}),
12
+ getAccountBalance(credential, {}),
13
+ // Funding Accounts
14
+ getAssetBalances(credential, {}),
15
+ // Earning Accounts
16
+ getFinanceSavingsBalance(credential, {}),
17
+ // Loan Accounts
18
+ getFlexibleLoanInfo(credential),
19
+ ]);
20
+ // 现货头寸
21
+ for (const detail of ((_b = (_a = balanceApi.data) === null || _a === void 0 ? void 0 : _a[0]) === null || _b === void 0 ? void 0 : _b.details) || []) {
22
+ const volume = +((_c = detail.cashBal) !== null && _c !== void 0 ? _c : 0);
23
+ const free_volume = Math.min(volume, // free should no more than balance if there is much profits
24
+ +((_d = detail.availEq) !== null && _d !== void 0 ? _d : 0));
25
+ const product_id = encodePath('OKX', 'SPOT', `${detail.ccy}-USDT`);
26
+ positions.push(makeSpotPosition({
27
+ position_id: product_id,
28
+ datasource_id: 'OKX',
29
+ product_id: product_id,
30
+ volume: volume,
31
+ free_volume: free_volume,
32
+ closable_price: getSpotPrice(detail.ccy),
33
+ }));
34
+ }
35
+ for (const x of positionsApi.data || []) {
36
+ const direction = x.posSide === 'long' ? 'LONG' : x.posSide === 'short' ? 'SHORT' : +x.pos > 0 ? 'LONG' : 'SHORT';
37
+ const volume = Math.abs(+x.pos);
38
+ const product_id = encodePath('OKX', x.instType, x.instId);
39
+ const closable_price = +x.last;
40
+ const theProduct = await productCache.query(product_id);
41
+ const valuation = ((_e = theProduct === null || theProduct === void 0 ? void 0 : theProduct.value_scale) !== null && _e !== void 0 ? _e : 1) * volume * closable_price || 0;
42
+ positions.push({
43
+ position_id: x.posId,
44
+ datasource_id: 'OKX',
45
+ product_id,
46
+ direction,
47
+ volume: volume,
48
+ free_volume: +x.availPos,
49
+ closable_price,
50
+ position_price: +x.avgPx,
51
+ floating_profit: +x.upl,
52
+ valuation,
53
+ });
54
+ }
55
+ for (const x of assetBalancesApi.data || []) {
56
+ positions.push(makeSpotPosition({
57
+ datasource_id: 'OKX',
58
+ position_id: encodePath('OKX', 'FUNDING-ASSET', `${x.ccy}`),
59
+ product_id: encodePath('OKX', 'FUNDING-ASSET', `${x.ccy}`),
60
+ volume: +x.bal,
61
+ free_volume: +x.bal,
62
+ closable_price: getSpotPrice(x.ccy),
63
+ }));
64
+ }
65
+ for (const offer of offersApi.data || []) {
66
+ positions.push(makeSpotPosition({
67
+ position_id: encodePath('OKX', 'EARNING-ASSET', `${offer.ccy}`),
68
+ datasource_id: 'OKX',
69
+ product_id: encodePath('OKX', 'EARNING-ASSET', `${offer.ccy}`),
70
+ volume: +offer.amt,
71
+ free_volume: +offer.amt,
72
+ closable_price: getSpotPrice(offer.ccy),
73
+ }));
74
+ }
75
+ for (const loan of ((_g = (_f = flexibleLoanInfoApi.data) === null || _f === void 0 ? void 0 : _f[0]) === null || _g === void 0 ? void 0 : _g.loanData) || []) {
76
+ positions.push({
77
+ datasource_id: 'OKX',
78
+ position_id: encodePath('OKX', 'LOAN', `${loan.ccy}`),
79
+ product_id: encodePath('OKX', 'LOAN', `${loan.ccy}`),
80
+ volume: +loan.amt,
81
+ free_volume: +loan.amt,
82
+ direction: 'SHORT',
83
+ position_price: 0,
84
+ closable_price: getSpotPrice(loan.ccy),
85
+ floating_profit: -getSpotPrice(loan.ccy) * +loan.amt,
86
+ valuation: getSpotPrice(loan.ccy) * +loan.amt,
87
+ });
88
+ }
89
+ for (const collateral of ((_j = (_h = flexibleLoanInfoApi.data) === null || _h === void 0 ? void 0 : _h[0]) === null || _j === void 0 ? void 0 : _j.collateralData) || []) {
90
+ positions.push(makeSpotPosition({
91
+ position_id: encodePath('OKX', 'COLLATERAL', `${collateral.ccy}`),
92
+ datasource_id: 'OKX',
93
+ product_id: encodePath('OKX', 'COLLATERAL', `${collateral.ccy}`),
94
+ volume: +collateral.amt,
95
+ free_volume: +collateral.amt,
96
+ closable_price: getSpotPrice(collateral.ccy),
97
+ }));
98
+ }
99
+ return positions;
100
+ };
101
+ //# sourceMappingURL=getPositions.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"getPositions.js","sourceRoot":"","sources":["../../src/exper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esContent":["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,58 @@
1
+ import { formatTime, decodePath, roundToStep } from '@yuants/utils';
2
+ import { firstValueFrom, map } from 'rxjs';
3
+ import { postTradeAmendOrder } from '../api/private-api';
4
+ import { productService } from '../public-data/product';
5
+ import { spotMarketTickers$ } from '../public-data/quote';
6
+ export const modifyOrder = async (credential, order) => {
7
+ const [, instType, instId] = decodePath(order.product_id);
8
+ const params = {
9
+ instId,
10
+ ordId: order.order_id, // 使用现有订单ID
11
+ };
12
+ // 如果需要修改价格
13
+ if (order.price !== undefined) {
14
+ params.newPx = order.price.toString();
15
+ }
16
+ // 如果需要修改数量
17
+ if (order.volume !== undefined) {
18
+ // 处理数量修改,类似于 SubmitOrder 中的逻辑
19
+ if (instType === 'SWAP') {
20
+ params.newSz = order.volume.toString();
21
+ }
22
+ else if (instType === 'SPOT') {
23
+ params.newSz = order.volume.toString();
24
+ }
25
+ else if (instType === 'MARGIN') {
26
+ if (order.order_type === 'LIMIT') {
27
+ params.newSz = order.volume.toString();
28
+ }
29
+ if (order.order_type === 'MAKER') {
30
+ params.newSz = order.volume.toString();
31
+ }
32
+ if (order.order_type === 'MARKET') {
33
+ // 对于市价单,可能需要根据当前价格计算新的数量
34
+ const price = await firstValueFrom(spotMarketTickers$.pipe(map((x) => order.order_direction === 'OPEN_LONG' || order.order_direction === 'CLOSE_SHORT'
35
+ ? +x[instId].askPx
36
+ : +x[instId].bidPx)));
37
+ if (!price) {
38
+ throw new Error(`invalid tick: ${price}`);
39
+ }
40
+ console.info(formatTime(Date.now()), 'ModifyOrder', 'price', price);
41
+ const theProduct = await firstValueFrom(productService.mapProductIdToProduct$.pipe(map((x) => x.get(order.product_id))));
42
+ if (!theProduct) {
43
+ throw new Error(`Unknown product: ${order.position_id}`);
44
+ }
45
+ params.newSz = roundToStep(order.volume * price, theProduct.volume_step).toString();
46
+ }
47
+ }
48
+ else {
49
+ throw new Error(`Unknown instType: ${instType}`);
50
+ }
51
+ }
52
+ console.info(formatTime(Date.now()), 'ModifyOrder', 'params', JSON.stringify(params));
53
+ const res = await postTradeAmendOrder(credential, params);
54
+ if (res.code !== '0') {
55
+ throw new Error(`ModifyOrder failed: code=${res.code}, msg=${res.msg}`);
56
+ }
57
+ };
58
+ //# sourceMappingURL=modifyOrder.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"modifyOrder.js","sourceRoot":"","sources":["../../src/experimental/modifyOrder.ts"],"names":[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C,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC,GAAG,EAAE,CAAC,EAAE,aAAa,EAAE,QAAQ,EAAE,IAAI,CAAC,SAAS,CAAC,MAAM,CAAC,CAAC,CAAC;IAEtF,MAAM,GAAG,GAAG,MAAM,mBAAmB,CAAC,UAAU,EAAE,MAAM,CAAC,CAAC;IAC1D,IAAI,GAAG,CAAC,IAAI,KAAK,GAAG,EAAE;QACpB,MAAM,IAAI,KAAK,CAAC,4BAA4B,GAAG,CAAC,IAAI,SAAS,GAAG,CAAC,GAAG,EAAE,CAAC,CAAC;KACzE;AACH,CAAC,CAAC","sourcesContent":["import { IOrder } from '@yuants/data-order';\nimport { formatTime, decodePath, roundToStep } from '@yuants/utils';\nimport { firstValueFrom, map } from 'rxjs';\nimport { ICredential, postTradeAmendOrder } from '../api/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,90 @@
1
+ import { createClientProductCache } from '@yuants/data-product';
2
+ import { Terminal } from '@yuants/protocol';
3
+ import { encodePath } from '@yuants/utils';
4
+ import { getInstruments } from '../api/public-api';
5
+ const terminal = Terminal.fromNodeEnv();
6
+ export const productCache = createClientProductCache(terminal, { expire: 3600000 });
7
+ export const listProducts = async () => {
8
+ const products = [];
9
+ // Get all instrument types in parallel
10
+ const [swapInstruments, marginInstruments, spotInstruments] = await Promise.all([
11
+ getInstruments({ instType: 'SWAP' }),
12
+ getInstruments({ instType: 'MARGIN' }),
13
+ getInstruments({ instType: 'SPOT' }),
14
+ ]);
15
+ // Get USDT swap products
16
+ for (const instrument of swapInstruments.data || []) {
17
+ if (instrument.ctType === 'linear' && +instrument.lever > 0) {
18
+ products.push({
19
+ datasource_id: 'OKX',
20
+ product_id: encodePath('OKX', instrument.instType, instrument.instId),
21
+ name: `${instrument.ctValCcy}-${instrument.settleCcy}-PERP`,
22
+ base_currency: instrument.ctValCcy,
23
+ quote_currency: instrument.settleCcy,
24
+ value_scale: +instrument.ctVal,
25
+ volume_step: +instrument.lotSz,
26
+ price_step: +instrument.tickSz,
27
+ margin_rate: 1 / +instrument.lever,
28
+ value_scale_unit: '',
29
+ value_based_cost: 0,
30
+ volume_based_cost: 0,
31
+ max_position: 0,
32
+ max_volume: 0,
33
+ allow_long: true,
34
+ allow_short: true,
35
+ market_id: 'OKX',
36
+ no_interest_rate: false,
37
+ });
38
+ }
39
+ }
40
+ // Get margin products
41
+ for (const instrument of marginInstruments.data || []) {
42
+ if (+instrument.lever > 0) {
43
+ products.push({
44
+ datasource_id: 'OKX',
45
+ product_id: encodePath('OKX', instrument.instType, instrument.instId),
46
+ base_currency: instrument.baseCcy,
47
+ quote_currency: instrument.quoteCcy,
48
+ value_scale: 1,
49
+ volume_step: +instrument.lotSz,
50
+ price_step: +instrument.tickSz,
51
+ margin_rate: 1 / +instrument.lever,
52
+ name: `${instrument.baseCcy}-${instrument.quoteCcy}-MARGIN`,
53
+ value_scale_unit: '',
54
+ value_based_cost: 0,
55
+ volume_based_cost: 0,
56
+ max_position: 0,
57
+ max_volume: 0,
58
+ allow_long: true,
59
+ allow_short: true,
60
+ market_id: 'OKX',
61
+ no_interest_rate: false,
62
+ });
63
+ }
64
+ }
65
+ // Get spot products
66
+ for (const instrument of spotInstruments.data || []) {
67
+ products.push({
68
+ datasource_id: 'OKX',
69
+ product_id: encodePath('OKX', instrument.instType, instrument.instId),
70
+ base_currency: instrument.baseCcy,
71
+ quote_currency: instrument.quoteCcy,
72
+ value_scale: 1,
73
+ volume_step: +instrument.lotSz,
74
+ price_step: +instrument.tickSz,
75
+ margin_rate: 1,
76
+ name: `${instrument.baseCcy}-${instrument.quoteCcy}-SPOT`,
77
+ value_scale_unit: '',
78
+ value_based_cost: 0,
79
+ volume_based_cost: 0,
80
+ max_position: 0,
81
+ max_volume: 0,
82
+ allow_long: true,
83
+ allow_short: true,
84
+ market_id: 'OKX',
85
+ no_interest_rate: true,
86
+ });
87
+ }
88
+ return products;
89
+ };
90
+ //# sourceMappingURL=product.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"product.js","sourceRoot":"","sources":["../../src/experimental/product.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,wBAAwB,EAAY,MAAM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AChB,gBAAgB,EAAE,KAAK;aACxB,CAAC,CAAC;SACJ;KACF;IAED,oBAAoB;IACpB,KAAK,MAAM,UAAU,IAAI,eAAe,CAAC,IAAI,IAAI,EAAE,EAAE;QACnD,QAAQ,CAAC,IAAI,CAAC;YACZ,aAAa,EAAE,KAAK;YACpB,UAAU,EAAE,UAAU,CAAC,KAAK,EAAE,UAAU,CAAC,QAAQ,EAAE,UAAU,CAAC,MAAM,CAAC;YACrE,aAAa,EAAE,UAAU,CAAC,OAAO;YACjC,cAAc,EAAE,UAAU,CAAC,QAAQ;YACnC,WAAW,EAAE,CAAC;YACd,WAAW,EAAE,CAAC,UAAU,CAAC,KAAK;YAC9B,UAAU,EAAE,CAAC,UAAU,CAAC,MAAM;YAC9B,WAAW,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","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,109 @@
1
+ import { decodePath, formatTime, roundToStep } from '@yuants/utils';
2
+ import { firstValueFrom, map } from 'rxjs';
3
+ import { postTradeOrder } from '../api/private-api';
4
+ import { productService } from '../public-data/product';
5
+ import { spotMarketTickers$ } from '../public-data/quote';
6
+ const mapOrderDirectionToSide = (direction) => {
7
+ switch (direction) {
8
+ case 'OPEN_LONG':
9
+ case 'CLOSE_SHORT':
10
+ return 'buy';
11
+ case 'OPEN_SHORT':
12
+ case 'CLOSE_LONG':
13
+ return 'sell';
14
+ }
15
+ throw new Error(`Unknown direction: ${direction}`);
16
+ };
17
+ const mapOrderDirectionToPosSide = (direction) => {
18
+ switch (direction) {
19
+ case 'OPEN_LONG':
20
+ case 'CLOSE_LONG':
21
+ return 'long';
22
+ case 'CLOSE_SHORT':
23
+ case 'OPEN_SHORT':
24
+ return 'short';
25
+ }
26
+ throw new Error(`Unknown direction: ${direction}`);
27
+ };
28
+ const mapOrderTypeToOrdType = (order_type) => {
29
+ switch (order_type) {
30
+ case 'LIMIT':
31
+ return 'limit';
32
+ case 'MARKET':
33
+ return 'market';
34
+ case 'MAKER':
35
+ return 'post_only';
36
+ }
37
+ throw new Error(`Unknown order type: ${order_type}`);
38
+ };
39
+ export const submitOrder = async (credential, order) => {
40
+ var _a, _b, _c;
41
+ const [, instType, instId] = decodePath(order.product_id);
42
+ // 交易数量,表示要购买或者出售的数量。
43
+ // 当币币/币币杠杆以限价买入和卖出时,指交易货币数量。
44
+ // 当币币杠杆以市价买入时,指计价货币的数量。
45
+ // 当币币杠杆以市价卖出时,指交易货币的数量。
46
+ // 对于币币市价单,单位由 tgtCcy 决定
47
+ // 当交割、永续、期权买入和卖出时,指合约张数。
48
+ const mapOrderVolumeToSz = async (order) => {
49
+ if (instType === 'SWAP') {
50
+ return order.volume;
51
+ }
52
+ if (instType === 'MARGIN') {
53
+ if (order.order_type === 'LIMIT') {
54
+ return order.volume;
55
+ }
56
+ if (order.order_type === 'MAKER') {
57
+ return order.volume;
58
+ }
59
+ if (order.order_type === 'MARKET') {
60
+ if (order.order_direction === 'OPEN_SHORT' || order.order_direction === 'CLOSE_LONG') {
61
+ return order.volume;
62
+ }
63
+ //
64
+ const price = await firstValueFrom(spotMarketTickers$.pipe(map((x) => mapOrderDirectionToPosSide(order.order_direction) === 'long'
65
+ ? +x[instId].askPx
66
+ : +x[instId].bidPx)));
67
+ if (!price) {
68
+ throw new Error(`invalid tick: ${price}`);
69
+ }
70
+ console.info(formatTime(Date.now()), 'SubmitOrder', 'price', price);
71
+ const theProduct = await firstValueFrom(productService.mapProductIdToProduct$.pipe(map((x) => x.get(order.product_id))));
72
+ if (!theProduct) {
73
+ throw new Error(`Unknown product: ${order.position_id}`);
74
+ }
75
+ return roundToStep(order.volume * price, theProduct.volume_step);
76
+ }
77
+ return 0;
78
+ }
79
+ if (instType === 'SPOT') {
80
+ return order.volume;
81
+ }
82
+ throw new Error(`Unknown instType: ${instType}`);
83
+ };
84
+ const params = {
85
+ instId,
86
+ tdMode: instType === 'SPOT' ? 'cash' : 'cross',
87
+ side: mapOrderDirectionToSide(order.order_direction),
88
+ posSide: instType === 'MARGIN' || instType === 'SPOT'
89
+ ? 'net'
90
+ : mapOrderDirectionToPosSide(order.order_direction),
91
+ ordType: mapOrderTypeToOrdType(order.order_type),
92
+ sz: (await mapOrderVolumeToSz(order)).toString(),
93
+ tgtCcy: instType === 'SPOT' && order.order_type === 'MARKET' ? 'base_ccy' : undefined,
94
+ reduceOnly: instType === 'MARGIN' && ['CLOSE_LONG', 'CLOSE_SHORT'].includes((_a = order.order_direction) !== null && _a !== void 0 ? _a : '')
95
+ ? 'true'
96
+ : undefined,
97
+ px: order.order_type === 'LIMIT' || order.order_type === 'MAKER' ? order.price.toString() : undefined,
98
+ ccy: instType === 'MARGIN' ? 'USDT' : undefined,
99
+ };
100
+ console.info(formatTime(Date.now()), 'SubmitOrder', 'params', JSON.stringify(params));
101
+ const res = await postTradeOrder(credential, params);
102
+ if (res.code === '0' && ((_c = (_b = res.data) === null || _b === void 0 ? void 0 : _b[0]) === null || _c === void 0 ? void 0 : _c.ordId)) {
103
+ return { order_id: res.data[0].ordId };
104
+ }
105
+ throw `Failed to submit order: ${res.code} ${res.msg}: ${res.data
106
+ .map((x) => `${x.sCode} ${x.sMsg}`)
107
+ .join('; ')}`;
108
+ };
109
+ //# sourceMappingURL=submitOrder.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"submitOrder.js","sourceRoot":"","sources":["../../src/experimental/submitOrder.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,UAAU,EAAE,UAAU,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC;AACpE,OAAO,EAAE,cAAc,EAAE,GAAG,EAAE,MAAM,MAAM,CAAC;AAC3C,OAAO,EAAe,cAAc,EAAE,MAAM,oBAAoB,CAAC;AACjE,OAAO,EAAE,cAAc,EAAE,MAAM,wBAAwB,CAAC;AACxD,OAAO,EAAE,kBAAkB,EAAE,MAAM,sBAAsB,CAAC;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,qBAAqB,GAAG,CAAC,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AAI,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","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/dist/index.js 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';
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","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","sourcesContent":["import './account';\nimport './account-actions-with-credential';\nimport './api-service';\nimport './order';\nimport './order-actions';\nimport './order-actions-with-credential';\nimport './public-data/interest_rate';\nimport './public-data/market-order';\nimport './public-data/ohlc';\nimport './public-data/quote';\nimport './services';\nimport './strategy-account';\nimport './trade';\nimport './transfer';\n"]}
1
+ {"version":3,"file":"index.js","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","sourcesContent":["import './account';\nimport './account-actions-with-credential';\nimport './api-service';\nimport './experimental/exchange';\nimport './order';\nimport './order-actions';\nimport './order-actions-with-credential';\nimport './public-data/interest_rate';\nimport './public-data/market-order';\nimport './public-data/ohlc';\nimport './public-data/quote';\nimport './services';\nimport './strategy-account';\nimport './trade';\nimport './transfer';\n"]}
@@ -0,0 +1,4 @@
1
+ import { IOrder } from '@yuants/data-order';
2
+ import { ICredential } from '../api/private-api';
3
+ export declare const cancelOrder: (credential: ICredential, order: IOrder) => Promise<void>;
4
+ //# sourceMappingURL=cancelOrder.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cancelOrder.d.ts","sourceRoot":"","sources":["../../src/experimental/cancelOrder.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,oBAAoB,CAAC;AAE5C,OAAO,EAAE,WAAW,EAAwB,MAAM,oBAAoB,CAAC;AAEvE,eAAO,MAAM,WAAW,eAAsB,WAAW,SAAS,MAAM,kBASvE,CAAC"}
@@ -0,0 +1,17 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.cancelOrder = void 0;
4
+ const utils_1 = require("@yuants/utils");
5
+ const private_api_1 = require("../api/private-api");
6
+ const cancelOrder = async (credential, order) => {
7
+ const [, , instId] = (0, utils_1.decodePath)(order.product_id);
8
+ const res = await (0, private_api_1.postTradeCancelOrder)(credential, {
9
+ instId,
10
+ ordId: order.order_id,
11
+ });
12
+ if (res.code !== '0') {
13
+ throw new Error(`Cancel order failed: code=${res.code} msg=${res.msg}`);
14
+ }
15
+ };
16
+ exports.cancelOrder = cancelOrder;
17
+ //# sourceMappingURL=cancelOrder.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cancelOrder.js","sourceRoot":"","sources":["../../src/experimental/cancelOrder.ts"],"names":[],"mappings":";;;AACA,yCAA2C;AAC3C,oDAAuE;AAEhE,MAAM,WAAW,GAAG,KAAK,EAAE,UAAuB,EAAE,KAAa,EAAE,EAAE;IAC1E,MAAM,CAAC,EAAE,AAAD,EAAG,MAAM,CAAC,GAAG,IAAA,kBAAU,EAAC,KAAK,CAAC,UAAU,CAAC,CAAC;IAClD,MAAM,GAAG,GAAG,MAAM,IAAA,kCAAoB,EAAC,UAAU,EAAE;QACjD,MAAM;QACN,KAAK,EAAE,KAAK,CAAC,QAAS;KACvB,CAAC,CAAC;IACH,IAAI,GAAG,CAAC,IAAI,KAAK,GAAG,EAAE;QACpB,MAAM,IAAI,KAAK,CAAC,6BAA6B,GAAG,CAAC,IAAI,QAAQ,GAAG,CAAC,GAAG,EAAE,CAAC,CAAC;KACzE;AACH,CAAC,CAAC;AATW,QAAA,WAAW,eAStB","sourcesContent":["import { IOrder } from '@yuants/data-order';\nimport { decodePath } from '@yuants/utils';\nimport { ICredential, postTradeCancelOrder } from '../api/private-api';\n\nexport const cancelOrder = async (credential: ICredential, order: IOrder) => {\n const [, , instId] = decodePath(order.product_id);\n const res = await postTradeCancelOrder(credential, {\n instId,\n ordId: order.order_id!,\n });\n if (res.code !== '0') {\n throw new Error(`Cancel order failed: code=${res.code} msg=${res.msg}`);\n }\n};\n"]}
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=exchange.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"exchange.d.ts","sourceRoot":"","sources":["../../src/experimental/exchange.ts"],"names":[],"mappings":""}