@yuants/vendor-okx 0.16.9 → 0.17.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/account.js +198 -0
- package/dist/account.js.map +1 -0
- package/dist/api.js +463 -0
- package/dist/api.js.map +1 -0
- package/dist/cli.js +3 -0
- package/dist/cli.js.map +1 -0
- package/dist/cluster.js +80 -0
- package/dist/cluster.js.map +1 -0
- package/dist/extension.js +89 -0
- package/dist/extension.js.map +1 -0
- package/dist/index.js +7 -0
- package/dist/index.js.map +1 -0
- package/dist/interest_rate.js +133 -0
- package/dist/interest_rate.js.map +1 -0
- package/dist/legacy_index.js +554 -0
- package/dist/legacy_index.js.map +1 -0
- package/dist/logger.js +91 -0
- package/dist/logger.js.map +1 -0
- package/dist/ohlc.js +171 -0
- package/dist/ohlc.js.map +1 -0
- package/dist/order.js +96 -0
- package/dist/order.js.map +1 -0
- package/dist/product.js +85 -0
- package/dist/product.js.map +1 -0
- package/dist/quote.js +58 -0
- package/dist/quote.js.map +1 -0
- package/dist/vendor-okx.d.ts +1 -0
- package/dist/websocket.js +80 -0
- package/dist/websocket.js.map +1 -0
- package/lib/account.d.ts +102 -0
- package/lib/account.d.ts.map +1 -0
- package/lib/account.js +201 -0
- package/lib/account.js.map +1 -0
- package/lib/api.d.ts +1401 -0
- package/lib/api.d.ts.map +1 -0
- package/lib/api.js +470 -0
- package/lib/api.js.map +1 -0
- package/lib/cli.d.ts +3 -0
- package/lib/cli.d.ts.map +1 -0
- package/lib/cli.js +5 -0
- package/lib/cli.js.map +1 -0
- package/lib/cluster.d.ts +2 -0
- package/lib/cluster.d.ts.map +1 -0
- package/lib/cluster.js +108 -0
- package/lib/cluster.js.map +1 -0
- package/lib/extension.d.ts +4 -0
- package/lib/extension.d.ts.map +1 -0
- package/lib/extension.js +91 -0
- package/lib/extension.js.map +1 -0
- package/lib/index.d.ts +7 -0
- package/lib/index.d.ts.map +1 -0
- package/lib/index.js +9 -0
- package/lib/index.js.map +1 -0
- package/lib/interest_rate.d.ts +2 -0
- package/lib/interest_rate.d.ts.map +1 -0
- package/lib/interest_rate.js +135 -0
- package/lib/interest_rate.js.map +1 -0
- package/lib/legacy_index.d.ts +2 -0
- package/lib/legacy_index.d.ts.map +1 -0
- package/lib/legacy_index.js +556 -0
- package/lib/legacy_index.js.map +1 -0
- package/lib/logger.d.ts +21 -0
- package/lib/logger.d.ts.map +1 -0
- package/lib/logger.js +98 -0
- package/lib/logger.js.map +1 -0
- package/lib/ohlc.d.ts +2 -0
- package/lib/ohlc.d.ts.map +1 -0
- package/lib/ohlc.js +173 -0
- package/lib/ohlc.js.map +1 -0
- package/lib/order.d.ts +4 -0
- package/lib/order.d.ts.map +1 -0
- package/lib/order.js +99 -0
- package/lib/order.js.map +1 -0
- package/lib/product.d.ts +6 -0
- package/lib/product.d.ts.map +1 -0
- package/lib/product.js +88 -0
- package/lib/product.js.map +1 -0
- package/lib/quote.d.ts +42 -0
- package/lib/quote.d.ts.map +1 -0
- package/lib/quote.js +61 -0
- package/lib/quote.js.map +1 -0
- package/lib/websocket.d.ts +14 -0
- package/lib/websocket.d.ts.map +1 -0
- package/lib/websocket.js +83 -0
- package/lib/websocket.js.map +1 -0
- package/package.json +9 -4
- package/temp/image-tag +1 -0
- package/temp/package-deps.json +42 -0
- package/temp/vendor-okx.api.json +177 -0
- package/temp/vendor-okx.api.md +9 -0
@@ -0,0 +1,80 @@
|
|
1
|
+
import { encodePath, formatTime } from '@yuants/utils';
|
2
|
+
// import WebSocket from 'ws';
|
3
|
+
class OKXWsClient {
|
4
|
+
constructor(url) {
|
5
|
+
this.connected = false;
|
6
|
+
// this.instId = instId;
|
7
|
+
this.ws = new WebSocket(url);
|
8
|
+
this.pendingSub = [];
|
9
|
+
// this.ws.
|
10
|
+
this.ws.addEventListener('open', () => {
|
11
|
+
this.connected = true;
|
12
|
+
console.info(formatTime(Date.now()), '✅ WS connected');
|
13
|
+
while (this.pendingSub.length > 0) {
|
14
|
+
const msg = this.pendingSub.shift();
|
15
|
+
if (msg) {
|
16
|
+
this.ws.send(msg);
|
17
|
+
console.info(formatTime(Date.now()), `📩 Sent subscribe for ${msg}`);
|
18
|
+
}
|
19
|
+
}
|
20
|
+
});
|
21
|
+
this.ws.addEventListener('message', (raw) => this.handleMessage(raw));
|
22
|
+
this.subscriptions = new Set();
|
23
|
+
this.handlers = {}; // key: channel, value: callback
|
24
|
+
}
|
25
|
+
// 处理消息
|
26
|
+
handleMessage(raw) {
|
27
|
+
var _a, _b;
|
28
|
+
const msg = JSON.parse(raw.data);
|
29
|
+
if ((_a = msg.arg) === null || _a === void 0 ? void 0 : _a.channel) {
|
30
|
+
const channelId = encodePath(msg.arg.channel, msg.arg.instId);
|
31
|
+
const data = (_b = msg.data) === null || _b === void 0 ? void 0 : _b[0];
|
32
|
+
if (data && this.handlers[channelId]) {
|
33
|
+
this.handlers[channelId](data, msg.arg);
|
34
|
+
}
|
35
|
+
}
|
36
|
+
else if (msg.event) {
|
37
|
+
console.info('Event:', msg);
|
38
|
+
}
|
39
|
+
}
|
40
|
+
// 调用订阅
|
41
|
+
subscribe(channel, instId, handler) {
|
42
|
+
const channelId = encodePath(channel, instId);
|
43
|
+
if (this.subscriptions.has(channelId)) {
|
44
|
+
console.info(formatTime(Date.now()), `⚠️ Already subscribed: ${channelId}`);
|
45
|
+
return;
|
46
|
+
}
|
47
|
+
const subMsg = {
|
48
|
+
op: 'subscribe',
|
49
|
+
args: [{ channel, instId }],
|
50
|
+
};
|
51
|
+
if (this.connected) {
|
52
|
+
this.ws.send(JSON.stringify(subMsg));
|
53
|
+
console.info(formatTime(Date.now()), `📩 Sent subscribe for ${channelId}`);
|
54
|
+
}
|
55
|
+
else {
|
56
|
+
this.pendingSub.push(JSON.stringify(subMsg));
|
57
|
+
console.info(formatTime(Date.now()), `📩 add subscribe for ${channelId} to pending list`);
|
58
|
+
}
|
59
|
+
this.subscriptions.add(channelId);
|
60
|
+
if (handler) {
|
61
|
+
this.handlers[channelId] = handler;
|
62
|
+
}
|
63
|
+
}
|
64
|
+
// 取消订阅
|
65
|
+
unsubscribe(channel, instId) {
|
66
|
+
const channelId = encodePath(channel, instId);
|
67
|
+
if (!this.subscriptions.has(channelId))
|
68
|
+
return;
|
69
|
+
const unSubMsg = {
|
70
|
+
op: 'unsubscribe',
|
71
|
+
args: [{ channel, instId }],
|
72
|
+
};
|
73
|
+
this.ws.send(JSON.stringify(unSubMsg));
|
74
|
+
this.subscriptions.delete(channelId);
|
75
|
+
delete this.handlers[channelId];
|
76
|
+
console.info(`📩 Sent unsubscribe for ${channelId}`);
|
77
|
+
}
|
78
|
+
}
|
79
|
+
export const okxBusinessWsClient = new OKXWsClient('wss://wspap.okx.com:8443/ws/v5/business');
|
80
|
+
//# sourceMappingURL=websocket.js.map
|
@@ -0,0 +1 @@
|
|
1
|
+
{"version":3,"file":"websocket.js","sourceRoot":"","sources":["../src/websocket.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,UAAU,EAAE,MAAM,eAAe,CAAC;AACvD,8BAA8B;AAE9B,MAAM,WAAW;IAMf,YAAY,GAAW;QAJvB,cAAS,GAAY,KAAK,CAAC;QAKzB,wBAAwB;QACxB,IAAI,CAAC,EAAE,GAAG,IAAI,SAAS,CAAC,GAAG,CAAC,CAAC;QAC7B,IAAI,CAAC,UAAU,GAAG,EAAE,CAAC;QACrB,WAAW;QACX,IAAI,CAAC,EAAE,CAAC,gBAAgB,CAAC,MAAM,EAAE,GAAG,EAAE;YACpC,IAAI,CAAC,SAAS,GAAG,IAAI,CAAC;YACtB,OAAO,CAAC,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC,GAAG,EAAE,CAAC,EAAE,gBAAgB,CAAC,CAAC;YACvD,OAAO,IAAI,CAAC,UAAU,CAAC,MAAM,GAAG,CAAC,EAAE;gBACjC,MAAM,GAAG,GAAG,IAAI,CAAC,UAAU,CAAC,KAAK,EAAE,CAAC;gBACpC,IAAI,GAAG,EA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M,EAAE,CAAC;SAC5B,CAAC;QAEF,IAAI,CAAC,EAAE,CAAC,IAAI,CAAC,IAAI,CAAC,SAAS,CAAC,QAAQ,CAAC,CAAC,CAAC;QACvC,IAAI,CAAC,aAAa,CAAC,MAAM,CAAC,SAAS,CAAC,CAAC;QACrC,OAAO,IAAI,CAAC,QAAQ,CAAC,SAAS,CAAC,CAAC;QAChC,OAAO,CAAC,IAAI,CAAC,2BAA2B,SAAS,EAAE,CAAC,CAAC;IACvD,CAAC;CACF;AAED,MAAM,CAAC,MAAM,mBAAmB,GAAG,IAAI,WAAW,CAAC,yCAAyC,CAAC,CAAC","sourcesContent":["import { encodePath, formatTime } from '@yuants/utils';\n// import WebSocket from 'ws';\n\nclass OKXWsClient {\n ws: WebSocket;\n connected: boolean = false;\n subscriptions: Set<string>;\n handlers: Record<string, Function>;\n pendingSub: string[];\n constructor(url: string) {\n // this.instId = instId;\n this.ws = new WebSocket(url);\n this.pendingSub = [];\n // this.ws.\n this.ws.addEventListener('open', () => {\n this.connected = true;\n console.info(formatTime(Date.now()), '✅ WS connected');\n while (this.pendingSub.length > 0) {\n const msg = this.pendingSub.shift();\n if (msg) {\n this.ws.send(msg);\n console.info(formatTime(Date.now()), `📩 Sent subscribe for ${msg}`);\n }\n }\n });\n this.ws.addEventListener('message', (raw) => this.handleMessage(raw));\n this.subscriptions = new Set();\n this.handlers = {}; // key: channel, value: callback\n }\n\n // 处理消息\n handleMessage(raw: any) {\n const msg = JSON.parse(raw.data);\n if (msg.arg?.channel) {\n const channelId = encodePath(msg.arg.channel, msg.arg.instId);\n const data = msg.data?.[0];\n if (data && this.handlers[channelId]) {\n this.handlers[channelId](data, msg.arg);\n }\n } else if (msg.event) {\n console.info('Event:', msg);\n }\n }\n\n // 调用订阅\n subscribe(channel: string, instId?: string, handler?: Function) {\n const channelId = encodePath(channel, instId);\n if (this.subscriptions.has(channelId)) {\n console.info(formatTime(Date.now()), `⚠️ Already subscribed: ${channelId}`);\n return;\n }\n\n const subMsg = {\n op: 'subscribe',\n args: [{ channel, instId }],\n };\n\n if (this.connected) {\n this.ws.send(JSON.stringify(subMsg));\n console.info(formatTime(Date.now()), `📩 Sent subscribe for ${channelId}`);\n } else {\n this.pendingSub.push(JSON.stringify(subMsg));\n console.info(formatTime(Date.now()), `📩 add subscribe for ${channelId} to pending list`);\n }\n this.subscriptions.add(channelId);\n if (handler) {\n this.handlers[channelId] = handler;\n }\n }\n\n // 取消订阅\n unsubscribe(channel: string, instId?: string) {\n const channelId = encodePath(channel, instId);\n if (!this.subscriptions.has(channelId)) return;\n\n const unSubMsg = {\n op: 'unsubscribe',\n args: [{ channel, instId }],\n };\n\n this.ws.send(JSON.stringify(unSubMsg));\n this.subscriptions.delete(channelId);\n delete this.handlers[channelId];\n console.info(`📩 Sent unsubscribe for ${channelId}`);\n }\n}\n\nexport const okxBusinessWsClient = new OKXWsClient('wss://wspap.okx.com:8443/ws/v5/business');\n"]}
|
package/lib/account.d.ts
ADDED
@@ -0,0 +1,102 @@
|
|
1
|
+
import { IAccountInfo } from '@yuants/data-account';
|
2
|
+
export declare const accountPosition$: import("rxjs").Observable<{
|
3
|
+
code: string;
|
4
|
+
msg: string;
|
5
|
+
data: {
|
6
|
+
adl: string;
|
7
|
+
availPos: string;
|
8
|
+
avgPx: string;
|
9
|
+
cTime: string;
|
10
|
+
ccy: string;
|
11
|
+
deltaBS: string;
|
12
|
+
deltaPA: string;
|
13
|
+
gammaBS: string;
|
14
|
+
gammaPA: string;
|
15
|
+
imr: string;
|
16
|
+
instId: string;
|
17
|
+
instType: string;
|
18
|
+
interest: string;
|
19
|
+
idxPx: string;
|
20
|
+
last: string;
|
21
|
+
usdPx: string;
|
22
|
+
bePx: string;
|
23
|
+
lever: string;
|
24
|
+
liab: string;
|
25
|
+
liabCcy: string;
|
26
|
+
liqPx: string;
|
27
|
+
markPx: string;
|
28
|
+
margin: string;
|
29
|
+
mgnMode: string;
|
30
|
+
mgnRatio: string;
|
31
|
+
mmr: string;
|
32
|
+
notionalUsd: string;
|
33
|
+
optVal: string;
|
34
|
+
pTime: string;
|
35
|
+
pos: string;
|
36
|
+
posCcy: string;
|
37
|
+
posId: string;
|
38
|
+
posSide: string;
|
39
|
+
spotInUseAmt: string;
|
40
|
+
spotInUseCcy: string;
|
41
|
+
thetaBS: string;
|
42
|
+
thetaPA: string;
|
43
|
+
tradeId: string;
|
44
|
+
bizRefId: string;
|
45
|
+
bizRefType: string;
|
46
|
+
quoteBal: string;
|
47
|
+
baseBal: string;
|
48
|
+
baseBorrowed: string;
|
49
|
+
baseInterest: string;
|
50
|
+
quoteBorrowed: string;
|
51
|
+
quoteInterest: string;
|
52
|
+
uTime: string;
|
53
|
+
upl: string;
|
54
|
+
uplLastPx: string;
|
55
|
+
uplRatio: string;
|
56
|
+
uplRatioLastPx: string;
|
57
|
+
vegaBS: string;
|
58
|
+
vegaPA: string;
|
59
|
+
realizedPnl: string;
|
60
|
+
pnl: string;
|
61
|
+
fee: string;
|
62
|
+
fundingFee: string;
|
63
|
+
liqPenalty: string;
|
64
|
+
closeOrderAlgo: {
|
65
|
+
algoId: string;
|
66
|
+
slTriggerPx: string;
|
67
|
+
slTriggerPxType: string;
|
68
|
+
tpTriggerPx: string;
|
69
|
+
tpTriggerPxType: string;
|
70
|
+
closeFraction: string;
|
71
|
+
}[];
|
72
|
+
}[];
|
73
|
+
}>;
|
74
|
+
export declare const accountConfig$: import("rxjs").Observable<{
|
75
|
+
code: string;
|
76
|
+
data: {
|
77
|
+
acctLv: string;
|
78
|
+
autoLoan: boolean;
|
79
|
+
ctIsoMode: string;
|
80
|
+
greeksType: string;
|
81
|
+
level: string;
|
82
|
+
levelTmp: string;
|
83
|
+
mgnIsoMode: string;
|
84
|
+
posMode: string;
|
85
|
+
spotOffsetType: string;
|
86
|
+
uid: string;
|
87
|
+
label: string;
|
88
|
+
roleType: string;
|
89
|
+
traderInsts: any[];
|
90
|
+
spotRoleType: string;
|
91
|
+
spotTraderInsts: any[];
|
92
|
+
opAuth: string;
|
93
|
+
kycLv: string;
|
94
|
+
ip: string;
|
95
|
+
perm: string;
|
96
|
+
mainUid: string;
|
97
|
+
}[];
|
98
|
+
msg: string;
|
99
|
+
}>;
|
100
|
+
export declare const accountUid$: import("rxjs").Observable<string>;
|
101
|
+
export declare const tradingAccountInfo$: import("rxjs").Observable<IAccountInfo>;
|
102
|
+
//# sourceMappingURL=account.d.ts.map
|
@@ -0,0 +1 @@
|
|
1
|
+
{"version":3,"file":"account.d.ts","sourceRoot":"","sources":["../src/account.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,YAAY,EAIb,MAAM,sBAAsB,CAAC;AAU9B,eAAO,MAAM,gBAAgB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAI5B,CAAC;AAEF,eAAO,MAAM,cAAc;;;;;;;;;;;;;;;;;;;;;;;;;EAI1B,CAAC;AAQF,eAAO,MAAM,WAAW,mCAIvB,CAAC;AA+BF,eAAO,MAAM,mBAAmB,yCAqI/B,CAAC"}
|
package/lib/account.js
ADDED
@@ -0,0 +1,201 @@
|
|
1
|
+
"use strict";
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
3
|
+
exports.tradingAccountInfo$ = exports.accountUid$ = exports.accountConfig$ = exports.accountPosition$ = void 0;
|
4
|
+
const data_account_1 = require("@yuants/data-account");
|
5
|
+
const protocol_1 = require("@yuants/protocol");
|
6
|
+
const utils_1 = require("@yuants/utils");
|
7
|
+
const rxjs_1 = require("rxjs");
|
8
|
+
const api_1 = require("./api");
|
9
|
+
const product_1 = require("./product");
|
10
|
+
const terminal = protocol_1.Terminal.fromNodeEnv();
|
11
|
+
exports.accountPosition$ = (0, rxjs_1.defer)(() => api_1.client.getAccountPositions({})).pipe((0, rxjs_1.repeat)({ delay: 5000 }), (0, rxjs_1.retry)({ delay: 5000 }), (0, rxjs_1.shareReplay)(1));
|
12
|
+
exports.accountConfig$ = (0, rxjs_1.defer)(() => api_1.client.getAccountConfig()).pipe((0, rxjs_1.repeat)({ delay: 10000 }), (0, rxjs_1.retry)({ delay: 10000 }), (0, rxjs_1.shareReplay)(1));
|
13
|
+
const subAccountUids$ = (0, rxjs_1.defer)(() => api_1.client.getSubAccountList()).pipe((0, rxjs_1.repeat)({ delay: 10000 }), (0, rxjs_1.retry)({ delay: 10000 }), (0, rxjs_1.shareReplay)(1));
|
14
|
+
exports.accountUid$ = exports.accountConfig$.pipe((0, rxjs_1.map)((x) => x.data[0].uid), (0, rxjs_1.filter)((x) => !!x), (0, rxjs_1.shareReplay)(1));
|
15
|
+
const accountBalance$ = (0, rxjs_1.defer)(() => api_1.client.getAccountBalance({})).pipe((0, rxjs_1.repeat)({ delay: 1000 }), (0, rxjs_1.retry)({ delay: 5000 }), (0, rxjs_1.shareReplay)(1));
|
16
|
+
const accountUsdtBalance$ = accountBalance$.pipe((0, rxjs_1.map)((x) => { var _a; return (_a = x.data[0]) === null || _a === void 0 ? void 0 : _a.details.find((x) => x.ccy === 'USDT'); }), (0, rxjs_1.filter)((x) => !!x), (0, rxjs_1.shareReplay)(1));
|
17
|
+
const pendingOrders$ = (0, rxjs_1.defer)(() => api_1.client.getTradeOrdersPending({})).pipe((0, rxjs_1.repeat)({ delay: 1000 }), (0, rxjs_1.retry)({ delay: 5000 }), (0, rxjs_1.shareReplay)(1));
|
18
|
+
const marketIndexTickerUSDT$ = (0, rxjs_1.defer)(() => api_1.client.getMarketIndexTicker({ quoteCcy: 'USDT' })).pipe((0, rxjs_1.map)((x) => {
|
19
|
+
const mapInstIdToPrice = new Map();
|
20
|
+
x.data.forEach((inst) => mapInstIdToPrice.set(inst.instId, Number(inst.idxPx)));
|
21
|
+
return mapInstIdToPrice;
|
22
|
+
}), (0, rxjs_1.repeat)({ delay: 1000 }), (0, rxjs_1.retry)({ delay: 5000 }), (0, rxjs_1.shareReplay)(1));
|
23
|
+
exports.tradingAccountInfo$ = exports.accountPosition$.pipe((0, rxjs_1.withLatestFrom)(exports.accountUid$, accountBalance$, pendingOrders$, product_1.mapProductIdToUsdtSwapProduct$, product_1.mapProductIdToMarginProduct$, marketIndexTickerUSDT$), (0, rxjs_1.map)(([positionsApi, uid, balanceApi, orders, mapProductIdToUsdtSwapProduct, mapProductIdToMarginProduct, marketIndexTickerUSDT,]) => {
|
24
|
+
var _a;
|
25
|
+
const account_id = `okx/${uid}/trading`;
|
26
|
+
const money = { currency: 'USDT', equity: 0, balance: 0, used: 0, free: 0, profit: 0 };
|
27
|
+
const positions = [];
|
28
|
+
(_a = balanceApi.data[0]) === null || _a === void 0 ? void 0 : _a.details.forEach((detail) => {
|
29
|
+
var _a, _b, _c, _d, _e;
|
30
|
+
if (detail.ccy === 'USDT') {
|
31
|
+
const balance = +((_a = detail.cashBal) !== null && _a !== void 0 ? _a : 0);
|
32
|
+
const free = Math.min(balance, // free should no more than balance if there is much profits
|
33
|
+
+((_b = detail.availEq) !== null && _b !== void 0 ? _b : 0));
|
34
|
+
const equity = +((_c = detail.eq) !== null && _c !== void 0 ? _c : 0);
|
35
|
+
const used = equity - free;
|
36
|
+
const profit = equity - balance;
|
37
|
+
money.equity += equity;
|
38
|
+
money.balance += balance;
|
39
|
+
money.used += used;
|
40
|
+
money.free += free;
|
41
|
+
money.profit += profit;
|
42
|
+
}
|
43
|
+
else {
|
44
|
+
const volume = +((_d = detail.cashBal) !== null && _d !== void 0 ? _d : 0);
|
45
|
+
const free_volume = Math.min(volume, // free should no more than balance if there is much profits
|
46
|
+
+((_e = detail.availEq) !== null && _e !== void 0 ? _e : 0));
|
47
|
+
const closable_price = marketIndexTickerUSDT.get(detail.ccy + '-USDT') || 0;
|
48
|
+
const delta_equity = volume * closable_price || 0;
|
49
|
+
const delta_profit = +detail.totalPnl || 0;
|
50
|
+
const delta_balance = delta_equity - delta_profit;
|
51
|
+
const delta_used = delta_equity; // all used
|
52
|
+
const delta_free = 0;
|
53
|
+
const product_id = (0, utils_1.encodePath)('SPOT', `${detail.ccy}-USDT`);
|
54
|
+
positions.push({
|
55
|
+
position_id: product_id,
|
56
|
+
datasource_id: 'OKX',
|
57
|
+
product_id: product_id,
|
58
|
+
direction: 'LONG',
|
59
|
+
volume: volume,
|
60
|
+
free_volume: free_volume,
|
61
|
+
position_price: +detail.accAvgPx,
|
62
|
+
floating_profit: delta_profit,
|
63
|
+
closable_price: closable_price,
|
64
|
+
valuation: delta_equity,
|
65
|
+
});
|
66
|
+
money.equity += delta_equity;
|
67
|
+
money.profit += delta_profit;
|
68
|
+
money.balance += delta_balance;
|
69
|
+
money.used += delta_used;
|
70
|
+
money.free += delta_free;
|
71
|
+
}
|
72
|
+
});
|
73
|
+
positionsApi.data.forEach((x) => {
|
74
|
+
var _a, _b, _c, _d;
|
75
|
+
const direction = x.posSide === 'long' ? 'LONG' : x.posSide === 'short' ? 'SHORT' : +x.pos > 0 ? 'LONG' : 'SHORT';
|
76
|
+
const volume = Math.abs(+x.pos);
|
77
|
+
const product_id = (0, utils_1.encodePath)(x.instType, x.instId);
|
78
|
+
const closable_price = +x.last;
|
79
|
+
const valuation = x.instType === 'SWAP'
|
80
|
+
? ((_b = (_a = mapProductIdToUsdtSwapProduct.get(product_id)) === null || _a === void 0 ? void 0 : _a.value_scale) !== null && _b !== void 0 ? _b : 1) * volume * closable_price
|
81
|
+
: x.instType === 'MARGIN'
|
82
|
+
? ((_d = (_c = mapProductIdToMarginProduct.get(product_id)) === null || _c === void 0 ? void 0 : _c.value_scale) !== null && _d !== void 0 ? _d : 1) * volume * closable_price
|
83
|
+
: 0;
|
84
|
+
positions.push({
|
85
|
+
position_id: x.posId,
|
86
|
+
datasource_id: 'OKX',
|
87
|
+
product_id,
|
88
|
+
direction,
|
89
|
+
volume: volume,
|
90
|
+
free_volume: +x.availPos,
|
91
|
+
closable_price,
|
92
|
+
position_price: +x.avgPx,
|
93
|
+
floating_profit: +x.upl,
|
94
|
+
valuation,
|
95
|
+
});
|
96
|
+
});
|
97
|
+
return {
|
98
|
+
account_id: account_id,
|
99
|
+
updated_at: Date.now(),
|
100
|
+
money: money,
|
101
|
+
currencies: [money],
|
102
|
+
positions: positions,
|
103
|
+
orders: orders.data.map((x) => {
|
104
|
+
const order_type = x.ordType === 'market' ? 'MARKET' : x.ordType === 'limit' ? 'LIMIT' : 'UNKNOWN';
|
105
|
+
const order_direction = x.side === 'buy'
|
106
|
+
? x.posSide === 'long'
|
107
|
+
? 'OPEN_LONG'
|
108
|
+
: 'CLOSE_SHORT'
|
109
|
+
: x.posSide === 'short'
|
110
|
+
? 'OPEN_SHORT'
|
111
|
+
: 'CLOSE_LONG';
|
112
|
+
return {
|
113
|
+
order_id: x.ordId,
|
114
|
+
account_id,
|
115
|
+
product_id: (0, utils_1.encodePath)(x.instType, x.instId),
|
116
|
+
submit_at: +x.cTime,
|
117
|
+
filled_at: +x.fillTime,
|
118
|
+
order_type,
|
119
|
+
order_direction,
|
120
|
+
volume: +x.sz,
|
121
|
+
traded_volume: +x.accFillSz,
|
122
|
+
price: +x.px,
|
123
|
+
traded_price: +x.avgPx,
|
124
|
+
};
|
125
|
+
}),
|
126
|
+
};
|
127
|
+
}), (0, rxjs_1.shareReplay)(1));
|
128
|
+
const sub = (0, rxjs_1.defer)(() => exports.accountUid$)
|
129
|
+
.pipe((0, rxjs_1.first)())
|
130
|
+
.subscribe((uid) => {
|
131
|
+
(0, data_account_1.publishAccountInfo)(terminal, `okx/${uid}/trading`, exports.tradingAccountInfo$);
|
132
|
+
(0, data_account_1.addAccountMarket)(terminal, { account_id: `okx/${uid}/trading`, market_id: 'OKX' });
|
133
|
+
(0, data_account_1.publishAccountInfo)(terminal, `okx/${uid}/funding/USDT`, fundingAccountInfo$);
|
134
|
+
(0, data_account_1.publishAccountInfo)(terminal, `okx/${uid}/earning/USDT`, earningAccountInfo$);
|
135
|
+
});
|
136
|
+
(0, rxjs_1.defer)(() => terminal.dispose$).subscribe(() => sub.unsubscribe());
|
137
|
+
const assetBalance$ = (0, rxjs_1.defer)(() => api_1.client.getAssetBalances({})).pipe((0, rxjs_1.repeat)({ delay: 1000 }), (0, rxjs_1.retry)({ delay: 5000 }), (0, rxjs_1.shareReplay)(1));
|
138
|
+
const fundingAccountInfo$ = (0, rxjs_1.combineLatest)([exports.accountUid$, assetBalance$, marketIndexTickerUSDT$]).pipe((0, rxjs_1.map)(([uid, assetBalances, marketIndexTickerUSDT]) => {
|
139
|
+
const money = { currency: 'USDT', equity: 0, balance: 0, used: 0, free: 0, profit: 0 };
|
140
|
+
const positions = [];
|
141
|
+
assetBalances.data.forEach((x) => {
|
142
|
+
if (x.ccy === 'USDT') {
|
143
|
+
money.equity += +x.bal;
|
144
|
+
money.balance += +x.bal;
|
145
|
+
money.free += +x.bal;
|
146
|
+
}
|
147
|
+
else {
|
148
|
+
const price = marketIndexTickerUSDT.get(x.ccy + '-USDT') || 0;
|
149
|
+
const productId = (0, utils_1.encodePath)('SPOT', `${x.ccy}-USDT`);
|
150
|
+
const valuation = price * +x.bal || 0;
|
151
|
+
positions.push({
|
152
|
+
datasource_id: 'OKX',
|
153
|
+
position_id: productId,
|
154
|
+
product_id: productId,
|
155
|
+
direction: 'LONG',
|
156
|
+
volume: +x.bal,
|
157
|
+
free_volume: +x.bal,
|
158
|
+
position_price: price,
|
159
|
+
floating_profit: 0,
|
160
|
+
closable_price: price,
|
161
|
+
valuation: valuation,
|
162
|
+
});
|
163
|
+
money.equity += valuation;
|
164
|
+
money.balance += valuation;
|
165
|
+
money.used += valuation;
|
166
|
+
}
|
167
|
+
});
|
168
|
+
return {
|
169
|
+
account_id: `okx/${uid}/funding/USDT`,
|
170
|
+
updated_at: Date.now(),
|
171
|
+
money: money,
|
172
|
+
currencies: [money],
|
173
|
+
positions: positions,
|
174
|
+
orders: [],
|
175
|
+
};
|
176
|
+
}), (0, rxjs_1.shareReplay)(1));
|
177
|
+
const savingBalance$ = (0, rxjs_1.defer)(() => api_1.client.getFinanceSavingsBalance({})).pipe((0, rxjs_1.repeat)({ delay: 5000 }), (0, rxjs_1.retry)({ delay: 5000 }), (0, rxjs_1.shareReplay)(1));
|
178
|
+
const earningAccountInfo$ = (0, rxjs_1.combineLatest)([exports.accountUid$, savingBalance$]).pipe((0, rxjs_1.map)(([uid, offers]) => {
|
179
|
+
const equity = offers.data.filter((x) => x.ccy === 'USDT').reduce((acc, x) => acc + +x.amt, 0);
|
180
|
+
const balance = equity;
|
181
|
+
const free = equity;
|
182
|
+
const used = 0;
|
183
|
+
const profit = 0;
|
184
|
+
const money = {
|
185
|
+
currency: 'USDT',
|
186
|
+
equity,
|
187
|
+
balance,
|
188
|
+
used,
|
189
|
+
free,
|
190
|
+
profit,
|
191
|
+
};
|
192
|
+
return {
|
193
|
+
account_id: `okx/${uid}/earning/USDT`,
|
194
|
+
updated_at: Date.now(),
|
195
|
+
money: money,
|
196
|
+
currencies: [money],
|
197
|
+
positions: [],
|
198
|
+
orders: [],
|
199
|
+
};
|
200
|
+
}), (0, rxjs_1.shareReplay)(1));
|
201
|
+
//# sourceMappingURL=account.js.map
|
@@ -0,0 +1 @@
|
|
1
|
+
{"version":3,"file":"account.js","sourceRoot":"","sources":["../src/account.ts"],"names":[],"mappings":";;;AAAA,uDAM8B;AAE9B,+CAA4C;AAC5C,yCAA2C;AAC3C,+BAA4G;AAC5G,+BAA+B;AAC/B,uCAAyF;AAEzF,MAAM,QAAQ,GAAG,mBAAQ,CAAC,WAAW,EAAE,CAAC;AAE3B,QAAA,gBAAgB,GAAG,IAAA,YAAK,EAAC,GAAG,EAAE,CAAC,YAAM,CAAC,mBAAmB,CAAC,EAAE,CAAC,CAAC,CAAC,IAAI,CAC9E,IAAA,aAAM,EAAC,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC,EACvB,IAAA,YAAK,EAAC,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC,EACtB,IAAA,kBAAW,EAAC,CAAC,CAAC,CACf,CAAC;AAEW,QAAA,cAAc,GAAG,IAAA,YAAK,EAAC,GAAG,EAAE,CAAC,YAAM,CAAC,gBAAg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AE,MAAM;QAChB,MAAM;QACN,OAAO;QACP,IAAI;QACJ,IAAI;QACJ,MAAM;KACP,CAAC;IACF,OAAO;QACL,UAAU,EAAE,OAAO,GAAG,eAAe;QACrC,UAAU,EAAE,IAAI,CAAC,GAAG,EAAE;QACtB,KAAK,EAAE,KAAK;QACZ,UAAU,EAAE,CAAC,KAAK,CAAC;QACnB,SAAS,EAAE,EAAE;QACb,MAAM,EAAE,EAAE;KACX,CAAC;AACJ,CAAC,CAAC,EACF,IAAA,kBAAW,EAAC,CAAC,CAAC,CACf,CAAC","sourcesContent":["import {\n addAccountMarket,\n IAccountInfo,\n IAccountMoney,\n IPosition,\n publishAccountInfo,\n} from '@yuants/data-account';\nimport { IOrder } from '@yuants/data-order';\nimport { Terminal } from '@yuants/protocol';\nimport { encodePath } from '@yuants/utils';\nimport { combineLatest, defer, filter, first, map, repeat, retry, shareReplay, withLatestFrom } from 'rxjs';\nimport { client } from './api';\nimport { mapProductIdToMarginProduct$, mapProductIdToUsdtSwapProduct$ } from './product';\n\nconst terminal = Terminal.fromNodeEnv();\n\nexport const accountPosition$ = defer(() => client.getAccountPositions({})).pipe(\n repeat({ delay: 5000 }),\n retry({ delay: 5000 }),\n shareReplay(1),\n);\n\nexport const accountConfig$ = defer(() => client.getAccountConfig()).pipe(\n repeat({ delay: 10_000 }),\n retry({ delay: 10_000 }),\n shareReplay(1),\n);\n\nconst subAccountUids$ = defer(() => client.getSubAccountList()).pipe(\n repeat({ delay: 10_000 }),\n retry({ delay: 10_000 }),\n shareReplay(1),\n);\n\nexport const accountUid$ = accountConfig$.pipe(\n map((x) => x.data[0].uid),\n filter((x) => !!x),\n shareReplay(1),\n);\n\nconst accountBalance$ = defer(() => client.getAccountBalance({})).pipe(\n repeat({ delay: 1000 }),\n retry({ delay: 5000 }),\n shareReplay(1),\n);\n\nconst accountUsdtBalance$ = accountBalance$.pipe(\n map((x) => x.data[0]?.details.find((x) => x.ccy === 'USDT')),\n filter((x): x is Exclude<typeof x, undefined> => !!x),\n shareReplay(1),\n);\n\nconst pendingOrders$ = defer(() => client.getTradeOrdersPending({})).pipe(\n repeat({ delay: 1000 }),\n retry({ delay: 5000 }),\n shareReplay(1),\n);\n\nconst marketIndexTickerUSDT$ = defer(() => client.getMarketIndexTicker({ quoteCcy: 'USDT' })).pipe(\n map((x) => {\n const mapInstIdToPrice = new Map<string, number>();\n x.data.forEach((inst) => mapInstIdToPrice.set(inst.instId, Number(inst.idxPx)));\n return mapInstIdToPrice;\n }),\n repeat({ delay: 1000 }),\n retry({ delay: 5000 }),\n shareReplay(1),\n);\n\nexport const tradingAccountInfo$ = accountPosition$.pipe(\n withLatestFrom(\n accountUid$,\n accountBalance$,\n pendingOrders$,\n mapProductIdToUsdtSwapProduct$,\n mapProductIdToMarginProduct$,\n marketIndexTickerUSDT$,\n ),\n map(\n ([\n positionsApi,\n uid,\n balanceApi,\n orders,\n mapProductIdToUsdtSwapProduct,\n mapProductIdToMarginProduct,\n marketIndexTickerUSDT,\n ]): IAccountInfo => {\n const account_id = `okx/${uid}/trading`;\n const money: IAccountMoney = { currency: 'USDT', equity: 0, balance: 0, used: 0, free: 0, profit: 0 };\n const positions: IPosition[] = [];\n\n balanceApi.data[0]?.details.forEach((detail) => {\n if (detail.ccy === 'USDT') {\n const balance = +(detail.cashBal ?? 0);\n const free = Math.min(\n balance, // free should no more than balance if there is much profits\n +(detail.availEq ?? 0),\n );\n const equity = +(detail.eq ?? 0);\n const used = equity - free;\n const profit = equity - balance;\n money.equity += equity;\n money.balance += balance;\n money.used += used;\n money.free += free;\n money.profit += profit;\n } else {\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 const closable_price = marketIndexTickerUSDT.get(detail.ccy + '-USDT') || 0;\n const delta_equity = volume * closable_price || 0;\n const delta_profit = +detail.totalPnl || 0;\n const delta_balance = delta_equity - delta_profit;\n const delta_used = delta_equity; // all used\n const delta_free = 0;\n\n const product_id = encodePath('SPOT', `${detail.ccy}-USDT`);\n positions.push({\n position_id: product_id,\n datasource_id: 'OKX',\n product_id: product_id,\n direction: 'LONG',\n volume: volume,\n free_volume: free_volume,\n position_price: +detail.accAvgPx,\n floating_profit: delta_profit,\n closable_price: closable_price,\n valuation: delta_equity,\n });\n\n money.equity += delta_equity;\n money.profit += delta_profit;\n money.balance += delta_balance;\n money.used += delta_used;\n money.free += delta_free;\n }\n });\n positionsApi.data.forEach((x) => {\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(x.instType, x.instId);\n const closable_price = +x.last;\n const valuation =\n x.instType === 'SWAP'\n ? (mapProductIdToUsdtSwapProduct.get(product_id)?.value_scale ?? 1) * volume * closable_price\n : x.instType === 'MARGIN'\n ? (mapProductIdToMarginProduct.get(product_id)?.value_scale ?? 1) * volume * closable_price\n : 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 return {\n account_id: account_id,\n updated_at: Date.now(),\n money: money,\n currencies: [money],\n positions: positions,\n orders: orders.data.map((x): IOrder => {\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 return {\n order_id: x.ordId,\n account_id,\n product_id: encodePath(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 },\n ),\n shareReplay(1),\n);\n\nconst sub = defer(() => accountUid$)\n .pipe(first())\n .subscribe((uid) => {\n publishAccountInfo(terminal, `okx/${uid}/trading`, tradingAccountInfo$);\n addAccountMarket(terminal, { account_id: `okx/${uid}/trading`, market_id: 'OKX' });\n publishAccountInfo(terminal, `okx/${uid}/funding/USDT`, fundingAccountInfo$);\n publishAccountInfo(terminal, `okx/${uid}/earning/USDT`, earningAccountInfo$);\n });\ndefer(() => terminal.dispose$).subscribe(() => sub.unsubscribe());\n\nconst assetBalance$ = defer(() => client.getAssetBalances({})).pipe(\n repeat({ delay: 1000 }),\n retry({ delay: 5000 }),\n shareReplay(1),\n);\n\nconst fundingAccountInfo$ = combineLatest([accountUid$, assetBalance$, marketIndexTickerUSDT$]).pipe(\n map(([uid, assetBalances, marketIndexTickerUSDT]): IAccountInfo => {\n const money: IAccountMoney = { currency: 'USDT', equity: 0, balance: 0, used: 0, free: 0, profit: 0 };\n const positions: IPosition[] = [];\n\n assetBalances.data.forEach((x) => {\n if (x.ccy === 'USDT') {\n money.equity += +x.bal;\n money.balance += +x.bal;\n money.free += +x.bal;\n } else {\n const price = marketIndexTickerUSDT.get(x.ccy + '-USDT') || 0;\n const productId = encodePath('SPOT', `${x.ccy}-USDT`);\n const valuation = price * +x.bal || 0;\n positions.push({\n datasource_id: 'OKX',\n position_id: productId,\n product_id: productId,\n direction: 'LONG',\n volume: +x.bal,\n free_volume: +x.bal,\n position_price: price,\n floating_profit: 0,\n closable_price: price,\n valuation: valuation,\n });\n\n money.equity += valuation;\n money.balance += valuation;\n money.used += valuation;\n }\n });\n\n return {\n account_id: `okx/${uid}/funding/USDT`,\n updated_at: Date.now(),\n money: money,\n currencies: [money],\n positions: positions,\n orders: [],\n };\n }),\n shareReplay(1),\n);\n\nconst savingBalance$ = defer(() => client.getFinanceSavingsBalance({})).pipe(\n repeat({ delay: 5000 }),\n retry({ delay: 5000 }),\n shareReplay(1),\n);\n\nconst earningAccountInfo$ = combineLatest([accountUid$, savingBalance$]).pipe(\n map(([uid, offers]): IAccountInfo => {\n const equity = offers.data.filter((x) => x.ccy === 'USDT').reduce((acc, x) => acc + +x.amt, 0);\n const balance = equity;\n const free = equity;\n const used = 0;\n const profit = 0;\n\n const money: IAccountMoney = {\n currency: 'USDT',\n equity,\n balance,\n used,\n free,\n profit,\n };\n return {\n account_id: `okx/${uid}/earning/USDT`,\n updated_at: Date.now(),\n money: money,\n currencies: [money],\n positions: [],\n orders: [],\n };\n }),\n shareReplay(1),\n);\n"]}
|