forked from whittlem/pycryptobot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
pycryptobot.py
executable file
·1467 lines (1295 loc) · 61.7 KB
/
pycryptobot.py
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
#!/usr/bin/env python3
# encoding: utf-8
"""Python Crypto Bot consuming Coinbase Pro or Binance APIs"""
import functools
import os
import sched
import sys
import time
import signal
import requests
from datetime import datetime, timedelta
import pandas as pd
from models.AppState import AppState
from models.helper.LogHelper import Logger
from models.helper.MarginHelper import calculate_margin
from models.PyCryptoBot import PyCryptoBot
from models.PyCryptoBot import truncate as _truncate
from models.Stats import Stats
from models.Strategy import Strategy
from models.Trading import TechnicalAnalysis
from models.TradingAccount import TradingAccount
from views.TradingGraphs import TradingGraphs
from models.Strategy import Strategy
from models.helper.LogHelper import Logger
from models.helper.TextBoxHelper import TextBox
from models.exchange.binance import WebSocketClient as BWebSocketClient
from models.exchange.coinbase_pro import WebSocketClient as CWebSocketClient
# minimal traceback
sys.tracebacklimit = 1
app = PyCryptoBot()
account = TradingAccount(app)
Stats(app, account).show()
technical_analysis = None
state = AppState(app, account)
state.initLastAction()
websocket = None
s = sched.scheduler(time.time, time.sleep)
def signal_handler(signum, frame):
if signum == 2:
print("Please be patient while websockets terminate!")
return
def executeJob(
sc=None,
app: PyCryptoBot = None,
state: AppState = None,
websocket=None,
trading_data=pd.DataFrame(),
):
"""Trading bot job which runs at a scheduled interval"""
global technical_analysis
# increment state.iterations
state.iterations = state.iterations + 1
if not app.isSimulation():
# retrieve the app.getMarket() data
trading_data = app.getHistoricalData(
app.getMarket(), app.getGranularity(), websocket
)
else:
if len(trading_data) == 0:
return None
# analyse the market data
if app.isSimulation() and len(trading_data.columns) > 8:
df = trading_data
if app.appStarted and app.simstartdate is not None:
# On first run set the iteration to the start date entered
# This sim mode now pulls 300 candles from before the entered start date
state.iterations = (
df.index.get_loc(str(app.getDateFromISO8601Str(app.simstartdate))) + 1
)
app.appStarted = False
# if smartswitch then get the market data using new granularity
if app.sim_smartswitch:
df_last = app.getInterval(df, state.iterations)
if len(df_last.index.format()) > 0:
if app.simstartdate is not None:
startDate = app.getDateFromISO8601Str(app.simstartdate)
else:
startDate = app.getDateFromISO8601Str(
str(df.head(1).index.format()[0])
)
if app.simenddate is not None:
if app.simenddate == "now":
endDate = app.getDateFromISO8601Str(str(datetime.now()))
else:
endDate = app.getDateFromISO8601Str(app.simenddate)
else:
endDate = app.getDateFromISO8601Str(
str(df.tail(1).index.format()[0])
)
simDate = app.getDateFromISO8601Str(str(df_last.index.format()[0]))
trading_data = app.getSmartSwitchHistoricalDataChained(
app.getMarket(), app.getGranularity(), str(startDate), str(endDate)
)
if app.getGranularity() == 3600:
simDate = app.getDateFromISO8601Str(str(simDate))
sim_rounded = pd.Series(simDate).dt.round("60min")
simDate = sim_rounded[0]
elif app.getGranularity() == 900:
simDate = app.getDateFromISO8601Str(str(simDate))
sim_rounded = pd.Series(simDate).dt.round("15min")
simDate = sim_rounded[0]
state.iterations = trading_data.index.get_loc(str(simDate))
if state.iterations == 0:
state.iterations = 1
elif app.getGranularity() == 3600:
state.iterations += 2
elif app.getGranularity() == 900:
state.iterations -= 2
trading_dataCopy = trading_data.copy()
technical_analysis = TechnicalAnalysis(trading_dataCopy)
# if 'morning_star' not in df:
technical_analysis.addAll()
df = technical_analysis.getDataFrame()
app.sim_smartswitch = False
elif app.getSmartSwitch() == 1 and technical_analysis is None:
trading_dataCopy = trading_data.copy()
technical_analysis = TechnicalAnalysis(trading_dataCopy)
if "morning_star" not in df:
technical_analysis.addAll()
df = technical_analysis.getDataFrame()
else:
trading_dataCopy = trading_data.copy()
technical_analysis = TechnicalAnalysis(trading_dataCopy)
technical_analysis.addAll()
df = technical_analysis.getDataFrame()
if app.isSimulation() and app.appStarted:
# On first run set the iteration to the start date entered
# This sim mode now pulls 300 candles from before the entered start date
state.iterations = (
df.index.get_loc(str(app.getDateFromISO8601Str(app.simstartdate))) + 1
)
app.appStarted = False
if app.isSimulation():
df_last = app.getInterval(df, state.iterations)
else:
df_last = app.getInterval(df)
if len(df_last.index.format()) > 0:
current_df_index = str(df_last.index.format()[0])
else:
current_df_index = state.last_df_index
formatted_current_df_index = (
f"{current_df_index} 00:00:00"
if len(current_df_index) == 10
else current_df_index
)
current_sim_date = formatted_current_df_index
# use actual sim mode date to check smartchswitch
if (
app.getSmartSwitch() == 1
and app.getGranularity() == 3600
and app.is1hEMA1226Bull(current_sim_date, websocket) is True
and app.is6hEMA1226Bull(current_sim_date, websocket) is True
):
Logger.info(
"*** smart switch from granularity 3600 (1 hour) to 900 (15 min) ***"
)
if app.isSimulation():
app.sim_smartswitch = True
app.notifyTelegram(
app.getMarket()
+ " smart switch from granularity 3600 (1 hour) to 900 (15 min)"
)
app.setGranularity(900)
list(map(s.cancel, s.queue))
s.enter(5, 1, executeJob, (sc, app, state, websocket))
# use actual sim mode date to check smartchswitch
if (
app.getSmartSwitch() == 1
and app.getGranularity() == 900
and app.is1hEMA1226Bull(current_sim_date, websocket) is False
and app.is6hEMA1226Bull(current_sim_date, websocket) is False
):
Logger.info(
"*** smart switch from granularity 900 (15 min) to 3600 (1 hour) ***"
)
if app.isSimulation():
app.sim_smartswitch = True
app.notifyTelegram(
f"{app.getMarket()} smart switch from granularity 900 (15 min) to 3600 (1 hour)"
)
app.setGranularity(3600)
list(map(s.cancel, s.queue))
s.enter(5, 1, executeJob, (sc, app, state, websocket))
if app.getExchange() == "binance" and app.getGranularity() == 86400:
if len(df) < 250:
# data frame should have 250 rows, if not retry
Logger.error(f"error: data frame length is < 250 ({str(len(df))})")
list(map(s.cancel, s.queue))
s.enter(300, 1, executeJob, (sc, app, state, websocket))
else:
if len(df) < 300:
if not app.isSimulation():
# data frame should have 300 rows, if not retry
Logger.error(f"error: data frame length is < 300 ({str(len(df))})")
list(map(s.cancel, s.queue))
s.enter(300, 1, executeJob, (sc, app, state, websocket))
if len(df_last) > 0:
now = datetime.today().strftime("%Y-%m-%d %H:%M:%S")
# last_action polling if live
if app.isLive():
last_action_current = state.last_action
state.pollLastAction()
if last_action_current != state.last_action:
Logger.info(
f"last_action change detected from {last_action_current} to {state.last_action}"
)
app.notifyTelegram(
f"{app.getMarket} last_action change detected from {last_action_current} to {state.last_action}"
)
if not app.isSimulation():
ticker = app.getTicker(app.getMarket(), websocket)
now = ticker[0]
price = ticker[1]
if price < df_last["low"].values[0] or price == 0:
price = float(df_last["close"].values[0])
else:
price = float(df_last["close"].values[0])
if price < 0.0001:
raise Exception(
f"{app.getMarket()} is unsuitable for trading, quote price is less than 0.0001!"
)
# technical indicators
ema12gtema26 = bool(df_last["ema12gtema26"].values[0])
ema12gtema26co = bool(df_last["ema12gtema26co"].values[0])
goldencross = bool(df_last["goldencross"].values[0])
macdgtsignal = bool(df_last["macdgtsignal"].values[0])
macdgtsignalco = bool(df_last["macdgtsignalco"].values[0])
ema12ltema26 = bool(df_last["ema12ltema26"].values[0])
ema12ltema26co = bool(df_last["ema12ltema26co"].values[0])
macdltsignal = bool(df_last["macdltsignal"].values[0])
macdltsignalco = bool(df_last["macdltsignalco"].values[0])
obv = float(df_last["obv"].values[0])
obv_pc = float(df_last["obv_pc"].values[0])
elder_ray_buy = bool(df_last["eri_buy"].values[0])
elder_ray_sell = bool(df_last["eri_sell"].values[0])
# if simulation, set goldencross based on actual sim date
if app.isSimulation():
goldencross = app.is1hSMA50200Bull(current_sim_date, websocket)
# candlestick detection
hammer = bool(df_last["hammer"].values[0])
inverted_hammer = bool(df_last["inverted_hammer"].values[0])
hanging_man = bool(df_last["hanging_man"].values[0])
shooting_star = bool(df_last["shooting_star"].values[0])
three_white_soldiers = bool(df_last["three_white_soldiers"].values[0])
three_black_crows = bool(df_last["three_black_crows"].values[0])
morning_star = bool(df_last["morning_star"].values[0])
evening_star = bool(df_last["evening_star"].values[0])
three_line_strike = bool(df_last["three_line_strike"].values[0])
abandoned_baby = bool(df_last["abandoned_baby"].values[0])
morning_doji_star = bool(df_last["morning_doji_star"].values[0])
evening_doji_star = bool(df_last["evening_doji_star"].values[0])
two_black_gapping = bool(df_last["two_black_gapping"].values[0])
if app.isSimulation():
# Reset the Strategy so that the last record is the current sim date
# To allow for calculations to be done on the sim date being processed
sdf = df[df["date"] <= current_sim_date].tail(300)
strategy = Strategy(
app, state, sdf, sdf.index.get_loc(str(current_sim_date)) + 1
)
else:
strategy = Strategy(app, state, df, state.iterations)
state.action = strategy.getAction(price)
immediate_action = False
margin, profit, sell_fee = 0, 0, 0
# Reset the TA so that the last record is the current sim date
# To allow for calculations to be done on the sim date being processed
if app.isSimulation():
trading_dataCopy = (
trading_data[trading_data["date"] <= current_sim_date].tail(300).copy()
)
technical_analysis = TechnicalAnalysis(trading_dataCopy)
if (
state.last_buy_size > 0
and state.last_buy_price > 0
and price > 0
and state.last_action == "BUY"
):
# update last buy high
if price > state.last_buy_high:
state.last_buy_high = price
if state.last_buy_high > 0:
change_pcnt_high = ((price / state.last_buy_high) - 1) * 100
else:
change_pcnt_high = 0
# buy and sell calculations
state.last_buy_fee = round(state.last_buy_size * app.getTakerFee(), 8)
state.last_buy_filled = round(
((state.last_buy_size - state.last_buy_fee) / state.last_buy_price), 8
)
# if not a simulation, sync with exchange orders
if not app.isSimulation():
exchange_last_buy = app.getLastBuy()
if exchange_last_buy is not None:
if state.last_buy_size != exchange_last_buy["size"]:
state.last_buy_size = exchange_last_buy["size"]
if state.last_buy_filled != exchange_last_buy["filled"]:
state.last_buy_filled = exchange_last_buy["filled"]
if state.last_buy_price != exchange_last_buy["price"]:
state.last_buy_price = exchange_last_buy["price"]
if app.getExchange() == "coinbasepro":
if state.last_buy_fee != exchange_last_buy["fee"]:
state.last_buy_fee = exchange_last_buy["fee"]
margin, profit, sell_fee = calculate_margin(
buy_size=state.last_buy_size,
buy_filled=state.last_buy_filled,
buy_price=state.last_buy_price,
buy_fee=state.last_buy_fee,
sell_percent=app.getSellPercent(),
sell_price=price,
sell_taker_fee=app.getTakerFee(),
)
# handle immedate sell actions
if strategy.isSellTrigger(
price,
technical_analysis.getTradeExit(price),
margin,
change_pcnt_high,
obv_pc,
macdltsignal,
):
state.action = "SELL"
state.last_action = "BUY"
immediate_action = True
# handle overriding wait actions (e.g. do not sell if sell at loss disabled!, do not buy in bull if bull only)
if strategy.isWaitTrigger(margin, goldencross):
state.action = "WAIT"
immediate_action = False
bullbeartext = ""
if app.disableBullOnly() is True or (
df_last["sma50"].values[0] == df_last["sma200"].values[0]
):
bullbeartext = ""
elif goldencross is True:
bullbeartext = " (BULL)"
elif goldencross is False:
bullbeartext = " (BEAR)"
# polling is every 5 minutes (even for hourly intervals), but only process once per interval
# Logger.debug("DateCheck: " + str(immediate_action) + ' ' + str(state.last_df_index) + ' ' + str(current_df_index))
if immediate_action is True or state.last_df_index != current_df_index:
textBox = TextBox(80, 22)
precision = 4
if price < 0.01:
precision = 8
# Since precision does not change after this point, it is safe to prepare a tailored `truncate()` that would
# work with this precision. It should save a couple of `precision` uses, one for each `truncate()` call.
truncate = functools.partial(_truncate, n=precision)
price_text = "Close: " + truncate(price)
ema_text = ""
if app.disableBuyEMA() is False:
ema_text = app.compare(
df_last["ema12"].values[0],
df_last["ema26"].values[0],
"EMA12/26",
precision,
)
macd_text = ""
if app.disableBuyMACD() is False:
macd_text = app.compare(
df_last["macd"].values[0],
df_last["signal"].values[0],
"MACD",
precision,
)
obv_text = ""
if app.disableBuyOBV() is False:
obv_text = (
"OBV: "
+ truncate(df_last["obv"].values[0])
+ " ("
+ str(truncate(df_last["obv_pc"].values[0]))
+ "%)"
)
state.eri_text = ""
if app.disableBuyElderRay() is False:
if elder_ray_buy is True:
state.eri_text = "ERI: buy | "
elif elder_ray_sell is True:
state.eri_text = "ERI: sell | "
else:
state.eri_text = "ERI: | "
if hammer is True:
log_text = '* Candlestick Detected: Hammer ("Weak - Reversal - Bullish Signal - Up")'
Logger.info(log_text)
if shooting_star is True:
log_text = '* Candlestick Detected: Shooting Star ("Weak - Reversal - Bearish Pattern - Down")'
Logger.info(log_text)
if hanging_man is True:
log_text = '* Candlestick Detected: Hanging Man ("Weak - Continuation - Bearish Pattern - Down")'
Logger.info(log_text)
if inverted_hammer is True:
log_text = '* Candlestick Detected: Inverted Hammer ("Weak - Continuation - Bullish Pattern - Up")'
Logger.info(log_text)
if three_white_soldiers is True:
log_text = '*** Candlestick Detected: Three White Soldiers ("Strong - Reversal - Bullish Pattern - Up")'
Logger.info(log_text)
if three_black_crows is True:
log_text = '* Candlestick Detected: Three Black Crows ("Strong - Reversal - Bearish Pattern - Down")'
Logger.info(log_text)
if morning_star is True:
log_text = '*** Candlestick Detected: Morning Star ("Strong - Reversal - Bullish Pattern - Up")'
Logger.info(log_text)
if evening_star is True:
log_text = '*** Candlestick Detected: Evening Star ("Strong - Reversal - Bearish Pattern - Down")'
Logger.info(log_text)
if three_line_strike is True:
log_text = '** Candlestick Detected: Three Line Strike ("Reliable - Reversal - Bullish Pattern - Up")'
Logger.info(log_text)
if abandoned_baby is True:
log_text = '** Candlestick Detected: Abandoned Baby ("Reliable - Reversal - Bullish Pattern - Up")'
Logger.info(log_text)
if morning_doji_star is True:
log_text = '** Candlestick Detected: Morning Doji Star ("Reliable - Reversal - Bullish Pattern - Up")'
Logger.info(log_text)
if evening_doji_star is True:
log_text = '** Candlestick Detected: Evening Doji Star ("Reliable - Reversal - Bearish Pattern - Down")'
Logger.info(log_text)
if two_black_gapping is True:
log_text = '*** Candlestick Detected: Two Black Gapping ("Reliable - Reversal - Bearish Pattern - Down")'
Logger.info(log_text)
ema_co_prefix = ""
ema_co_suffix = ""
if app.disableBuyEMA() is False:
if ema12gtema26co is True:
ema_co_prefix = "*^ "
ema_co_suffix = " ^* | "
elif ema12ltema26co is True:
ema_co_prefix = "*v "
ema_co_suffix = " v* | "
elif ema12gtema26 is True:
ema_co_prefix = "^ "
ema_co_suffix = " ^ | "
elif ema12ltema26 is True:
ema_co_prefix = "v "
ema_co_suffix = " v | "
macd_co_prefix = ""
macd_co_suffix = ""
if app.disableBuyMACD() is False:
if macdgtsignalco is True:
macd_co_prefix = "*^ "
macd_co_suffix = " ^* | "
elif macdltsignalco is True:
macd_co_prefix = "*v "
macd_co_suffix = " v* | "
elif macdgtsignal is True:
macd_co_prefix = "^ "
macd_co_suffix = " ^ | "
elif macdltsignal is True:
macd_co_prefix = "v "
macd_co_suffix = " v | "
obv_prefix = ""
obv_suffix = ""
if app.disableBuyOBV() is False:
if float(obv_pc) > 0:
obv_prefix = "^ "
obv_suffix = " ^ | "
elif float(obv_pc) < 0:
obv_prefix = "v "
obv_suffix = " v | "
else:
obv_suffix = " | "
if not app.isVerbose():
if state.last_action != "":
# Not sure if this if is needed just preserving any exisitng functionality that may have been missed
# Updated to show over margin and profit
if not app.isSimulation:
output_text = (
formatted_current_df_index
+ " | "
+ app.getMarket()
+ bullbeartext
+ " | "
+ app.printGranularity()
+ " | "
+ price_text
+ " | "
+ ema_co_prefix
+ ema_text
+ ema_co_suffix
+ macd_co_prefix
+ macd_text
+ macd_co_suffix
+ obv_prefix
+ obv_text
+ obv_suffix
+ state.eri_text
+ state.action
+ " | Last Action: "
+ state.last_action
+ " | DF HIGH: "
+ str(df["close"].max())
+ " | "
+ "DF LOW: "
+ str(df["close"].min())
+ " | SWING: "
+ str(
round(
(
(df["close"].max() - df["close"].min())
/ df["close"].min()
)
* 100,
2,
)
)
+ "% |"
+ " CURR Price is "
+ str(
round(
((price - df["close"].max()) / df["close"].max())
* 100,
2,
)
)
+ "% "
+ "away from DF HIGH | Range: "
+ str(df.iloc[0, 0])
+ " <--> "
+ str(df.iloc[len(df) - 1, 0])
)
else:
df_high = df[df["date"] <= current_sim_date]["close"].max()
df_low = df[df["date"] <= current_sim_date]["close"].min()
# print(df_high)
output_text = (
formatted_current_df_index
+ " | "
+ app.getMarket()
+ bullbeartext
+ " | "
+ app.printGranularity()
+ " | "
+ price_text
+ " | "
+ ema_co_prefix
+ ema_text
+ ema_co_suffix
+ macd_co_prefix
+ macd_text
+ macd_co_suffix
+ obv_prefix
+ obv_text
+ obv_suffix
+ state.eri_text
+ state.action
+ " | Last Action: "
+ state.last_action
+ " | DF HIGH: "
+ str(df_high)
+ " | "
+ "DF LOW: "
+ str(df_low)
+ " | SWING: "
+ str(round(((df_high - df_low) / df_low) * 100, 2))
+ "% |"
+ " CURR Price is "
+ str(round(((price - df_high) / df_high) * 100, 2))
+ "% "
+ "away from DF HIGH | Range: "
+ str(df.iloc[state.iterations - 300, 0])
+ " <--> "
+ str(df.iloc[state.iterations - 1, 0])
)
else:
if not app.isSimulation:
output_text = (
formatted_current_df_index
+ " | "
+ app.getMarket()
+ bullbeartext
+ " | "
+ app.printGranularity()
+ " | "
+ price_text
+ " | "
+ ema_co_prefix
+ ema_text
+ ema_co_suffix
+ macd_co_prefix
+ macd_text
+ macd_co_suffix
+ obv_prefix
+ obv_text
+ obv_suffix
+ state.eri_text
+ state.action
+ " | DF HIGH: "
+ str(df["close"].max())
+ " | "
+ "DF LOW: "
+ str(df["close"].min())
+ " | SWING: "
+ str(
round(
(
(df["close"].max() - df["close"].min())
/ df["close"].min()
)
* 100,
2,
)
)
+ "%"
+ " CURR Price is "
+ str(
round(
((price - df["close"].max()) / df["close"].max())
* 100,
2,
)
)
+ "% "
+ "away from DF HIGH | Range: "
+ str(df.iloc[0, 0])
+ " <--> "
+ str(df.iloc[len(df) - 1, 0])
)
else:
df_high = df[df["date"] <= current_sim_date]["close"].max()
df_low = df[df["date"] <= current_sim_date]["close"].min()
output_text = (
formatted_current_df_index
+ " | "
+ app.getMarket()
+ bullbeartext
+ " | "
+ app.printGranularity()
+ " | "
+ price_text
+ " | "
+ ema_co_prefix
+ ema_text
+ ema_co_suffix
+ macd_co_prefix
+ macd_text
+ macd_co_suffix
+ obv_prefix
+ obv_text
+ obv_suffix
+ state.eri_text
+ state.action
+ " | DF HIGH: "
+ str(df_high)
+ " | "
+ "DF LOW: "
+ str(df_low)
+ " | SWING: "
+ str(round(((df_high - df_low) / df_low) * 100, 2))
+ "%"
+ " CURR Price is "
+ str(round(((price - df_high) / df_high) * 100, 2))
+ "% "
+ "away from DF HIGH | Range: "
+ str(df.iloc[state.iterations - 300, 0])
+ " <--> "
+ str(df.iloc[state.iterations - 1, 0])
)
if state.last_action == "BUY":
if state.last_buy_size > 0:
margin_text = truncate(margin) + "%"
else:
margin_text = "0%"
output_text += (
" | "
+ margin_text
+ " (delta: "
+ str(round(price - state.last_buy_price, precision))
+ ")"
)
Logger.info(output_text)
if app.enableML():
# Seasonal Autoregressive Integrated Moving Average (ARIMA) model (ML prediction for 3 intervals from now)
if not app.isSimulation():
try:
prediction = (
technical_analysis.seasonalARIMAModelPrediction(
int(app.getGranularity() / 60) * 3
)
) # 3 intervals from now
Logger.info(
f"Seasonal ARIMA model predicts the closing price will be {str(round(prediction[1], 2))} at {prediction[0]} (delta: {round(prediction[1] - price, 2)})"
)
except:
pass
if state.last_action == "BUY":
# display support, resistance and fibonacci levels
Logger.info(
technical_analysis.printSupportResistanceFibonacciLevels(price)
)
else:
Logger.debug(f"-- Iteration: {str(state.iterations)} --{bullbeartext}")
if state.last_action == "BUY":
if state.last_buy_size > 0:
margin_text = truncate(margin) + "%"
else:
margin_text = "0%"
Logger.debug(f"-- Margin: {margin_text} --")
Logger.debug(f"price: {truncate(price)}")
Logger.debug(f'ema12: {truncate(float(df_last["ema12"].values[0]))}')
Logger.debug(f'ema26: {truncate(float(df_last["ema26"].values[0]))}')
Logger.debug(f"ema12gtema26co: {str(ema12gtema26co)}")
Logger.debug(f"ema12gtema26: {str(ema12gtema26)}")
Logger.debug(f"ema12ltema26co: {str(ema12ltema26co)}")
Logger.debug(f"ema12ltema26: {str(ema12ltema26)}")
Logger.debug(f'sma50: {truncate(float(df_last["sma50"].values[0]))}')
Logger.debug(f'sma200: {truncate(float(df_last["sma200"].values[0]))}')
Logger.debug(f'macd: {truncate(float(df_last["macd"].values[0]))}')
Logger.debug(f'signal: {truncate(float(df_last["signal"].values[0]))}')
Logger.debug(f"macdgtsignal: {str(macdgtsignal)}")
Logger.debug(f"macdltsignal: {str(macdltsignal)}")
Logger.debug(f"obv: {str(obv)}")
Logger.debug(f"obv_pc: {str(obv_pc)}")
Logger.debug(f"action: {state.action}")
# informational output on the most recent entry
Logger.info("")
textBox.doubleLine()
textBox.line("Iteration", str(state.iterations) + bullbeartext)
textBox.line("Timestamp", str(df_last.index.format()[0]))
textBox.singleLine()
textBox.line("Close", truncate(price))
textBox.line("EMA12", truncate(float(df_last["ema12"].values[0])))
textBox.line("EMA26", truncate(float(df_last["ema26"].values[0])))
textBox.line("Crossing Above", str(ema12gtema26co))
textBox.line("Currently Above", str(ema12gtema26))
textBox.line("Crossing Below", str(ema12ltema26co))
textBox.line("Currently Below", str(ema12ltema26))
if ema12gtema26 is True and ema12gtema26co is True:
textBox.line("Condition", "EMA12 is currently crossing above EMA26")
elif ema12gtema26 is True and ema12gtema26co is False:
textBox.line(
"Condition",
"EMA12 is currently above EMA26 and has crossed over",
)
elif ema12ltema26 is True and ema12ltema26co is True:
textBox.line("Condition", "EMA12 is currently crossing below EMA26")
elif ema12ltema26 is True and ema12ltema26co is False:
textBox.line(
"Condition",
"EMA12 is currently below EMA26 and has crossed over",
)
else:
textBox.line("Condition", "-")
textBox.line("SMA20", truncate(float(df_last["sma20"].values[0])))
textBox.line("SMA200", truncate(float(df_last["sma200"].values[0])))
textBox.singleLine()
textBox.line("MACD", truncate(float(df_last["macd"].values[0])))
textBox.line("Signal", truncate(float(df_last["signal"].values[0])))
textBox.line("Currently Above", str(macdgtsignal))
textBox.line("Currently Below", str(macdltsignal))
if macdgtsignal is True and macdgtsignalco is True:
textBox.line("Condition", "MACD is currently crossing above Signal")
elif macdgtsignal is True and macdgtsignalco is False:
textBox.line(
"Condition",
"MACD is currently above Signal and has crossed over",
)
elif macdltsignal is True and macdltsignalco is True:
textBox.line("Condition", "MACD is currently crossing below Signal")
elif macdltsignal is True and macdltsignalco is False:
textBox.line(
"Condition",
"MACD is currently below Signal and has crossed over",
)
else:
textBox.line("Condition", "-")
textBox.singleLine()
textBox.line("Action", state.action)
textBox.doubleLine()
if state.last_action == "BUY":
textBox.line("Margin", margin_text)
textBox.doubleLine()
# if a buy signal
if state.action == "BUY":
state.last_buy_price = price
state.last_buy_high = state.last_buy_price
# if live
if app.isLive():
app.notifyTelegram(
app.getMarket()
+ " ("
+ app.printGranularity()
+ ") BUY at "
+ price_text
)
if not app.isVerbose():
Logger.info(
f"{formatted_current_df_index} | {app.getMarket()} | {app.printGranularity()} | {price_text} | BUY"
)
else:
textBox.singleLine()
textBox.center("*** Executing LIVE Buy Order ***")
textBox.singleLine()
# display balances
Logger.info(
f"{app.getBaseCurrency()} balance before order: {str(account.getBalance(app.getBaseCurrency()))}"
)
Logger.info(
f"{app.getQuoteCurrency()} balance before order: {str(account.getBalance(app.getQuoteCurrency()))}"
)
# execute a live market buy
state.last_buy_size = float(
account.getBalance(app.getQuoteCurrency())
)
if (
app.getBuyMaxSize()
and state.last_buy_size > app.getBuyMaxSize()
):
state.last_buy_size = app.getBuyMaxSize()
resp = app.marketBuy(
app.getMarket(), state.last_buy_size, app.getBuyPercent()
)
Logger.debug(resp)
# display balances
Logger.info(
f"{app.getBaseCurrency()} balance after order: {str(account.getBalance(app.getBaseCurrency()))}"
)
Logger.info(
f"{app.getQuoteCurrency()} balance after order: {str(account.getBalance(app.getQuoteCurrency()))}"
)
# if not live
else:
app.notifyTelegram(
f"{app.getMarket()} ({app.printGranularity()}) TEST BUY at {price_text}"
)
if state.last_buy_size == 0 and state.last_buy_filled == 0:
# Sim mode can now use buymaxsize as the amount used for a buy
if app.getBuyMaxSize() != None:
state.last_buy_size = app.getBuyMaxSize()
state.first_buy_size = app.getBuyMaxSize()
else:
state.last_buy_size = 1000
state.first_buy_size = 1000
state.buy_count = state.buy_count + 1
state.buy_sum = state.buy_sum + state.last_buy_size
if not app.isVerbose():
Logger.info(
f"{formatted_current_df_index} | {app.getMarket()} | {app.printGranularity()} | {price_text} | BUY"
)
bands = technical_analysis.getFibonacciRetracementLevels(
float(price)
)
technical_analysis.printSupportResistanceLevel(float(price))
Logger.info(f" Fibonacci Retracement Levels:{str(bands)}")
if len(bands) >= 1 and len(bands) <= 2:
if len(bands) == 1:
first_key = list(bands.keys())[0]
if first_key == "ratio1":
state.fib_low = 0
state.fib_high = bands[first_key]
if first_key == "ratio1_618":
state.fib_low = bands[first_key]
state.fib_high = bands[first_key] * 2
else:
state.fib_low = bands[first_key]
elif len(bands) == 2:
first_key = list(bands.keys())[0]
second_key = list(bands.keys())[1]
state.fib_low = bands[first_key]
state.fib_high = bands[second_key]
else:
textBox.singleLine()
textBox.center("*** Executing TEST Buy Order ***")
textBox.singleLine()
app.trade_tracker = app.trade_tracker.append(
{
"Datetime": str(current_sim_date),
"Market": app.getMarket(),
"Action": "BUY",
"Price": price,
"Quote": state.last_buy_size,
"Base": float(state.last_buy_size) / float(price),
"DF_High": df[df["date"] <= current_sim_date][
"close"
].max(),
"DF_Low": df[df["date"] <= current_sim_date]["close"].min(),
},
ignore_index=True,
)
if app.shouldSaveGraphs():
tradinggraphs = TradingGraphs(technical_analysis)
ts = datetime.now().timestamp()