@yuants/vendor-huobi 0.9.7 → 0.10.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 (60) hide show
  1. package/dist/api.js +313 -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/cluster.js +72 -0
  6. package/dist/cluster.js.map +1 -0
  7. package/dist/extension.js +87 -0
  8. package/dist/extension.js.map +1 -0
  9. package/dist/index.js +582 -0
  10. package/dist/index.js.map +1 -0
  11. package/dist/interest_rate.js +59 -0
  12. package/dist/interest_rate.js.map +1 -0
  13. package/dist/logger.js +91 -0
  14. package/dist/logger.js.map +1 -0
  15. package/dist/product.js +85 -0
  16. package/dist/product.js.map +1 -0
  17. package/dist/quote.js +93 -0
  18. package/dist/quote.js.map +1 -0
  19. package/dist/vendor-huobi.d.ts +1 -0
  20. package/lib/api.d.ts +634 -0
  21. package/lib/api.d.ts.map +1 -0
  22. package/lib/api.js +320 -0
  23. package/lib/api.js.map +1 -0
  24. package/lib/cli.d.ts +3 -0
  25. package/lib/cli.d.ts.map +1 -0
  26. package/lib/cli.js +5 -0
  27. package/lib/cli.js.map +1 -0
  28. package/lib/cluster.d.ts +2 -0
  29. package/lib/cluster.d.ts.map +1 -0
  30. package/lib/cluster.js +100 -0
  31. package/lib/cluster.js.map +1 -0
  32. package/lib/extension.d.ts +4 -0
  33. package/lib/extension.d.ts.map +1 -0
  34. package/lib/extension.js +89 -0
  35. package/lib/extension.js.map +1 -0
  36. package/lib/index.d.ts +3 -0
  37. package/lib/index.d.ts.map +1 -0
  38. package/lib/index.js +584 -0
  39. package/lib/index.js.map +1 -0
  40. package/lib/interest_rate.d.ts +2 -0
  41. package/lib/interest_rate.d.ts.map +1 -0
  42. package/lib/interest_rate.js +61 -0
  43. package/lib/interest_rate.js.map +1 -0
  44. package/lib/logger.d.ts +21 -0
  45. package/lib/logger.d.ts.map +1 -0
  46. package/lib/logger.js +98 -0
  47. package/lib/logger.js.map +1 -0
  48. package/lib/product.d.ts +4 -0
  49. package/lib/product.d.ts.map +1 -0
  50. package/lib/product.js +88 -0
  51. package/lib/product.js.map +1 -0
  52. package/lib/quote.d.ts +2 -0
  53. package/lib/quote.d.ts.map +1 -0
  54. package/lib/quote.js +95 -0
  55. package/lib/quote.js.map +1 -0
  56. package/package.json +14 -11
  57. package/temp/image-tag +1 -0
  58. package/temp/package-deps.json +37 -0
  59. package/temp/vendor-huobi.api.json +177 -0
  60. package/temp/vendor-huobi.api.md +9 -0
package/dist/api.js ADDED
@@ -0,0 +1,313 @@
1
+ import { createConnectionWs } from '@yuants/protocol';
2
+ import { formatTime } from '@yuants/utils';
3
+ import { Subject, filter, from, map, share, tap } from 'rxjs';
4
+ import zlib from 'zlib';
5
+ // @ts-ignore
6
+ import CryptoJS from 'crypto-js';
7
+ const createConnectionGzipWS = (URL) => {
8
+ const conn = createConnectionWs(URL);
9
+ const input$ = from(conn.input$).pipe(map((msg) => zlib.gunzipSync(msg)), map((msg) => msg.toString()), map((msg) => JSON.parse(msg)), share());
10
+ const output$ = new Subject();
11
+ output$.pipe(map((msg) => JSON.stringify(msg))).subscribe(conn.output$);
12
+ return Object.assign(Object.assign({}, conn), { input$: input$, output$: output$ });
13
+ };
14
+ export class HuobiClient {
15
+ constructor(params) {
16
+ this.params = params;
17
+ // https://www.htx.com/zh-cn/opend/newApiPages/?id=510
18
+ this.swap_api_root = 'api.hbdm.com';
19
+ // https://www.htx.com/zh-cn/opend/newApiPages/?id=404
20
+ this.spot_api_root = 'api.huobi.pro';
21
+ /**
22
+ * 【全仓】获取平台阶梯保证金
23
+ *
24
+ * https://www.htx.com/zh-cn/opend/newApiPages/?id=8cb72290-77b5-11ed-9966-0242ac110003
25
+ */
26
+ this.getSwapCrossLadderMargin = (params) => this.request('GET', '/linear-swap-api/v1/swap_cross_ladder_margin', this.swap_api_root, params);
27
+ /**
28
+ * 【通用】批量获取合约资金费率
29
+ *
30
+ * 接口权限: 读取
31
+ *
32
+ * 限频: 其他非行情类的公开接口,比如获取指数信息,限价信息,交割结算、平台持仓信息等,所有用户都是每个IP3秒最多240次请求(所有该IP的非行情类的公开接口请求共享3秒240次的额度)
33
+ *
34
+ * 接口描述: 该接口支持全仓模式和逐仓模式
35
+ *
36
+ * https://www.htx.com/zh-cn/opend/newApiPages/?id=8cb71b45-77b5-11ed-9966-0242ac110003
37
+ */
38
+ this.getSwapBatchFundingRate = (params) => {
39
+ // https://www.htx.com/zh-cn/opend/newApiPages/?id=8cb7a7b5-77b5-11ed-9966-0242ac110003
40
+ return this.request('GET', `/linear-swap-api/v1/swap_batch_funding_rate`, this.swap_api_root, params);
41
+ };
42
+ /**
43
+ * 【通用】获取市场最近成交记录
44
+ *
45
+ * 接口权限: 读取
46
+ *
47
+ * 限频: 行情类的公开接口,比如:获取K线数据、获取聚合行情、市场行情、获取行情深度数据、获取溢价指数K线、获取实时预测资金费率k线,获取基差数据、获取市场最近成交记录:
48
+ *
49
+ * (1) restful接口:同一个IP, 所有业务(交割合约、币本位永续合约和U本位合约)总共1秒最多800个请求
50
+ *
51
+ * 接口描述: 该接口支持全仓模式和逐仓模式
52
+ *
53
+ * 请求参数contract_code支持交割合约代码,格式为BTC-USDT-210625;同时支持合约标识,格式为 BTC-USDT(永续)、BTC-USDT-CW(当周)、BTC-USDT-NW(次周)、BTC-USDT-CQ(当季)、BTC-USDT-NQ(次季)。
54
+ *
55
+ * business_type 在查询交割合约数据时为必填参数。且参数值要传:futures 或 all 。
56
+ *
57
+ * https://www.htx.com/zh-cn/opend/newApiPages/?id=8cb73c34-77b5-11ed-9966-0242ac110003
58
+ */
59
+ this.getSwapMarketTrade = (params) => this.request('GET', `/linear-swap-ex/market/trade`, this.swap_api_root, params);
60
+ /**
61
+ * 获得当前合约的总持仓量
62
+ *
63
+ * https://huobiapi.github.io/docs/usdt_swap/v1/cn/#3218e7531a
64
+ */
65
+ this.getSwapOpenInterest = (params) => this.request('GET', '/linear-swap-api/v1/swap_open_interest', this.swap_api_root, params);
66
+ /**
67
+ * 【通用】获取市场最优挂单
68
+ *
69
+ * 接口权限: 读取
70
+ *
71
+ * 限频: 行情类的公开接口,比如:获取K线数据、获取聚合行情、市场行情、获取行情深度数据、获取溢价指数K线、获取实时预测资金费率k线,获取基差数据、获取市场最近成交记录:
72
+ *
73
+ * (1) restful接口:同一个IP, 所有业务(交割合约、币本位永续合约和U本位合约)总共1秒最多800个请求
74
+ *
75
+ * 接口描述: 该接口支持全仓模式和逐仓模式
76
+ *
77
+ * 请求参数contract_code支持交割合约代码,格式为BTC-USDT-210625;同时支持合约标识,格式为 BTC-USDT(永续)、BTC-USDT-CW(当周)、BTC-USDT-NW(次周)、BTC-USDT-CQ(当季)、BTC-USDT-NQ(次季)。
78
+ *
79
+ * business_type 在查询交割合约数据时为必填参数。且参数值要传:futures 或 all 。
80
+ *
81
+ * https://www.htx.com/zh-cn/opend/newApiPages/?id=8cb735e0-77b5-11ed-9966-0242ac110003
82
+ */
83
+ this.getSwapMarketBbo = (params) => this.request('GET', `/linear-swap-ex/market/bbo`, this.swap_api_root, params);
84
+ /**
85
+ * APIv2币链参考信息
86
+ *
87
+ * https://www.htx.com/zh-cn/opend/newApiPages/?id=7ec478f0-7773-11ed-9966-0242ac110003
88
+ */
89
+ this.getV2ReferenceCurrencies = (params) => this.request('GET', '/v2/reference/currencies', this.spot_api_root, params);
90
+ /**
91
+ * APIv2币链参考信息
92
+ *
93
+ * https://www.htx.com/zh-cn/opend/newApiPages/?id=7ec41049-7773-11ed-9966-0242ac110003
94
+ */
95
+ this.getAccountHistory = (params) => this.request('GET', '/v1/account/history', this.spot_api_root, params);
96
+ this.spot_ws = createConnectionGzipWS(`wss://${this.spot_api_root}/ws`);
97
+ from(this.spot_ws.input$)
98
+ .pipe(
99
+ //
100
+ filter((v) => v.ping), tap((v) => {
101
+ this.spot_ws.output$.next({ pong: v.ping });
102
+ }))
103
+ .subscribe();
104
+ }
105
+ async request(method, path, api_root, params) {
106
+ const noAuth = !(this.params.auth.access_key && this.params.auth.secret_key);
107
+ if (noAuth) {
108
+ const requestParams = `${method === 'GET' && params !== undefined
109
+ ? `&${Object.entries(params)
110
+ .sort(([a], [b]) => a.localeCompare(b))
111
+ .map(([k, v]) => `${k}=${v}`)
112
+ .join('&')}`
113
+ : ''}`;
114
+ const body = method === 'GET' ? '' : JSON.stringify(params);
115
+ const url = new URL(`https://${api_root}${path}?${requestParams}`);
116
+ // url.searchParams.sort();
117
+ console.info(formatTime(Date.now()), method, url.href, body);
118
+ const res = await fetch(url.href, {
119
+ method,
120
+ headers: { 'Content-Type': 'application/json' },
121
+ body: body || undefined,
122
+ });
123
+ const retStr = await res.text();
124
+ // console.info(formatTime(Date.now()), 'response', url.href, retStr);
125
+ try {
126
+ return JSON.parse(retStr);
127
+ }
128
+ catch (e) {
129
+ console.error(formatTime(Date.now()), 'huobiRequestFailed', path, JSON.stringify(params), retStr);
130
+ throw e;
131
+ }
132
+ }
133
+ const requestParams = `AccessKeyId=${this.params.auth.access_key}&SignatureMethod=HmacSHA256&SignatureVersion=2&Timestamp=${encodeURIComponent(new Date().toISOString().split('.')[0])}${method === 'GET' && params !== undefined
134
+ ? `&${Object.entries(params)
135
+ .sort(([a], [b]) => a.localeCompare(b))
136
+ .map(([k, v]) => `${k}=${v}`)
137
+ .join('&')}`
138
+ : ''}`;
139
+ const body = method === 'GET' ? '' : JSON.stringify(params);
140
+ const requestString = `${method}\n${api_root}\n${path}\n${requestParams}`;
141
+ const str = CryptoJS.enc.Base64.stringify(CryptoJS.HmacSHA256(requestString, this.params.auth.secret_key));
142
+ const url = new URL(`https://${api_root}${path}?${requestParams}&Signature=${encodeURIComponent(str)}`);
143
+ // url.searchParams.sort();
144
+ console.info(formatTime(Date.now()), method, url.href, body);
145
+ const res = await fetch(url.href, {
146
+ method,
147
+ headers: { 'Content-Type': 'application/json' },
148
+ body: body || undefined,
149
+ });
150
+ const retStr = await res.text();
151
+ // console.info(formatTime(Date.now()), 'response', url.href, retStr);
152
+ try {
153
+ return JSON.parse(retStr);
154
+ }
155
+ catch (e) {
156
+ console.error(formatTime(Date.now()), 'huobiRequestFailed', path, JSON.stringify(params), retStr);
157
+ throw e;
158
+ }
159
+ }
160
+ // swap_ws = new WebSocket(new URL(`wss://${this.swap_api_root}/linear-swap-ws`));
161
+ getAccount() {
162
+ // https://www.htx.com/zh-cn/opend/newApiPages/?id=7ec40743-7773-11ed-9966-0242ac110003
163
+ return this.request('GET', '/v1/account/accounts', this.spot_api_root);
164
+ }
165
+ getPerpetualContractSymbols(params) {
166
+ // https://www.htx.com/zh-cn/opend/newApiPages/?id=8cb72f34-77b5-11ed-9966-0242ac110003
167
+ return this.request('GET', '/linear-swap-api/v1/swap_contract_info', this.swap_api_root, params);
168
+ }
169
+ getSpotSymbols() {
170
+ // https://www.htx.com/zh-cn/opend/newApiPages/?id=7ec47f16-7773-11ed-9966-0242ac110003
171
+ return this.request('GET', '/v2/settings/common/symbols', this.spot_api_root);
172
+ }
173
+ getUid() {
174
+ // https://www.htx.com/zh-cn/opend/newApiPages/?id=7ec491c9-7773-11ed-9966-0242ac110003
175
+ return this.request('GET', '/v2/user/uid', this.spot_api_root);
176
+ }
177
+ getUnifiedAccountInfo() {
178
+ // https://www.htx.com/zh-cn/opend/newApiPages/?id=10000073-77b7-11ed-9966-0242ac110003
179
+ return this.request('GET', '/linear-swap-api/v3/unified_account_info', this.swap_api_root);
180
+ }
181
+ getSwapCrossPositionInfo(params) {
182
+ // https://www.htx.com/zh-cn/opend/newApiPages/?id=8cb74963-77b5-11ed-9966-0242ac110003
183
+ return this.request('POST', '/linear-swap-api/v1/swap_cross_position_info', this.swap_api_root, params);
184
+ }
185
+ getSwapOpenOrders(params) {
186
+ // https://www.htx.com/zh-cn/opend/newApiPages/?id=8cb784d4-77b5-11ed-9966-0242ac110003
187
+ return this.request('POST', '/linear-swap-api/v1/swap_cross_openorders', this.swap_api_root, params);
188
+ }
189
+ getSpotAccountBalance(account_uid) {
190
+ // https://www.htx.com/zh-cn/opend/newApiPages/?id=7ec40922-7773-11ed-9966-0242ac110003
191
+ return this.request('GET', `/v1/account/accounts/${account_uid}/balance`, this.spot_api_root);
192
+ }
193
+ getCrossMarginLoanInfo() {
194
+ // https://www.htx.com/zh-cn/opend/newApiPages/?id=7ec41863-7773-11ed-9966-0242ac110003
195
+ return this.request('GET', '/v1/cross-margin/loan-info', this.spot_api_root);
196
+ }
197
+ getSpotTick(params) {
198
+ // https://www.htx.com/zh-cn/opend/newApiPages/?id=7ec3fc25-7773-11ed-9966-0242ac110003
199
+ return this.request('GET', `/market/detail/merged`, this.spot_api_root, params);
200
+ }
201
+ postSpotOrder(params) {
202
+ // https://www.htx.com/zh-cn/opend/newApiPages/?id=10000065-77b7-11ed-9966-0242ac110003
203
+ return this.request('POST', `/v1/order/auto/place`, this.spot_api_root, params);
204
+ }
205
+ postSwapOrder(params) {
206
+ // https://www.htx.com/zh-cn/opend/newApiPages/?id=8cb77159-77b5-11ed-9966-0242ac110003
207
+ return this.request('POST', '/linear-swap-api/v1/swap_cross_order', this.swap_api_root, params);
208
+ }
209
+ getSpotAccountDepositAddresses(params) {
210
+ // https://www.htx.com/zh-cn/opend/newApiPages/?id=7ec45fb7-7773-11ed-9966-0242ac110003
211
+ return this.request('GET', `/v2/account/deposit/address`, this.spot_api_root, params);
212
+ }
213
+ getAccountLedger(params) {
214
+ // https://www.htx.com/zh-cn/opend/newApiPages/?id=7ec4610b-7773-11ed-9966-0242ac110003
215
+ return this.request('GET', `/v2/account/ledger`, this.spot_api_root, params);
216
+ }
217
+ postSuperMarginAccountTransferOut(params) {
218
+ // https://www.htx.com/zh-cn/opend/newApiPages/?id=7ec41ff0-7773-11ed-9966-0242ac110003
219
+ return this.request('POST', `/v1/cross-margin/transfer-out`, this.spot_api_root, params);
220
+ }
221
+ postSuperMarginAccountTransferIn(params) {
222
+ // https://www.htx.com/zh-cn/opend/newApiPages/?id=7ec41f0e-7773-11ed-9966-0242ac110003
223
+ return this.request('POST', `/v1/cross-margin/transfer-in`, this.spot_api_root, params);
224
+ }
225
+ postSpotAccountTransfer(params) {
226
+ // https://www.htx.com/zh-cn/opend/newApiPages/?id=10000095-77b7-11ed-9966-0242ac110003
227
+ return this.request('POST', `/v2/account/transfer`, this.spot_api_root, params);
228
+ }
229
+ postBorrow(params) {
230
+ // https://www.htx.com/zh-cn/opend/newApiPages/?id=7ec41b5d-7773-11ed-9966-0242ac110003
231
+ return this.request('POST', `/v1/cross-margin/orders`, this.spot_api_root, params);
232
+ }
233
+ postWithdraw(params) {
234
+ // https://www.htx.com/zh-cn/opend/newApiPages/?id=7ec42cfd-7773-11ed-9966-0242ac110003
235
+ return this.request('POST', `/v1/dw/withdraw/api/create`, this.spot_api_root, params);
236
+ }
237
+ getDepositWithdrawHistory(params) {
238
+ // https://www.htx.com/zh-cn/opend/newApiPages/?id=7ec44f99-7773-11ed-9966-0242ac110003
239
+ return this.request(`GET`, `/v1/query/deposit-withdraw`, this.spot_api_root, params);
240
+ }
241
+ /**
242
+ * 获取合约的历史资金费率
243
+ *
244
+ * 接口权限: 读取
245
+ *
246
+ * https://www.htx.com/zh-cn/opend/newApiPages/?id=5d51f1f9-77b6-11ed-9966-0242ac110003
247
+ */
248
+ getSwapHistoricalFundingRate(params) {
249
+ return this.request('GET', `/linear-swap-api/v1/swap_historical_funding_rate`, this.swap_api_root, params);
250
+ }
251
+ /**
252
+ * 资产划转(母子用户之间)
253
+ *
254
+ * 接口权限: 交易
255
+ *
256
+ * 限频: 2次/2s
257
+ *
258
+ * https://www.htx.com/zh-cn/opend/newApiPages/?id=7ec45d8e-7773-11ed-9966-0242ac110003
259
+ */
260
+ postSubUserTransfer(params) {
261
+ return this.request('POST', '/v1/subuser/transfer', this.spot_api_root, params);
262
+ }
263
+ /**
264
+ * 获取子用户列表
265
+ *
266
+ * 接口权限: 读取
267
+ *
268
+ * https://www.htx.com/zh-cn/opend/newApiPages/?id=7ec48f09-7773-11ed-9966-0242ac110003
269
+ */
270
+ getSubUserList(params) {
271
+ return this.request('GET', `/v2/sub-user/user-list`, this.spot_api_root, params);
272
+ }
273
+ /**
274
+ * 账户类型查询
275
+ *
276
+ * 是否验签: 是
277
+ *
278
+ * 接口权限: 读取
279
+ *
280
+ * 限频: 每个UID 3秒最多 144 次请求(交易接口3秒最多 72 次请求,查询接口3秒最多 72 次请求) (该UID的所有币种和不同到期日的合约的所有私有接口共享该限制) 。
281
+ *
282
+ * 接口描述: 此接口用于客户查询的账号类型,当前U本位合约有统一账户和非统一账户(全仓逐仓账户)类型。统一账户类型资产放在USDT一个账户上,全仓逐仓账户类型资产放在不同的币对。
283
+ * 统一账户类型为最新升级的,当前不支持API下单。若需要用用API下单请切换账户类型为非统一账户。
284
+ *
285
+ * https://www.htx.com/zh-cn/opend/newApiPages/?id=8cb71825-77b5-11ed-9966-0242ac110003
286
+ */
287
+ getSwapUnifiedAccountType() {
288
+ return this.request('GET', '/linear-swap-api/v3/swap_unified_account_type', this.swap_api_root);
289
+ }
290
+ /**
291
+ * 账户类型更改接口
292
+ *
293
+ * 是否验签: 是
294
+ *
295
+ * 接口权限: 交易
296
+ *
297
+ * 限频: 每个UID 3秒最多 144 次请求(交易接口3秒最多 72 次请求,查询接口3秒最多 72 次请求) (该UID的所有币种和不同到期日的合约的所有私有接口共享该限制) 。
298
+ *
299
+ * 接口描述: 调用该接口前需要保证U本位合约无持仓和挂单,当由非统一账户(全仓逐仓账户)变为统一账户还需将资产从逐仓账户划转到全仓账户。
300
+ *
301
+ * https://www.htx.com/zh-cn/opend/newApiPages/?id=8cb7196b-77b5-11ed-9966-0242ac110003
302
+ */
303
+ postSwapSwitchAccountType(params) {
304
+ return this.request('POST', '/linear-swap-api/v3/swap_switch_account_type', this.swap_api_root, params);
305
+ }
306
+ }
307
+ export const client = new HuobiClient({
308
+ auth: {
309
+ access_key: process.env.ACCESS_KEY,
310
+ secret_key: process.env.SECRET_KEY,
311
+ },
312
+ });
313
+ //# sourceMapp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AAE,wBAAwB,EAAE,IAAI,CAAC,aAAa,EAAE,MAAM,CAAC,CAAC;IACnF,CAAC;IAED;;;;;;;;;;;;;OAaG;IACH,yBAAyB;QAQvB,OAAO,IAAI,CAAC,OAAO,CAAC,KAAK,EAAE,+CAA+C,EAAE,IAAI,CAAC,aAAa,CAAC,CAAC;IAClG,CAAC;IAED;;;;;;;;;;;;OAYG;IACH,yBAAyB,CAAC,MAAgC;QAQxD,OAAO,IAAI,CAAC,OAAO,CAAC,MAAM,EAAE,8CAA8C,EAAE,IAAI,CAAC,aAAa,EAAE,MAAM,CAAC,CAAC;IAC1G,CAAC;CA8EF;AAED,MAAM,CAAC,MAAM,MAAM,GAAG,IAAI,WAAW,CAAC;IACpC,IAAI,EAAE;QACJ,UAAU,EAAE,OAAO,CAAC,GAAG,CAAC,UAAW;QACnC,UAAU,EAAE,OAAO,CAAC,GAAG,CAAC,UAAW;KACpC;CACF,CAAC,CAAC","sourcesContent":["import { IConnection, createConnectionWs } from '@yuants/protocol';\nimport { formatTime } from '@yuants/utils';\nimport { Subject, filter, from, map, share, tap } from 'rxjs';\nimport zlib from 'zlib';\n\n// @ts-ignore\nimport CryptoJS from 'crypto-js';\ninterface IHuobiParams {\n auth: { access_key: string; secret_key: string };\n}\n\nconst createConnectionGzipWS = <T = any>(URL: string): IConnection<T> => {\n const conn = createConnectionWs(URL);\n const input$ = from(conn.input$).pipe(\n map((msg) => zlib.gunzipSync(msg)),\n map((msg) => msg.toString()),\n map((msg) => JSON.parse(msg)),\n share(),\n );\n\n const output$ = new Subject<any>();\n output$.pipe(map((msg) => JSON.stringify(msg))).subscribe(conn.output$);\n return {\n ...conn,\n input$: input$,\n output$: output$,\n };\n};\n\nexport class HuobiClient {\n // https://www.htx.com/zh-cn/opend/newApiPages/?id=510\n swap_api_root = 'api.hbdm.com';\n // https://www.htx.com/zh-cn/opend/newApiPages/?id=404\n spot_api_root = 'api.huobi.pro';\n\n spot_ws: IConnection<any>;\n\n constructor(public params: IHuobiParams) {\n this.spot_ws = createConnectionGzipWS(`wss://${this.spot_api_root}/ws`);\n from(this.spot_ws.input$)\n .pipe(\n //\n filter((v) => v.ping),\n tap((v) => {\n this.spot_ws.output$.next({ pong: v.ping });\n }),\n )\n .subscribe();\n }\n\n async request(method: string, path: string, api_root: string, params?: any) {\n const noAuth = !(this.params.auth.access_key && this.params.auth.secret_key);\n\n if (noAuth) {\n const requestParams = `${\n method === 'GET' && params !== undefined\n ? `&${Object.entries(params)\n .sort(([a], [b]) => a.localeCompare(b))\n .map(([k, v]) => `${k}=${v}`)\n .join('&')}`\n : ''\n }`;\n\n const body = method === 'GET' ? '' : JSON.stringify(params);\n\n const url = new URL(`https://${api_root}${path}?${requestParams}`);\n // url.searchParams.sort();\n console.info(formatTime(Date.now()), method, url.href, body);\n\n const res = await fetch(url.href, {\n method,\n headers: { 'Content-Type': 'application/json' },\n body: body || undefined,\n });\n\n const retStr = await res.text();\n // console.info(formatTime(Date.now()), 'response', url.href, retStr);\n try {\n return JSON.parse(retStr);\n } catch (e) {\n console.error(formatTime(Date.now()), 'huobiRequestFailed', path, JSON.stringify(params), retStr);\n throw e;\n }\n }\n\n const requestParams = `AccessKeyId=${\n this.params.auth.access_key\n }&SignatureMethod=HmacSHA256&SignatureVersion=2&Timestamp=${encodeURIComponent(\n new Date().toISOString().split('.')[0],\n )}${\n method === 'GET' && params !== undefined\n ? `&${Object.entries(params)\n .sort(([a], [b]) => a.localeCompare(b))\n .map(([k, v]) => `${k}=${v}`)\n .join('&')}`\n : ''\n }`;\n\n const body = method === 'GET' ? '' : JSON.stringify(params);\n\n const requestString = `${method}\\n${api_root}\\n${path}\\n${requestParams}`;\n\n const str = CryptoJS.enc.Base64.stringify(\n CryptoJS.HmacSHA256(requestString, this.params.auth.secret_key),\n );\n\n const url = new URL(`https://${api_root}${path}?${requestParams}&Signature=${encodeURIComponent(str)}`);\n // url.searchParams.sort();\n console.info(formatTime(Date.now()), method, url.href, body);\n const res = await fetch(url.href, {\n method,\n headers: { 'Content-Type': 'application/json' },\n body: body || undefined,\n });\n\n const retStr = await res.text();\n // console.info(formatTime(Date.now()), 'response', url.href, retStr);\n try {\n return JSON.parse(retStr);\n } catch (e) {\n console.error(formatTime(Date.now()), 'huobiRequestFailed', path, JSON.stringify(params), retStr);\n throw e;\n }\n }\n\n // swap_ws = new WebSocket(new URL(`wss://${this.swap_api_root}/linear-swap-ws`));\n\n getAccount(): Promise<{\n status: string;\n data: {\n id: number;\n type: string;\n state: string;\n subtype: string;\n }[];\n }> {\n // https://www.htx.com/zh-cn/opend/newApiPages/?id=7ec40743-7773-11ed-9966-0242ac110003\n return this.request('GET', '/v1/account/accounts', this.spot_api_root);\n }\n\n getPerpetualContractSymbols(params?: {\n contract_code?: string;\n support_margin_mode?: string;\n pair?: string;\n contract_type?: string;\n business_type?: string;\n }): Promise<{\n status: string;\n data: {\n symbol: string;\n contract_code: string;\n contract_size: number;\n price_tick: number;\n settlement_date: string;\n delivery_time: string;\n create_date: string;\n contract_status: number;\n support_margin_mode: string;\n contract_type: string;\n pair: string;\n business_type: string;\n dilivery_date: string;\n }[];\n ts: string;\n }> {\n // https://www.htx.com/zh-cn/opend/newApiPages/?id=8cb72f34-77b5-11ed-9966-0242ac110003\n return this.request('GET', '/linear-swap-api/v1/swap_contract_info', this.swap_api_root, params);\n }\n\n getSpotSymbols(): Promise<{\n status: string;\n data: {\n si: string;\n scr: string;\n sc: string;\n dn: string;\n bc: string;\n bcdn: string;\n qc: string;\n qcdn: string;\n state: string;\n whe: boolean;\n cd: boolean;\n te: boolean;\n toa: number;\n sp: string;\n w: number;\n ttp: number;\n tap: number;\n tpp: number;\n fp: number;\n suspend_desc: string;\n transfer_board_desc: string;\n tags: string;\n lr: number;\n smlr: number;\n flr: string;\n wr: string;\n d: number;\n elr: number;\n p: any;\n castate: string;\n ca1oa: number;\n ca2oa: number;\n }[];\n ts: string;\n full: number;\n err_code: string;\n err_msg: string;\n }> {\n // https://www.htx.com/zh-cn/opend/newApiPages/?id=7ec47f16-7773-11ed-9966-0242ac110003\n return this.request('GET', '/v2/settings/common/symbols', this.spot_api_root);\n }\n\n getUid(): Promise<{ data: number; code: number }> {\n // https://www.htx.com/zh-cn/opend/newApiPages/?id=7ec491c9-7773-11ed-9966-0242ac110003\n return this.request('GET', '/v2/user/uid', this.spot_api_root);\n }\n\n getUnifiedAccountInfo(): Promise<{\n status: string;\n code: number;\n msg: string;\n data: {\n margin_asset: string;\n margin_balance: number;\n cross_margin_static: number;\n cross_profit_unreal: number;\n withdraw_available: number;\n }[];\n }> {\n // https://www.htx.com/zh-cn/opend/newApiPages/?id=10000073-77b7-11ed-9966-0242ac110003\n return this.request('GET', '/linear-swap-api/v3/unified_account_info', this.swap_api_root);\n }\n\n getSwapCrossPositionInfo(params?: {\n contract_code?: string;\n pair?: string;\n contract_type: string;\n }): Promise<{\n status: string;\n ts: number;\n data: {\n contract_code: string;\n contract_type: string;\n direction: string;\n margin_mode: string;\n volume: number;\n available: number;\n cost_hold: number;\n last_price: number;\n profit_unreal: number;\n lever_rate: number;\n }[];\n }> {\n // https://www.htx.com/zh-cn/opend/newApiPages/?id=8cb74963-77b5-11ed-9966-0242ac110003\n return this.request('POST', '/linear-swap-api/v1/swap_cross_position_info', this.swap_api_root, params);\n }\n\n /**\n * 【全仓】获取平台阶梯保证金\n *\n * https://www.htx.com/zh-cn/opend/newApiPages/?id=8cb72290-77b5-11ed-9966-0242ac110003\n */\n getSwapCrossLadderMargin = (params?: {\n contract_code?: string;\n pair?: string;\n contract_type?: string;\n business_type?: string;\n }): Promise<{\n status: string;\n data: Array<{ contract_code: string; pair: string; list: Array<{ lever_rate: number }> }>;\n }> => this.request('GET', '/linear-swap-api/v1/swap_cross_ladder_margin', this.swap_api_root, params);\n\n getSwapOpenOrders(params?: {\n contract_code?: string;\n pair?: string;\n page_index?: number;\n page_size?: number;\n sort_by?: string;\n trade_type?: string;\n }): Promise<{\n status: string;\n data: {\n orders: {\n order_id_str: string;\n contract_code: string;\n order_price_type: string;\n direction: string;\n offset: string;\n volume: number;\n created_at: number;\n price: number;\n trade_volume: number;\n }[];\n };\n }> {\n // https://www.htx.com/zh-cn/opend/newApiPages/?id=8cb784d4-77b5-11ed-9966-0242ac110003\n return this.request('POST', '/linear-swap-api/v1/swap_cross_openorders', this.swap_api_root, params);\n }\n\n getSpotAccountBalance(account_uid: number): Promise<{\n status: string;\n data: {\n list: {\n currency: string;\n balance: string;\n type: string;\n }[];\n };\n }> {\n // https://www.htx.com/zh-cn/opend/newApiPages/?id=7ec40922-7773-11ed-9966-0242ac110003\n return this.request('GET', `/v1/account/accounts/${account_uid}/balance`, this.spot_api_root);\n }\n\n getCrossMarginLoanInfo(): Promise<{\n status: string;\n code: number;\n data: {\n currency: string;\n 'loanable-amt': string;\n }[];\n }> {\n // https://www.htx.com/zh-cn/opend/newApiPages/?id=7ec41863-7773-11ed-9966-0242ac110003\n return this.request('GET', '/v1/cross-margin/loan-info', this.spot_api_root);\n }\n\n getSpotTick(params: { symbol: string }): Promise<{\n status: string;\n tick: {\n close: number;\n };\n }> {\n // https://www.htx.com/zh-cn/opend/newApiPages/?id=7ec3fc25-7773-11ed-9966-0242ac110003\n return this.request('GET', `/market/detail/merged`, this.spot_api_root, params);\n }\n\n /**\n * 【通用】批量获取合约资金费率\n *\n * 接口权限: 读取\n *\n * 限频: 其他非行情类的公开接口,比如获取指数信息,限价信息,交割结算、平台持仓信息等,所有用户都是每个IP3秒最多240次请求(所有该IP的非行情类的公开接口请求共享3秒240次的额度)\n *\n * 接口描述: 该接口支持全仓模式和逐仓模式\n *\n * https://www.htx.com/zh-cn/opend/newApiPages/?id=8cb71b45-77b5-11ed-9966-0242ac110003\n */\n getSwapBatchFundingRate = (params: {\n contract_code?: string;\n }): Promise<{\n status: string;\n ts: number;\n data: {\n estimated_rate: null;\n funding_rate: string;\n contract_code: string;\n symbol: string;\n fee_asset: string;\n funding_time: string;\n next_funding_time: null;\n trade_partition: string;\n }[];\n }> => {\n // https://www.htx.com/zh-cn/opend/newApiPages/?id=8cb7a7b5-77b5-11ed-9966-0242ac110003\n return this.request('GET', `/linear-swap-api/v1/swap_batch_funding_rate`, this.swap_api_root, params);\n };\n\n /**\n * 【通用】获取市场最近成交记录\n *\n * 接口权限: 读取\n *\n * 限频: 行情类的公开接口,比如:获取K线数据、获取聚合行情、市场行情、获取行情深度数据、获取溢价指数K线、获取实时预测资金费率k线,获取基差数据、获取市场最近成交记录:\n *\n * (1) restful接口:同一个IP, 所有业务(交割合约、币本位永续合约和U本位合约)总共1秒最多800个请求\n *\n * 接口描述: 该接口支持全仓模式和逐仓模式\n *\n * 请求参数contract_code支持交割合约代码,格式为BTC-USDT-210625;同时支持合约标识,格式为 BTC-USDT(永续)、BTC-USDT-CW(当周)、BTC-USDT-NW(次周)、BTC-USDT-CQ(当季)、BTC-USDT-NQ(次季)。\n *\n * business_type 在查询交割合约数据时为必填参数。且参数值要传:futures 或 all 。\n *\n * https://www.htx.com/zh-cn/opend/newApiPages/?id=8cb73c34-77b5-11ed-9966-0242ac110003\n */\n getSwapMarketTrade = (params: {\n contract_code?: string;\n business_type?: string;\n }): Promise<{\n ch: string;\n status: string;\n tick: {\n data: {\n amount: string;\n quantity: string;\n trade_turnover: string;\n ts: number;\n id: number;\n price: string;\n direction: string;\n contract_code: string;\n business_type: string;\n trade_partition: string;\n }[];\n id: number;\n ts: number;\n };\n ts: number;\n }> => this.request('GET', `/linear-swap-ex/market/trade`, this.swap_api_root, params);\n\n /**\n * 获得当前合约的总持仓量\n *\n * https://huobiapi.github.io/docs/usdt_swap/v1/cn/#3218e7531a\n */\n getSwapOpenInterest = (params: {\n contract_code?: string;\n pair?: string;\n contract_type?: string;\n business_type?: string;\n }): Promise<{\n status: string;\n data: {\n volume: number;\n amount: number;\n symbol: string;\n value: number;\n contract_code: string;\n trade_amount: number;\n trade_volume: number;\n trade_turnover: number;\n business_type: string;\n pair: string;\n contract_type: string;\n }[];\n ts: number;\n }> => this.request('GET', '/linear-swap-api/v1/swap_open_interest', this.swap_api_root, params);\n\n /**\n * 【通用】获取市场最优挂单\n *\n * 接口权限: 读取\n *\n * 限频: 行情类的公开接口,比如:获取K线数据、获取聚合行情、市场行情、获取行情深度数据、获取溢价指数K线、获取实时预测资金费率k线,获取基差数据、获取市场最近成交记录:\n *\n * (1) restful接口:同一个IP, 所有业务(交割合约、币本位永续合约和U本位合约)总共1秒最多800个请求\n *\n * 接口描述: 该接口支持全仓模式和逐仓模式\n *\n * 请求参数contract_code支持交割合约代码,格式为BTC-USDT-210625;同时支持合约标识,格式为 BTC-USDT(永续)、BTC-USDT-CW(当周)、BTC-USDT-NW(次周)、BTC-USDT-CQ(当季)、BTC-USDT-NQ(次季)。\n *\n * business_type 在查询交割合约数据时为必填参数。且参数值要传:futures 或 all 。\n *\n * https://www.htx.com/zh-cn/opend/newApiPages/?id=8cb735e0-77b5-11ed-9966-0242ac110003\n */\n getSwapMarketBbo = (params: {\n contract_code?: string;\n }): Promise<{\n status: string;\n ticks: {\n trade_partition: string;\n business_type: string;\n contract_code: string;\n ask: number[] | null;\n bid: number[] | null;\n mrid: number;\n ts: number;\n }[];\n ts: number;\n }> => this.request('GET', `/linear-swap-ex/market/bbo`, this.swap_api_root, params);\n\n postSpotOrder(params: {\n symbol: string;\n 'account-id': string;\n amount: string;\n market_amount?: string;\n 'borrow-amount'?: string;\n type: string;\n 'trade-purpose': string;\n price?: string;\n source: string;\n }): Promise<{ success: boolean; code: number; message: string }> {\n // https://www.htx.com/zh-cn/opend/newApiPages/?id=10000065-77b7-11ed-9966-0242ac110003\n return this.request('POST', `/v1/order/auto/place`, this.spot_api_root, params);\n }\n\n postSwapOrder(params: {\n contract_code: string;\n contract_type: string;\n price?: number;\n volume: number;\n offset: string;\n direction: string;\n lever_rate: number;\n order_price_type: string;\n }): Promise<{ status: string; ts: number; data: { order_id: number; order_id_str: string } }> {\n // https://www.htx.com/zh-cn/opend/newApiPages/?id=8cb77159-77b5-11ed-9966-0242ac110003\n return this.request('POST', '/linear-swap-api/v1/swap_cross_order', this.swap_api_root, params);\n }\n\n getSpotAccountDepositAddresses(params: { currency: string }): Promise<{\n code: number;\n message: string;\n data: {\n currency: string;\n chain: string;\n address: string;\n }[];\n }> {\n // https://www.htx.com/zh-cn/opend/newApiPages/?id=7ec45fb7-7773-11ed-9966-0242ac110003\n return this.request('GET', `/v2/account/deposit/address`, this.spot_api_root, params);\n }\n\n getAccountLedger(params: { accountId: string; currency: string }): Promise<{\n status: string;\n data: {\n transactTime: number;\n transactAmt: number;\n }[];\n }> {\n // https://www.htx.com/zh-cn/opend/newApiPages/?id=7ec4610b-7773-11ed-9966-0242ac110003\n return this.request('GET', `/v2/account/ledger`, this.spot_api_root, params);\n }\n\n postSuperMarginAccountTransferOut(params: {\n currency: string;\n amount: string;\n }): Promise<{ status: string; data: number }> {\n // https://www.htx.com/zh-cn/opend/newApiPages/?id=7ec41ff0-7773-11ed-9966-0242ac110003\n return this.request('POST', `/v1/cross-margin/transfer-out`, this.spot_api_root, params);\n }\n\n postSuperMarginAccountTransferIn(params: {\n currency: string;\n amount: string;\n }): Promise<{ status: string; data: number }> {\n // https://www.htx.com/zh-cn/opend/newApiPages/?id=7ec41f0e-7773-11ed-9966-0242ac110003\n return this.request('POST', `/v1/cross-margin/transfer-in`, this.spot_api_root, params);\n }\n\n postSpotAccountTransfer(params: {\n from: string;\n to: string;\n currency: string;\n amount: number;\n 'margin-account': string;\n }): Promise<{ success: boolean; data: number; code: number; message: string }> {\n // https://www.htx.com/zh-cn/opend/newApiPages/?id=10000095-77b7-11ed-9966-0242ac110003\n return this.request('POST', `/v2/account/transfer`, this.spot_api_root, params);\n }\n\n postBorrow(params: { currency: string; amount: string }): Promise<{\n status: string;\n data: number;\n }> {\n // https://www.htx.com/zh-cn/opend/newApiPages/?id=7ec41b5d-7773-11ed-9966-0242ac110003\n return this.request('POST', `/v1/cross-margin/orders`, this.spot_api_root, params);\n }\n\n postWithdraw(params: {\n address: string;\n amount: string;\n currency: string;\n fee: string;\n chain: string;\n }): Promise<{\n status: string;\n data: number;\n }> {\n // https://www.htx.com/zh-cn/opend/newApiPages/?id=7ec42cfd-7773-11ed-9966-0242ac110003\n return this.request('POST', `/v1/dw/withdraw/api/create`, this.spot_api_root, params);\n }\n\n getDepositWithdrawHistory(params: {\n currency: string;\n type: string;\n from?: string;\n size?: string;\n direct?: string;\n }): Promise<{\n status: string;\n 'error-code': string;\n 'error-msg': string;\n data: {\n id: number;\n type: string;\n currency: string;\n 'tx-hash': string;\n chain: string;\n amount: string;\n address: string;\n 'address-tag': string;\n fee: string;\n state: string;\n 'create-at': number;\n 'update-at': number;\n }[];\n }> {\n // https://www.htx.com/zh-cn/opend/newApiPages/?id=7ec44f99-7773-11ed-9966-0242ac110003\n return this.request(`GET`, `/v1/query/deposit-withdraw`, this.spot_api_root, params);\n }\n\n /**\n * 获取合约的历史资金费率\n *\n * 接口权限: 读取\n *\n * https://www.htx.com/zh-cn/opend/newApiPages/?id=5d51f1f9-77b6-11ed-9966-0242ac110003\n */\n getSwapHistoricalFundingRate(params: {\n contract_code: string;\n page_index?: number;\n page_size?: number;\n }): Promise<{\n status: string;\n ts: number;\n data: {\n data: {\n symbol: string;\n contract_code: string;\n fee_asset: string;\n funding_time: string;\n funding_rate: string;\n realized_rate: string;\n avg_premium_index: string;\n }[];\n total_page: number;\n current_page: number;\n total_size: number;\n };\n }> {\n return this.request(\n 'GET',\n `/linear-swap-api/v1/swap_historical_funding_rate`,\n this.swap_api_root,\n params,\n );\n }\n\n /**\n * 资产划转(母子用户之间)\n *\n * 接口权限: 交易\n *\n * 限频: 2次/2s\n *\n * https://www.htx.com/zh-cn/opend/newApiPages/?id=7ec45d8e-7773-11ed-9966-0242ac110003\n */\n postSubUserTransfer(params: {\n 'sub-uid': number;\n currency: string;\n amount: number;\n 'client-order-id'?: string;\n type: string;\n }): Promise<{\n data: number;\n status: string;\n }> {\n return this.request('POST', '/v1/subuser/transfer', this.spot_api_root, params);\n }\n\n /**\n * 获取子用户列表\n *\n * 接口权限: 读取\n *\n * https://www.htx.com/zh-cn/opend/newApiPages/?id=7ec48f09-7773-11ed-9966-0242ac110003\n */\n getSubUserList(params?: { fromId?: number }): Promise<{\n code: number;\n message?: string;\n data: {\n uid: number;\n userState: string;\n subUserName: string;\n note: string;\n }[];\n nextId?: number;\n ok: boolean;\n }> {\n return this.request('GET', `/v2/sub-user/user-list`, this.spot_api_root, params);\n }\n\n /**\n * 账户类型查询\n *\n * 是否验签: 是\n *\n * 接口权限: 读取\n *\n * 限频: 每个UID 3秒最多 144 次请求(交易接口3秒最多 72 次请求,查询接口3秒最多 72 次请求) (该UID的所有币种和不同到期日的合约的所有私有接口共享该限制) 。\n *\n * 接口描述: 此接口用于客户查询的账号类型,当前U本位合约有统一账户和非统一账户(全仓逐仓账户)类型。统一账户类型资产放在USDT一个账户上,全仓逐仓账户类型资产放在不同的币对。\n * 统一账户类型为最新升级的,当前不支持API下单。若需要用用API下单请切换账户类型为非统一账户。\n *\n * https://www.htx.com/zh-cn/opend/newApiPages/?id=8cb71825-77b5-11ed-9966-0242ac110003\n */\n getSwapUnifiedAccountType(): Promise<{\n code: number;\n msg: string;\n ts: number;\n data: {\n account_type: number;\n };\n }> {\n return this.request('GET', '/linear-swap-api/v3/swap_unified_account_type', this.swap_api_root);\n }\n\n /**\n * 账户类型更改接口\n *\n * 是否验签: 是\n *\n * 接口权限: 交易\n *\n * 限频: 每个UID 3秒最多 144 次请求(交易接口3秒最多 72 次请求,查询接口3秒最多 72 次请求) (该UID的所有币种和不同到期日的合约的所有私有接口共享该限制) 。\n *\n * 接口描述: 调用该接口前需要保证U本位合约无持仓和挂单,当由非统一账户(全仓逐仓账户)变为统一账户还需将资产从逐仓账户划转到全仓账户。\n *\n * https://www.htx.com/zh-cn/opend/newApiPages/?id=8cb7196b-77b5-11ed-9966-0242ac110003\n */\n postSwapSwitchAccountType(params: { account_type: number }): Promise<{\n code: number;\n msg: string;\n ts: number;\n data: {\n account_type: number;\n };\n }> {\n return this.request('POST', '/linear-swap-api/v3/swap_switch_account_type', this.swap_api_root, params);\n }\n\n /**\n * APIv2币链参考信息\n *\n * https://www.htx.com/zh-cn/opend/newApiPages/?id=7ec478f0-7773-11ed-9966-0242ac110003\n */\n getV2ReferenceCurrencies = (params: {\n currency?: string;\n authorizedUser?: string;\n }): Promise<{\n code: number;\n data: {\n currency: string;\n assetType: number;\n chains: {\n chain: string;\n displayName: string;\n fullName: string;\n baseChain?: string;\n baseChainProtocol?: string;\n isDynamic?: boolean;\n numOfConfirmations: number;\n numOfFastConfirmations: number;\n depositStatus: string;\n minDepositAmt: string;\n withdrawStatus: string;\n minWithdrawAmt: string;\n withdrawPrecision: number;\n maxWithdrawAmt: string;\n withdrawQuotaPerDay: string;\n withdrawQuotaPerYear: null;\n withdrawQuotaTotal: null;\n withdrawFeeType: string;\n transactFeeWithdraw?: string;\n addrWithTag: boolean;\n addrDepositTag: boolean;\n minTransactFeeWithdraw?: string;\n transactFeeRateWithdraw?: string;\n maxTransactFeeWithdraw?: string;\n }[];\n instStatus: string;\n }[];\n }> => this.request('GET', '/v2/reference/currencies', this.spot_api_root, params);\n\n /**\n * APIv2币链参考信息\n *\n * https://www.htx.com/zh-cn/opend/newApiPages/?id=7ec41049-7773-11ed-9966-0242ac110003\n */\n getAccountHistory = (params: {\n 'account-id': string;\n currency?: string;\n 'transact-types'?: number;\n 'start-time'?: number;\n 'end-time'?: number;\n sort?: 'asc' | 'desc';\n size?: number;\n 'from-id'?: number;\n }): Promise<{\n // code: number;\n 'transact-amt': string;\n 'avail-balance': string;\n 'acct-balance': string;\n 'transact-time': string;\n 'record-id': string;\n status: string;\n data: {\n 'account-id': string;\n currency: string;\n 'record-id': string;\n 'transact-amt': string;\n 'transact-type': string;\n 'avail-balance': string;\n 'acct-balance': string;\n 'transact-time': string;\n }[];\n }> => this.request('GET', '/v1/account/history', this.spot_api_root, params);\n}\n\nexport const client = new HuobiClient({\n auth: {\n access_key: process.env.ACCESS_KEY!,\n secret_key: process.env.SECRET_KEY!,\n },\n});\n"]}
package/dist/cli.js ADDED
@@ -0,0 +1,3 @@
1
+ #!/usr/bin/env node
2
+ import './index';
3
+ //# sourceMappingURL=cli.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cli.js","sourceRoot":"","sources":["../src/cli.ts"],"names":[],"mappings":";AACA,OAAO,SAAS,CAAC","sourcesContent":["#!/usr/bin/env node\nimport './index';\n"]}
@@ -0,0 +1,72 @@
1
+ import { Terminal } from '@yuants/protocol';
2
+ import { loadSecrets } from '@yuants/secret';
3
+ import { listWatch } from '@yuants/utils';
4
+ import cluster from 'cluster';
5
+ import { bufferTime, defer, filter, map, Observable, repeat, retry, Subject } from 'rxjs';
6
+ import { overrideConsole } from './logger';
7
+ overrideConsole();
8
+ if (cluster.isPrimary) {
9
+ console.info('This is the primary process');
10
+ const logBuffer = new Subject();
11
+ logBuffer
12
+ .pipe(
13
+ //
14
+ bufferTime(100), map((v) => v.join('\n')), filter((v) => v.trim() !== ''))
15
+ .subscribe((message) => {
16
+ console.info(message);
17
+ });
18
+ defer(() => loadSecrets({
19
+ terminal: Terminal.fromNodeEnv(),
20
+ encryption_key_base58: process.env.ENCRYPTION_KEY_BASE58,
21
+ }))
22
+ .pipe(
23
+ //
24
+ retry({ delay: 5000 }), repeat({ delay: 5000 }))
25
+ .pipe(listWatch((x) => x.secret.id, (account) => defer(() => new Observable((subscriber) => {
26
+ if (account.secret.public_data.type !== 'api_key_htx')
27
+ return;
28
+ if (!account.secret.public_data.name)
29
+ return;
30
+ if (!account.decrypted_data)
31
+ return;
32
+ if (!account.decrypted_data.access_key)
33
+ return;
34
+ if (!account.decrypted_data.secret_key)
35
+ return;
36
+ const worker = cluster.fork({
37
+ ENCRYPTION_KEY_BASE58: '',
38
+ ACCESS_KEY: account.decrypted_data.access_key,
39
+ SECRET_KEY: account.decrypted_data.secret_key,
40
+ WRITE_QUOTE_TO_SQL: account.secret.public_data.write_quote_to_sql ? 'true' : 'false',
41
+ TERMINAL_ID: `@yuants/vendor-huobi/worker/${account.secret.public_data.name}`,
42
+ WORKER_LABEL: account.secret.public_data.name,
43
+ });
44
+ worker.on('message', (message) => {
45
+ if (message.type === 'log') {
46
+ logBuffer.next(`[Worker ${worker.process.pid} ${message.label}] ${message.level}: ${message.message}`);
47
+ }
48
+ });
49
+ worker.on('exit', (code, signal) => {
50
+ if (code === 0) {
51
+ console.log(`Worker ${worker.process.pid} exited gracefully`);
52
+ subscriber.complete();
53
+ }
54
+ else {
55
+ console.error(`Worker ${worker.process.pid} exited with code ${code} and signal ${signal}`);
56
+ subscriber.error(new Error(`Worker ${worker.process.pid} exited with code ${code} and signal ${signal}`));
57
+ }
58
+ });
59
+ return () => {
60
+ worker.kill();
61
+ console.log(`Worker ${worker.process.pid} killed`);
62
+ };
63
+ })).pipe(
64
+ //
65
+ retry({ delay: 1000 }), repeat({ delay: 1000 })), (a, b) => a.secret.updated_at === b.secret.updated_at))
66
+ .subscribe();
67
+ }
68
+ else {
69
+ console.info('This is the worker process', process.pid, process.env);
70
+ import('./index');
71
+ }
72
+ //# sourceMappingURL=cluster.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cluster.js","sourceRoot":"","sources":["../src/cluster.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,kBAAkB,CAAC;AAC5C,OAAO,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAC;AAC7C,OAAO,EAAE,SAAS,EAAE,MAAM,eAAe,CAAC;AAC1C,OAAO,OAAO,MAAM,SAAS,CAAC;AAC9B,OAAO,EAAE,UAAU,EAAE,KAAK,EAAE,MAAM,EAAE,GAAG,EAAE,UAAU,EAAE,MAAM,EAAE,KAAK,EAAE,OAAO,EAAE,MAAM,MAAM,CAAC;AAC1F,OAAO,EAAE,eAAe,EAAE,MAAM,UAAU,CAAC;AAE3C,eAAe,EAAE,CAAC;AAElB,IAAI,OAAO,CAAC,SAAS,EAAE;IACrB,OAAO,CAAC,IAAI,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MAAM,EAAE,CAAC,CACxF,CAAC;aACH;QACH,CAAC,CAAC,CAAC;QACH,OAAO,GAAG,EAAE;YACV,MAAM,CAAC,IAAI,EAAE,CAAC;YACd,OAAO,CAAC,GAAG,CAAC,UAAU,MAAM,CAAC,OAAO,CAAC,GAAG,SAAS,CAAC,CAAC;QACrD,CAAC,CAAC;IACJ,CAAC,CAAC,CACL,CAAC,IAAI;IACJ,EAAE;IACF,KAAK,CAAC,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC,EACtB,MAAM,CAAC,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC,CACxB,EACH,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,MAAM,CAAC,UAAU,KAAK,CAAC,CAAC,MAAM,CAAC,UAAU,CACtD,CACF;SACA,SAAS,EAAE,CAAC;CAChB;KAAM;IACL,OAAO,CAAC,IAAI,CAAC,4BAA4B,EAAE,OAAO,CAAC,GAAG,EAAE,OAAO,CAAC,GAAG,CAAC,CAAC;IACrE,MAAM,CAAC,SAAS,CAAC,CAAC;CACnB","sourcesContent":["import { Terminal } from '@yuants/protocol';\nimport { loadSecrets } from '@yuants/secret';\nimport { listWatch } from '@yuants/utils';\nimport cluster from 'cluster';\nimport { bufferTime, defer, filter, map, Observable, repeat, retry, Subject } from 'rxjs';\nimport { overrideConsole } from './logger';\n\noverrideConsole();\n\nif (cluster.isPrimary) {\n console.info('This is the primary process');\n\n const logBuffer = new Subject<string>();\n\n logBuffer\n .pipe(\n //\n bufferTime(100),\n map((v) => v.join('\\n')),\n filter((v) => v.trim() !== ''),\n )\n .subscribe((message) => {\n console.info(message);\n });\n\n defer(() =>\n loadSecrets<{ access_key: string; secret_key: string }>({\n terminal: Terminal.fromNodeEnv(),\n encryption_key_base58: process.env.ENCRYPTION_KEY_BASE58!,\n }),\n )\n .pipe(\n //\n retry({ delay: 5000 }),\n repeat({ delay: 5000 }),\n )\n .pipe(\n listWatch(\n (x) => x.secret.id,\n (account) =>\n defer(\n () =>\n new Observable((subscriber) => {\n if (account.secret.public_data.type !== 'api_key_htx') return;\n if (!account.secret.public_data.name) return;\n if (!account.decrypted_data) return;\n if (!account.decrypted_data.access_key) return;\n if (!account.decrypted_data.secret_key) return;\n\n const worker = cluster.fork({\n ENCRYPTION_KEY_BASE58: '',\n ACCESS_KEY: account.decrypted_data.access_key,\n SECRET_KEY: account.decrypted_data.secret_key,\n WRITE_QUOTE_TO_SQL: account.secret.public_data.write_quote_to_sql ? 'true' : 'false',\n TERMINAL_ID: `@yuants/vendor-huobi/worker/${account.secret.public_data.name}`,\n WORKER_LABEL: account.secret.public_data.name,\n });\n\n worker.on('message', (message: any) => {\n if (message.type === 'log') {\n logBuffer.next(\n `[Worker ${worker.process.pid} ${message.label}] ${message.level}: ${message.message}`,\n );\n }\n });\n\n worker.on('exit', (code, signal) => {\n if (code === 0) {\n console.log(`Worker ${worker.process.pid} exited gracefully`);\n subscriber.complete();\n } else {\n console.error(\n `Worker ${worker.process.pid} exited with code ${code} and signal ${signal}`,\n );\n subscriber.error(\n new Error(`Worker ${worker.process.pid} exited with code ${code} and signal ${signal}`),\n );\n }\n });\n return () => {\n worker.kill();\n console.log(`Worker ${worker.process.pid} killed`);\n };\n }),\n ).pipe(\n //\n retry({ delay: 1000 }),\n repeat({ delay: 1000 }), // 重试间隔为 1 秒\n ),\n (a, b) => a.secret.updated_at === b.secret.updated_at,\n ),\n )\n .subscribe();\n} else {\n console.info('This is the worker process', process.pid, process.env);\n import('./index');\n}\n"]}
@@ -0,0 +1,87 @@
1
+ import { makeDockerEnvs, makeK8sEnvs } from '@yuants/extension';
2
+ export default (context) => {
3
+ context.registerDeployProvider({
4
+ make_json_schema: () => ({
5
+ type: 'object',
6
+ properties: {
7
+ env: {
8
+ type: 'object',
9
+ required: ['HOST_URL'],
10
+ properties: {
11
+ HOST_URL: { type: 'string' },
12
+ TERMINAL_ID: { type: 'string' },
13
+ ENCRYPTION_KEY_BASE58: { type: 'string' },
14
+ },
15
+ },
16
+ },
17
+ }),
18
+ make_docker_compose_file: async (ctx, envCtx) => {
19
+ var _a;
20
+ return {
21
+ [`huobi-${ctx.env.ACCESS_KEY}`.replace(/\s/g, '')]: {
22
+ image: `ghcr.io/no-trade-no-life/vendor-huobi:${(_a = ctx.version) !== null && _a !== void 0 ? _a : envCtx.version}`,
23
+ restart: 'always',
24
+ environment: makeDockerEnvs(ctx.env),
25
+ },
26
+ };
27
+ },
28
+ make_k8s_resource_objects: async (ctx, envCtx) => {
29
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l;
30
+ return {
31
+ deployment: {
32
+ apiVersion: 'apps/v1',
33
+ kind: 'Deployment',
34
+ metadata: {
35
+ labels: {
36
+ 'y.ntnl.io/version': (_a = ctx.version) !== null && _a !== void 0 ? _a : envCtx.version,
37
+ 'y.ntnl.io/manifest_key': ctx.key,
38
+ 'y.ntnl.io/component': 'huobi',
39
+ },
40
+ name: `huobi-${ctx.key}`.replace(/\s/g, '').toLocaleLowerCase(),
41
+ namespace: 'yuan',
42
+ },
43
+ spec: {
44
+ replicas: 1,
45
+ selector: {
46
+ matchLabels: {
47
+ 'y.ntnl.io/component': 'huobi',
48
+ 'y.ntnl.io/manifest_key': ctx.key,
49
+ },
50
+ },
51
+ template: {
52
+ metadata: {
53
+ labels: {
54
+ 'y.ntnl.io/version': (_b = ctx.version) !== null && _b !== void 0 ? _b : envCtx.version,
55
+ 'y.ntnl.io/manifest_key': ctx.key,
56
+ 'y.ntnl.io/component': 'huobi',
57
+ },
58
+ },
59
+ spec: {
60
+ containers: [
61
+ {
62
+ env: makeK8sEnvs(ctx.env),
63
+ image: `ghcr.io/no-trade-no-life/vendor-huobi:${(_c = ctx.version) !== null && _c !== void 0 ? _c : envCtx.version}`,
64
+ imagePullPolicy: 'IfNotPresent',
65
+ name: 'huobi',
66
+ resources: {
67
+ limits: {
68
+ cpu: (_e = (_d = ctx.cpu) === null || _d === void 0 ? void 0 : _d.max) !== null && _e !== void 0 ? _e : '500m',
69
+ memory: (_g = (_f = ctx.memory) === null || _f === void 0 ? void 0 : _f.max) !== null && _g !== void 0 ? _g : '256Mi',
70
+ },
71
+ requests: {
72
+ cpu: (_j = (_h = ctx.cpu) === null || _h === void 0 ? void 0 : _h.min) !== null && _j !== void 0 ? _j : '120m',
73
+ memory: (_l = (_k = ctx.memory) === null || _k === void 0 ? void 0 : _k.min) !== null && _l !== void 0 ? _l : '128Mi',
74
+ },
75
+ },
76
+ },
77
+ ],
78
+ hostname: 'huobi',
79
+ },
80
+ },
81
+ },
82
+ },
83
+ };
84
+ },
85
+ });
86
+ };
87
+ //# sourceMappingURL=extension.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"extension.js","sourceRoot":"","sources":["../src/extension.ts"],"names":[],"mappings":"AAAA,OAAO,EAAqB,cAAc,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AACnF,eAAe,CAAC,OAA0B,EAAE,EAAE;IAC5C,OAAO,CAAC,sBAAsB,CAAC;QAC7B,gBAAgB,EAAE,GAAG,EAAE,CAAC,CAAC;YACvB,IAAI,EAAE,QAAQ;YACd,UAAU,EAAE;gBACV,GAAG,EAAE;oBACH,IAAI,EAAE,QAAQ;oBACd,QAAQ,EAAE,CAAC,UAAU,CAAC;oBACtB,UAAU,EAAE;wBACV,QAAQ,EAAE,EAAE,IAAI,EAAE,QAAQ,EAAE;wBAC5B,WAAW,EAAE,EAAE,IAAI,EAAE,QAAQ,EAAE;wBAC/B,qBAAqB,EAAE,EAAE,IAAI,EAAE,QAAQ,EAAE;qBAC1C;iBACF;aACF;SACF,CAAC;QACF,wBAAwB,EAAE,KAAK,EAAE,GAAG,EAAE,MAAM,EAAE,EAAE;;YAC9C,OAAO;gBACL,CAAC,SAAS,GAAG,CAAC,GAAI,CAAC,UAAU,EAAE,CAAC,OAAO,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC,EAAE;oBACnD,KAAK,EAAE,yCAAyC,MAAA,GAAG,CAAC,OAA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AS,EAAE;4CACT,MAAM,EAAE;gDACN,GAAG,EAAE,MAAA,MAAA,GAAG,CAAC,GAAG,0CAAE,GAAG,mCAAI,MAAM;gDAC3B,MAAM,EAAE,MAAA,MAAA,GAAG,CAAC,MAAM,0CAAE,GAAG,mCAAI,OAAO;6CACnC;4CACD,QAAQ,EAAE;gDACR,GAAG,EAAE,MAAA,MAAA,GAAG,CAAC,GAAG,0CAAE,GAAG,mCAAI,MAAM;gDAC3B,MAAM,EAAE,MAAA,MAAA,GAAG,CAAC,MAAM,0CAAE,GAAG,mCAAI,OAAO;6CACnC;yCACF;qCACF;iCACF;gCACD,QAAQ,EAAE,OAAO;6BAClB;yBACF;qBACF;iBACF;aACF,CAAC;QACJ,CAAC;KACF,CAAC,CAAC;AACL,CAAC,CAAC","sourcesContent":["import { IExtensionContext, makeDockerEnvs, makeK8sEnvs } from '@yuants/extension';\nexport default (context: IExtensionContext) => {\n context.registerDeployProvider({\n make_json_schema: () => ({\n type: 'object',\n properties: {\n env: {\n type: 'object',\n required: ['HOST_URL'],\n properties: {\n HOST_URL: { type: 'string' },\n TERMINAL_ID: { type: 'string' },\n ENCRYPTION_KEY_BASE58: { type: 'string' },\n },\n },\n },\n }),\n make_docker_compose_file: async (ctx, envCtx) => {\n return {\n [`huobi-${ctx.env!.ACCESS_KEY}`.replace(/\\s/g, '')]: {\n image: `ghcr.io/no-trade-no-life/vendor-huobi:${ctx.version ?? envCtx.version}`,\n restart: 'always',\n\n environment: makeDockerEnvs(ctx.env),\n },\n };\n },\n make_k8s_resource_objects: async (ctx, envCtx) => {\n return {\n deployment: {\n apiVersion: 'apps/v1',\n kind: 'Deployment',\n metadata: {\n labels: {\n 'y.ntnl.io/version': ctx.version ?? envCtx.version,\n 'y.ntnl.io/manifest_key': ctx.key,\n 'y.ntnl.io/component': 'huobi',\n },\n name: `huobi-${ctx.key}`.replace(/\\s/g, '').toLocaleLowerCase(),\n namespace: 'yuan',\n },\n spec: {\n replicas: 1,\n selector: {\n matchLabels: {\n 'y.ntnl.io/component': 'huobi',\n 'y.ntnl.io/manifest_key': ctx.key,\n },\n },\n template: {\n metadata: {\n labels: {\n 'y.ntnl.io/version': ctx.version ?? envCtx.version,\n 'y.ntnl.io/manifest_key': ctx.key,\n 'y.ntnl.io/component': 'huobi',\n },\n },\n spec: {\n containers: [\n {\n env: makeK8sEnvs(ctx.env),\n image: `ghcr.io/no-trade-no-life/vendor-huobi:${ctx.version ?? envCtx.version}`,\n imagePullPolicy: 'IfNotPresent',\n name: 'huobi',\n resources: {\n limits: {\n cpu: ctx.cpu?.max ?? '500m',\n memory: ctx.memory?.max ?? '256Mi',\n },\n requests: {\n cpu: ctx.cpu?.min ?? '120m',\n memory: ctx.memory?.min ?? '128Mi',\n },\n },\n },\n ],\n hostname: 'huobi',\n },\n },\n },\n },\n };\n },\n });\n};\n"]}