Repository navigation
Expand file tree
/
Copy pathcrime-cdc2.js
More file actions
1436 lines (1294 loc) · 67.1 KB
/
Copy pathcrime-cdc2.js
File metadata and controls
1436 lines (1294 loc) · 67.1 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="crime-cdc2"
require('./settings-'+algo_namespace+'.js')();
const log4js = require('log4js');
// log the cheese logger messages to a file, and the console ones as well.
log4js.configure( {
appenders: {
file: {
type: 'file',
filename: 'logs/crime-'+algo_namespace+'.log',
maxLogSize: 10 * 1024 * 1024, // = 10Mb
numBackups: 25, // keep five backup files
compress: true, // compress the backups
encoding: 'utf-8',
pattern: 'yyyy-MM-dd-hh',
mode: 0o0640,
keepFileExt: true,
flags: 'a'
},
out: {
type: 'stdout'
}
},
categories: {
default: { appenders: ['file'], level: 'debug' }
}
});
const logger = log4js.getLogger();
const fs = require ('fs')
const functions = require ('./functions')
var database = require('./db-aca.js'); //sqllite3.x
var therocksqv = require ('./therocksqv.js')
require('./crime-ti.js')();
require('./crime-exchange.js')();
let coin_last= {}, coin_bid = {}, coin_ask = {}
var mainError = false
let fileCSV = ''; //opportunities enalbed
let fileStubCSV= '' //stub logging
var bootEnv = true; //load environment during the first launch
let result = {};
var accounts = require ('./credentials-1.json')
var symbols
var exchanges =[]
var markets={};
var exchanges_markets = []
var dateBuy, dateSell
let tradingFee_taker
let tradingFee_maker
//date1 the start of our age
var date1
var crime_account
var pricesBuy=[] //used for the exit criteria
var pricesSell=[] //used for the exit criteria
const exchangeId = TDC_EXCHANGE
const symbol =TDC_COIN
var profit = TDC_PROFIT
const stoploss= TDC_STOPLOSS
const stoploss_counter = TDC_STOPLOSS_COUNTER
const wallet_percentage = TDC_WALLET_QUANTITY_PERCENTAGE
const wallet_enabled=TDC_WALLET_ENABLED
const wallet_divider= TDC_WALLET_DIVIDER
const ohlcv_period = TDC_OHLCV_PERIOD
const coin_fee_autocharge = TDC_COIN_FEE_AUTOCHARGE
const coin_fee = TDC_COIN_FEE
const coin_fee_charge = TDC_COIN_FEE_CHARGE
const coin_fee_threshold = TDC_COIN_FEE_THRESHOLD
const ob_level = TDC_OB_LEVEL
const ob_filter = ORDERBOOK_FILTER
const direction = TDC_TREND_DIRECTIONL
const price_changed = TDC_PRICE_CHANGED
const stoploss_enabled= STOPLOSS_ENABLED
const spread_high_low_threshold = SPREAD_HIGH_LOW_THRESHOLD
const spread_hl_filter =SPREAD_HL_FILTER
const spread_hl_level =SPREAD_HIGH_LOW_LEVEL
const stoploss_timewindows = 1000 * 60 * STOPLOSS_TIMEWINDOWS
const ma_period = MA_PERIOD
const fibonacci_ohlcv_period = TDC_FIBONACCI_OHLCV_PERIOD
const coin_pair = COIN_PAIR
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 ]
module.exports = function () {
this.algo_namespace=algo_namespace
}
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(exchangeid) {
var timestamp = new Date().getTime();
fileCSV = './data/'+algo_namespace+'.'+exchangeid +'.'+ crime_account+'.'+ symbol +'.'+ new Date().getFullYear() +'.'+ (new Date().getMonth() +1)+'.'+new Date().getDate()+'.csv'; //opportunities enalbed
if (!fs.existsSync(fileCSV)) {
fs.appendFile(fileCSV, "datetime, symbol, open, high, low, close, volume",(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+'.'+exchangeid +'.'+ crime_account+'.'+ symbol +'.'+ new Date().getFullYear() +'.'+(new Date().getMonth() +1)+'.'+new Date().getDate()+'.csv'; //opportunities enalbed
if (!fs.existsSync(fileStubCSV)) {
fs.appendFile(fileStubCSV, "datetime, symbol, open, high, low, close, volume",(err) => {
if (err) log.red( err.message);
log.magenta('CSV created for writing the opportunity found during the arbitrage single exchange!!!')})
}
}
}
//fetch KPI every tot mins -- maybe the best is every tot + another tot mins.
async function checkKPIs(exchangeid, symbol, sync) {
log.bright(CDC2_EXCHANGE.green, "checkKPIs started", "sync",sync )
var date2 = new Date();
if (date2.getTime()>((date1.getTime())+ (1000*60*5))) {
await fetchKPIs(exchangeid, symbol, sync)
date1.setTime(new Date())
} else {
date2.setTime(new Date())
}
}
// fetch sync KPI: TIs and Volumes if needed
async function fetchKPIs(exchangeId, asset, sync) {
log.bright(exchangeId.green, "fetchKPIs started", "sync",sync)
if (sync){
await fetchTIs(exchanges[exchangeId],asset,ohlcv_period )
}
else {
fetchTIs(exchanges[exchangeId],asset, ohlcv_period )
}
}
async function rollbackSellOrder (exchangeid, symbol, priceBuy, orderSell) {
var exchange = exchanges[exchangeid]
log.bright(exchange.iso8601 (Date.now ()),exchange.id.green,algo_namespace.yellow, "rollebackSellOrder order id", orderSell.id, "symbol", symbol)
var result = true;
if (!stoploss_enabled) return result
await fetchTIs (exchange, symbol, ohlcv_period)
if (ADX_FILTER) {
var adxResult = await checkADX(exchangeid,symbol,10)
if (adxResult[0]) {
log.bright.red(exchange.iso8601(Date.now ()),exchange.id.green,algo_namespace.yellow, "ADX ti for (",symbol,") positive trend, skip the rollback on sell order",adxResult[0], adxResult[1])
return true;
}
}
if (RSI_FILTER) {
var rsiResult = await checkRSI(exchangeid, symbol, 10)
if (rsiResult[1]<RSI_OVERSOLD || rsiResult[0]) {
log.bright.red(exchange.iso8601(Date.now ()),exchange.id.green,algo_namespace.yellow, "RSI ti for (",symbol,") positive trend, skip the rollback on sell order",rsiResult)
return true;
}
}
try {
var price = orderSell.price
var filled = orderSell.filled
var status = orderSell.status
var amount = orderSell.amount
if (status==='open') {
// 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 ticker = await exchange.fetchTicker(symbol)
let bid = ticker['bid']
await ccxt.sleep (exchange.rateLimit)
let new_order
var ex_id_sell,ex_info_sell
var new_amount = amount-filled
//add an half of profit to the new price hoping to close the opportunity quickly
if (bid <= price * (1-stoploss)) {
await exchange.cancelOrder(orderSell.id, symbol)
await ccxt.sleep (exchange.rateLimit*2)
log.bright.yellow(exchange.iso8601 (Date.now ()),exchange.id.green,algo_namespace.yellow, "rollebackSellOrder sell order id",orderSell.id, "cancelled stoploss reached")
new_order = await exchange.createOrder (symbol,'limit', 'sell',new_amount, bid, {'recvWindow': 60000000})
ex_id_sell = new_order.id
ex_info_sell = JSON.stringify(new_order.info)
log.magenta(exchange.iso8601 (Date.now ()),exchange.id.green,algo_namespace.yellow, "rollebackSellOrder new_order","symbol",symbol, "id", ex_id_sell, "info",ex_info_sell )
extra = {
'rollbackSellOrder timestamp': exchange.iso8601 (Date.now ()),
'current bid': bid,
'price': price,
'stoploss reached':true
};
functions.addToLog(exchange,extra)
logger.debug("rollbackSellOrder timestamp",exchange.iso8601(Date.now()),"current bid",bid, 'price', price, "stoploss reached true");
await ccxt.sleep (exchange.rateLimit)
result = false
} else if ((bid < priceBuy) && (pricesSell.length<stoploss_counter)) {
pricesSell.push(bid)
result = true
if (pricesSell.length===stoploss_counter) {
await exchange.cancelOrder(orderSell.id, symbol)
await ccxt.sleep (exchange.rateLimit*2)
log.bright.yellow(exchange.iso8601 (Date.now ()),exchange.id.green,algo_namespace.yellow, "rollebackSellOrder sell order id",orderSell.id, "cancelled max price above the sell price reached")
new_order = await exchange.createOrder (symbol,'limit', 'sell', new_amount, bid, {'recvWindow': 60000000})
ex_id_sell = new_order.id
ex_info_sell = JSON.stringify(new_order.info)
log.magenta(exchange.iso8601 (Date.now ()),exchange.id.green,algo_namespace.yellow, "rollebackSellOrder new_order","symbol",symbol, "id", ex_id_sell, "info",ex_info_sell )
await ccxt.sleep (exchange.rateLimit)
logger.debug("rollbackSellOrder timestamp",exchange.iso8601(Date.now()),"current bid",bid, 'price', price, "stoploss reached true");
extra = {
'rollbackSellOrder timestamp': exchange.iso8601 (Date.now ()),
'current bid': bid,
'price': price,
'stoploss reached':true
};
functions.addToLog(exchange,extra)
result = false
}
} else {
log.bright.yellow(exchange.iso8601 (Date.now ()),exchange.id.green,algo_namespace.yellow, "rollebackSellOrder nothing to do for sell order id",orderSell.id, "price is in the buy and sell price","buy price", priceBuy, "bid", bid, "sell price", price)
result = true
}
}
}catch (e) {
log.red(exchange.iso8601 (Date.now ()),exchange.id.green,algo_namespace.yellow, "error during the rollebackSellOrder", orderSell.id, "error",e)
if (e instanceof ccxt.DDoSProtection || e.message.includes ('ECONNRESET')) {
log.bright.yellow (exchange.id,"error rollebackSellOrder",'[DDoS Protection] ' + e.message)
} else if (e instanceof ccxt.RequestTimeout) {
log.bright.yellow (exchange.id,"error rollebackSellOrder",'[Request Timeout] ' + e.message)
} else if (e instanceof ccxt.AuthenticationError) {
log.bright.yellow (exchange.id,"error rollebackSellOrder",'[Authentication Error] ' + e.message)
} else if (e instanceof ccxt.ExchangeNotAvailable) {
log.bright.yellow (exchange.id,"error rollebackSellOrder",'[Exchange Not Available Error] ' + e.message)
} else if (e instanceof ccxt.ExchangeError) {
log.bright.yellow (exchange.id,"error rollebackSellOrder",'[Exchange Error] ' + e.message)
} else if (e instanceof ccxt.NetworkError) {
log.bright.yellow (exchange.id,"error rollebackSellOrder",'[Network Error] ' + e.message)
} else if (e instanceof ccxt.InvalidNonce) {
log.bright.yellow(exchange.id,"error rollebackSellOrder",'[InvalidNonce Error] ' + e.message)
} else if (e instanceof ccxt.OrderNotFound) {
log.bright.yellow(exchange.id,"error rollebackSellOrder",'[OrderNotFound Error] ' + e.message)
} else if (e instanceof ccxt.InvalidOrder) {
log.bright.yellow(exchange.id,"error rollebackSellOrder",'[InvalidOrder Error] ' + e.message)
} else if (e instanceof ccxt.InsufficientFunds) {
log.bright.yellow(exchange.id,"error rollebackSellOrder",'[InsufficientFunds Error] ' + e.message)
}
}
return result
}
async function rollbackOrders (exchangeid, symbol, orderBuy, orderSell) {
var exchange = exchanges[exchangeid]
var result = true;
log.bright(exchange.iso8601 (Date.now ()),exchange.id.green,algo_namespace.yellow, "rollebackOrders ", "order buy", orderBuy.id, "order sell",orderSell.id)
try {
var priceBuy = orderBuy.price
var filledBuy = orderBuy.filled
var statusBuy = orderBuy.status
var amountBuy = orderBuy.amount
var priceSell = orderSell.price
var filledSell = orderSell.filled
var statusSell = orderSell.status
var amountSell = orderSell.amount
if (statusBuy==='open' && statusSell === 'open' && filledSell ===0 && filledBuy==0) {
if (filledSell === filledBuy) {
await exchange.cancelOrder(orderBuy.id, symbol)
await ccxt.sleep (exchange.rateLimit)
await exchange.cancelOrder(orderSell.id, symbol)
await ccxt.sleep (exchange.rateLimit)
log.bright.yellow(exchange.iso8601 (Date.now ()),exchange.id.green,algo_namespace.yellow, "order ids (",orderBuy.id, orderSell.id, ") cancelled")
result = false
extra = {
'rollbackOrders timestamp': exchange.iso8601 (Date.now ()),
'stoploss reached':true
};
functions.addToLog(exchange,extra)
logger.debug("rollbackOrders timestamp",exchange.iso8601(Date.now()), "stoploss reached true");
}
}
}
catch (e) {
log.red(exchange.iso8601 (Date.now ()),exchange.id.green,algo_namespace.yellow, "error during the rollebackOrders", orderBuy.id, orderSell.id, "error",e)
if (e instanceof ccxt.DDoSProtection || e.message.includes ('ECONNRESET')) {
log.bright.yellow (exchange.id,"error rollebackOrders",'[DDoS Protection] ' + e.message)
} else if (e instanceof ccxt.RequestTimeout) {
log.bright.yellow (exchange.id,"error rollebackOrders",'[Request Timeout] ' + e.message)
} else if (e instanceof ccxt.AuthenticationError) {
log.bright.yellow (exchange.id,"error rollebackOrders",'[Authentication Error] ' + e.message)
} else if (e instanceof ccxt.ExchangeNotAvailable) {
log.bright.yellow (exchange.id,"error rollebackOrders",'[Exchange Not Available Error] ' + e.message)
} else if (e instanceof ccxt.ExchangeError) {
log.bright.yellow (exchange.id,"error rollebackOrders",'[Exchange Error] ' + e.message)
} else if (e instanceof ccxt.NetworkError) {
log.bright.yellow (exchange.id,"error rollebackOrders",'[Network Error] ' + e.message)
} else if (e instanceof ccxt.InvalidNonce) {
log.bright.yellow(exchange.id,"error rollebackOrders",'[InvalidNonce Error] ' + e.message)
} else if (e instanceof ccxt.OrderNotFound) {
log.bright.yellow(exchange.id,"error rollebackOrders",'[OrderNotFound Error] ' + e.message)
} else if (e instanceof ccxt.InvalidOrder) {
log.bright.yellow(exchange.id,"error rollebackOrders",'[InvalidOrder Error] ' + e.message)
} else if (e instanceof ccxt.InsufficientFunds) {
log.bright.yellow(exchange.id,"error rollebackOrders",'[InsufficientFunds Error] ' + e.message)
}
result = true
}
return result
}
async function rollbackBuyOrder (exchangeid, symbol, order, priceSell) {
var exchange = exchanges[exchangeid]
log.bright(exchange.iso8601 (Date.now ()),exchange.id.green,algo_namespace.yellow, "rollebackBuyOrder order id", order.id)
var result = true;
if (!stoploss_enabled) return result
await fetchTIs (exchange, symbol, ohlcv_period)
if (ADX_FILTER) {
var adxResult = await checkADX(exchangeid,symbol,3 )
if (!adxResult[0]) {
log.bright.red(exchange.iso8601(Date.now ()),exchange.id.green,algo_namespace.yellow, "ADX ti for (",symbol,") says: negative trend, skip the rollback on sell order",adxResult[1], "adx trend",adxResult[0])
return result;
}
}
if (RSI_FILTER) {
var rsiResult = await checkRSI(exchangeid, symbol, 3)
if (rsiResult[1]>RSI_OVERBOUGHT-20 || !rsiResult[0]) {
log.bright.red(exchange.iso8601(Date.now ()),exchange.id.green,algo_namespace.yellow, "RSI ti for (",symbol,") says: negative trend, skip the rollback on sell order",rsiResult[1])
return result;
}
}
try {
var price = order.price
var filled = order.filled
var status = order.status
var amount = order.amount
let ticker = await exchange.fetchTicker(symbol)
let ask = ticker['ask']
let bid = ticker['bid']
var new_order
if (status==='open' && filled===0) {
await ccxt.sleep (exchange.rateLimit)
//add an half of profit to the new price hoping to close the opportunity quickly
if (ask >= price * (1+stoploss)) {
await exchange.cancelOrder(order.id, symbol)
await ccxt.sleep (exchange.rateLimit)
log.bright.yellow(exchange.iso8601 (Date.now ()),exchange.id.green,algo_namespace.yellow, "rollbackBuyOrder buy order id",order.id, "cancelled stoploss reached")
result = false
extra = {
'rollbackBuyOrder timestamp': exchange.iso8601 (Date.now ()),
'current ask': ask,
'price': price,
'stoploss reached':true
};
functions.addToLog(exchange,extra)
logger.debug("rollbackBuyOrder timestamp",exchange.iso8601(Date.now()),"current ask",ask, 'price', price, "stoploss reached true ");
} else if ((ask > priceSell) && (pricesBuy.length<stoploss_counter)) {
pricesBuy.push(ask)
log.bright.yellow(exchange.iso8601 (Date.now ()),exchange.id.green,algo_namespace.yellow, "rollbackBuyOrder new ask prices",ask," pushed on pricesBuy" )
if (pricesBuy.length===stoploss_counter) {
await exchange.cancelOrder(order.id, symbol)
await ccxt.sleep (exchange.rateLimit)
log.bright.yellow(exchange.iso8601 (Date.now ()),exchange.id.green,algo_namespace.yellow, "rollbackBuyOrder buy order id",order.id, "cancelled max ask price above the sell price reached")
result = false
} else {
result = true
}
} else {
log.bright.yellow(exchange.iso8601 (Date.now ()),exchange.id.green,algo_namespace.yellow, "rollbackBuyOrder nothing to do for buy order id",order.id, "ask price is in the buy and sell price","buy price", price, "ask price", ask, "sell price", priceSell)
result = true
}
} else {
if (bid >= price * (1+0.0015)) {
await exchange.cancelOrder(order.id, symbol)
await ccxt.sleep (exchange.rateLimit*2)
log.bright.yellow(exchange.iso8601 (Date.now ()),exchange.id.green,algo_namespace.yellow, "rollbackBuyOrder buy order id",order.id, "cancelled stoploss reached")
new_order = await exchange.createOrder (symbol,'limit', 'sell',filled, bid, {'recvWindow': 60000000})
ex_id_sell = new_order.id
ex_info_sell = JSON.stringify(new_order.info)
log.green(exchange.iso8601 (Date.now ()),exchange.id.green,algo_namespace.yellow, "rollbackBuyOrder sell order executed symbol",symbol, "to this price", bid, "id", ex_id_sell, "info",ex_info_sell )
logger.debug("rollbackBuyOrder timestamp",exchange.iso8601(Date.now()),"current bid",bid, 'price', price, "stoploss reached true ");
extra = {
'rollbackBuyOrder timestamp': exchange.iso8601 (Date.now ()),
'current bid': bid,
'price': price,
'stoploss reached':true
};
functions.addToLog(exchange,extra)
result = false
}
}
}catch (e) {
log.red(exchange.iso8601 (Date.now ()),exchange.id.green,algo_namespace.yellow, "error rollebackBuyOrder", order.id, "error",e)
if (e instanceof ccxt.DDoSProtection || e.message.includes ('ECONNRESET')) {
log.bright.yellow (exchange.id,"error rollbackBuyOrder",'[DDoS Protection] ' + e.message)
} else if (e instanceof ccxt.RequestTimeout) {
log.bright.yellow (exchange.id,"error rollbackBuyOrder",'[Request Timeout] ' + e.message)
} else if (e instanceof ccxt.AuthenticationError) {
log.bright.yellow (exchange.id,"error rollbackBuyOrder",'[Authentication Error] ' + e.message)
} else if (e instanceof ccxt.ExchangeNotAvailable) {
log.bright.yellow (exchange.id,"error rollbackBuyOrder",'[Exchange Not Available Error] ' + e.message)
} else if (e instanceof ccxt.ExchangeError) {
log.bright.yellow (exchange.id,"error rollbackBuyOrder",'[Exchange Error] ' + e.message)
} else if (e instanceof ccxt.NetworkError) {
log.bright.yellow (exchange.id,"error rollbackBuyOrder",'[Network Error] ' + e.message)
} else if (e instanceof ccxt.InvalidNonce) {
log.bright.yellow(exchange.id,"error rollbackBuyOrder",'[InvalidNonce Error] ' + e.message)
} else if (e instanceof ccxt.OrderNotFound) {
log.bright.yellow(exchange.id,"error rollbackBuyOrder",'[OrderNotFound Error] ' + e.message)
} else if (e instanceof ccxt.InvalidOrder) {
log.bright.yellow(exchange.id,"error rollbackBuyOrder",'[InvalidOrder Error] ' + e.message)
} else if (e instanceof ccxt.InsufficientFunds) {
log.bright.yellow(exchange.id,"error rollbackBuyOrder",'[InsufficientFunds Error] ' + e.message)
}
result = true
}
return result
}
//return true if order executed succesful false otherwise
async function checkFillOrder(exchange ,symbol,orderid, orderidsell, priceBuy, priceSell) {
log.bright(exchange.iso8601 (Date.now ()),exchange.id.green,algo_namespace.yellow, "checkFillOrder started for", symbol,"buy order id", orderid, "sell order id",orderidsell, "stoploss enabled", stoploss_enabled)
var dateFill = new Date()
var processedBuy = false
var processedSell = false
var boBuy = false
var boSell = false
var buyOrder, sellOrder
var found = true
var orders
//inizialazed variables
pricesBuy = []
pricesSell = []
while (found) {
try {
orders = await exchange.fetchOpenOrders (symbol,undefined,undefined, {'recvWindow': 60000000})
await ccxt.sleep (exchange.rateLimit)
found=false
boBuy = false;
boBuy = false;
for (var j=0;j<orders.length;j++) {
var order = orders[j]
if (orderid===order.id || orderidsell===order.id){
if (DEBUG) {
log.bright.magenta(exchange.iso8601 (Date.now ()),exchange.id.green,algo_namespace.yellow, "order(s) found...still pending")
log.bright.magenta(exchange.iso8601 (Date.now ()),exchange.id.green,algo_namespace.yellow, "order.amount", order.amount)
log.bright.magenta(exchange.iso8601 (Date.now ()),exchange.id.green,algo_namespace.yellow, "order.cost", order.cost)
log.bright.magenta(exchange.iso8601 (Date.now ()),exchange.id.green,algo_namespace.yellow, "order.price", order.price)
log.bright.magenta(exchange.iso8601 (Date.now ()),exchange.id.green,algo_namespace.yellow, "order.filled", order.filled)
log.bright.magenta(exchange.iso8601 (Date.now ()),exchange.id.green,algo_namespace.yellow, "order.status", order.status)
log.bright.magenta(exchange.iso8601 (Date.now ()),exchange.id.green,algo_namespace.yellow, "order.fee", order.fee)
log.bright.magenta(exchange.iso8601 (Date.now ()),exchange.id.green,algo_namespace.yellow, "order.side", order.side)
}
found=true
if (order.side === 'buy') {
boBuy = true;
buyOrder = order
} else {
boSell = true;
sellOrder = order
}
}
}
//Checking for rollback actions
if (dateFill.getTime()>(dateBuy.getTime()+ (stoploss_timewindows))) {
log.bright.cyan(exchange.iso8601 (Date.now ()),"start rollback if it is possibile","buy order", boBuy, "sell order", boSell )
if (boBuy && boSell) {
found = rollbackOrders(exchange.id,symbol, buyOrder, sellOrder)
} else if (boBuy && !boSell) {
found = rollbackBuyOrder(exchange.id,symbol, buyOrder, priceSell)
} else if (!boBuy && boSell) {
found = rollbackSellOrder(exchange.id,symbol, priceBuy, sellOrder)
}
dateFill.setTime(new Date())
dateBuy.setTime(new Date())
} else {
dateFill.setTime(new Date())
}
}
catch (e) {
log.bright.red (exchange.id,"error checkFillOrder",e.message, "Try to retrieve 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) {
log.bright.yellow(exchange.id,"error checkFillOrder",'[InvalidNonce Error] ' + e.message)
} else if (e instanceof ccxt.OrderNotFound) {
log.bright.yellow(exchange.id,"error checkFillOrder",'[OrderNotFound Error] ' + e.message)
} else if (e instanceof ccxt.InvalidOrder) {
log.bright.yellow(exchange.id,"error checkFillOrder",'[InvalidOrder Error] ' + e.message)
} else if (e instanceof ccxt.InsufficientFunds) {
log.bright.yellow(exchange.id,"error checkFillOrder",'[InsufficientFunds Error] ' + e.message)
}
found = true
// orders = await exchange.fetchOpenOrders (symbol,undefined,undefined, {'recvWindow': 60000000})
// await ccxt.sleep (exchange.rateLimit)
}
}
log.bright(exchange.iso8601 (Date.now ()),exchange.id.green,algo_namespace.yellow, "checkFillOrder completed for", symbol, "order(",orderid,",",orderidsell,") closed", found)
return found;
}
//see:http://www.metastocktools.com/downloads/turtlerules.pdf
async function fetchTickers(exchangeid, assets) {
const exchange = exchanges[exchangeid];
log.bright(exchange.iso8601 (Date.now ()),exchange.id.green,algo_namespace.yellow, "fetchTickers started")
// TODO: skip the iteration if there is an open order pending.
var asset
var amount
var transaction_id
//log.red("exchange",exchange.id,"assets", assets, "account", crime_account);
try {
for (var j=0;j<assets.length;j++) {
asset = assets[j][0]
var trend
var details, extra
details = {
'exchange': exchangeid,
'asset': asset,
'account': crime_account,
};
functions.addToLog(exchange,asset, details,true)
logger.debug(" ");
logger.debug("exchange",exchangeid,"asset", asset, "account", crime_account);
log.bright(exchange.iso8601 (Date.now ()),exchange.id.green,algo_namespace.yellow, "fetchTickers asset", asset)
transaction_id = "CRIME_"+ algo_namespace + "_" + new Date().getTime()
var _profit ="0%"
var result = false
var ex_id_buy=null, ex_info_buy, ex_error_buy, ex_error;
var ex_id_sell=null, ex_info_sell, ex_error_sell;
var cashOut, cashIn
var textCSV
var coin_db = coin_pair + '_' + algo_namespace
var selectOpp = await database.selectOpportunities (crime_account, exchange.id, coin_db)
var orderPending = selectOpp.rows_length;
if (VOLUME_FILTER) {
var usdVolume = await calculateUSDTVolume(exchange,asset)
extra = {
'volume': usdVolume,
'volume thresold': VOLUME_THRESHOLD,
};
functions.addToLog(exchange,extra)
logger.debug("volume",usdVolume,"volume thresold", VOLUME_THRESHOLD);
if (isNaN(usdVolume) || usdVolume < VOLUME_THRESHOLD ) {
log.bright.red(exchange.iso8601(Date.now ()),exchange.id.green,algo_namespace.yellow, "skip the following assets",asset)
log.bright.red(exchange.iso8601(Date.now ()),exchange.id.green,algo_namespace.yellow, "volumes below the threshold[",VOLUME_THRESHOLD,"]",usdVolume)
continue;
}
}
await fetchTIs(exchange, asset, ohlcv_period)
var candlesticks = fetchOHLCV().slice(-2)
var close, open, low, high
var p_close, p_open, p_low, p_high
const previousCS = candlesticks[0]
const currentCS = candlesticks[1]
var rsi = await checkRSI(exchange.id,asset )
var adx = await checkADX(exchange.id,asset,10 )
var bb = await checkBB(exchange.id,asset, 15)
var mom = await checkMOM(exchange.id,asset, 15)
var ma = await checkMA(exchange.id,asset, 15)
var ema = await checkEMA(exchange.id,asset, 15)
var wma = await checkWMA(exchange.id,asset, 15)
var atr = await checkATR(exchange.id,asset, 15)
var fp = await checkFloorPivots(exchange.id,asset, 15)
var tdp = await checkTomDemarksPoints(exchange.id,asset, 15)
var woodies = await checkWoodiesPoints(exchange.id,asset, 15)
var fibonacci = await checkFibonacci(exchange.id,asset, 15)
var macd = await checkMACD(exchange.id,asset)
var stochastic = await checkKD(exchange.id,asset)
if (adx === undefined) {
adx = []
adx[0]=undefined
adx[1]=undefined
}
if (DEBUG) {
log.green("kpi RSI TI", rsi)
log.green("kpi ADX TI", adx)
log.green("kpi BB TI", bb)
log.green("kpi mom TI", mom)
log.green("kpi ma TI", ma)
log.green("kpi ema TI", ma)
log.green("kpi wma TI", wma)
log.green("kpi atr TI", atr)
log.green("kpi MACD TI", macd)
log.green("kpi Stochastic TI", stochastic)
log.green("kpi FloorPivots TI", fp)
log.green("kpi TomDemarks TI", tdp)
log.green("kpi Woodies TI", woodies)
log.green("kpi fibonacci TI", fibonacci)
log.green("bullshift" , isBullish())
}
if (adx === undefined) {
adx = []
adx[0]=undefined
adx[1]=undefined
}
if (macd === undefined) {
macd = []
macd[0]=undefined
macd[1]=undefined
}
if (rsi === undefined) {
rsi = []
rsi[0]=undefined
rsi[1]=undefined
}
if (bb === undefined) {
bb = []
bb[0]=undefined
bb[1]=undefined
bb[2]=undefined
bb[3]=undefined
}
if (stochastic === undefined) {
stochastic = []
stochastic[0]=undefined
stochastic[1]=undefined
stochastic[2]=undefined
stochastic[3]=undefined
}
extra = {
'macd': macd[1],
'rsi': rsi[1],
'rsi-trend': rsi[0],
'mom': mom[1],
'ma': ma[1],
'ema': ema[1],
'wma': wma[1],
'atr': atr[1],
'macd': macd[1],
'adx': adx[1],
'adx-result': adx[0],
'bb' : bb[3],
'stochastic-kd': stochastic[0],
'stochastic-kd-data': stochastic[1],
'bullish' : isBullish(),
'fibonacci-up':fibonacci[0],
'fibonacci-down':fibonacci[1],
};
functions.addToLog(exchange,extra)
functions.logToFile(exchange.id,symbol,algo_namespace)
logger.debug("extra",extra);
if (ADX_FILTER) {
//check if we are in uptrend market leveraging on ADX indicator
if (adx === undefined || adx[0] === undefined ) {
log.bright.red(exchange.iso8601(Date.now ()),exchange.id.green,algo_namespace.yellow,algo_namespace.yellow, "skip the following assets",symbol )
log.bright.red(exchange.iso8601(Date.now ()),exchange.id.green,algo_namespace.yellow, "ti ADX check is undefined. No trend found",adx[1])
continue;
}
if (adx[1]<ADX_LEVEL_4 -5 || !adx[0]){
//skip the opportunitiy if the market is lateral
log.bright.red(exchange.iso8601(Date.now ()),exchange.id.green,algo_namespace.yellow, "skip the following assets",asset )
log.bright.red(exchange.iso8601(Date.now ()),exchange.id.green,algo_namespace.yellow, "ti ADX below the threshold and not alingend to trend: result ",adx[1], "adx trend", adx[0])
continue
}
if (adx[0]) {
trend = 'up'
} else {
trend = 'down'
}
}
if (RSI_FILTER) {
log.yellow()
//check if we are in uptrend market leveraging on RSI indicator
if ((rsi[1]>RSI_OVERBOUGHT-10 && !rsi[0]) || (rsi[1]>RSI_OVERBOUGHT-10 && rsi[0]===undefined) ){
//skip the opportunitiy if the market is lateral
log.bright.red(exchange.iso8601(Date.now ()),exchange.id.green,algo_namespace.yellow, "skip the following assets",asset )
log.bright.red(exchange.iso8601(Date.now ()),exchange.id.green,algo_namespace.yellow, "ti RSI not alingend to trend: result ",rsi)
continue
}
if (!isBullish()) {
log.bright.red(exchange.iso8601(Date.now ()),exchange.id.green,algo_namespace.yellow, "skip the following assets",asset )
log.bright.red(exchange.iso8601(Date.now ()),exchange.id.green,algo_namespace.yellow, "bullshift",isBullish())
continue
} else if (isBullish() && trend==='up') {
trend = 'up'
}
}
if (MA_FILTER) {
close = currentCS[indexClose]
open = currentCS[indexOpen]
low = currentCS[indexLow]
high = currentCS[indexHigh]
if (ma[0] && trend==='up') {
trend = 'up'
} else if (!ma[0] && trend==='down') {
trend = 'down'
continue
} else {
log.bright.red(exchange.iso8601(Date.now ()),exchange.id.green,algo_namespace.yellow, "skip the following assets",asset )
log.bright.red(exchange.iso8601(Date.now ()),exchange.id.green,algo_namespace.yellow, "ma",ma)
continue
}
}
if (MACD_FILTER ) {
if (macd[0] && trend==='up') {
trend = "up"
} else if (!macd[0] && trend==='down'){
log.bright.red(exchange.iso8601(Date.now ()),exchange.id.green,algo_namespace.yellow, "skip the following assets",asset )
log.bright.red(exchange.iso8601(Date.now ()),exchange.id.green,algo_namespace.yellow, "macd",macd,"trend",trend )
trend = "down"
continue;
} else {
log.bright.red(exchange.iso8601(Date.now ()),exchange.id.green,algo_namespace.yellow, "skip the following assets",asset )
log.bright.red(exchange.iso8601(Date.now ()),exchange.id.green,algo_namespace.yellow, "macd",macd,"trend",trend )
continue;
}
}
if (KD_FILTER) {
if (stochastic[0] && trend==='up') {
trend = "up"
} else if (!stochastic[0] && trend==='down'){
log.bright.red(exchange.iso8601(Date.now ()),exchange.id.green,algo_namespace.yellow, "skip the following assets",asset )
log.bright.red(exchange.iso8601(Date.now ()),exchange.id.green,algo_namespace.yellow, "stochastic", stochastic,"trend",trend )
//trend = "down"
continue;
} else {
log.bright.red(exchange.iso8601(Date.now ()),exchange.id.green,algo_namespace.yellow, "skip the following assets",asset )
log.bright.red(exchange.iso8601(Date.now ()),exchange.id.green,algo_namespace.yellow, "stochastic", stochastic,"trend",trend )
continue;
}
}
if (BB_FILTER) {
/**
In linea di massima quando i prezzi salgono per andare a contatto con la banda superiore,
si ha la conferma di un trend rialzista,
mentre quando invece i prezzi scendono verso la banda inferiore si conferma la presenza di un trend ribassista.
In questi casi possiamo ricevere un segnale di inversione del trend,
nel caso in cui il prezzo esce dalla banda superiore per poi rientrarci (segnale ribassista),
oppure se il prezzo sfonda la banda inferiore per poi rientrarci (segnale di acquisto).
Riceviamo un SEGNALE DI ACQUISTO quando:
1) Il prezzo "sfonda" la banda di Bollinger inferiore
2) Lo Stocastico è in condizione di ipervenduto o la sta lasciando spostandosi verso l'alto.
3) Siamo in presenza di un pattern candelstick di inversione bullish (doji, bullish harami, morning star, bullish engulfing, hammer, etc - vedi l'elenco dei pattern)
Se siamo in presenza di queste condizioni, si può piazzare un buy stop order 2-5pips sopra il massimo di quel pattern di inversione rialzista. Quello sarà il nostro punto di ingresso.
Viceversa, riceviamo un SEGNALE DI VENDITA quando:
1) Il prezzo "sfonda" la banda di Bollinger superiore
2) Lo Stocastico è in condizione di ipercomprato o la sta lasciando spostandosi verso il basso.
3) Siamo in presenza di un pattern candelstick di inversione bearish (come ad esempio doji, bearish harami, evening star, bearish engulfing, hammer, etc - vedi l'elenco dei pattern)
Se siamo in presenza di queste condizioni, si può piazzare un sell stop order 2-5pips sotto il minimo di quel pattern di inversione rialzista. Quello sarà il nostro punto di ingresso.
*/
close = currentCS[indexClose]
open = currentCS[indexOpen]
low = currentCS[indexLow]
high = currentCS[indexHigh]
p_close = previousCS[indexClose]
p_open = previousCS[indexOpen]
p_low = previousCS[indexLow]
p_high = previousCS[indexHigh]
//current BB
var bb_lower = functions.priceToPrecision(exchange.id,markets, symbol,bb[3].lower)
var bb_middle = functions.priceToPrecision(exchange.id,markets, symbol,bb[3].middle)
var bb_upper = functions.priceToPrecision(exchange.id,markets, symbol,bb[3].upper)
//previous BB
var previous_bb_lower = functions.priceToPrecision(exchange.id,markets, symbol,bb[4].lower)
var previous_bb_middle = functions.priceToPrecision(exchange.id,markets, symbol,bb[4].middle)
var previous_bb_upper = functions.priceToPrecision(exchange.id,markets, symbol,bb[4].upper)
if (high >= bb_upper && low > bb_middle && trend==='down' ) {
log.bright.red(exchange.iso8601(Date.now ()),exchange.id.green,algo_namespace.yellow, "skip the following assets",symbol )
log.bright.red(exchange.iso8601(Date.now ()),exchange.id.green,algo_namespace.yellow, "ti BB is not alignet to the trend",bb, "high", high, "low", low)
await ccxt.sleep (exchange.rateLimit)
continue;
trend = "down"
} else if (low<= bb_lower && high < bb_middle && trend==='up' ) {
log.bright(exchange.iso8601(Date.now ()),exchange.id.green,algo_namespace.yellow, "trend changed by BB previous", trend, "current UP")
trend = "up"
} else {
log.bright.red(exchange.iso8601(Date.now ()),exchange.id.green,algo_namespace.yellow, "skip the following assets",symbol )
log.bright.red(exchange.iso8601(Date.now ()),exchange.id.green,algo_namespace.yellow, "ti BB is not alignet to the trend",bb, "high", high, "low", low)
await ccxt.sleep (exchange.rateLimit)
continue;
}
}
//results ::=[result, master_wallet, quantity]
var results = await checkBalances(exchange,coin_fee_autocharge, coin_fee,symbol, wallet_percentage)
var quantity = results[2]
var master_wallet = results[1]
if (!results[0]) continue
quantity = quantity / (wallet_divider - orderPending)
log.bright(exchange.iso8601(Date.now ()),exchange.id.green,algo_namespace.yellow, "fetchTickers percentage [",wallet_percentage,"] of wallet available based on order pending [",orderPending,"] wallet divider [", wallet_divider, "] quantity [",quantity, "]")
var priceBuy, priceSell, priceClose,priceLast,priceBid,priceAsk, priceOpen, priceLow, priceHigh
const ticker = await exchange.fetchTicker(asset);
var strongTrend = false
priceBuy = ticker['last'] //as default
priceSell = ticker['last'] //as default
priceLast = ticker['last']
priceAsk = ticker['ask']
priceBid = ticker['bid']
priceLast = functions.priceToPrecision(exchange.id,markets, asset,priceLast)
priceClose = functions.priceToPrecision(exchange.id,markets, asset,ticker['close'])
priceOpen = functions.priceToPrecision(exchange.id,markets, asset,ticker['open'])
priceLow = functions.priceToPrecision(exchange.id,markets, asset,ticker['low'])
priceHigh = functions.priceToPrecision(exchange.id,markets, asset,ticker['high'])
if (SPREAD_FILTER) {
var spreadBidAsk = ticker['ask'] - ticker['bid']
if (spreadBidAsk > SPREAD_THRESHOLD) {
log.bright.red(exchange.iso8601(Date.now ()),exchange.id.green,algo_namespace.yellow, "skip the following assets",asset )
log.bright.red(exchange.iso8601(Date.now ()),exchange.id.green,algo_namespace.yellow, "spread ",spreadBidAsk.toString().magenta,"below the threshold",SPREAD_THRESHOLD)
await ccxt.sleep (exchange.rateLimit)
continue;
}
extra = {
'spreadBidAsk': spreadBidAsk,
'spread threshold': SPREAD_THRESHOLD,
};
functions.addToLog(exchange,extra)
}
if (trend==='down'){
strongTrend = true
priceBuy = ticker['ask'] * (1 - profit);
priceSell = ticker['ask']
log.bright.red(exchange.iso8601(Date.now ()),exchange.id.green,algo_namespace.yellow, "skip the following assets",asset )
log.bright.red(exchange.iso8601(Date.now ()),exchange.id.green,algo_namespace.yellow, "trend down".magenta)
await ccxt.sleep (exchange.rateLimit)
// continue;
} else if (trend==='up'){
if (ADX_FILTER) {
if (adx[1]>=ADX_LEVEL_5-5){
strongTrend = true
profit = functions.fetchProfit (priceAsk, profit, markets[exchange.id][asset].precision.price )
priceBuy = ticker['ask']
priceSell = ticker['ask'] * (1 + profit)
if (exchange.id==='gdax' || exchange.id==='coinbaseprime' || exchange.id==='coinbasepro' || exchange.id==='coinbase' ) {
priceBuy = priceBuy * (1 + SLIPPAGE_ALLOWED)
priceSell = priceSell * (1 + SLIPPAGE_ALLOWED)
}
} else {
profit = functions.fetchProfit (priceLast, (profit/2), markets[exchange.id][asset].precision.price )
priceBuy = priceLast * (1 - profit);
priceSell = priceLast * (1 + profit);
profit=profit*2
}
} else if (!ADX_FILTER && RSI_FILTER) {
if (rsi[1]<=RSI_OVERSOLD-5) {
strongTrend = true
profit = functions.fetchProfit (priceAsk, profit, markets[exchange.id][asset].precision.price )
priceBuy = ticker['ask']
priceSell = ticker['ask'] * (1 + profit)
if (exchange.id==='gdax' || exchange.id==='coinbaseprime' || exchange.id==='coinbasepro' || exchange.id==='coinbase' ) {
priceBuy = priceBuy * (1 + SLIPPAGE_ALLOWED)
priceSell = priceSell * (1 + SLIPPAGE_ALLOWED)
}
} else {
profit = functions.fetchProfit (priceLast, (profit/2), markets[exchange.id][asset].precision.price )
priceBuy = priceLast * (1 - profit);
priceSell = priceLast * (1 + profit);
profit=profit*2
}
} else { //TODO: TO BE COMLETED ALL cases
profit = functions.fetchProfit (priceLast, (profit/2), markets[exchange.id][asset].precision.price )
priceBuy = priceLast * (1 - profit);
priceSell = priceLast * (1 + profit);
profit=profit*2
}
} else {
profit = functions.fetchProfit (priceLast, (profit/2), markets[exchange.id][asset].precision.price )
priceBuy = priceLast * (1 - profit);
priceSell = priceLast * (1 + profit);
profit=profit*2
}
//resistence::=[rResult, sResult,priceBuy, priceSell ]
// var resistence = await checkResistenceSupport(exchange, priceAsk,priceBid, priceLast, fibonacci )
// if (resistence[0] && resistence[1]) {
// priceBuy = resistence[2]
// priceSell = resistence[3]
// } else {
// continue;
// }
priceBuy = functions.priceToPrecision(exchange.id,markets, asset,priceBuy)
priceSell = functions.priceToPrecision(exchange.id,markets, asset,priceSell)
amount = (quantity / priceBuy)
amount = amount - (amount * tradingFee_maker)
amount = functions.amountToPrecision(exchange.id,markets, asset, amount )
extra = {
'trend': trend,
'strongTrend': strongTrend,
'priceLast': priceLast,
'priceAsk': priceAsk,
'priceBid': priceBid,
'priceClose': priceClose,
'priceBuy': priceBuy,
'priceSell': priceSell,
'quantity': quantity,
'amount (quantity/buy)': amount,