@icgio/icg-utils 1.6.21

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/lib/utils.js ADDED
@@ -0,0 +1,651 @@
1
+ const _ = require('lodash')
2
+
3
+ Number.prototype.toFixed_old = Number.prototype.toFixed
4
+
5
+ Number.prototype.toFixed = function(s) {
6
+ if (s >= 0 && s <= 20) {
7
+ return this.toFixed_old(s)
8
+ }
9
+ let changenum = (parseInt(this * Math.pow(10, s) + 0.5) / Math.pow(10, s)).toString()
10
+ index = changenum.indexOf('.')
11
+ if (index < 0 && s > 0) {
12
+ changenum = changenum + '.'
13
+ for (i = 0; i < s; i++) {
14
+ changenum = changenum + '0'
15
+ }
16
+ } else {
17
+ index = changenum.length - index;
18
+ for (i = 0; i < (s - index) + 1; i++) {
19
+ changenum = changenum + '0'
20
+ }
21
+ }
22
+ return changenum
23
+ }
24
+
25
+ Number.prototype.toStringNoExponents = function() {
26
+ let data= String(this).split(/[eE]/)
27
+ if(data.length== 1) return data[0]
28
+ let z= '', sign= this<0? '-':'',
29
+ str= data[0].replace('.', ''),
30
+ mag= Number(data[1])+ 1
31
+ if(mag<0){
32
+ z= sign + '0.'
33
+ while(mag++) z += '0'
34
+ return z + str.replace(/^\-/,'')
35
+ }
36
+ mag -= str.length
37
+ while(mag--) z += '0'
38
+ return str + z
39
+ }
40
+
41
+ Date.prototype.addHours = function(h) {
42
+ return new Date(this.getTime() + (h * 60 * 60 * 1000))
43
+ }
44
+
45
+ Date.prototype.roundHours = function(m) {
46
+ let coeff = m * 60 * 60 * 1000
47
+ return new Date(Math.round(this.getTime() / coeff) * coeff)
48
+ }
49
+
50
+ Date.prototype.ceilHours = function(m) {
51
+ let coeff = m * 60 * 60 * 1000
52
+ return new Date(Math.ceil(this.getTime() / coeff) * coeff)
53
+ }
54
+
55
+ Date.prototype.floorHours = function(m) {
56
+ let coeff = m * 60 * 60 * 1000
57
+ return new Date(Math.floor(this.getTime() / coeff) * coeff)
58
+ }
59
+
60
+ Date.prototype.addMinutes = function(m) {
61
+ return new Date(this.getTime() + (m * 60 * 1000))
62
+ }
63
+
64
+ Date.prototype.roundMinutes = function(m) {
65
+ let coeff = m * 60 * 1000
66
+ return new Date(Math.round(this.getTime() / coeff) * coeff)
67
+ }
68
+
69
+ Date.prototype.ceilMinutes = function(m) {
70
+ let coeff = m * 60 * 1000
71
+ return new Date(Math.ceil(this.getTime() / coeff) * coeff)
72
+ }
73
+
74
+ Date.prototype.floorMinutes = function(m) {
75
+ let coeff = m * 60 * 1000
76
+ return new Date(Math.floor(this.getTime() / coeff) * coeff)
77
+ }
78
+
79
+ Date.prototype.addSeconds = function(s) {
80
+ return new Date(this.getTime() + (s * 1000))
81
+ }
82
+
83
+ String.prototype.replaceAt = function(index, replacement) {
84
+ return this.substr(0, index) + replacement + this.substr(index + replacement.length)
85
+ }
86
+
87
+ module.exports.ordered_dict = function (is_ask) {
88
+ let keys = [], vals = {}
89
+ return {
90
+ push: function (k, v) {
91
+ k = parseFloat(k)
92
+ if (!vals[k]) keys.push(k)
93
+ vals[k] = v
94
+ },
95
+ insert: function (k, v) {
96
+ if (v != 0) {
97
+ k = parseFloat(k)
98
+ let search = binary_find(k, is_ask, keys)
99
+ let pos = search.index
100
+ if (!vals[k]) {
101
+ keys.splice(pos,0,k)
102
+ vals[k] = v
103
+ } else {
104
+ vals[k] = v
105
+ }
106
+ }
107
+ },
108
+ del: function (k) {
109
+ k = parseFloat(k)
110
+ let search = binary_find(k, is_ask, keys)
111
+ let pos = search.index
112
+ if (search.found) {
113
+ keys = keys.slice(0, pos).concat(keys.slice(pos+1, keys.length))
114
+ delete vals[k]
115
+ }
116
+ },
117
+ val: function (k) { return vals[k] },
118
+ length: function () { return keys.length },
119
+ keys: function () { return keys },
120
+ values: function () { return vals },
121
+ entries: function () { return keys.map(key => [key, vals[key]]) }
122
+ }
123
+ }
124
+
125
+ function binary_find (searchElement, is_ask, keys) {
126
+ let minIndex = 0
127
+ let maxIndex = keys.length - 1
128
+ let currentIndex
129
+ let currentElement
130
+
131
+ while (minIndex <= maxIndex) {
132
+ currentIndex = (minIndex + maxIndex) / 2 | 0
133
+ currentElement = keys[currentIndex]
134
+
135
+ if (currentElement < searchElement && is_ask || currentElement > searchElement && !is_ask) {
136
+ minIndex = currentIndex + 1
137
+ }
138
+ else if (currentElement > searchElement && is_ask || currentElement < searchElement && !is_ask) {
139
+ maxIndex = currentIndex - 1
140
+ }
141
+ else {
142
+ return { // Modification
143
+ found: true,
144
+ index: currentIndex
145
+ }
146
+ }
147
+ }
148
+
149
+ return { // Modification
150
+ found: false,
151
+ index: (currentElement < searchElement && is_ask || currentElement > searchElement && !is_ask) ? currentIndex + 1 : currentIndex
152
+ }
153
+ }
154
+
155
+ module.exports.random_id = function () {
156
+ return _.random(100000000, 999999999)
157
+ }
158
+
159
+ module.exports.get_hhmmss = function () {
160
+ return new Date().toTimeString().split(' ')[0]
161
+ }
162
+
163
+ module.exports.round = function (number, precision) {
164
+ if (typeof number === 'string')
165
+ number = parseFloat(number)
166
+ return Math.round(number * Math.pow(10, precision)) / Math.pow(10, precision)
167
+ }
168
+
169
+ module.exports.cut_orderbook = function(input_array, level_target) {
170
+ return input_array.slice(level_target)
171
+ }
172
+
173
+ module.exports.level_position = function (input_array, level_target) {
174
+ if (input_array.length <= level_target) {
175
+ level_target--
176
+ return module.exports.level_position(input_array, level_target)
177
+ }
178
+ let vol = 0, price = 0, sum = 0, pos = 0
179
+ for (let i = 0; i < level_target; i++) {
180
+ vol = vol + input_array[i][1]
181
+ sum = sum + input_array[i][0] * input_array[i][1]
182
+ price = input_array[i][0]
183
+ pos = i
184
+ }
185
+ return { price, avg_price: sum / vol ? sum / vol : price, vol, sum, pos }
186
+ }
187
+
188
+ module.exports.price_position = function (input_array, price) {
189
+ if (input_array.length === 1) {
190
+ return {
191
+ price: input_array[0][0],
192
+ avg_price: input_array[0][0],
193
+ vol: input_array[0][1],
194
+ sum: input_array[0][0] * input_array[0][1],
195
+ pos: 0
196
+ }
197
+ }
198
+ let vol = 0, sum = 0, pos = 0, type
199
+ if (input_array[0][0] > input_array[1][0])
200
+ type = 'bid'
201
+ else
202
+ type = 'ask'
203
+ for (let i = 0; i < input_array.length; i++) {
204
+ if (input_array[i][0] <= price && type === 'ask') {
205
+ vol = vol + input_array[i][1]
206
+ sum = sum + input_array[i][0] * input_array[i][1]
207
+ pos = i
208
+ } else if (input_array[i][0] >= price && type === 'bid') {
209
+ vol = vol + input_array[i][1]
210
+ sum = sum + input_array[i][0] * input_array[i][1]
211
+ pos = i
212
+ } else {
213
+ break
214
+ }
215
+ }
216
+ return { price, avg_price: sum / vol ? sum / vol : price, vol, sum, pos }
217
+ }
218
+
219
+ module.exports.sum_position = function (input_array, sum_target) {
220
+ if (input_array.length === 1) {
221
+ return {
222
+ price: input_array[0][0],
223
+ avg_price: input_array[0][0],
224
+ vol: input_array[0][1],
225
+ sum: input_array[0][0] * input_array[0][1],
226
+ sum_original: input_array[0][0] * input_array[0][1],
227
+ pos: 0
228
+ }
229
+ }
230
+ let vol = 0, price = 0, sum = 0, pos = 0, sum_original = 0
231
+ for (let i = 0; i < input_array.length; i++) {
232
+ if (sum < sum_target) {
233
+ vol = vol + input_array[i][1]
234
+ sum = sum + input_array[i][0] * input_array[i][1]
235
+ price = input_array[i][0]
236
+ pos = i
237
+ sum_original = sum
238
+ } else if (sum >= sum_target) {
239
+ break
240
+ }
241
+ }
242
+ return { price, avg_price: sum / vol ? sum / vol : price, vol, sum, sum_original, pos }
243
+ }
244
+
245
+ module.exports.vol_position = function (input_array, vol_target) {
246
+ if (input_array.length === 1) {
247
+ return {
248
+ price: input_array[0][0],
249
+ avg_price: input_array[0][0],
250
+ vol: input_array[0][1],
251
+ vol_original: input_array[0][1],
252
+ sum: input_array[0][0] * input_array[0][1],
253
+ pos: 0
254
+ }
255
+ }
256
+ let vol = 0, price = 0, sum = 0, pos = 0, vol_original = 0
257
+ for (let i = 0; i < input_array.length; i++) {
258
+ if (vol < vol_target) {
259
+ vol = vol + input_array[i][1]
260
+ sum = sum + input_array[i][0] * input_array[i][1]
261
+ price = input_array[i][0]
262
+ pos = i
263
+ vol_original = vol
264
+ } else if (vol >= vol_target) {
265
+ sum = sum - input_array[i - 1][0] * (vol - vol_target)
266
+ vol = vol_target
267
+ break
268
+ }
269
+ }
270
+ return { price, avg_price: sum / vol ? sum / vol : price, vol, vol_original, sum, pos }
271
+ }
272
+
273
+ module.exports.sum_position_orderbook = (input_array, sum_target) => {
274
+ let { sum_original, pos } = module.exports.sum_position(input_array, sum_target)
275
+ let result = JSON.parse(JSON.stringify(input_array.slice(0, pos + 1)))
276
+ result[pos][1] += (sum_target - sum_original) / result[pos][0]
277
+ return result
278
+ }
279
+
280
+ module.exports.vol_position_orderbook = (input_array, vol_target) => {
281
+ let { vol_original, pos } = module.exports.vol_position(input_array, vol_target)
282
+ let result = JSON.parse(JSON.stringify(input_array.slice(0, pos + 1)))
283
+ result[pos][1] += vol_target - vol_original
284
+ return result
285
+ }
286
+
287
+ // console.log(module.exports.sum_position_orderbook([[2, 1], [6, 6], [7, 7]], 0))
288
+ // console.log(module.exports.vol_position_orderbook([ [ 0.00004637, 14.12 ],
289
+ // [ 0.00004636, 19.37 ],
290
+ // [ 0.0000463, 77.76 ],
291
+ // [ 0.00004625, 17.93 ],
292
+ // [ 0.00004623, 14.89 ],
293
+ // [ 0.00004621, 34.25 ],
294
+ // [ 0.0000462, 131.77 ],
295
+ // [ 0.00004619, 24.79 ],
296
+ // [ 0.00004618, 36.71 ],
297
+ // [ 0.00004617, 18.36 ],
298
+ // [ 0.00004616, 9 ],
299
+ // [ 0.00004615, 67.22 ],
300
+ // [ 0.00004614, 74.74 ],
301
+ // [ 0.00004613, 31.89 ],
302
+ // [ 0.00004608, 31.25 ],
303
+ // [ 0.00004606, 72 ],
304
+ // [ 0.00004605, 11.69 ],
305
+ // [ 0.00004604, 36.68 ],
306
+ // [ 0.00004601, 29.77 ],
307
+ // [ 0.00004598, 11.17 ],
308
+ // [ 0.00004596, 25.19 ],
309
+ // [ 0.00004593, 9.01 ],
310
+ // [ 0.00004592, 15.56 ],
311
+ // [ 0.00004589, 15.21 ],
312
+ // [ 0.00004588, 21.25 ],
313
+ // [ 0.00004583, 25.19 ],
314
+ // [ 0.00004582, 81.02 ],
315
+ // [ 0.00004581, 24.55 ],
316
+ // [ 0.0000458, 0.26 ],
317
+ // [ 0.00004577, 71.32 ],
318
+ // [ 0.00004576, 43.39 ],
319
+ // [ 0.00004574, 41.3 ],
320
+ // [ 0.00004573, 0.75 ],
321
+ // [ 0.0000457, 10.84 ],
322
+ // [ 0.00004567, 0.26 ],
323
+ // [ 0.00004549, 239.91 ],
324
+ // [ 0.00004548, 115.89 ],
325
+ // [ 0.00004542, 192.91 ],
326
+ // [ 0.00004512, 0.64 ],
327
+ // [ 0.000045, 3.24 ] ], 0))
328
+
329
+ module.exports.combine_orderbooks = (orderbooks_dict, length=undefined) => {
330
+ function merge_sorted (type) {
331
+ let count = {}
332
+ for (let exchange in orderbooks_dict) {
333
+ count[exchange] = 0
334
+ }
335
+ let result = []
336
+ while (_.sum(_.values(count)) !== _.keys(orderbooks_dict).length * -1) {
337
+ let picked
338
+ for (let exchange in orderbooks_dict) {
339
+ if (count[exchange] === -1)
340
+ continue
341
+ if (_.get(orderbooks_dict, [exchange, type, count[exchange], 'length']) === 2)
342
+ orderbooks_dict[exchange][type][count[exchange]].push(exchange)
343
+ if (!picked) {
344
+ picked = orderbooks_dict[exchange][type][count[exchange]]
345
+ } else if (type === 'asks' && picked[0] > orderbooks_dict[exchange][type][count[exchange]][0]) {
346
+ picked = orderbooks_dict[exchange][type][count[exchange]]
347
+ } else if (type === 'bids' && picked[0] < orderbooks_dict[exchange][type][count[exchange]][0]) {
348
+ picked = orderbooks_dict[exchange][type][count[exchange]]
349
+ }
350
+ }
351
+ result.push(picked)
352
+ if (count[picked[2]] < orderbooks_dict[picked[2]][type].length - 1) {
353
+ count[picked[2]] += 1
354
+ } else {
355
+ count[picked[2]] = -1
356
+ }
357
+ if (result.length === length)
358
+ break
359
+ }
360
+ return result
361
+ }
362
+ let asks = merge_sorted('asks')
363
+ let bids = merge_sorted('bids')
364
+ return { asks, bids }
365
+ }
366
+
367
+ // console.log(module.exports.combine_orderbooks({
368
+ // 'binance': {
369
+ // asks: [[1, 1], [2, 2], [3, 3]],
370
+ // bids: [[0.9, 0.9], [0.5, 0.5], [0.3, 0.2]]
371
+ // },
372
+ // 'bittrex': {
373
+ // asks: [[4, 4], [5, 5], [8, 8]],
374
+ // bids: [[0.6, 0.9], [0.5, 0.2], [0.2, 0.2]]
375
+ // },
376
+ // 'poloniex': {
377
+ // asks: [[1, 1], [6, 6], [7, 7]],
378
+ // bids: [[0.95, 0.9], [0.7, 0.5], [0.4, 0.2]]
379
+ // }
380
+ // }, 3))
381
+
382
+ module.exports.arb_opportunities_from_combined_orderbook = (orderbook_combined, profit_percentage=0) => {
383
+ let i = 0, j = 0, ask_amount = 0, bid_amount = 0
384
+ let asks = orderbook_combined.asks, bids = orderbook_combined.bids
385
+ if (asks[0][0] * (1 + profit_percentage) >= bids[0][0])
386
+ return {}
387
+ let last_step = ''
388
+ while (i < asks.length && j < bids.length) {
389
+ if (asks[i][0] * (1 + profit_percentage) < bids[j][0]) {
390
+ if (ask_amount === 0 && bid_amount === 0) {
391
+ ask_amount = asks[i][1], bid_amount = bids[j][1]
392
+ } else if (ask_amount <= bid_amount) {
393
+ i++
394
+ ask_amount += asks[i][1]
395
+ last_step = 'ask'
396
+ } else {
397
+ j++
398
+ bid_amount += bids[j][1]
399
+ last_step = 'bid'
400
+ }
401
+ } else {
402
+ if (last_step === 'ask') {
403
+ ask_amount -= asks[i][1]
404
+ i--
405
+ } else if (last_step === 'bid') {
406
+ bid_amount -= bids[j][1]
407
+ j--
408
+ }
409
+ break
410
+ }
411
+ }
412
+ let opportunities = {}, diff = ask_amount - bid_amount
413
+ asks = asks.slice(0, i + 1)
414
+ bids = bids.slice(0, j + 1)
415
+ if (diff > 0) {
416
+ asks[i][1] -= diff
417
+ } else {
418
+ bids[j][1] += diff
419
+ }
420
+ asks.map(ask => {
421
+ if (!opportunities[ask[2]]) {
422
+ opportunities[ask[2]] = {
423
+ price: 0,
424
+ amount: 0,
425
+ exchange: ask[2],
426
+ method: 'buy'
427
+ }
428
+ }
429
+ opportunities[ask[2]].avg_price = (opportunities[ask[2]].price * opportunities[ask[2]].amount + ask[0] * ask[1]) / (opportunities[ask[2]].amount + ask[1])
430
+ opportunities[ask[2]].price = ask[0]
431
+ opportunities[ask[2]].amount += ask[1]
432
+ opportunities[ask[2]].total = opportunities[ask[2]].avg_price * opportunities[ask[2]].amount
433
+ })
434
+ bids.map(bid => {
435
+ if (!opportunities[bid[2]]) {
436
+ opportunities[bid[2]] = {
437
+ price: 0,
438
+ amount: 0,
439
+ exchange: bid[2],
440
+ method: 'sell'
441
+ }
442
+ }
443
+ opportunities[bid[2]].avg_price = (opportunities[bid[2]].price * opportunities[bid[2]].amount + bid[0] * bid[1]) / (opportunities[bid[2]].amount + bid[1])
444
+ opportunities[bid[2]].price = bid[0]
445
+ opportunities[bid[2]].amount += bid[1]
446
+ opportunities[bid[2]].total = opportunities[bid[2]].avg_price * opportunities[bid[2]].amount
447
+ })
448
+ return opportunities
449
+ }
450
+
451
+ // console.log(module.exports.arb_opportunities_from_combined_orderbook({
452
+ // asks: [ [ 0.3049, 150, 'bitget' ],
453
+ // [ 0.30791, 50.5556, 'bitget' ],
454
+ // [ 0.30792, 175.49623901, 'bitfinex' ],
455
+ // [ 0.30793, 86.89887994, 'bitfinex' ],
456
+ // [ 0.3081, 2.4526, 'huobi' ] ],
457
+ // bids: [ [ 0.3079, 100, 'huobi' ],
458
+ // [ 0.305, 100, 'huobi' ],
459
+ // [ 0.3049, 5956.5837, 'huobi' ],
460
+ // [ 0.3038, 4373.4668, 'huobi' ],
461
+ // [ 0.3027, 867.8638, 'huobi' ] ]
462
+ // }, 0.0004))
463
+
464
+ module.exports.vol_position_combined = function (input_array, vol_target) {
465
+ if (input_array.length === 1) {
466
+ return {
467
+ price: input_array[0][0],
468
+ price_exchange: { [input_array[0][2]]: input_array[0][0] },
469
+ avg_price: input_array[0][0],
470
+ vol: input_array[0][1],
471
+ vol_exchange: { [input_array[0][2]]: input_array[0][1] },
472
+ sum: input_array[0][0] * input_array[0][1],
473
+ pos: 0
474
+ }
475
+ }
476
+ let vol = 0, price = 0, sum = 0, pos = 0, vol_exchange = {}, price_exchange = {}, sum_exchange = {}, pos_exchange = {}
477
+ for (let i = 0; i < input_array.length; i++) {
478
+ if (vol < vol_target) {
479
+ let exchange = input_array[i][2]
480
+ vol = vol + input_array[i][1]
481
+ vol_exchange[exchange] = (vol_exchange[exchange] === undefined) ? input_array[i][1] : vol_exchange[exchange] + input_array[i][1]
482
+ sum = sum + input_array[i][0] * input_array[i][1]
483
+ sum_exchange[exchange] = (sum_exchange[exchange] === undefined) ? input_array[i][0] * input_array[i][1] : sum_exchange[exchange] + input_array[i][0] * input_array[i][1]
484
+ price = input_array[i][0]
485
+ price_exchange[exchange] = price
486
+ pos = i
487
+ pos_exchange[exchange] = (pos_exchange[exchange] === undefined) ? 0 : pos_exchange[exchange] + 1
488
+ } else if (vol >= vol_target) {
489
+ sum_exchange[input_array[i - 1][2]] -= input_array[i - 1][0] * (vol - vol_target)
490
+ sum -= input_array[i - 1][0] * (vol - vol_target)
491
+ vol_exchange[input_array[i - 1][2]] -= vol - vol_target
492
+ vol = vol_target
493
+ break
494
+ }
495
+ }
496
+ avg_price = sum / vol ? sum / vol : price
497
+ return { price, price_exchange, avg_price, vol, vol_exchange, sum, sum_exchange, pos, pos_exchange }
498
+ }
499
+
500
+ // console.log(module.exports.vol_position_combined([ [ 1, 1, 'binance' ],
501
+ // [ 1, 1, 'poloniex' ],
502
+ // [ 2, 2, 'binance' ],
503
+ // [ 3, 3, 'binance' ],
504
+ // [ 4, 4, 'bittrex' ],
505
+ // [ 5, 5, 'bittrex' ],
506
+ // [ 6, 6, 'poloniex' ],
507
+ // [ 7, 7, 'poloniex' ],
508
+ // [ 8, 8, 'bittrex' ] ], 5))
509
+
510
+ module.exports.sort_dict = function(dict, mode) {
511
+ var items = Object.keys(dict).map(function(key) {
512
+ return [key, dict[key]]
513
+ })
514
+ items.sort(function(first, second) {
515
+ if (mode === 0) {
516
+ return second[1] - first[1]
517
+ } else {
518
+ return first[1] - second[1]
519
+ }
520
+ })
521
+ return items
522
+ }
523
+
524
+ module.exports.merge_trades_with_same_time = function (array) {
525
+ if (array.length === 1) {
526
+ return array
527
+ } else {
528
+ let trades = []
529
+ let processed_index = []
530
+ for (let i = 0; i < array.length; i++) {
531
+ if (processed_index.indexOf(i) === -1) {
532
+ let trade = array[i]
533
+ processed_index.push(i)
534
+ for (let j = i + 1; j < array.length; j++) {
535
+ if (processed_index.indexOf(j) === -1) {
536
+ let to_compare_trade = array[j]
537
+ if (to_compare_trade.close_time.getTime() === trade.close_time.getTime() && to_compare_trade.market === trade.market && to_compare_trade.type === trade.type) {
538
+ trade.amount = trade.amount + to_compare_trade.amount
539
+ trade.total = trade.total + to_compare_trade.total
540
+ processed_index.push(j)
541
+ }
542
+ }
543
+ }
544
+ trade.amount = parseFloat(trade.amount)
545
+ trade.total = parseFloat(trade.total)
546
+ trade.price = trade.total / trade.amount
547
+ trades.push(trade)
548
+ }
549
+ }
550
+ return trades
551
+ }
552
+ }
553
+
554
+ module.exports.merge_trades_with_same_id = function (array) {
555
+ if (array.length === 1) {
556
+ return array
557
+ } else {
558
+ let trades = []
559
+ let processed_index_set = new Set()
560
+ for (let i = 0; i < array.length; i++) {
561
+ if (!processed_index_set.has(i)) {
562
+ let trade = array[i]
563
+ processed_index_set.add(i)
564
+ for (let j = i + 1; j < array.length; j++) {
565
+ if (!processed_index_set.has(j)) {
566
+ let to_compare_trade = array[j]
567
+ if (to_compare_trade.order_id === trade.order_id) {
568
+ trade.amount = trade.amount + to_compare_trade.amount
569
+ trade.total = trade.total + to_compare_trade.total
570
+ processed_index_set.add(j)
571
+ }
572
+ }
573
+ }
574
+ trade.amount = parseFloat(trade.amount)
575
+ trade.total = parseFloat(trade.total)
576
+ trade.price = trade.total / trade.amount
577
+ trades.push(trade)
578
+ }
579
+ }
580
+ return trades
581
+ }
582
+ }
583
+
584
+ module.exports.similar = function (a, b, scale) {
585
+ if (Math.abs(a - b) / a < scale) {
586
+ return true
587
+ }
588
+ return false
589
+ }
590
+
591
+ module.exports.parse_pair = function (pair) {
592
+ pair = pair.toUpperCase()
593
+ let time
594
+ [pair, time] = _.split(pair, '_')
595
+ let result
596
+ if (pair.endsWith('USDT') || pair.endsWith('USDC') || pair.endsWith('TUSD') || pair.endsWith('BUSD') || pair.endsWith('USDS') || pair.endsWith('DKKT') || pair.endsWith('CNYT'))
597
+ result = [pair.substr(0, pair.length - 4), pair.substr(pair.length - 4, pair.length)]
598
+ else if (pair.endsWith('QC') || pair.endsWith('ZB'))
599
+ result = [pair.substr(0, pair.length - 2), pair.substr(pair.length - 2, pair.length)]
600
+ else
601
+ result = [pair.substr(0, pair.length - 3), pair.substr(pair.length - 3, pair.length)]
602
+ if (time)
603
+ result[1] += '_' + time
604
+ return result
605
+ }
606
+
607
+ module.exports.reverse_pair = function (pair) {
608
+ let [cur, base_cur] = module.exports.parse_pair(pair)
609
+ return base_cur + cur
610
+ }
611
+
612
+ module.exports.cur_dict_to_pair_list = function (cur_dict) {
613
+ return [].concat.apply([], Object.entries(cur_dict).map(e => e[1].map(j => j + e[0])))
614
+ }
615
+
616
+ module.exports.number_with_commas = (x) => {
617
+ let parts = x.toString().split('.')
618
+ parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ',')
619
+ return parts.join('.')
620
+ }
621
+
622
+ module.exports.exchange_basecur_curs_converter = (exchange_basecur_curs) => {
623
+ let exchange_pairs = {}, exchange_curs = {}
624
+ for (let exchange in exchange_basecur_curs) {
625
+ _.set(exchange_pairs, [exchange], [])
626
+ _.set(exchange_curs, [exchange], [])
627
+ for (let base_cur in exchange_basecur_curs[exchange]) {
628
+ exchange_pairs[exchange] = exchange_pairs[exchange].concat(_.map(exchange_basecur_curs[exchange][base_cur], cur => cur + base_cur))
629
+ exchange_curs[exchange] = _.union(exchange_curs[exchange], _.union(exchange_basecur_curs[exchange][base_cur], [base_cur]))
630
+ }
631
+ }
632
+ let pair_exchanges = {}
633
+ for (let exchange in exchange_pairs) {
634
+ exchange_pairs[exchange].map(pair => {
635
+ if (!pair_exchanges[pair]) {
636
+ pair_exchanges[pair] = []
637
+ }
638
+ pair_exchanges[pair].push(exchange)
639
+ })
640
+ }
641
+ return {
642
+ exchange_basecur_curs,
643
+ exchange_pairs,
644
+ exchange_curs,
645
+ pair_exchanges
646
+ }
647
+ }
648
+
649
+ module.exports.sort_keys = (dict) => {
650
+ return _.fromPairs(_.sortBy(_.toPairs(dict), e => e[0]))
651
+ }
@@ -0,0 +1,49 @@
1
+ const websocketclient = require('websocket').client
2
+
3
+ module.exports = class Wechat {
4
+ constructor (server_addr = 'http://172.105.199.80:8080', origin='') {
5
+ this.client = new websocketclient()
6
+ this.server_addr = server_addr
7
+ this.connection
8
+ this.connection_status
9
+ this.client.on('connectfailed', (err) => {
10
+ console.error('wechat connect error: ' + err)
11
+ })
12
+ this.client.on('connect', (connection) => {
13
+ console.log('wechat websocket client connected')
14
+ this.connection = connection
15
+ this.connection_status = 'opened'
16
+ connection.on('error', (err) => {
17
+ console.error('wechat connection error: ' + err)
18
+ })
19
+ connection.on('close', () => {
20
+ console.log('wechat connection closed')
21
+ this.connection_status = 'n-opened'
22
+ setTimeout(() => {
23
+ this.client.connect(this.server_addr, 'wechat-protocol', origin)
24
+ }, 1000)
25
+ })
26
+ connection.on('message', (message) => {
27
+ if (message.type === 'utf8') {
28
+ console.log('received: ' + message)
29
+ }
30
+ })
31
+ })
32
+ this.client.connect(this.server_addr, 'wechat-protocol', origin)
33
+ }
34
+ send (name, content, isgroup) {
35
+ if (this.connection_status === 'opened') {
36
+ let json = {
37
+ name,
38
+ content,
39
+ isgroup
40
+ }
41
+ this.connection.sendUTF(JSON.stringify(json))
42
+ } else {
43
+ console.error('wechat websocket not connected')
44
+ setTimeout(() => {
45
+ this.client.connect(this.server_addr, 'wechat-protocol', origin)
46
+ }, 10000)
47
+ }
48
+ }
49
+ }