Repository navigation
Expand file tree
/
Copy patharbitrage.js
More file actions
1653 lines (1479 loc) · 79.8 KB
/
Copy patharbitrage.js
File metadata and controls
1653 lines (1479 loc) · 79.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"use strict";
/* ------------------------------------------------------------------------ */
const Promise = require("bluebird");
const ccxt = require ('ccxt')
, asTable = require ('as-table') // .configure ({ print: require ('string.ify').noPretty })
, log = require ('ololog').noLocate
, ansi = require ('ansicolor').nice
log.configure ({ time: true })
const algo_namespace="arbitrage"
require('./settings-'+algo_namespace+'.js')();
const concurrentProcess = ARBITRAGE_EXCHANGE_WALLET_DIVIDER
const fs = require ('fs')
const functions = require ('./functions')
var database = require('./db-aca.js'); //sqllite3.x
var therocksqv = require ('./therocksqv.js')
const technicalindicators = require('technicalindicators')
var RSI = require('technicalindicators').RSI;
var MFI = require('technicalindicators').MFI;
var CCI = require('technicalindicators').CCI;
var ADX = require('technicalindicators').ADX;
var BB = require('technicalindicators').BollingerBands
var MACD = require('technicalindicators').MACD;
var OBV = require('technicalindicators').OBV;
var KD = require('technicalindicators').Stochastic;
let coin_last= {}, coin_bid = {}, coin_macd={}, coin_obv={}, coin_kd={},coin_rsi ={},coin_mfi ={},coin_cci ={}, coin_adx={}, coin_bb={}, coin_ask = {},coin_prices_quote_volume={}, coin_prices_base_volume={}
let fileCSV = ''; //opportunities enalbed
let fileStubCSV = ''
var bootEnv = true; //load environment during the first launch
const NULL_CRITERIA="TBD"
let result = {};
var accounts = require ('./credentials-1.json')
var exchanges =[]
let sqvWallets={}
var markets={};
var exchanges_markets = []
var coinMaster = ARBITRAGE_EXCHANGE_COIN
var quantity=0
var master_wallet
let coinPairsMaster=[]
let coinPairs=[]
let tradingFee_taker
let tradingFee_maker
//date1 the start of our age
var date1, dateOrder
var crime_account
var amountFilled=0
const wallet_percentage = ARBITRAGE_WALLET_QUANTITY_PERCENTAGE
const stoploss_timewindows = ARBITRAGE_STOPLOSS_TIMEWINDOWS
let human_value = function (price) {
return typeof price === 'undefined' ? 'N/A' : price
}
var capabilities = [
'publicAPI',
'privateAPI',
'CORS',
'fetchTicker',
'fetchTickers',
'fetchOrderBook',
'fetchTrades',
'fetchOHLCV',
'fetchBalance',
'createOrder',
'createMarketOrder',
'createLimitOrder',
'editOrder',
'cancelOrder',
'fetchOrder',
'fetchOrders',
'fetchOpenOrders',
'fetchClosedOrders',
'fetchMyTrades',
'fetchCurrencies',
'fetchDepositAddress',
'createDepositAddress',
'withdraw',
];
function initFile(exchange) {
var timestamp = new Date().getTime();
fileCSV = './data/'+algo_namespace+'.'+exchange +'.'+ crime_account+'.'+ ARBITRAGE_EXCHANGE_COIN +'.'+ new Date().getFullYear() +'.'+(new Date().getMonth() +1)+'.'+new Date().getDate()+'.csv'; //opportunities enalbed
// try {
// fs.unlinkSync(fileCSV,(err) => {
// if (err) log.red( err.message);
// log.magenta('CSV created for writing the opportunity found during the arbitrage!!!');
// });
// } catch (error) {
// log("error during delete file");
// }
if (!fs.existsSync(fileCSV)) {
fs.appendFile(fileCSV, "datetime, head_symbol, pair_symbol, tail_symbol, head_price, pair_price, tail_price, cash_out, cash_pair_in, cash_tail_in, profit, result",(err) => {
if (err) log.red( err.message);
log.magenta('CSV created for writing the opportunity found during the arbitrage single exchange!!!')})
}
if (STUB) {
fileStubCSV = './data/'+algo_namespace+'.stub.'+exchange +'.'+ crime_account+'.'+ ARBITRAGE_EXCHANGE_COIN +'.'+ new Date().getFullYear() +'.'+(new Date().getMonth() +1)+'.'+new Date().getDate()+'.csv'; //opportunities enalbed
// try {
// fs.unlinkSync(fileCSV,(err) => {
// if (err) log.red( err.message);
// log.magenta('CSV created for writing the opportunity found during the arbitrage!!!');
// });
// } catch (error) {
// log("error during delete file");
// }
if (!fs.existsSync(fileStubCSV)) {
fs.appendFile(fileStubCSV, "start datetime, symbol, amount,price,rsi-1,rsi-2,rsi-3,rsi-4,rsi-5,end datetime",(err) => {
if (err) log.red( err.message);
log.magenta('CSV created for writing the opportunity found during the arbitrage single exchange!!!')})
}
}
}
//calculate Volume from coin quote to USD(T)
async function calculateUSDTVolume(exchangeId, asset){
//log.bright(ARBITRAGE_EXCHANGE.green, "calculateUSDTVolume started", asset)
var priceCQ;
var quoteVolume = coin_prices_quote_volume[asset][exchangeId]
var coinQuote = asset.slice(asset.indexOf("/")+1)
if (!coinQuote.startsWith("USD")) {
priceCQ = coin_last[coinQuote+"/USDT"][exchangeId]
//log.magenta("calculateUSDTVolume".yellow, exchangeId.green, "USDT priceCQ", priceCQ)
if (priceCQ === undefined) {
priceCQ = coin_last[coinQuote+"/USD"][exchangeId]
//log.magenta("calculateUSDTVolume".yellow, exchangeId.green, "USD priceCQ", priceCQ)
}
} else {
priceCQ=1;//already in USD
}
const quoteVolumeUSD = quoteVolume * priceCQ
return quoteVolumeUSD;
}
// Retrieve Volumes for all master and pair coins
async function fetchVolumes(exchangeId) { //GET Volume DATA
log.bright(ARBITRAGE_EXCHANGE.green, "fetchVolumes started", "VOLUME_FILTER", VOLUME_FILTER)
if (!VOLUME_FILTER) return
return new Promise (async (resolve, reject) => {
const exchange = exchanges[ARBITRAGE_EXCHANGE];
const tickers = await exchange.fetchTickers();
Object.keys (tickers).map (exchangeId => {
const ticker = tickers[exchangeId]
const symbol = ticker['symbol']
if (!coin_prices_quote_volume[symbol]) coin_prices_quote_volume[symbol] = {};
if (!coin_prices_base_volume[symbol]) coin_prices_base_volume[symbol] = {};
if (!coin_last[symbol]) coin_last[symbol] = {};
coin_last[symbol][exchange.id] = ticker['last'];
coin_prices_quote_volume[symbol][exchange.id] = ticker['quoteVolume'];
coin_prices_base_volume[symbol][exchange.id] = ticker['baseVolume'];
})
if (DEBUG) {
log.yellow(ARBITRAGE_EXCHANGE.green,"coin_prices_quote_volume", coin_prices_quote_volume)
log.yellow(ARBITRAGE_EXCHANGE.green,"coin_prices_base_volume", coin_prices_base_volume)
log.yellow(ARBITRAGE_EXCHANGE.green,"coin_last", coin_last)
}
await ccxt.sleep (120)
resolve()
})
}
//fetch KPI every 5 mins
async function checkKPIs(sync) {
log.bright(ARBITRAGE_EXCHANGE.green, "checkKPIs started", "sync",sync )
var date2 = new Date();
if (date2.getTime()>((date1.getTime())+ (1000*60*5))) {
await fetchKPIs(sync)
date1.setTime(new Date())
} /*else {
date2.setTime(new Date())
} */
}
// fetch sync KPI
async function fetchKPIs(sync) {
log.bright(ARBITRAGE_EXCHANGE.green, "fetchKPIs started", "sync",sync )
if (sync){
await fetchVolumes()
}
else {
fetchVolumes()
}
}
//check Technical Indicator : RSI, MFI and CCI
//true for positive growing trend - false otherwise
async function checkRSI (exchId, asset, length) {
//log.bright.magenta(exchanges[exchId].iso8601 (Date.now ()),exchId.green, "checkRFI started", exchId, asset)
if (!TI_FILTER && !RSI_FILTER) return
var rsi = coin_rsi[asset][exchId]
var currentRsi =rsi[rsi.length-1]
var result = false
//one based and no zero based
length =length+1;
var incRsi = true
if ((currentRsi - rsi[rsi.length-length])<0) incRsi=false
result = incRsi
if (DEBUG){
log.bright(exchanges[exchId].iso8601 (Date.now ()),exchId.green,asset, "checkRFI output", [result,currentRsi])
}
return [result,currentRsi]
}
async function checkBB (exchId, asset, length) {
log.bright.magenta(exchanges[exchId].iso8601 (Date.now ()),exchId.green, "checkBB started", exchId, asset)
if (!BB_FILTER) return
var bb = coin_bb[asset][exchId]
var currentBB =bb[bb.length-1]
var result = false
//one based and no zero based
length =length+1;
var incBBLower = true
var incBBMiddle = true
var incBBUpper = true
var bbs =bb[bb.length-length]
if ((currentBB.lower - bbs.lower)<0) incBBLower=false
if ((currentBB.middle - bbs.middle)<0) incBBMiddle=false
if ((currentBB.upper - bbs.upper)<0) incBBUpper=false
if (DEBUG){
log.bright(exchanges[exchId].iso8601 (Date.now ()),exchId.green,asset, "checkBB output", [!incBBLower, !incBBMiddle, !incBBUpper, currentBB])
}
return [incBBLower, incBBMiddle, incBBUpper, currentBB]
}
//check Technical Indicator : MACD
//true for positive growing trend - false ; undefined to skip the opportunity
async function checkMACD (exchId, asset, length) {
if (!MACD_FILTER) return
log.bright.magenta(exchId.green, "checkMACD started", exchId, asset)
var macd = coin_macd[asset][exchId]
var currentMacd =macd[macd.length-1]
var previousMacd =macd[macd.length-2]
var result = undefined
if (DEBUG){
log.bright(exchId.green,asset, "currentMacd", currentMacd.MACD, "signal",currentAdx.signal, "histogram", currentAdx.histogram)
}
if (currentMacd.MACD > currentMacd.signal && previousMacd.MACD <= previousMacd.signal) {
result = true //# If the MACD crosses the signal line upward -- "BUY"
} else if ((currentMacd.MACD < currentMacd.signal && previousMacd.MACD >= previousMacd.signal) ) {
result = false //# The other way around -- "SELL"
} else {
result = undefined
}
return [result, currentMacd]
}
//check Technical Indicator : KD
//true for positive growing trend - false ; undefined to skip the opportunity
async function checkKD (exchId, asset, length) {
if (!KD_FILTER) return
log.bright.magenta(exchId.green, "checkKD started", exchId, asset, "andrea")
var kd = coin_kd[asset][exchId]
var currentKD =kd[kd.length-1]
var result = undefined
if (DEBUG){
log.bright(exchId.green,asset, "currentKD", currentKD, "K",currentKD.k, "D", currentKD.d)
}
if (currentKD.k >= KD_OVERBOUGHT && currentKD.d>=KD_OVERBOUGHT) {
result = false //# -- "SELL"
} else if (currentKD.k <= KD_OVERSOLD && currentKD.d<=KD_OVERSOLD ) {
result = true //# The other way around -- "BUY"
} else {
result = undefined
}
return [result, currentKD]
}
async function checkStrengthTrend (exchId, side, length, asset) {
// log.bright.magenta(exchId.green, "checkStrengthTrend started", exchId, side, "length", length, asset)
var adx = coin_adx[asset][exchId]
var currentAdx =adx[adx.length-1]
var result = false
if (DEBUG){
log.bright(exchId.green,asset, "currentAdx", currentAdx.adx, "PDI",currentAdx.pdi, "MDI", currentAdx.mdi)
log.bright(exchId.green,asset, "currentAdx", currentAdx.adx, "ADX_LEVEL_5", ADX_LEVEL_5, "ADX_LEVEL_2",ADX_LEVEL_2)
}
log.bright(exchId.green,asset, "currentAdx", currentAdx.adx.toString().yellow, "PDI",currentAdx.pdi.toString().green, "MDI", currentAdx.mdi.toString().magenta, "ADX_LEVEL_7", ADX_LEVEL_7, "ADX_LEVEL_3 (+5)",(ADX_LEVEL_3+5))
var _adx= currentAdx.adx
if ( _adx<= ADX_LEVEL_7 && _adx>=ADX_LEVEL_3+5) {
var pdi = currentAdx.pdi
var mdi = currentAdx.mdi
if (side==='buy') {
if (pdi>mdi) result = true
} else {
if (mdi>pdi) result = true
}
}
return result
}
async function checkTIs (exchId, side, length, asset) {
log.bright.magenta(exchId.green, "checkTIs started", exchId, side, "length", length, asset)
var rsi = coin_rsi[asset][exchId]
var mfi = coin_mfi[asset][exchId]
var cci = coin_cci[asset][exchId]
var adx = coin_adx[asset][exchId]
var bb = coin_bb[asset][exchId]
var currentRsi =rsi[rsi.length-1]
var currentMfi =mfi[mfi.length-1]
var currentCci =cci[cci.length-1]
var currentAdx =adx[adx.length-1]
var currentBb =bb[bb.length-1]
var result = false
var resultRsi, resultMfi, resultCci
//check RSI, MFI and CCI momentum trend
var incRsi = true
if ((currentRsi - rsi[rsi.length-length])<0) incRsi=false
var incMfi =true
if ((currentMfi - mfi[mfi.length-length])<0) incMfi=false
var incCci = true
if ((currentCci - cci[cci.length-length])<0) incCci=false
if (DEBUG){
log.bright(exchId.green,asset, "currentRsi", currentRsi, "curent-length","("+length+")", rsi[rsi.length-length], "rsi length", rsi.length)
log.bright(exchId.green,asset, "currentMfi", currentMfi,"curent-length","("+length+")", mfi[mfi.length-length], "mfi length", mfi.length)
log.bright(exchId.green,asset, "currentCci", currentCci, "curent-length","("+length+")",cci[cci.length-length], "cci length", cci.length)
log.bright(exchId.green,asset, "incRsi", incRsi, "incMfi", incMfi, "incCci", incCci)
log.bright(exchId.green,asset, "currentAdx", currentAdx.adx, "PDI",currentAdx.pdi, "MDI", currentAdx.mdi)
log.bright(exchId.green,asset, "currentAdx", currentAdx.adx, "ADX_LEVEL_5", ADX_LEVEL_5, "ADX_LEVEL_2",ADX_LEVEL_2)
}
if (side==='buy') {
if ((!incRsi) ||
(incRsi && currentRsi>=RSI_OVERSOLD))
result = true
else
result = false
} else {
if ((incRsi ) ||
(currentRsi <= RSI_OVERSOLD +10))
result = true
else
result = false
}
// if (side==='buy') {
// if (( !incRsi && !incMfi && !incCci) ||
// ((incRsi && currentRsi>=RSI_OVERSOLD ) &&
// (incMfi && currentMfi>=MFI_OVERSOLD)) ||
// ((incRsi && currentRsi>=RSI_OVERSOLD ) &&
// (incCci && currentCci>=CCI_OVERSOLD) ) ||
// ((incMfi && currentMfi>=MFI_OVERSOLD ) &&
// (incCci && currentCci>=CCI_OVERSOLD) ))
// result = true
// else
// result = false
// } else {
// if ((incRsi && incMfi && incCci) ||
// (incMfi && incCci) || (incRsi && incCci) || (incRsi && incMfi) ||
// ((currentRsi <= RSI_OVERSOLD +10) &&
// ( currentMfi <= MFI_OVERSOLD +10) &&
// ( currentCci <= CCI_OVERSOLD ) ))
// result = true
// else
// result = false
// }
// if (side==='buy') { //RSI_OVERBOUGHT 70
// if ( (RSI_OVERSOLD <= currentRsi) && (currentRsi<= RSI_OVERBOUGHT) && result)
// result = true
// else
// result = false
// } else {//RSI_OVERSOLD 30
// if ((RSI_OVERBOUGHT >= currentRsi) && (currentRsi>= RSI_OVERSOLD) && result)
// result = true
// else
// result = false
// }
//log.bright(ARBITRAGE_EXCHANGE.green,side, asset,"rsi",currentRsi, result, "RSI_OVERBOUGHT", RSI_OVERBOUGHT, "RSI_OVERSOLD", RSI_OVERSOLD)
return result
}
async function fetchTIs (exchId, coins) {
log.bright(ARBITRAGE_EXCHANGE.green, "fetchTIs started for", coins.length, "symbols", "TI_FILTER", TI_FILTER)
if (!TI_FILTER && !ADX_FILTER) return;
const exchange = exchanges[exchId];
const indexOpen = 1 // [ timestamp, open, high, low, close, volume ]
const indexHigh = 2 // [ timestamp, open, high, low, close, volume ]
const indexLow = 3 // [ timestamp, open, high, low, close, volume ]
const indexClose = 4 // [ timestamp, open, high, low, close, volume ]
const indexVolume = 5 // [ timestamp, open, high, low, close, volume ]
for (var i =0; i<coins.length; i++) {
//coins[i] ="ARK/ETH"
const ohlcv = await exchange.fetchOHLCV (coins[i], ARBITRAGE_OHLCV_PERIOD)
// const lastPrice = ohlcv[ohlcv.length - 1][indexClose] // closing price
const seriesHigh = ohlcv.slice (-80).map (x => x[indexHigh]) // high price
const seriesLow = ohlcv.slice (-80).map (x => x[indexLow]) // low price
const seriesOpen = ohlcv.slice (-80).map (x => x[indexOpen]) // popening price
const seriesClose = ohlcv.slice (-80).map (x => x[indexClose]) // closing price
const seriesVolume = ohlcv.slice (-80).map (x => x[indexVolume]) // volume price
// const seriesHigh = ohlcv.map (x => x[indexHigh]) // high price
// const seriesLow = ohlcv.map (x => x[indexLow]) // low price
// const seriesOpen = ohlcv.map (x => x[indexOpen]) // popening price
// const seriesClose = ohlcv.map (x => x[indexClose]) // closing price
// const seriesVolume = ohlcv.map (x => x[indexVolume]) // volume price
if (RSI_FILTER) {
var inputRSI = {
values : seriesClose,
period : 8
}
var rsi = RSI.calculate(inputRSI)
if (!coin_rsi[coins[i]]) coin_rsi[coins[i]] = {};
coin_rsi[coins[i]][exchId] = rsi
if (DEBUG) {
log(exchange.id.yellow, "asset", coins[i].toString().green, "rsi:", rsi[rsi.length-1], "coin_rsi", coin_rsi[coins[i]][exchId]);
}
}
if (MFI_FILTER) {
var inputMFI = {
high : seriesHigh,
low : seriesLow,
close : seriesClose,
volume : seriesVolume,
period : 14
}
var mfi = MFI.calculate(inputMFI)
if (!coin_mfi[coins[i]]) coin_mfi[coins[i]] = {};
coin_mfi[coins[i]][exchId] = mfi
if (DEBUG) {
log(exchange.id.yellow, "asset", coins[i].toString().green, "mfi:", mfi[mfi.length-1], "coin_mfi", coin_mfi[coins[i]][exchId]);
}
}
if (CCI_FILTER) {
var inputCII = {
open : seriesOpen,
high : seriesHigh,
low : seriesLow,
close : seriesClose,
period : 20
}
var cci = CCI.calculate(inputCII)
if (!coin_cci[coins[i]]) coin_cci[coins[i]] = {};
coin_cci[coins[i]][exchId] = cci
if (DEBUG) {
log(exchange.id.yellow, "asset", coins[i].toString().green, "cci:", cci[cci.length-1], "coin_cci", coin_cci[coins[i]][exchId]);
}
}
if (ADX_FILTER) {
var inputADX = {
high : seriesHigh,
low : seriesLow,
close : seriesClose,
period : 20 //like a binary trading
}
var adx = ADX.calculate(inputADX)
if (!coin_adx[coins[i]]) coin_adx[coins[i]] = {};
coin_adx[coins[i]][exchId] = adx
if (DEBUG) {
log(exchange.id.yellow, "asset", coins[i].toString().green, "adx[adx.length-1]:", adx[adx.length-1], "coin_adx", coin_adx[coins[i]][exchId]);
log(exchange.id.yellow, "asset", coins[i].toString().green, "adx[0]:", adx[0], "coin_adx", coin_adx[coins[i]][exchId]);
}
}
if (BB_FILTER) {
var inputBB = {
values : seriesClose,
period : 20, //binary trading
stdDev : 2 //binary trading
}
var bb = BB.calculate(inputBB)
if (!coin_bb[coins[i]]) coin_bb[coins[i]] = {};
coin_bb[coins[i]][exchId] = bb
if (DEBUG) {
log(exchange.id.yellow, "asset", coins[i].toString().green, "bb[adx.length-1]:", bb[bb.length-1], "coin_bb", coin_bb[coins[i]][exchId]);
log(exchange.id.yellow, "asset", coins[i].toString().green, "bb[0]:", bb[0], "coin_bb", coin_bb[coins[i]][exchId]);
}
}
if (MACD_FILTER) {
var inputMACD = {
values : seriesClose,
fastPeriod : 5,
slowPeriod : 8,
signalPeriod : 3 ,
SimpleMAOscillator: false,
SimpleMASignal : false
}
var macd = MACD.calculate(inputMACD);
if (!coin_macd[coins[i]]) coin_macd[coins[i]] = {};
coin_macd[coins[i]][exchId] = macd
if (DEBUG) {
log(exchange.id.yellow, "asset", coins[i].toString().green, "macd:", macd[macd.length-1], "coin_macd", coin_macd[coins[i]][exchId]);
}
}
if (OBV_FILTER) {
let inputOBV = {
close : seriesClose,
volume : seriesVolume
}
var obv = OBV.calculate(inputOBV)
if (!coin_obv[coins[i]]) coin_obv[coins[i]] = {};
coin_obv[coins[i]][exchId] =obv
if (DEBUG) {
log(exchange.id.yellow, "asset", coins[i].toString().green, "obv:", obv[obv.length-1], "coin_obv", coin_obv[coins[i]][exchId]);
}
}
if (KD_FILTER) {
let inputKD = {
high: seriesHigh,
low: seriesLow,
close: seriesClose,
period: 14,
signalPeriod: 3
};
var kd = KD.calculate(inputKD)
if (!coin_kd[coins[i]]) coin_kd[coins[i]] = {};
coin_kd[coins[i]][exchId] = kd
if (DEBUG) {
log(exchange.id.yellow, "asset", coins[i].toString().green, "kd:", kd[kd.length-1], "coin_kd", coin_kd[coins[i]][exchId]);
}
log(exchange.id.yellow, "asset", coins[i].toString().green, "kd:", kd[kd.length-1], "coin_kd", coin_kd[coins[i]][exchId]);
}
}
await ccxt.sleep (exchange.rateLimit*concurrentProcess)
}
// Retrieve Wallet by AltCoin and Exchange
function fetchBalance(altcoin, exchId) {
var result = undefined;
try {
log.bright(ARBITRAGE_EXCHANGE.green, "fetchBalance started", altcoin, sqvWallets[exchId][altcoin])
result = sqvWallets[exchId][altcoin]
if (typeof result === 'undefined' || result === NULL_CRITERIA) {
result = undefined
}
return result;
} catch (error) {
//empty wallet for the specific exchage and altcoin
//log.red ('empty wallet for the specific exchage and altcoin', exchId,altcoin )
return undefined;
}
}
// Retrieve balances by Exchange for all coins
async function fetchBalances(exchId) {
// return new Promise (async (resolve, reject) => {
try {
const exchange = exchanges[exchId];
let balance
if (exchId ==='binance') {
let binance = new ccxt.binance (accounts[exchId])
balance = await binance.fetchBalance({'recvWindow': 60000000})
//exchange.verbose = true
} else {
// output the balance from the exchange
balance = await exchange.fetchBalance ()
}
//HITBTC has two kind of wallet: Bank and Exchange wallet --> move to Exchange for trading
if (exchId === "hitbtc2") {
var balanceAccount = await exchange.fetchBalance ({ type: 'account' })
var balanceTotal =balanceAccount.total
for(var i = 0; i < baseCoins.length; i++) {
var amount = balanceTotal[baseCoins[i]];
if (typeof amount !== 'undefined' && amount >0) {
exchange.private_post_account_transfer({'currency': baseCoins[i], 'amount': amount, 'type': 'bankToExchange'})
//log (exchange.name.green, "currency",baseCoins[i], 'balance', "amount", amount)
}
}
}
//log("balance.total", balance.total)
if (STUB) {
sqvWallets[exchId]=JSON.parse('{"' + sqvCoin + '":"' + sqvAmount +'"}')
} else {
//store the total balance by altcoin
sqvWallets[exchId]=balance.free
}
await ccxt.sleep (exchange.rateLimit*concurrentProcess)
//resolve(balance);
} catch (e) {
log.red("Error retrieving balances (fetchBalances)", e.message);
if (e instanceof ccxt.DDoSProtection || e.message.includes ('ECONNRESET')) {
log.bright.yellow (exchange.id,"error fetchBalances",'[DDoS Protection] ' + e.message)
} else if (e instanceof ccxt.RequestTimeout) {
log.bright.yellow (exchange.id,"error fetchBalances",'[Request Timeout] ' + e.message)
} else if (e instanceof ccxt.AuthenticationError) {
log.bright.yellow (exchange.id,"error fetchBalances",'[Authentication Error] ' + e.message)
} else if (e instanceof ccxt.ExchangeNotAvailable) {
log.bright.yellow (exchange.id,"error fetchBalances",'[Exchange Not Available Error] ' + e.message)
} else if (e instanceof ccxt.ExchangeError) {
log.bright.yellow (exchange.id,"error fetchBalances",'[Exchange Error] ' + e.message)
} else if (e instanceof ccxt.NetworkError) {
log.bright.yellow (exchange.id,"error fetchBalances",'[Network Error] ' + e.message)
} else if (e instanceof ccxt.InvalidNonce) {
log.bright.yellow(exchange.id,"error fetchBalances",'[InvalidNonce Error] ' + e.message)
}
}
// })
}
async function rollbackSellOrder (exchangeid, symbol, order, priceTail, symbolTail, priceBuy, symbolBuy) {
var exchange = exchanges[exchangeid]
log.bright(exchange.iso8601 (Date.now ()),exchange.id.green, "rollebackSellOrder", order.id)
var result = true
var price = order.price
var filled = order.filled
var status = order.status
var amount = order.amount
var umse
amountFilled = 0
var ticker
log.bright(exchange.iso8601 (Date.now ()),exchange.id.green, "rollebackSellOrder status", status, "filled", filled)
if (status==='open' && filled!==0 ) {
//check if the trading for the tail is a good opportunity
ticker = await exchange.fetchTicker (symbolTail)
//if the ticker for the tail has a price greater than the previous one the cancel the current order
var _price = ticker['bid']
//order price is minus than
if (_price>priceTail && symbolBuy !== undefined) {
//fetch ticker for the rollback trading (head side)
ticker = await exchange.fetchTicker (symbolBuy)
var price_bought_to_sell = ticker['bid']
if (price_bought_to_sell>=(priceBuy * (1+0.0015))) {
let order_ = await exchange.createOrder (symbolBuy,'limit', 'sell', (amount-filled),price_bought_to_sell, {'recvWindow': 60000000})
amountFilled=filled
await exchange.cancelOrder(order.id, symbol)
await ccxt.sleep (exchange.rateLimit*3)
order_ = await exchange.createOrder (symbolTail,'limit', 'sell', filled,_price, {'recvWindow': 60000000})
result = false;
}
}
log.bright(exchange.iso8601 (Date.now ()),exchange.id.green, "rollebackSellOrder price for tail order(sell)", price, "origianl price tail", priceTail)
log.bright(exchange.iso8601 (Date.now ()),exchange.id.green, "rollebackSellOrder price for rollback order symbol", symbolBuy, "price", price_bought_to_sell, "vs original price", priceBuy)
log.bright(exchange.iso8601 (Date.now ()),exchange.id.green, "rollebackSellOrder closed successfully", !result)
await ccxt.sleep (exchange.rateLimit*5*concurrentProcess)
} else if (status==='open' && filled===0) {
ticker = await exchange.fetchTicker (symbolBuy)
var price_bought_to_sell = ticker['bid']
if (price_bought_to_sell>=priceBuy * (1+0.0015)) {
await exchange.cancelOrder(order.id, symbol)
await ccxt.sleep (exchange.rateLimit*2)
let order_ = await exchange.createOrder (symbolBuy,'limit', 'sell', amount,price_bought_to_sell, {'recvWindow': 60000000})
await ccxt.sleep (exchange.rateLimit*3*concurrentProcess)
log.bright(exchange.iso8601 (Date.now ()),exchange.id.green, "rollebackSellOrder rollback order done for symbol", symbolBuy, "new order id", order_.id, "price", price_bought_to_sell, "vs original price", priceBuy)
result = false;
} else if (symbolBuy !== undefined) { //pair opportunity on going
//check if the trading for the tail is a good opportunity
var tickerPair = await exchange.fetchTicker (symbol)
var __price = tickerPair['bid'] //the current bid price for the current order
var newPairAmount = __price * amount //the new current amount selling to the current bid price
var newTailAmount = _price * newPairAmount
var theOriginalAmount = price * amount * _price
log.bright(exchange.iso8601 (Date.now ()),exchange.id.green, "rollebackSellOrder current bid price", __price, "amout based on current bid price", newPairAmount, "new tail amount", newTailAmount,"origianl amount", theOriginalAmount)
if (theOriginalAmount<=newTailAmount) {
await exchange.cancelOrder(order.id, symbol)
await ccxt.sleep (exchange.rateLimit*2)
let __order = await exchange.createOrder (symbolBuy,'limit', 'sell', (amount-filled),__price, {'recvWindow': 60000000})
await ccxt.sleep (exchange.rateLimit)
__order = await exchange.createOrder (symbolBuy,'limit', 'buy', newTailAmount,_price, {'recvWindow': 60000000})
}
await ccxt.sleep (exchange.rateLimit)
log.bright.green(exchange.iso8601 (Date.now ()),exchange.id.green, "rollebackSellOrder closed: cancelled current order, sold to current price and sold the final opportinity")
}
log.bright(exchange.iso8601 (Date.now ()),exchange.id.green, "rollebackSellOrder price for rollback order symbol", symbolBuy, "price", price_bought_to_sell, "vs original price", priceBuy)
log.bright(exchange.iso8601 (Date.now ()),exchange.id.green, "rollebackSellOrder closed successfully", !result)
}
return result
}
async function rollbackBuyOrder (exchangeid, symbol, order, transaction_id) {
var result = true
try {
var exchange = exchanges[exchangeid]
log.bright(exchange.id.green, "rollebackBuyOrder started for", order.id)
var price = order.price
var filled = order.filled
var status = order.status
var amount = order.amount
var umse
if (status==='open' && filled===0 ) {
await exchange.cancelOrder(order.id, symbol)
log.bright.magenta(exchange.iso8601 (Date.now ()),"order id",order.id, "cancelled")
umse = database.updateOpportunity ("HEAD", 3, amount, transaction_id)
result = false;
}
else if (status==='open' && filled>0 ) {
let orderbook = await exchange.fetchOrderBook (symbol)
let bid = orderbook.bids.length ? orderbook.bids[0][0] : undefined
let ask = orderbook.asks.length ? orderbook.asks[0][0] : undefined
if (bid >= (price*(1+0.002))) {
await exchange.cancelOrder(order.id, symbol)
await ccxt.sleep (exchange.rateLimit*4*concurrentProcess)
log.bright.magenta(exchange.iso8601 (Date.now ()),"order id",order.id, "cancelled")
let orderSell = await exchange.createOrder (symbol,'limit', 'sell', filled,bid, {'recvWindow': 60000000})
await ccxt.sleep (exchange.rateLimit*4*concurrentProcess)
log.bright.magenta(exchange.iso8601 (Date.now ()),"order id",orderSell.id, "sold", "amount", filled)
umse = database.updateOpportunity ("HEAD", 2, (filled*bid), transaction_id)
result = false;
}
} else {
log.bright.magenta(exchange.iso8601 (Date.now ()),exchange.id.green,"rollback failed. Order status !== 'open'")
}
} catch (error) {
log.bright.red (exchange.iso8601 (Date.now ()),exchange.id,"buy order rollback failure",error.message, symbol )
result = true;
}
return result
}
//return true if order executed succesful false otherwise
async function checkFillOrder(exchange ,symbol,orderid,transaction_id, priceTail, symbolTail,priceBuy, symbolBuy ) {
log.bright(exchange.iso8601 (Date.now ()),exchange.id.green, "checkFillOrder started for", symbol,orderid)
var found = true
var dateFill = new Date()
var orders
while (found) {
try {
orders = await exchange.fetchOpenOrders (symbol,undefined,undefined, {'recvWindow': 60000000})
await ccxt.sleep (exchange.rateLimit*concurrentProcess)
found=false
var order
for (var j=0;j<orders.length;j++) {
order = orders[j]
//log.bright.magenta(exchange.iso8601 (Date.now ()),exchange.id.green, "order [",j,"] order(s) open symbol", order.info.symbol, "orderid", order.info.orderId)
//var _symbol = symbol.replace("/", "")
if (orderid===order.id){
found = true
if (dateFill.getTime()>(dateOrder.getTime() + (1000*60*10))) {
if (order.side === 'buy') {
log.bright.magenta(exchange.iso8601 (Date.now ()),"start rollback if it is possibile for the following order id", order.id)
found = await rollbackBuyOrder (exchange.id,symbol, order)
}
else {
if (priceTail!==null) {
found = await rollbackSellOrder (exchange.id,symbol, order, priceTail, symbolTail,priceBuy, symbolBuy)
}
//log.bright(exchange.id.green, "checkFillOrder order still pending for", symbol,orderid, "order(",orderid,")")
}
dateFill.setTime(new Date())
dateOrder.setTime(new Date())
} else {
dateFill.setTime(new Date())
}
}
}
//log.bright.magenta(exchange.id.green, "still [",orders.length,"] order(s) open for the current asset",symbol)
//await ccxt.sleep (exchange.rateLimit*concurrentProcess)
//orders = await exchange.fetchOpenOrders (symbol,undefined,undefined, {'recvWindow': 60000000})
}
catch (e) {
log.bright.red (exchange.iso8601 (Date.now ()),exchange.id,"error checkFillOrder",e, "Try to retrieving order list another time", symbol )
if (e instanceof ccxt.DDoSProtection || e.message.includes ('ECONNRESET')) {
log.bright.yellow (exchange.id,"error checkFillOrder",'[DDoS Protection] ' + e.message)
} else if (e instanceof ccxt.RequestTimeout) {
log.bright.yellow (exchange.id,"error checkFillOrder",'[Request Timeout] ' + e.message)
} else if (e instanceof ccxt.AuthenticationError) {
log.bright.yellow (exchange.id,"error checkFillOrder",'[Authentication Error] ' + e.message)
} else if (e instanceof ccxt.ExchangeNotAvailable) {
log.bright.yellow (exchange.id,"error checkFillOrder",'[Exchange Not Available Error] ' + e.message)
} else if (e instanceof ccxt.ExchangeError) {
log.bright.yellow (exchange.id,"error checkFillOrder",'[Exchange Error] ' + e.message)
} else if (e instanceof ccxt.NetworkError) {
log.bright.yellow (exchange.id,"error checkFillOrder",'[Network Error] ' + e.message)
} else if (e instanceof ccxt.InvalidNonce) {
// it has thrown the exception as expected
log.bright.yellow(exchange.id,"error checkFillOrder",'[InvalidNonce Error] ' + e.message)
}else if (e instanceof ccxt.OrderNotFound) {
// it has thrown the exception as expected
log.bright.yellow(exchange.id,"error checkFillOrder",'[OrderNotFound Error] ' + e.message)
} else if (e instanceof ccxt.InvalidOrder) {
// it has thrown the exception as expected
log.bright.yellow(exchange.id,"error checkFillOrder",'[InvalidOrder Error] ' + e.message)
} else if (e instanceof ccxt.InsufficientFunds) {
// it has thrown the exception as expected
log.bright.yellow(exchange.id,"error checkFillOrder",'[InsufficientFunds Error] ' + e.message)
}
found = true
}
}
log.bright(exchange.id.green, "checkFillOrder completed for", symbol, "order(",orderid,") closed", found)
return found;
}
//check limimts provided by exchange with the current opportunity
async function checkLimit(exchangeid,symbol, amount, price, cost) {
var result = true;
let marketLimits = markets[exchangeid][symbol].limits
if (marketLimits === undefined || marketLimits["price"] === undefined || marketLimits["amount"] === undefined || marketLimits["cost"] === undefined) {
log.red('market.limits.[price|amount|cost] property is not set. I don\'t care',exchangeid, symbol )
} else{
if (marketLimits.amount.min>amount || marketLimits.amount.max < amount) {
log.red('market.limits.[amount] is above your order',exchangeid, symbol, amount )
result = false;
}
if (marketLimits.price.min>price || marketLimits.price.max < price) {
log.red('market.limits.[price] is above your order',exchangeid, symbol, price )
result = false;
}
if (marketLimits.cost.min>cost || marketLimits.cost.max < cost) {
log.red('market.limits.[cost] is above your order',exchangeid, symbol, cost )
result = false;
}
}
return result
}
async function checkLastPrice(exchangeid, symbol, price, side){
var exchange = exchanges[exchangeid]
log.bright(exchange.iso8601 (Date.now ()),exchange.id.green, "checkLastPrice started", exchangeid, symbol, price, side)
//var priceBuy, priceSell
var found = false
while (!found) {
try {
var ticker = await exchange.fetchTicker(symbol);
await ccxt.sleep (exchange.rateLimit*4)
var priceLast = ticker['last']
if (side==='buy') {
if (priceLast <= price) found=true
} else {
if (priceLast >= price) found=true
}
}
catch (e){
log.bright.red (exchange.id,"error checkLastPrice",e.message, "Try to fetch lat price another time", exchangeid )
if (e instanceof ccxt.DDoSProtection || e.message.includes ('ECONNRESET')) {
log.bright.yellow (exchange.id,"error checkLastPrice",'[DDoS Protection] ' + e.message)
} else if (e instanceof ccxt.RequestTimeout) {
log.bright.yellow (exchange.id,"error checkLastPrice",'[Request Timeout] ' + e.message)
} else if (e instanceof ccxt.AuthenticationError) {
log.bright.yellow (exchange.id,"error checkLastPrice",'[Authentication Error] ' + e.message)
} else if (e instanceof ccxt.ExchangeNotAvailable) {
log.bright.yellow (exchange.id,"error checkLastPrice",'[Exchange Not Available Error] ' + e.message)
} else if (e instanceof ccxt.ExchangeError) {
log.bright.yellow (exchange.id,"error checkLastPrice",'[Exchange Error] ' + e.message)
} else if (e instanceof ccxt.NetworkError) {
log.bright.yellow (exchange.id,"error checkLastPrice",'[Network Error] ' + e.message)
} else if (e instanceof ccxt.InvalidNonce) {
// it has thrown the exception as expected
log.bright.yellow(exchange.id,"error checkLastPrice",'[InvalidNonce Error] ' + e.message)
} else if (e instanceof ccxt.OrderNotFound) {
// it has thrown the exception as expected
log.bright.yellow(exchange.id,"error checkLastPrice",'[OrderNotFound Error] ' + e.message)
} else if (e instanceof ccxt.InvalidOrder) {
// it has thrown the exception as expected
log.bright.yellow(exchange.id,"error checkLastPrice",'[InvalidOrder Error] ' + e.message)
} else if (e instanceof ccxt.InsufficientFunds) {
// it has thrown the exception as expected
log.bright.yellow(exchange.id,"error checkLastPrice",'[InsufficientFunds Error] ' + e.message)
}
}
}
log.bright(exchange.iso8601 (Date.now ()),exchange.id.green, "checkLastPrice completed", symbol, price, side)
}
//true for bid price -- false for ask
async function checkOrderbook(exchangeid, symbol) {
var exchange = exchanges[exchangeid]
log.bright(exchange.id.green, "checkOrderbook started", exchangeid)
if (!ARBITRAGE_ORDERBOOK_FILTER) return
var result = true;
let orderbook = await exchange.fetchOrderBook (symbol)
// let bid = orderbook.bids.length ? orderbook.bids[0][0] : undefined
// let ask = orderbook.asks.length ? orderbook.asks[0][0] : undefined
// let spread = (bid && ask) ? ask - bid : undefined
// let spreadPerc = (ask/bid -1)*100
// console.log (exchange.id, 'market price', { bid, ask, spread, spreadPerc })
var totalAsks=0, totalBids=0;
var maxTotalBidAmount = 0
var maxTotalAskAmount = 0
var maxBidAmount = 0
var maxAskAmount = 0
// for (var i =0;i<orderbook.bids.length; i++ ) {
for (var i =0;i<(SALESMAN_OB_LEVEL+1); i++ ) {
var priceBid = orderbook.bids[i][0]
var amountBid = orderbook.bids[i][1]
var partialTotalBid = priceBid*amountBid
if (i===0) {
maxBidAmount = partialTotalBid
maxTotalBidAmount = maxBidAmount
}
if (maxBidAmount < partialTotalBid) {
maxBidAmount = partialTotalBid;
maxTotalBidAmount=maxTotalBidAmount+maxBidAmount
}
totalBids = totalBids + (priceBid*amountBid)
if (DEBUG) {
log (exchange.iso8601 (Date.now ()),exchange.id.green,"orderbook BID price", priceBid, "amount", amountBid, "total", totalBids )
log.green(exchange.iso8601 (Date.now ()),exchange.id.green,"bid wall","price", priceBid,"amount", amountBid,"total", partialTotalBid )
}
}
for (var j =0;j<(ARBITRAGE_OB_LEVEL+1); j++ ) {
//for (var j =0;j<orderbook.asks.length; j++ ) {
var priceAsk = orderbook.asks[j][0]
var amountAsk = orderbook.asks[j][1]
var partialTotalAsk = priceAsk*amountAsk
if (j===0) {
maxAskAmount = partialTotalAsk
maxTotalAskAmount = maxAskAmount
}
if (maxAskAmount < partialTotalAsk) {
maxAskAmount = partialTotalAsk;
maxTotalAskAmount = maxTotalAskAmount + maxAskAmount
}
totalAsks = totalAsks + (priceAsk*amountAsk)
if (DEBUG) {
log.magenta(exchange.iso8601 (Date.now ()),exchange.id.green,"ask wall","price", priceAsk,"amount", amountAsk,"total", partialTotalAsk)
log (exchange.iso8601 (Date.now ()),exchange.id.green,"orderbook ASK price", priceAsk, "amount", amountAsk, "total", totalAsks )
}
}
var threshold = 0 //as CDC --- DEFINITO A CazzoDeCane
log.yellow(exchange.iso8601 (Date.now ()),exchange.id.green,"max bid amount",maxBidAmount.toString().green, "max total bid amount",maxTotalBidAmount.toString().green, "symbol", symbol )
log.yellow(exchange.iso8601 (Date.now ()),exchange.id.green,"max ask amount",maxAskAmount.toString().magenta, "max total ask amount",maxTotalAskAmount.toString().magenta, "symbol", symbol)
log.bright(exchange.id.green, "checkOrderbook totals bids", totalBids, "asks", totalAsks, "spread", totalAsks- totalBids, "result", (totalAsks- totalBids<0), "symbol", symbol )
var trednUp = (totalBids - totalAsks >threshold)?true:false
var pressionUp = (maxTotalBidAmount - maxTotalAskAmount > 0)?true:false
//return (totalAsks - totalBids<threshold)?true:false
return [trednUp, pressionUp]
}
async function fetchTickers() {
log.bright(ARBITRAGE_EXCHANGE.green, "fetchTickers started")
const exchange = exchanges[ARBITRAGE_EXCHANGE];
//const numParallelProcess = ARBITRAGE_EXCHANGE_WALLET_DIVIDER
// TODO: skip the iteration if there is an open order pending.
try {
for (var i=0;i<coinPairsMaster.length;i++) {
var symbol = coinPairsMaster[i]
var symbolMasterBase = symbol.slice(0,symbol.indexOf("/"))
for (var j=0;j<coinPairs.length;j++) {
amountFilled=0
let symbolPair = coinPairs[j]