-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathanalisi.js
1249 lines (919 loc) · 45.9 KB
/
analisi.js
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
const dotenv = require('dotenv');
dotenv.config();
global.http = require('http');
global.https = require('https');
global.express = require('express');
global.EMA = require('technicalindicators').EMA;
global.RSI = require('technicalindicators').RSI;
global.BB = require('technicalindicators').BollingerBands;
//------------------------------------------- INIZIO BINANCE
let binance_api_status = false;
//const Binance = require('node-binance-api-testnet');
const Binance = require('node-binance-api');
let binance;
async function initializeBinanceAPI() {
binance_api_status = true;
binance = new Binance().options({
APIKEY: process.env.BINANCE_FUTURES_TESTNET_KEY,
APISECRET: process.env.BINANCE_FUTURES_TESTNET_SECRET
});
await binance.futuresLeverage('BTCUSDT', 5);
}
//nella one way mode, se shorti va negativo, e se longhi va positivo l'ammontare
//ma la positionSide è sempre BOTH
async function currency_conversion(currency_pair_1, currency_pair_2, currency_pair_2_amount) {
if (currency_pair_2 === "USD") {
currency_pair_2 = "USDT";
}
//restituisce la somma di currency_pair_1 ottenuta pagando con currency_pair_2
let currency_pair_1_price = await binance_future_price(currency_pair_1, currency_pair_2);
return currency_pair_2_amount / currency_pair_1_price;
}
async function binance_future_price(currency_pair_1, currency_pair_2) {
if (currency_pair_2 === "USD") {
currency_pair_2 = "USDT";
}
let futurePrices = await binance.futuresPrices();
//console.log("MARK PRICE", await binance.futuresMarkPrice(currency_pair_1 + currency_pair_2));
//console.info("QUOTE", await binance.futuresQuote("BCHUSDT"));
return futurePrices[currency_pair_1 + currency_pair_2];
}
async function binance_future_wallet_balance(currency_pair_2) {
if (currency_pair_2 === "USD") {
currency_pair_2 = "USDT";
}
let futuresBalance = await binance.futuresBalance();
let USDTBalance = futuresBalance.filter(word => word.asset === currency_pair_2);
if (USDTBalance[0]) {
return USDTBalance[0].availableBalance;
} else {
return 0;
}
}
async function binance_future_opened_position(currency_pair_1, currency_pair_2, message) {
if (currency_pair_2 === "USD") {
currency_pair_2 = "USDT";
}
let futuresPositions = await binance.futuresPositionRisk();
let BTCUSDTPosition = futuresPositions.filter(word => word.symbol === currency_pair_1 + currency_pair_2);
//BTCUSDTPosition.forEach((v) => {
if (message != undefined) {
console.log("FUTURES POSITIONS", message, BTCUSDTPosition);
}
if (BTCUSDTPosition[0]) {
return BTCUSDTPosition[0].positionAmt;
} else {
return 0;
}
}
//stop loss and take profit
//https://github.com/jaggedsoft/node-binance-api/issues/754
//nelle closeposition non serve il reduceOnly perchè già si presume.
//il reduceOnly serve solo quando si riduce la posizione, ma non del tutto, o anche del tutto, ma senza chiudera
//se è chiusa è ovvio che viene ridotta del 100%
//infatti controllando mette da solo il reduce only. in teoria non andrebbe neanche impostata la quantità da ridurre ma funziona uguale
async function binance_future_buy(currency_pair_1, currency_pair_2, /*quantity,*/
limit = 0, take_profit = 0, stop_loss_perc = 0, actual_price = 0, trailing_stop_percent = 0, take_profit_percent = 0) {
if (currency_pair_2 === "USD") {
currency_pair_2 = "USDT";
}
limit = limit.toFixed(0);
take_profit = take_profit.toFixed(0);
let invested_amount = await binance_future_wallet_balance(currency_pair_2);
let quantity = await currency_conversion(currency_pair_1, currency_pair_2, invested_amount / 100);
quantity = quantity.toFixed(3);
//temporaneo
quantity = '0.001';
//chiude se ci sono sell
let opened_position = await binance_future_opened_position(currency_pair_1, currency_pair_2);
console.log("BUY DEBUG", invested_amount, quantity, currency_pair_1, currency_pair_2, limit, opened_position);
let close_qty = 0;
if (opened_position < 0) {
console.log("CLOSE SELL POSITION", currency_pair_1 + currency_pair_2, opened_position * -1);
close_qty += Math.abs(opened_position);
console.info(await binance.futuresMarketBuy(currency_pair_1 + currency_pair_2, close_qty.toFixed(3), {
type: "MARKET",
priceProtect: true,
reduceOnly: true,
//workingType: 'MARK_PRICE',
//closePosition: true
}));
}
if (opened_position <= 0) {
binance.futuresCancelAll(currency_pair_1 + currency_pair_2);
//let size = parseFloat(quantity) + parseFloat(close_qty);
console.log("SEND BUY", currency_pair_1 + currency_pair_2, quantity /*+ close_qty*/ );
console.info(await binance.futuresMarketBuy(currency_pair_1 + currency_pair_2, quantity
/*, {
workingType: 'MARK_PRICE',
}*/
));
//se arriva allo stop loss deve vendere per chiudere la posizione in long
if (stop_loss_perc > 0) {
//quantity è in currency pair 1, limit in currency pair 2
console.log("SET BUY STOP LOSS", currency_pair_1 + currency_pair_2, quantity, limit);
//console.info(await binance.futuresSell(currency_pair_1 + currency_pair_2, quantity, limit));
console.log(await binance.futuresMarketSell(currency_pair_1 + currency_pair_2, quantity, {
type: "STOP_MARKET",
stopPrice: (parseFloat(actual_price) / 100 * (100 - stop_loss_perc)).toFixed(0),
priceProtect: true,
reduceOnly: true,
/* workingType: 'MARK_PRICE',*/
//closePosition: true
}));
}
if (trailing_stop_percent > 0) {
console.log("SET BUY TAKE PROFIT", currency_pair_1 + currency_pair_2, quantity, take_profit);
console.log(await binance.futuresMarketSell(currency_pair_1 + currency_pair_2, quantity, {
//newClientOrderId: my_order_id_tp,
stopPrice: (parseFloat(actual_price) / 100 * (100 + take_profit_percent)).toFixed(0),
type: "TAKE_PROFIT_MARKET",
//timeInForce: "GTC",
priceProtect: true,
//reduceOnly: true,
closePosition: true
}));
/*if (trailing_stop_percent < 0.1) {
console.log("FORZATURA STOP LOSS BUY");
trailing_stop_percent = 0.1;
}
console.log("TAKE PROFIT BUY", currency_pair_1 + currency_pair_2, 'quantity', quantity, 'activation_price', (parseFloat(actual_price) / 100 * (100 + stop_loss_perc)).toFixed(0), 'callback_rate', (trailing_stop_percent).toFixed(1));
console.log(await binance.futuresMarketSell(currency_pair_1 + currency_pair_2, quantity, {
//newClientOrderId: my_order_id_tp,
callbackRate: (trailing_stop_percent).toFixed(1),
type: "TRAILING_STOP_MARKET",
//timeInForce: "GTC",
priceProtect: true,
reduceOnly: true,
//closePosition: true
}));*/
}
await binance_future_opened_position(currency_pair_1, currency_pair_2, "AFTER BUY");
}
}
async function binance_future_sell(currency_pair_1, currency_pair_2, /* quantity,*/
limit = 0, take_profit = 0, stop_loss_perc = 0, actual_price = 0, trailing_stop_percent = 0, take_profit_percent = 0) {
if (currency_pair_2 === "USD") {
currency_pair_2 = "USDT";
}
limit = limit.toFixed(0);
take_profit = take_profit.toFixed(0);
let invested_amount = await binance_future_wallet_balance(currency_pair_2);
let quantity = await currency_conversion(currency_pair_1, currency_pair_2, invested_amount / 100);
quantity = quantity.toFixed(3);
//temporaneo
quantity = '0.001';
//chiude se ci sono buy
let opened_position = await binance_future_opened_position(currency_pair_1, currency_pair_2);
console.log("SELL DEBUG", invested_amount, quantity, currency_pair_1, currency_pair_2, limit, opened_position);
let close_qty = 0;
if (opened_position > 0) {
console.log("CLOSE BUY POSITION", currency_pair_1 + currency_pair_2, opened_position * -1);
close_qty += Math.abs(opened_position);
console.info(await binance.futuresMarketSell(currency_pair_1 + currency_pair_2, close_qty.toFixed(3), {
type: "MARKET",
priceProtect: true,
reduceOnly: true,
/*workingType: 'MARK_PRICE',*/
//closePosition: true
}));
}
if (opened_position >= 0) {
binance.futuresCancelAll(currency_pair_1 + currency_pair_2);
//let size = parseFloat(quantity) + parseFloat(close_qty);
console.log("SEND SELL", currency_pair_1 + currency_pair_2, quantity);
console.info(await binance.futuresMarketSell(currency_pair_1 + currency_pair_2, quantity
/*, {
workingType: 'MARK_PRICE',
}*/
));
//se arriva allo stop loss deve comprare per chiudere la posizione in short
if (stop_loss_perc > 0) {
//quantity è in currency pair 1, limit in currency pair 2
console.log("SET SELL STOP LOSS", currency_pair_1 + currency_pair_2, quantity, limit);
//console.info(await binance.futuresBuy(currency_pair_1 + currency_pair_2, quantity, limit));
console.log(await binance.futuresMarketBuy(currency_pair_1 + currency_pair_2, quantity, {
type: "STOP_MARKET",
stopPrice: (parseFloat(actual_price) / 100 * (100 + stop_loss_perc)).toFixed(0),
priceProtect: true,
reduceOnly: true,
/* workingType: 'MARK_PRICE',*/
//closePosition: true
}));
}
if (trailing_stop_percent > 0) {
console.log("SET SELL TAKE PROFIT", currency_pair_1 + currency_pair_2, quantity, take_profit);
console.log(await binance.futuresMarketBuy(currency_pair_1 + currency_pair_2, quantity, {
//newClientOrderId: my_order_id_tp,
stopPrice: (parseFloat(actual_price) / 100 * (100 - take_profit_percent)).toFixed(0),
type: "TAKE_PROFIT_MARKET",
//timeInForce: "GTC",
priceProtect: true,
//reduceOnly: true,
closePosition: true
}));
/*if (trailing_stop_percent < 0.1) {
console.log("FORZATURA STOP LOSS SELL");
trailing_stop_percent = 0.1;
}
console.log("TAKE PROFIT SELL", currency_pair_1 + currency_pair_2, 'quantity', quantity, 'activation_price', (parseFloat(actual_price) / 100 * (100 - stop_loss_perc)).toFixed(0), 'callback_rate', (trailing_stop_percent).toFixed(1));
console.log(await binance.futuresMarketBuy(currency_pair_1 + currency_pair_2, quantity, {
//newClientOrderId: my_order_id_tp,
callbackRate: (trailing_stop_percent).toFixed(1),
type: "TRAILING_STOP_MARKET",
//timeInForce: "GTC",
priceProtect: true,
reduceOnly: true,
//closePosition: true
}));*/
}
await binance_future_opened_position(currency_pair_1, currency_pair_2, "AFTER SELL");
}
}
//------------------------------------------- FINE BINANCE
async function getData(market_name, time_interval, currency_pair_1, currency_pair_2) {
console.log(market_name, time_interval, currency_pair_1, currency_pair_2);
//QOUA4VUTZJXS3M01
return new Promise((resolve, reject) => {
/* EUR USD */
/*let url = 'https://www.alphavantage.co/query?function=FX_DAILY&from_symbol=EUR&to_symbol=USD&interval=5min&outputsize=full&apikey=KEY';*/
/* S&P 500 */
/*url = 'https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol=SP&interval=5min&outputsize=full&apikey=KEY';*/
/* sentimento sull'attrattivit� della valuta o la fragilit� del momento */
/*
* https://www.alphavantage.co/query?function=CRYPTO_RATING&symbol=BTC&apikey=KEY
*
* OPPURE
*
* https://app.flipsidecrypto.com/tracker/all-coins (se tutti comprano sale di valore, se tutti vendono scende perch� la capitalizzazione cambia)
* */
/*prova con 5 timeseries (minuti in questo caso), 20 epochs . err 0.0005. previsione tra 5 minuti */
let market_name_url = "";
let symbol_name_1 = "";
let symbol_name_2 = "";
let interval = "";
let json_data_name = "";
switch (time_interval) {
/*<option value="INTRADAY_1_MIN">1 min</option>
<option value="INTRADAY_5_MIN">5 min</option>
<option value="INTRADAY_15_MIN">15 min</option>
<option value="INTRADAY_30_MIN">30 min</option>
<option value="INTRADAY_60_MIN">60 min</option>
<option value="DAILY" selected>1 DAY</option>
<option value="WEEKLY">1 WEEK</option>
<option value="MONTHLY">1 MONTH</option>*/
case "INTRADAY_1_MIN":
switch (market_name) {
case "CRYPTO":
market_name_url = "CRYPTO_";
symbol_name_1 = "symbol";
symbol_name_2 = "market";
json_data_name = "Time Series Crypto (1min)";
break;
case "FOREX":
market_name_url = "FX_";
symbol_name_1 = "from_symbol";
symbol_name_2 = "to_symbol";
json_data_name = "Time Series FX (1min)";
break;
}
market_name_url += "INTRADAY";
interval = "&interval=1min";
break;
case "INTRADAY_5_MIN":
switch (market_name) {
case "CRYPTO":
market_name_url = "CRYPTO_";
symbol_name_1 = "symbol";
symbol_name_2 = "market";
json_data_name = "Time Series Crypto (5min)";
break;
case "FOREX":
market_name_url = "FX_";
symbol_name_1 = "from_symbol";
symbol_name_2 = "to_symbol";
json_data_name = "Time Series FX (5min)";
break;
}
market_name_url += "INTRADAY";
interval = "&interval=5min";
break;
case "INTRADAY_15_MIN":
switch (market_name) {
case "CRYPTO":
market_name_url = "CRYPTO_";
symbol_name_1 = "symbol";
symbol_name_2 = "market";
json_data_name = "Time Series Crypto (15min)";
break;
case "FOREX":
market_name_url = "FX_";
symbol_name_1 = "from_symbol";
symbol_name_2 = "to_symbol";
json_data_name = "Time Series FX (15min)";
break;
}
market_name_url += "INTRADAY";
interval = "&interval=15min";
break;
case "INTRADAY_30_MIN":
switch (market_name) {
case "CRYPTO":
market_name_url = "CRYPTO_";
symbol_name_1 = "symbol";
symbol_name_2 = "market";
json_data_name = "Time Series Crypto (30min)";
break;
case "FOREX":
market_name_url = "FX_";
symbol_name_1 = "from_symbol";
symbol_name_2 = "to_symbol";
json_data_name = "Time Series FX (30min)";
break;
}
market_name_url += "INTRADAY";
interval = "&interval=30min";
break;
case "INTRADAY_60_MIN":
switch (market_name) {
case "CRYPTO":
market_name_url = "CRYPTO_";
symbol_name_1 = "symbol";
symbol_name_2 = "market";
json_data_name = "Time Series Crypto (60min)";
break;
case "FOREX":
market_name_url = "FX_";
symbol_name_1 = "from_symbol";
symbol_name_2 = "to_symbol";
json_data_name = "Time Series FX (60min)";
break;
}
market_name_url += "INTRADAY";
interval = "&interval=60min";
break;
case "DAILY":
switch (market_name) {
case "CRYPTO":
market_name_url = "DIGITAL_CURRENCY_DAILY";
symbol_name_1 = "symbol";
symbol_name_2 = "market";
json_data_name = "Time Series (Digital Currency Daily)";
break;
case "FOREX":
market_name_url = "FX_DAILY";
symbol_name_1 = "from_symbol";
symbol_name_2 = "to_symbol";
json_data_name = "Time Series FX (Daily)";
break;
}
break;
case "WEEKLY":
switch (market_name) {
case "CRYPTO":
market_name_url = "DIGITAL_CURRENCY_WEEKLY";
symbol_name_1 = "symbol";
symbol_name_2 = "market";
json_data_name = "Time Series (Digital Currency Weekly)";
break;
case "FOREX":
market_name_url = "FX_WEEKLY";
symbol_name_1 = "from_symbol";
symbol_name_2 = "to_symbol";
json_data_name = "Time Series FX (Weekly)";
break;
}
break;
case "MONTHLY":
switch (market_name) {
case "CRYPTO":
market_name_url = "DIGITAL_CURRENCY_MONTHLY";
symbol_name_1 = "symbol";
symbol_name_2 = "market";
json_data_name = "Time Series (Digital Currency Monthly)";
break;
case "FOREX":
market_name_url = "FX_MONTHLY";
symbol_name_1 = "from_symbol";
symbol_name_2 = "to_symbol";
json_data_name = "Time Series FX (Monthly)";
break;
}
break;
}
let url = 'https://www.alphavantage.co/query?function=' + market_name_url + '&' + symbol_name_1 + '=' + currency_pair_1 + '&' + symbol_name_2 + '=' + currency_pair_2 + '' + interval + '&outputsize=full&apikey=' + process.env.ALPHADVANTAGE_API_KEY;
//console.log("URL", url);
//console.trace();
let timeseriesRequest = https.get(url, function(res) {
let data = '',
json_data;
res.on('data', function(stream) {
data += stream;
});
res.on('end', function() {
json_data = JSON.parse(data);
// will output a Javascript object
//console.log("data received");
/*Time Series FX (Daily) per il forex*/
let rawData = null;
switch (market_name) {
case "CRYPTO":
if (time_interval.indexOf("INTRADAY") === 0) {
if (currency_pair_1 === "SHIB") {
rawData = Object.values(json_data[json_data_name]).map(d => ({
open: parseFloat(d["1. open"]) * 1000,
high: parseFloat(d["2. high"]) * 1000,
low: parseFloat(d["3. low"]) * 1000,
close: parseFloat(d["4. close"]) * 1000,
volume: parseFloat(d["5. volume"])
}));
} else {
rawData = Object.values(json_data[json_data_name]).map(d => ({
open: parseFloat(d["1. open"]),
high: parseFloat(d["2. high"]),
low: parseFloat(d["3. low"]),
close: parseFloat(d["4. close"]),
volume: parseFloat(d["5. volume"])
}));
}
} else {
if (currency_pair_1 === "SHIB") {
rawData = Object.values(json_data[json_data_name]).map(d => ({
open: parseFloat(d["1b. open (USD)"]) * 1000,
high: parseFloat(d["2b. high (USD)"]) * 1000,
low: parseFloat(d["3b. low (USD)"]) * 1000,
close: parseFloat(d["4b. close (USD)"]) * 1000,
volume: parseFloat(d["5. volume"]) * 1000,
market_cap: parseFloat(d["6. market cap (USD)"])
}));
} else {
rawData = Object.values(json_data[json_data_name]).map(d => ({
open: parseFloat(d["1b. open (USD)"]),
high: parseFloat(d["2b. high (USD)"]),
low: parseFloat(d["3b. low (USD)"]),
close: parseFloat(d["4b. close (USD)"]),
volume: parseFloat(d["5. volume"]),
market_cap: parseFloat(d["6. market cap (USD)"])
}));
}
}
break;
case "FOREX":
rawData = Object.values(json_data[json_data_name]).map(d => ({
open: parseFloat(d["1. open"]),
high: parseFloat(d["2. high"]),
low: parseFloat(d["3. low"]),
close: parseFloat(d["4. close"])
}));
break;
}
resolve(rawData.reverse());
});
});
timeseriesRequest.on('error', function(e) {
console.log(e.message);
});
});
}
async function getFuturesData(json_data) {
let rawData = null;
rawData = json_data.map(d => ({
date: new Date(d[0]),
open: parseFloat(d[1]),
high: parseFloat(d[2]),
low: parseFloat(d[3]),
close: parseFloat(d[4]),
volume: parseFloat(d[5])
}));
//console.log("CANDELE RAW DATA", rawData);
return rawData;
}
async function applyIndicators(data) {
let ema_5 = EMA.calculate({
period: 5,
values: data.map(d => d.close)
});
let ema_10 = EMA.calculate({
period: 10,
//semmai rimettere su close e cambiare trigger dell'azione
values: data.map(d => d.close)
});
let ema_60 = EMA.calculate({
period: 60,
values: data.map(d => d.close)
});
let ema_223 = EMA.calculate({
period: 223,
values: data.map(d => d.close)
});
let rsi = RSI.calculate({
period: 14,
//semmai rimettere su close e cambiare trigger dell'azione
values: data.map(d => d.close)
});
data.forEach((v, i) => {
v.ema_10 = 0;
v.ema_60 = 0
v.ema_223 = 0;
v.rsi = 0;
v.aumento = false;
v.uguale = false;
v.diminuzione = false;
v.azione = "NIENTE";
});
let d = 0;
for (let i = 5; i < data.length; i++) {
data[i].ema_5 = ema_5[d];
d++;
}
d = 0;
for (let i = 10; i < data.length; i++) {
data[i].ema_10 = ema_10[d];
d++;
}
d = 0;
for (let i = 60; i < data.length; i++) {
data[i].ema_60 = ema_60[d];
d++;
}
d = 0;
for (let i = 223; i < data.length; i++) {
data[i].ema_223 = ema_223[d];
d++;
}
d = 0;
for (let i = 14; i < data.length; i++) {
data[i].rsi = rsi[d];
d++;
}
numero_media_rsi_buy = 0;
valori_media_rsi_buy = 0;
numero_media_rsi_sell = 0;
valori_media_rsi_sell = 0;
d = 0;
//i dev'essere 14, anche se anche sotto è così il controllo
for (let i = 14; i < data.length; i++) {
data[i].aumento = data[i].close > data[i - 1].close;
data[i].uguale = data[i].close == data[i - 1].close;
data[i].diminuzione = data[i].close < data[i - 1].close;
//questo è l'indicatore che ho testato il 15 marzo notte che ha prodotto discreti risultati
//TRIGGER ACTION 15032022 SERA
if (data[i].rsi > 40 && data[i].open < data[i].ema_10) {
valori_media_rsi_buy += data[i].close - data[i - 1].close;
numero_media_rsi_buy++;
data[i].azione = "BUY";
} else if (data[i].rsi < 60 && data[i].open > data[i].ema_10) {
valori_media_rsi_sell += data[i - 1].close - data[i].close;
numero_media_rsi_sell++;
data[i].azione = "SELL";
}
//questo da il risultato migliore ma statisticamente su pochi numeri
//sembra giusto. rsi e ema non cambiano durante il minuto quindi dovrebbe andare bene
//senza dover mettere indietro di 1 data[i]
/*if (data[i].rsi > 55 && data[i].rsi < 90 && data[i].open < data[i].ema_10) {
valori_media_rsi_buy += data[i].close - data[i - 1].close;
numero_media_rsi_buy++;
data[i].azione = "BUY";
} else
if (data[i].rsi < 45 && data[i].rsi > 10 && data[i].open > data[i].ema_10) {
valori_media_rsi_sell += data[i - 1].close - data[i].close;
numero_media_rsi_sell++;
data[i].azione = "SELL";
}*/
//test con rsi e ema su open invece che su close. forse è meglio
/*if (data[i - 1].open < data[i].open && data[i].open < data[i].ema_10 && data[i].rsi > 50) {
valori_media_rsi_buy += data[i].close - data[i - 1].close;
numero_media_rsi_buy++;
data[i].azione = "BUY";
} else if (data[i - 1].open > data[i].open && data[i].open > data[i].ema_10 && data[i].rsi < 50) {
valori_media_rsi_sell += data[i - 1].close - data[i].close;
numero_media_rsi_sell++;
data[i].azione = "SELL";
}*/
}
//console.log("\n\nGUADAGNO SU 1 BTC BUY: ", valori_media_rsi_buy, "SELL: ", valori_media_rsi_sell, "\n\n")
return data;
}
let roundByNumber = (value, number) => number * Math.round(value / number);
async function getOrderBook(currency_pair_1, actual_price) {
console.log(actual_price);
//documentazione: https://cryptowat.ch/docs/api
//Il raggruppamento o tick size indica in che misura raggruppare il book
//Esempio:
//100 significa che da 39100 a 39199 vanno in 39100 i conti
//50 invece significa che da 39050 a 39059 vanno in 39050
//4 da 39055 a 39059 vanno in 39050
//quindi ad esempio potrebbe dire che 3500 persone vorrebbero vendere 84 bitcoin a 40300 USDT per bitcoin
//mentre 6000 persone magari vorrebbero acquistare 50 bitcoin pagandolo 39000 dollari
//quindi succede che il prezzo si muoverà tra questi valori (il valore medio è lo spread)
//per accontentare i compratori e venditori
//nei trades si vedono le quantità di soldi movimentata, e se è una vendita o un acquisto
//MIGLIORE SPREAD (MIGLIOR BID E ASK)
//https://api.cryptowat.ch/markets/binance/btcusdt/orderbook?limit=1
//SOLO ORDINI NEL 5% PIU' ALTO DEL BOOK
//https://api.cryptowat.ch/markets/binance/btcusdt/orderbook?span=0.5
//Solo ordini sufficienti per aggiungere fino a 100 BTC su ciascun lato
//https://api.cryptowat.ch/markets/binance/btcusdt/orderbook?depth=100
//Liquidità dell'order book (da approfondire)
//https://api.cryptowat.ch/markets/binance/btcusdt/orderbook/liquidity
//Trades (operazioni di mercato) più recenti
//https://api.cryptowat.ch/markets/:exchange/:pair/trades
//se è maggiore del trade precedente è verde, se è minore è rosso
//quindi se è verde ha comprato, se è rosso ha venduto
//da questo si possono analizzare anche se ci sono whales
let url = "https://api.cryptowat.ch/markets/binance/" + currency_pair_1 + "usdt/orderbook";
//console.log(url);
let asks = new Object();
let bids = new Object();
return new Promise((resolve, reject) => {
https.get(url.toLowerCase(), function(res) {
let data = '',
json_data;
res.on('data', function(stream) {
data += stream;
});
res.on('end', function() {
json_data = JSON.parse(data);
let total_asks_volume = 0;
json_data.result.asks.forEach((v) => {
// if (roundByNumber(v[0], 100) > actual_price) {
//total_asks_volume += v[0] * v[1];
if (asks[roundByNumber(v[0], 100)] === undefined) {
asks[roundByNumber(v[0], 100)] = new Object();
asks[roundByNumber(v[0], 100)].volume = 0;
}
asks[roundByNumber(v[0], 100)].volume++;
if (asks[roundByNumber(v[0], 100)][roundByNumber(v[0], 50)] === undefined) {
asks[roundByNumber(v[0], 100)][roundByNumber(v[0], 50)] = new Object();
asks[roundByNumber(v[0], 100)][roundByNumber(v[0], 50)].volume = 0;
}
asks[roundByNumber(v[0], 100)][roundByNumber(v[0], 50)].volume++;
if (asks[roundByNumber(v[0], 100)][roundByNumber(v[0], 50)][roundByNumber(v[0], 10)] === undefined) {
asks[roundByNumber(v[0], 100)][roundByNumber(v[0], 50)][roundByNumber(v[0], 10)] = new Object();
asks[roundByNumber(v[0], 100)][roundByNumber(v[0], 50)][roundByNumber(v[0], 10)].volume = 0;
}
asks[roundByNumber(v[0], 100)][roundByNumber(v[0], 50)][roundByNumber(v[0], 10)].volume++;
if (asks[roundByNumber(v[0], 100)][roundByNumber(v[0], 50)][roundByNumber(v[0], 10)][roundByNumber(v[0], 5)] === undefined) {
asks[roundByNumber(v[0], 100)][roundByNumber(v[0], 50)][roundByNumber(v[0], 10)][roundByNumber(v[0], 5)] = new Object();
asks[roundByNumber(v[0], 100)][roundByNumber(v[0], 50)][roundByNumber(v[0], 10)][roundByNumber(v[0], 5)].volume = 0;
}
asks[roundByNumber(v[0], 100)][roundByNumber(v[0], 50)][roundByNumber(v[0], 10)][roundByNumber(v[0], 5)].volume++;
// }
});
let total_bids_volume = 0;
json_data.result.bids.forEach((v) => {
//console.log(v[0], actual_price, v[0] < actual_price)
//if (roundByNumber(v[0], 100) < actual_price) {
//total_bids_volume += v[0] * v[1];
if (bids[roundByNumber(v[0], 100)] === undefined) {
bids[roundByNumber(v[0], 100)] = new Object();
bids[roundByNumber(v[0], 100)].volume = 0;
}
bids[roundByNumber(v[0], 100)].volume++;
if (bids[roundByNumber(v[0], 100)][roundByNumber(v[0], 50)] === undefined) {
bids[roundByNumber(v[0], 100)][roundByNumber(v[0], 50)] = new Object();
bids[roundByNumber(v[0], 100)][roundByNumber(v[0], 50)].volume = 0;
}
bids[roundByNumber(v[0], 100)][roundByNumber(v[0], 50)].volume++;
if (bids[roundByNumber(v[0], 100)][roundByNumber(v[0], 50)][roundByNumber(v[0], 10)] === undefined) {
bids[roundByNumber(v[0], 100)][roundByNumber(v[0], 50)][roundByNumber(v[0], 10)] = new Object();
bids[roundByNumber(v[0], 100)][roundByNumber(v[0], 50)][roundByNumber(v[0], 10)].volume = 0;
}
bids[roundByNumber(v[0], 100)][roundByNumber(v[0], 50)][roundByNumber(v[0], 10)].volume++;
if (bids[roundByNumber(v[0], 100)][roundByNumber(v[0], 50)][roundByNumber(v[0], 10)][roundByNumber(v[0], 5)] === undefined) {
bids[roundByNumber(v[0], 100)][roundByNumber(v[0], 50)][roundByNumber(v[0], 10)][roundByNumber(v[0], 5)] = new Object();
bids[roundByNumber(v[0], 100)][roundByNumber(v[0], 50)][roundByNumber(v[0], 10)][roundByNumber(v[0], 5)].volume = 0;
}
bids[roundByNumber(v[0], 100)][roundByNumber(v[0], 50)][roundByNumber(v[0], 10)][roundByNumber(v[0], 5)].volume++;
// }
});
//console.log("\n\n\n");
let next_ask_volume = 0;
let next_ask_price = 0;
let next_bid_volume = 0;
let next_bid_price = 0;
i = 0;
for (let key of Object.keys(asks)) {
if (i === 3) { break; }
//console.log("ASK 100", asks[key].volume, key);
total_asks_volume += asks[key].volume * key;
let asks_50_highest_key = 0;
let asks_50_highest_value = 0;
for (let keykey of Object.keys(asks[key]).reverse()) {
if (asks[key][keykey].volume > asks_50_highest_value) {
asks_50_highest_value = asks[key][keykey].volume;
asks_50_highest_key = keykey;
}
}
//console.log("ASK 50", asks_50_highest_key, asks_50_highest_value);
let asks_10_highest_key = 0;
let asks_10_highest_value = 0;
for (let keykeykey of Object.keys(asks[key][asks_50_highest_key]).reverse()) {
if (asks[key][asks_50_highest_key][keykeykey].volume > asks_10_highest_value) {
asks_10_highest_value = asks[key][asks_50_highest_key][keykeykey].volume;
asks_10_highest_key = keykeykey;
}
}
//console.log("ASK 10", asks_10_highest_key, asks_10_highest_value);
let asks_5_highest_key = 0;
let asks_5_highest_value = 0;
for (let keykeykeykey of Object.keys(asks[key][asks_50_highest_key][asks_10_highest_key]).reverse()) {
if (asks[key][asks_50_highest_key][asks_10_highest_key][keykeykeykey].volume > asks_5_highest_value) {
asks_5_highest_value = asks[key][asks_50_highest_key][asks_10_highest_key][keykeykeykey].volume;
asks_5_highest_key = keykeykeykey;
if (i === 0) {
next_ask_volume = asks_5_highest_value;
next_ask_price = asks_5_highest_key;
}
}
}
//console.log("ASK 5", asks_5_highest_key, asks_5_highest_value);
i++;
}
//console.log("\n\n\n");
i = 0;
for (let key of Object.keys(bids).reverse()) {
if (i === 3) { break; }
//console.log("BID 100", bids[key].volume, key);
total_bids_volume += bids[key].volume * key;
let bids_50_highest_key = 0;
let bids_50_highest_value = 0;
for (let keykey of Object.keys(bids[key]).reverse()) {
if (bids[key][keykey].volume > bids_50_highest_value) {
bids_50_highest_value = bids[key][keykey].volume;
bids_50_highest_key = keykey;
}
}
//console.log("BID 50", bids_50_highest_key, bids_50_highest_value);
let bids_10_highest_key = 0;
let bids_10_highest_value = 0;
for (let keykeykey of Object.keys(bids[key][bids_50_highest_key]).reverse()) {
if (bids[key][bids_50_highest_key][keykeykey].volume > bids_10_highest_value) {
bids_10_highest_value = bids[key][bids_50_highest_key][keykeykey].volume;
bids_10_highest_key = keykeykey;