@yuants/vendor-binance 0.4.49 → 0.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (54) hide show
  1. package/dist/api.js +249 -0
  2. package/dist/api.js.map +1 -0
  3. package/dist/cli.js +3 -0
  4. package/dist/cli.js.map +1 -0
  5. package/dist/extension.js +90 -0
  6. package/dist/extension.js.map +1 -0
  7. package/dist/index.js +4 -0
  8. package/dist/index.js.map +1 -0
  9. package/dist/interest_rate.js +54 -0
  10. package/dist/interest_rate.js.map +1 -0
  11. package/dist/legacy_index.js +323 -0
  12. package/dist/legacy_index.js.map +1 -0
  13. package/dist/product.js +40 -0
  14. package/dist/product.js.map +1 -0
  15. package/dist/terminal.js +7 -0
  16. package/dist/terminal.js.map +1 -0
  17. package/dist/vendor-binance.d.ts +1 -0
  18. package/lib/api.d.ts +555 -0
  19. package/lib/api.d.ts.map +1 -0
  20. package/lib/api.js +257 -0
  21. package/lib/api.js.map +1 -0
  22. package/lib/cli.d.ts +3 -0
  23. package/lib/cli.d.ts.map +1 -0
  24. package/lib/cli.js +5 -0
  25. package/lib/cli.js.map +1 -0
  26. package/lib/extension.d.ts +4 -0
  27. package/lib/extension.d.ts.map +1 -0
  28. package/lib/extension.js +92 -0
  29. package/lib/extension.js.map +1 -0
  30. package/lib/index.d.ts +4 -0
  31. package/lib/index.d.ts.map +1 -0
  32. package/lib/index.js +6 -0
  33. package/lib/index.js.map +1 -0
  34. package/lib/interest_rate.d.ts +2 -0
  35. package/lib/interest_rate.d.ts.map +1 -0
  36. package/lib/interest_rate.js +56 -0
  37. package/lib/interest_rate.js.map +1 -0
  38. package/lib/legacy_index.d.ts +2 -0
  39. package/lib/legacy_index.d.ts.map +1 -0
  40. package/lib/legacy_index.js +325 -0
  41. package/lib/legacy_index.js.map +1 -0
  42. package/lib/product.d.ts +2 -0
  43. package/lib/product.d.ts.map +1 -0
  44. package/lib/product.js +42 -0
  45. package/lib/product.js.map +1 -0
  46. package/lib/terminal.d.ts +3 -0
  47. package/lib/terminal.d.ts.map +1 -0
  48. package/lib/terminal.js +10 -0
  49. package/lib/terminal.js.map +1 -0
  50. package/package.json +6 -3
  51. package/temp/image-tag +1 -0
  52. package/temp/package-deps.json +33 -0
  53. package/temp/vendor-binance.api.json +177 -0
  54. package/temp/vendor-binance.api.md +9 -0
@@ -0,0 +1,323 @@
1
+ import { addAccountMarket, publishAccountInfo, } from '@yuants/data-account';
2
+ import { addAccountTransferAddress } from '@yuants/transfer';
3
+ import { decodePath, encodePath, formatTime } from '@yuants/utils';
4
+ import { defer, from, map, mergeMap, repeat, retry, shareReplay, tap, toArray } from 'rxjs';
5
+ import { client, isError } from './api';
6
+ import { terminal } from './terminal';
7
+ const memoizeMap = (fn) => {
8
+ const cache = {};
9
+ return ((...params) => { var _a; var _b; return ((_a = cache[_b = encodePath(params)]) !== null && _a !== void 0 ? _a : (cache[_b] = fn(...params))); });
10
+ };
11
+ const mapSymbolToFuturePremiumIndex$ = defer(() => client.getFuturePremiumIndex({})).pipe(repeat({ delay: 1000 }), retry({ delay: 30000 }), mergeMap((x) => from(x).pipe(map((v) => [v.symbol, v]), toArray(), map((v) => new Map(v)))), shareReplay(1));
12
+ const mapSymbolToFutureBookTicker$ = defer(() => client.getFutureBookTicker({})).pipe(repeat({ delay: 1000 }), retry({ delay: 30000 }), mergeMap((x) => from(x).pipe(map((v) => [v.symbol, v]), toArray(), map((v) => new Map(v)))), shareReplay(1));
13
+ const _mapSymbolToOpenInterest = {};
14
+ const getOpenInterest = async (symbol) => {
15
+ const expired_at = Date.now() - 600000; // 10min expired
16
+ const cache = _mapSymbolToOpenInterest[symbol];
17
+ if (cache) {
18
+ if (cache.updated_at > expired_at) {
19
+ return cache.value;
20
+ }
21
+ }
22
+ const data = await client.getFutureOpenInterest({ symbol });
23
+ const value = +data.openInterest || 0;
24
+ _mapSymbolToOpenInterest[symbol] = { value, updated_at: Date.now() };
25
+ return value;
26
+ };
27
+ // provideTicks(terminal, 'binance', (product_id) => {
28
+ // const [instType, symbol] = decodePath(product_id);
29
+ // if (instType === 'usdt-future') {
30
+ // return combineLatest([mapSymbolToFuturePremiumIndex$, mapSymbolToFutureBookTicker$]).pipe(
31
+ // combineLatestWith(defer(() => getOpenInterest(symbol))),
32
+ // map(([[mapSymbolToFuturePremiumIndex, mapSymbolToFutureBookTicker], openInterestVolume]): ITick => {
33
+ // const premiumIndex = mapSymbolToFuturePremiumIndex.get(symbol);
34
+ // const bookTicker = mapSymbolToFutureBookTicker.get(symbol);
35
+ // if (!premiumIndex) {
36
+ // throw new Error(`Premium Index Not Found: ${symbol}`);
37
+ // }
38
+ // if (!bookTicker) {
39
+ // throw new Error(`Book Ticker Not Found: ${symbol}`);
40
+ // }
41
+ // return {
42
+ // datasource_id: 'binance',
43
+ // product_id,
44
+ // updated_at: Date.now(),
45
+ // price: +premiumIndex.markPrice,
46
+ // ask: +bookTicker.askPrice,
47
+ // bid: +bookTicker.bidPrice,
48
+ // interest_rate_for_long: -+premiumIndex.lastFundingRate,
49
+ // interest_rate_for_short: +premiumIndex.lastFundingRate,
50
+ // settlement_scheduled_at: premiumIndex.nextFundingTime,
51
+ // open_interest: openInterestVolume,
52
+ // };
53
+ // }),
54
+ // );
55
+ // }
56
+ // return EMPTY;
57
+ // });
58
+ (async () => {
59
+ const spotAccountInfo = await client.getSpotAccountInfo();
60
+ if (isError(spotAccountInfo)) {
61
+ throw new Error(spotAccountInfo.msg);
62
+ }
63
+ const uid = spotAccountInfo.uid;
64
+ const SPOT_ACCOUNT_ID = `binance/${uid}/spot/usdt`;
65
+ const UNIFIED_ACCOUNT_ID = `binance/${uid}/unified/usdt`;
66
+ {
67
+ // unified accountInfo
68
+ const unifiedAccountInfo$ = defer(async () => {
69
+ const accountResult = await client.getUnifiedAccountBalance();
70
+ if (isError(accountResult)) {
71
+ throw new Error(accountResult.msg);
72
+ }
73
+ const usdtAssets = accountResult.find((v) => v.asset === 'USDT');
74
+ if (!usdtAssets) {
75
+ throw new Error('USDT not found');
76
+ }
77
+ const umAccountResult = await client.getUnifiedUmAccount();
78
+ if (isError(umAccountResult)) {
79
+ throw new Error(umAccountResult.msg);
80
+ }
81
+ const usdtUmAssets = umAccountResult.assets.find((v) => v.asset === 'USDT');
82
+ if (!usdtUmAssets) {
83
+ throw new Error('um USDT not found');
84
+ }
85
+ const money = {
86
+ currency: 'USDT',
87
+ leverage: 1,
88
+ equity: +usdtAssets.totalWalletBalance + +usdtAssets.umUnrealizedPNL,
89
+ balance: +usdtAssets.totalWalletBalance,
90
+ profit: +usdtAssets.umUnrealizedPNL,
91
+ used: +usdtUmAssets.initialMargin,
92
+ free: +usdtAssets.totalWalletBalance + +usdtAssets.umUnrealizedPNL - +usdtUmAssets.initialMargin,
93
+ };
94
+ const positions = umAccountResult.positions
95
+ .filter((v) => +v.positionAmt !== 0)
96
+ .map((v) => {
97
+ return {
98
+ position_id: `${v.symbol}/${v.positionSide}`,
99
+ datasource_id: 'BINANCE',
100
+ product_id: encodePath('usdt-future', v.symbol),
101
+ direction: v.positionSide,
102
+ volume: +v.positionAmt,
103
+ free_volume: +v.positionAmt,
104
+ position_price: +v.entryPrice,
105
+ closable_price: +v.entryPrice + +v.unrealizedProfit / +v.positionAmt,
106
+ floating_profit: +v.unrealizedProfit,
107
+ valuation: +v.positionAmt * (+v.entryPrice + +v.unrealizedProfit / +v.positionAmt),
108
+ };
109
+ });
110
+ return {
111
+ updated_at: Date.now(),
112
+ account_id: UNIFIED_ACCOUNT_ID,
113
+ money,
114
+ positions,
115
+ };
116
+ }).pipe(tap({
117
+ error: (err) => {
118
+ console.error(formatTime(Date.now()), 'unifiedAccountInfo$', err);
119
+ },
120
+ }), retry({ delay: 5000 }), repeat({ delay: 1000 }));
121
+ publishAccountInfo(terminal, UNIFIED_ACCOUNT_ID, unifiedAccountInfo$);
122
+ addAccountMarket(terminal, { account_id: UNIFIED_ACCOUNT_ID, market_id: 'BINANCE/UNIFIED' });
123
+ }
124
+ {
125
+ // spot account info
126
+ const spotAccountInfo$ = defer(async () => {
127
+ const spotAccountResult = await client.getSpotAccountInfo({ omitZeroBalances: true });
128
+ if (isError(spotAccountResult)) {
129
+ throw new Error(spotAccountResult.msg);
130
+ }
131
+ const usdtAssets = spotAccountResult.balances.find((v) => v.asset === 'USDT');
132
+ const money = {
133
+ currency: 'USDT',
134
+ leverage: 1,
135
+ equity: +((usdtAssets === null || usdtAssets === void 0 ? void 0 : usdtAssets.free) || 0),
136
+ balance: +((usdtAssets === null || usdtAssets === void 0 ? void 0 : usdtAssets.free) || 0),
137
+ profit: 0,
138
+ used: 0,
139
+ free: +((usdtAssets === null || usdtAssets === void 0 ? void 0 : usdtAssets.free) || 0),
140
+ };
141
+ return {
142
+ updated_at: Date.now(),
143
+ account_id: SPOT_ACCOUNT_ID,
144
+ money,
145
+ positions: [],
146
+ };
147
+ }).pipe(tap({
148
+ error: (err) => {
149
+ console.error(formatTime(Date.now()), 'unifiedAccountInfo$', err);
150
+ },
151
+ }), retry({ delay: 5000 }), repeat({ delay: 1000 }));
152
+ publishAccountInfo(terminal, SPOT_ACCOUNT_ID, spotAccountInfo$);
153
+ addAccountMarket(terminal, { account_id: SPOT_ACCOUNT_ID, market_id: 'BINANCE/SPOT' });
154
+ }
155
+ // transfer
156
+ {
157
+ // spot -> unified
158
+ const SPOT_UNIFIED_NETWORK_ID = `binance/${uid}/spot/unified`;
159
+ addAccountTransferAddress({
160
+ terminal,
161
+ account_id: SPOT_ACCOUNT_ID,
162
+ network_id: SPOT_UNIFIED_NETWORK_ID,
163
+ currency: 'USDT',
164
+ address: `unified`,
165
+ onApply: {
166
+ INIT: async (order) => {
167
+ const transferResult = await client.postAssetTransfer({
168
+ type: 'MAIN_PORTFOLIO_MARGIN',
169
+ asset: 'USDT',
170
+ amount: order.current_amount,
171
+ });
172
+ if (isError(transferResult)) {
173
+ return { state: 'INIT', message: transferResult.msg };
174
+ }
175
+ return { state: 'COMPLETE', transaction_id: '' + transferResult.tranId };
176
+ },
177
+ },
178
+ onEval: async (order) => {
179
+ return { state: 'COMPLETE', received_amount: order.current_amount };
180
+ },
181
+ });
182
+ // unified -> spot
183
+ addAccountTransferAddress({
184
+ terminal,
185
+ account_id: UNIFIED_ACCOUNT_ID,
186
+ network_id: SPOT_UNIFIED_NETWORK_ID,
187
+ currency: 'USDT',
188
+ address: `spot`,
189
+ onApply: {
190
+ INIT: async (order) => {
191
+ const transferResult = await client.postAssetTransfer({
192
+ type: 'PORTFOLIO_MARGIN_MAIN',
193
+ asset: 'USDT',
194
+ amount: order.current_amount,
195
+ });
196
+ if (isError(transferResult)) {
197
+ return { state: 'INIT', message: transferResult.msg };
198
+ }
199
+ return { state: 'COMPLETE', transaction_id: '' + transferResult.tranId };
200
+ },
201
+ },
202
+ onEval: async (order) => {
203
+ return { state: 'COMPLETE', received_amount: order.current_amount };
204
+ },
205
+ });
206
+ const subAccountsResult = await client.getSubAccountList();
207
+ const isMain = !isError(subAccountsResult);
208
+ // main -> sub
209
+ // TODO...
210
+ // blockchain
211
+ if (isMain) {
212
+ const depositAddressResult = await client.getDepositAddress({ coin: 'USDT', network: 'TRX' });
213
+ addAccountTransferAddress({
214
+ terminal,
215
+ account_id: SPOT_ACCOUNT_ID,
216
+ network_id: 'TRC20',
217
+ currency: 'USDT',
218
+ address: depositAddressResult.address,
219
+ onApply: {
220
+ INIT: async (order) => {
221
+ const transferResult = await client.postWithdraw({
222
+ coin: 'USDT',
223
+ network: 'TRX',
224
+ address: order.current_rx_address,
225
+ amount: order.current_amount,
226
+ });
227
+ if (isError(transferResult)) {
228
+ return { state: 'ERROR', message: transferResult.msg };
229
+ }
230
+ const wdId = transferResult.id;
231
+ return { state: 'PENDING', context: wdId };
232
+ },
233
+ PENDING: async (order) => {
234
+ const wdId = order.current_tx_context;
235
+ const withdrawResult = await client.getWithdrawHistory({ coin: 'USDT' });
236
+ const record = withdrawResult === null || withdrawResult === void 0 ? void 0 : withdrawResult.find((v) => v.id === wdId);
237
+ const txId = record === null || record === void 0 ? void 0 : record.txId;
238
+ if (!txId) {
239
+ return { state: 'PENDING', context: wdId };
240
+ }
241
+ return { state: 'COMPLETE', transaction_id: txId };
242
+ },
243
+ },
244
+ onEval: async (order) => {
245
+ var _a;
246
+ const checkResult = await client.getDepositHistory({
247
+ coin: 'USDT',
248
+ txId: order.current_transaction_id,
249
+ });
250
+ if (((_a = checkResult === null || checkResult === void 0 ? void 0 : checkResult[0]) === null || _a === void 0 ? void 0 : _a.status) !== 1) {
251
+ return { state: 'PENDING' };
252
+ }
253
+ const received_amount = +checkResult[0].amount;
254
+ return { state: 'COMPLETE', received_amount };
255
+ },
256
+ });
257
+ }
258
+ }
259
+ // order related
260
+ {
261
+ terminal.provideService('SubmitOrder', {
262
+ required: ['account_id'],
263
+ properties: {
264
+ account_id: { const: UNIFIED_ACCOUNT_ID },
265
+ },
266
+ }, async (msg) => {
267
+ console.info(formatTime(Date.now()), 'SubmitOrder', msg.req);
268
+ const order = msg.req;
269
+ const [instType, symbol] = decodePath(order.product_id);
270
+ if (instType === 'usdt-future') {
271
+ const mapOrderDirectionToSide = (direction) => {
272
+ switch (direction) {
273
+ case 'OPEN_LONG':
274
+ case 'CLOSE_SHORT':
275
+ return 'BUY';
276
+ case 'OPEN_SHORT':
277
+ case 'CLOSE_LONG':
278
+ return 'SELL';
279
+ }
280
+ throw new Error(`Unknown direction: ${direction}`);
281
+ };
282
+ const mapOrderDirectionToPosSide = (direction) => {
283
+ switch (direction) {
284
+ case 'OPEN_LONG':
285
+ case 'CLOSE_LONG':
286
+ return 'LONG';
287
+ case 'CLOSE_SHORT':
288
+ case 'OPEN_SHORT':
289
+ return 'SHORT';
290
+ }
291
+ throw new Error(`Unknown direction: ${direction}`);
292
+ };
293
+ const mapOrderTypeToOrdType = (order_type) => {
294
+ switch (order_type) {
295
+ case 'LIMIT':
296
+ return 'LIMIT';
297
+ case 'MARKET':
298
+ return 'MARKET';
299
+ }
300
+ throw new Error(`Unknown order type: ${order_type}`);
301
+ };
302
+ // return
303
+ const params = {
304
+ symbol,
305
+ side: mapOrderDirectionToSide(order.order_direction),
306
+ positionSide: mapOrderDirectionToPosSide(order.order_direction),
307
+ type: mapOrderTypeToOrdType(order.order_type),
308
+ timeInForce: order.order_type === 'LIMIT' ? 'GTC' : undefined,
309
+ quantity: order.volume,
310
+ price: order.price,
311
+ };
312
+ console.info(formatTime(Date.now()), 'SubmitOrder', 'params', JSON.stringify(params));
313
+ const orderResult = await client.postUmOrder(params);
314
+ if (isError(orderResult)) {
315
+ return { res: { code: orderResult.code, message: orderResult.msg } };
316
+ }
317
+ return { res: { code: 0, message: 'OK', order_id: orderResult.orderId } };
318
+ }
319
+ return { res: { code: 400, message: `unsupported type: ${instType}` } };
320
+ });
321
+ }
322
+ })();
323
+ //# sourceMappingURL=legacy_index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"legacy_index.js","sourceRoot":"","sources":["../src/legacy_index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,gBAAgB,EAIhB,kBAAkB,GACnB,MAAM,sBAAsB,CAAC;AAC9B,OAAO,EAAE,yBAAyB,EAAE,MAAM,kBAAkB,CAAC;AAC7D,OAAO,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,MAAM,eAAe,CAAC;AACnE,OAAO,EAAE,KAAK,EAAE,IAAI,EAAE,GAAG,EAAE,QAAQ,EAAE,MAAM,EAAE,KAAK,EAAE,WAAW,EAAE,GAAG,EAAE,OAAO,EAAE,MAAM,MAAM,CAAC;AAC5F,OAAO,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,OAAO,CAAC;AACxC,OAAO,EAAE,QAAQ,EAAE,MAAM,YAAY,CAAC;AAEtC,MAAM,UAAU,GAAG,CAAsC,EAAK,EAAK,EAAE;IACnE,MAAM,KAAK,GAAwB,EAAE,CAAC;IACtC,OAAO,CAAC,CAAC,GAAG,MAAa,EAAE,EAAE,mBAAC,OAAA,OAAC,KAAK,MAAC,UAAU,CAAC,MAAM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,UAAU,CAAC;oBAC7C,WAAW,EAAE,KAAK,CAAC,UAAU,KAAK,OAAO,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,SAAS;oBAC7D,QAAQ,EAAE,KAAK,CAAC,MAAM;oBACtB,KAAK,EAAE,KAAK,CAAC,KAAK;iBACnB,CAAC;gBAEF,OAAO,CAAC,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC,GAAG,EAAE,CAAC,EAAE,aAAa,EAAE,QAAQ,EAAE,IAAI,CAAC,SAAS,CAAC,MAAM,CAAC,CAAC,CAAC;gBACtF,MAAM,WAAW,GAAG,MAAM,MAAM,CAAC,WAAW,CAAC,MAAM,CAAC,CAAC;gBACrD,IAAI,OAAO,CAAC,WAAW,CAAC,EAAE;oBACxB,OAAO,EAAE,GAAG,EAAE,EAAE,IAAI,EAAE,WAAW,CAAC,IAAI,EAAE,OAAO,EAAE,WAAW,CAAC,GAAG,EAAE,EAAE,CAAC;iBACtE;gBACD,OAAO,EAAE,GAAG,EAAE,EAAE,IAAI,EAAE,CAAC,EAAE,OAAO,EAAE,IAAI,EAAE,QAAQ,EAAE,WAAW,CAAC,OAAO,EAAE,EAAE,CAAC;aAC3E;YACD,OAAO,EAAE,GAAG,EAAE,EAAE,IAAI,EAAE,GAAG,EAAE,OAAO,EAAE,qBAAqB,QAAQ,EAAE,EAAE,EAAE,CAAC;QAC1E,CAAC,CACF,CAAC;KACH;AACH,CAAC,CAAC,EAAE,CAAC","sourcesContent":["import {\n addAccountMarket,\n IAccountInfo,\n IAccountMoney,\n IPosition,\n publishAccountInfo,\n} from '@yuants/data-account';\nimport { addAccountTransferAddress } from '@yuants/transfer';\nimport { decodePath, encodePath, formatTime } from '@yuants/utils';\nimport { defer, from, map, mergeMap, repeat, retry, shareReplay, tap, toArray } from 'rxjs';\nimport { client, isError } from './api';\nimport { terminal } from './terminal';\n\nconst memoizeMap = <T extends (...params: any[]) => any>(fn: T): T => {\n const cache: Record<string, any> = {};\n return ((...params: any[]) => (cache[encodePath(params)] ??= fn(...params))) as T;\n};\n\nconst mapSymbolToFuturePremiumIndex$ = defer(() => client.getFuturePremiumIndex({})).pipe(\n repeat({ delay: 1_000 }),\n retry({ delay: 30_000 }),\n mergeMap((x) =>\n from(x).pipe(\n map((v) => [v.symbol, v] as const),\n toArray(),\n map((v) => new Map(v)),\n ),\n ),\n shareReplay(1),\n);\n\nconst mapSymbolToFutureBookTicker$ = defer(() => client.getFutureBookTicker({})).pipe(\n repeat({ delay: 1_000 }),\n retry({ delay: 30_000 }),\n mergeMap((x) =>\n from(x).pipe(\n map((v) => [v.symbol, v] as const),\n toArray(),\n map((v) => new Map(v)),\n ),\n ),\n shareReplay(1),\n);\n\nconst _mapSymbolToOpenInterest: Record<string, { value: number; updated_at: number }> = {};\nconst getOpenInterest = async (symbol: string) => {\n const expired_at = Date.now() - 600_000; // 10min expired\n const cache = _mapSymbolToOpenInterest[symbol];\n if (cache) {\n if (cache.updated_at > expired_at) {\n return cache.value;\n }\n }\n const data = await client.getFutureOpenInterest({ symbol });\n const value = +data.openInterest || 0;\n _mapSymbolToOpenInterest[symbol] = { value, updated_at: Date.now() };\n return value;\n};\n\n// provideTicks(terminal, 'binance', (product_id) => {\n// const [instType, symbol] = decodePath(product_id);\n// if (instType === 'usdt-future') {\n// return combineLatest([mapSymbolToFuturePremiumIndex$, mapSymbolToFutureBookTicker$]).pipe(\n// combineLatestWith(defer(() => getOpenInterest(symbol))),\n// map(([[mapSymbolToFuturePremiumIndex, mapSymbolToFutureBookTicker], openInterestVolume]): ITick => {\n// const premiumIndex = mapSymbolToFuturePremiumIndex.get(symbol);\n// const bookTicker = mapSymbolToFutureBookTicker.get(symbol);\n// if (!premiumIndex) {\n// throw new Error(`Premium Index Not Found: ${symbol}`);\n// }\n// if (!bookTicker) {\n// throw new Error(`Book Ticker Not Found: ${symbol}`);\n// }\n// return {\n// datasource_id: 'binance',\n// product_id,\n// updated_at: Date.now(),\n// price: +premiumIndex.markPrice,\n// ask: +bookTicker.askPrice,\n// bid: +bookTicker.bidPrice,\n// interest_rate_for_long: -+premiumIndex.lastFundingRate,\n// interest_rate_for_short: +premiumIndex.lastFundingRate,\n// settlement_scheduled_at: premiumIndex.nextFundingTime,\n// open_interest: openInterestVolume,\n// };\n// }),\n// );\n// }\n// return EMPTY;\n// });\n\n(async () => {\n const spotAccountInfo = await client.getSpotAccountInfo();\n if (isError(spotAccountInfo)) {\n throw new Error(spotAccountInfo.msg);\n }\n const uid = spotAccountInfo.uid;\n\n const SPOT_ACCOUNT_ID = `binance/${uid}/spot/usdt`;\n const UNIFIED_ACCOUNT_ID = `binance/${uid}/unified/usdt`;\n\n {\n // unified accountInfo\n const unifiedAccountInfo$ = defer(async (): Promise<IAccountInfo> => {\n const accountResult = await client.getUnifiedAccountBalance();\n if (isError(accountResult)) {\n throw new Error(accountResult.msg);\n }\n const usdtAssets = accountResult.find((v) => v.asset === 'USDT');\n if (!usdtAssets) {\n throw new Error('USDT not found');\n }\n const umAccountResult = await client.getUnifiedUmAccount();\n if (isError(umAccountResult)) {\n throw new Error(umAccountResult.msg);\n }\n const usdtUmAssets = umAccountResult.assets.find((v) => v.asset === 'USDT');\n if (!usdtUmAssets) {\n throw new Error('um USDT not found');\n }\n const money: IAccountMoney = {\n currency: 'USDT',\n leverage: 1,\n equity: +usdtAssets.totalWalletBalance + +usdtAssets.umUnrealizedPNL,\n balance: +usdtAssets.totalWalletBalance,\n profit: +usdtAssets.umUnrealizedPNL,\n used: +usdtUmAssets.initialMargin,\n free: +usdtAssets.totalWalletBalance + +usdtAssets.umUnrealizedPNL - +usdtUmAssets.initialMargin,\n };\n\n const positions = umAccountResult.positions\n .filter((v) => +v.positionAmt !== 0)\n .map((v): IPosition => {\n return {\n position_id: `${v.symbol}/${v.positionSide}`,\n datasource_id: 'BINANCE',\n product_id: encodePath('usdt-future', v.symbol),\n direction: v.positionSide,\n volume: +v.positionAmt,\n free_volume: +v.positionAmt,\n position_price: +v.entryPrice,\n closable_price: +v.entryPrice + +v.unrealizedProfit / +v.positionAmt,\n floating_profit: +v.unrealizedProfit,\n valuation: +v.positionAmt * (+v.entryPrice + +v.unrealizedProfit / +v.positionAmt),\n };\n });\n\n return {\n updated_at: Date.now(),\n account_id: UNIFIED_ACCOUNT_ID,\n money,\n positions,\n };\n }).pipe(\n tap({\n error: (err) => {\n console.error(formatTime(Date.now()), 'unifiedAccountInfo$', err);\n },\n }),\n retry({ delay: 5000 }),\n repeat({ delay: 1000 }),\n );\n publishAccountInfo(terminal, UNIFIED_ACCOUNT_ID, unifiedAccountInfo$);\n addAccountMarket(terminal, { account_id: UNIFIED_ACCOUNT_ID, market_id: 'BINANCE/UNIFIED' });\n }\n\n {\n // spot account info\n const spotAccountInfo$ = defer(async (): Promise<IAccountInfo> => {\n const spotAccountResult = await client.getSpotAccountInfo({ omitZeroBalances: true });\n if (isError(spotAccountResult)) {\n throw new Error(spotAccountResult.msg);\n }\n const usdtAssets = spotAccountResult.balances.find((v) => v.asset === 'USDT');\n const money: IAccountMoney = {\n currency: 'USDT',\n leverage: 1,\n equity: +(usdtAssets?.free || 0),\n balance: +(usdtAssets?.free || 0),\n profit: 0,\n used: 0,\n free: +(usdtAssets?.free || 0),\n };\n\n return {\n updated_at: Date.now(),\n account_id: SPOT_ACCOUNT_ID,\n money,\n positions: [],\n };\n }).pipe(\n tap({\n error: (err) => {\n console.error(formatTime(Date.now()), 'unifiedAccountInfo$', err);\n },\n }),\n retry({ delay: 5000 }),\n repeat({ delay: 1000 }),\n );\n\n publishAccountInfo(terminal, SPOT_ACCOUNT_ID, spotAccountInfo$);\n addAccountMarket(terminal, { account_id: SPOT_ACCOUNT_ID, market_id: 'BINANCE/SPOT' });\n }\n\n // transfer\n {\n // spot -> unified\n const SPOT_UNIFIED_NETWORK_ID = `binance/${uid}/spot/unified`;\n addAccountTransferAddress({\n terminal,\n account_id: SPOT_ACCOUNT_ID,\n network_id: SPOT_UNIFIED_NETWORK_ID,\n currency: 'USDT',\n address: `unified`,\n onApply: {\n INIT: async (order) => {\n const transferResult = await client.postAssetTransfer({\n type: 'MAIN_PORTFOLIO_MARGIN',\n asset: 'USDT',\n amount: order.current_amount!,\n });\n if (isError(transferResult)) {\n return { state: 'INIT', message: transferResult.msg };\n }\n return { state: 'COMPLETE', transaction_id: '' + transferResult.tranId };\n },\n },\n onEval: async (order) => {\n return { state: 'COMPLETE', received_amount: order.current_amount };\n },\n });\n\n // unified -> spot\n addAccountTransferAddress({\n terminal,\n account_id: UNIFIED_ACCOUNT_ID,\n network_id: SPOT_UNIFIED_NETWORK_ID,\n currency: 'USDT',\n address: `spot`,\n onApply: {\n INIT: async (order) => {\n const transferResult = await client.postAssetTransfer({\n type: 'PORTFOLIO_MARGIN_MAIN',\n asset: 'USDT',\n amount: order.current_amount!,\n });\n if (isError(transferResult)) {\n return { state: 'INIT', message: transferResult.msg };\n }\n return { state: 'COMPLETE', transaction_id: '' + transferResult.tranId };\n },\n },\n onEval: async (order) => {\n return { state: 'COMPLETE', received_amount: order.current_amount };\n },\n });\n\n const subAccountsResult = await client.getSubAccountList();\n const isMain = !isError(subAccountsResult);\n // main -> sub\n // TODO...\n\n // blockchain\n if (isMain) {\n const depositAddressResult = await client.getDepositAddress({ coin: 'USDT', network: 'TRX' });\n addAccountTransferAddress({\n terminal,\n account_id: SPOT_ACCOUNT_ID,\n network_id: 'TRC20',\n currency: 'USDT',\n address: depositAddressResult.address,\n onApply: {\n INIT: async (order) => {\n const transferResult = await client.postWithdraw({\n coin: 'USDT',\n network: 'TRX',\n address: order.current_rx_address!,\n amount: order.current_amount!,\n });\n if (isError(transferResult)) {\n return { state: 'ERROR', message: transferResult.msg };\n }\n const wdId = transferResult.id;\n return { state: 'PENDING', context: wdId };\n },\n PENDING: async (order) => {\n const wdId = order.current_tx_context;\n const withdrawResult = await client.getWithdrawHistory({ coin: 'USDT' });\n const record = withdrawResult?.find((v) => v.id === wdId);\n const txId = record?.txId;\n if (!txId) {\n return { state: 'PENDING', context: wdId };\n }\n return { state: 'COMPLETE', transaction_id: txId };\n },\n },\n onEval: async (order) => {\n const checkResult = await client.getDepositHistory({\n coin: 'USDT',\n txId: order.current_transaction_id,\n });\n if (checkResult?.[0]?.status !== 1) {\n return { state: 'PENDING' };\n }\n const received_amount = +checkResult[0].amount;\n return { state: 'COMPLETE', received_amount };\n },\n });\n }\n }\n\n // order related\n {\n terminal.provideService(\n 'SubmitOrder',\n {\n required: ['account_id'],\n properties: {\n account_id: { const: UNIFIED_ACCOUNT_ID },\n },\n },\n async (msg) => {\n console.info(formatTime(Date.now()), 'SubmitOrder', msg.req);\n const order = msg.req;\n const [instType, symbol] = decodePath(order.product_id);\n if (instType === 'usdt-future') {\n const mapOrderDirectionToSide = (direction?: string) => {\n switch (direction) {\n case 'OPEN_LONG':\n case 'CLOSE_SHORT':\n return 'BUY';\n case 'OPEN_SHORT':\n case 'CLOSE_LONG':\n return 'SELL';\n }\n throw new Error(`Unknown direction: ${direction}`);\n };\n const mapOrderDirectionToPosSide = (direction?: string) => {\n switch (direction) {\n case 'OPEN_LONG':\n case 'CLOSE_LONG':\n return 'LONG';\n case 'CLOSE_SHORT':\n case 'OPEN_SHORT':\n return 'SHORT';\n }\n throw new Error(`Unknown direction: ${direction}`);\n };\n const mapOrderTypeToOrdType = (order_type?: string) => {\n switch (order_type) {\n case 'LIMIT':\n return 'LIMIT';\n case 'MARKET':\n return 'MARKET';\n }\n throw new Error(`Unknown order type: ${order_type}`);\n };\n // return\n const params = {\n symbol,\n side: mapOrderDirectionToSide(order.order_direction),\n positionSide: mapOrderDirectionToPosSide(order.order_direction),\n type: mapOrderTypeToOrdType(order.order_type),\n timeInForce: order.order_type === 'LIMIT' ? 'GTC' : undefined,\n quantity: order.volume,\n price: order.price,\n };\n\n console.info(formatTime(Date.now()), 'SubmitOrder', 'params', JSON.stringify(params));\n const orderResult = await client.postUmOrder(params);\n if (isError(orderResult)) {\n return { res: { code: orderResult.code, message: orderResult.msg } };\n }\n return { res: { code: 0, message: 'OK', order_id: orderResult.orderId } };\n }\n return { res: { code: 400, message: `unsupported type: ${instType}` } };\n },\n );\n }\n})();\n"]}
@@ -0,0 +1,40 @@
1
+ import { encodePath } from '@yuants/utils';
2
+ import { createSQLWriter } from '@yuants/sql';
3
+ import { Subject, defer, from, map, mergeMap, repeat, retry, shareReplay, tap, toArray } from 'rxjs';
4
+ import { client } from './api';
5
+ import { terminal } from './terminal';
6
+ const product$ = new Subject();
7
+ const futureExchangeInfo$ = defer(() => client.getFutureExchangeInfo()).pipe(repeat({ delay: 3600000 }), retry({ delay: 60000 }), shareReplay(1));
8
+ const futureProducts$ = futureExchangeInfo$.pipe(mergeMap((x) => from(x.symbols).pipe(
9
+ //
10
+ map((symbol) => {
11
+ return {
12
+ datasource_id: 'BINANCE',
13
+ product_id: encodePath('usdt-future', symbol.symbol),
14
+ base_currency: symbol.baseAsset,
15
+ quote_currency: symbol.quoteAsset,
16
+ price_step: +`1e-${symbol.pricePrecision}`,
17
+ value_scale: 1,
18
+ volume_step: +`1e-${symbol.quantityPrecision}`,
19
+ name: `${symbol.baseAsset}/${symbol.quoteAsset} PERP`,
20
+ value_scale_unit: '',
21
+ margin_rate: +symbol.requiredMarginPercent / 100,
22
+ value_based_cost: 0,
23
+ volume_based_cost: 0,
24
+ max_position: 0,
25
+ max_volume: 0,
26
+ allow_long: true,
27
+ allow_short: true,
28
+ market_id: 'BINANCE/USDT-FUTURE',
29
+ no_interest_rate: false,
30
+ };
31
+ }), tap((v) => product$.next(v)), toArray())), shareReplay(1));
32
+ futureProducts$.subscribe();
33
+ createSQLWriter(terminal, {
34
+ data$: product$,
35
+ tableName: 'product',
36
+ keyFn: (x) => encodePath(x.datasource_id, x.product_id),
37
+ conflictKeys: ['datasource_id', 'product_id'],
38
+ writeInterval: 1000,
39
+ });
40
+ //# sourceMappingURL=product.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"product.js","sourceRoot":"","sources":["../src/product.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAA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AAE,EAAE;QACpB,WAAW,EAAE,CAAC,MAAM,CAAC,qBAAqB,GAAG,GAAG;QAChD,gBAAgB,EAAE,CAAC;QACnB,iBAAiB,EAAE,CAAC;QACpB,YAAY,EAAE,CAAC;QACf,UAAU,EAAE,CAAC;QACb,UAAU,EAAE,IAAI;QAChB,WAAW,EAAE,IAAI;QACjB,SAAS,EAAE,qBAAqB;QAChC,gBAAgB,EAAE,KAAK;KACxB,CAAC;AACJ,CAAC,CAAC,EACF,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,EAC5B,OAAO,EAAE,CACV,CACF,EACD,WAAW,CAAC,CAAC,CAAC,CACf,CAAC;AAEF,eAAe,CAAC,SAAS,EAAE,CAAC;AAE5B,eAAe,CAAW,QAAQ,EAAE;IAClC,KAAK,EAAE,QAAQ;IACf,SAAS,EAAE,SAAS;IACpB,KAAK,EAAE,CAAC,CAAC,EAAE,EAAE,CAAC,UAAU,CAAC,CAAC,CAAC,aAAa,EAAE,CAAC,CAAC,UAAU,CAAC;IACvD,YAAY,EAAE,CAAC,eAAe,EAAE,YAAY,CAAC;IAC7C,aAAa,EAAE,IAAI;CACpB,CAAC,CAAC","sourcesContent":["import { encodePath } from '@yuants/utils';\nimport { IProduct } from '@yuants/data-product';\nimport { createSQLWriter } from '@yuants/sql';\nimport { Subject, defer, from, map, mergeMap, repeat, retry, shareReplay, tap, toArray } from 'rxjs';\nimport { client } from './api';\nimport { terminal } from './terminal';\n\nconst product$ = new Subject<IProduct>();\n\nconst futureExchangeInfo$ = defer(() => client.getFutureExchangeInfo()).pipe(\n repeat({ delay: 3600_000 }),\n retry({ delay: 60_000 }),\n shareReplay(1),\n);\n\nconst futureProducts$ = futureExchangeInfo$.pipe(\n mergeMap((x) =>\n from(x.symbols).pipe(\n //\n map((symbol): IProduct => {\n return {\n datasource_id: 'BINANCE',\n product_id: encodePath('usdt-future', symbol.symbol),\n base_currency: symbol.baseAsset,\n quote_currency: symbol.quoteAsset,\n price_step: +`1e-${symbol.pricePrecision}`,\n value_scale: 1,\n volume_step: +`1e-${symbol.quantityPrecision}`,\n name: `${symbol.baseAsset}/${symbol.quoteAsset} PERP`,\n value_scale_unit: '',\n margin_rate: +symbol.requiredMarginPercent / 100,\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: 'BINANCE/USDT-FUTURE',\n no_interest_rate: false,\n };\n }),\n tap((v) => product$.next(v)),\n toArray(),\n ),\n ),\n shareReplay(1),\n);\n\nfutureProducts$.subscribe();\n\ncreateSQLWriter<IProduct>(terminal, {\n data$: product$,\n tableName: 'product',\n keyFn: (x) => encodePath(x.datasource_id, x.product_id),\n conflictKeys: ['datasource_id', 'product_id'],\n writeInterval: 1000,\n});\n"]}
@@ -0,0 +1,7 @@
1
+ import { Terminal } from '@yuants/protocol';
2
+ import { UUID } from '@yuants/utils';
3
+ export const terminal = new Terminal(process.env.HOST_URL, {
4
+ terminal_id: process.env.TERMINAL_ID || `binance/${UUID()}`,
5
+ name: '@yuants/vendor-binance',
6
+ });
7
+ //# sourceMappingURL=terminal.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"terminal.js","sourceRoot":"","sources":["../src/terminal.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,kBAAkB,CAAC;AAC5C,OAAO,EAAE,IAAI,EAAE,MAAM,eAAe,CAAC;AAErC,MAAM,CAAC,MAAM,QAAQ,GAAG,IAAI,QAAQ,CAAC,OAAO,CAAC,GAAG,CAAC,QAAS,EAAE;IAC1D,WAAW,EAAE,OAAO,CAAC,GAAG,CAAC,WAAW,IAAI,WAAW,IAAI,EAAE,EAAE;IAC3D,IAAI,EAAE,wBAAwB;CAC/B,CAAC,CAAC","sourcesContent":["import { Terminal } from '@yuants/protocol';\nimport { UUID } from '@yuants/utils';\n\nexport const terminal = new Terminal(process.env.HOST_URL!, {\n terminal_id: process.env.TERMINAL_ID || `binance/${UUID()}`,\n name: '@yuants/vendor-binance',\n});\n"]}
@@ -0,0 +1 @@
1
+ export { }