forked from whittlem/pycryptobot
-
Notifications
You must be signed in to change notification settings - Fork 1
/
pycryptobot.py.20220730
2248 lines (2000 loc) · 100 KB
/
pycryptobot.py.20220730
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 json
import os
import sched
import signal
import sys
import time
from datetime import datetime, timedelta
import pandas as pd
from models.AppState import AppState
from models.chat import telegram
from models.exchange.binance import WebSocketClient as BWebSocketClient
from models.exchange.coinbase_pro import WebSocketClient as CWebSocketClient
from models.exchange.ExchangesEnum import Exchange
from models.exchange.Granularity import Granularity
from models.exchange.kucoin import WebSocketClient as KWebSocketClient
from models.helper.LogHelper import Logger
from models.helper.MarginHelper import calculate_margin
from models.helper.TelegramBotHelper import TelegramBotHelper
from models.helper.TextBoxHelper import TextBox
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.mqtt.helper import *
# minimal traceback
sys.tracebacklimit = 1
app = PyCryptoBot()
account = TradingAccount(app)
Stats(app, account).show()
technical_analysis = None
state = AppState(app, account)
state.initLastAction()
telegram_bot = TelegramBotHelper(app)
s = sched.scheduler(time.time, time.sleep)
pd.set_option('display.float_format', '{:.8f}'.format)
def signal_handler(signum):
if signum == 2:
print("Please be patient while websockets terminate!")
#Logger.debug(frame)
return
def execute_job(
sc=None,
_app: PyCryptoBot = None,
_state: AppState = None,
_technical_analysis=None,
_websocket=None,
trading_data=pd.DataFrame(),
):
"""Trading bot job which runs at a scheduled interval"""
# MQTT.set_Market(_app.getMarket())
if app.isLive():
state.account.mode = "live"
else:
state.account.mode = "test"
# This is used to control some API calls when using websockets
last_api_call_datetime = datetime.now() - _state.last_api_call_datetime
if last_api_call_datetime.seconds > 60:
_state.last_api_call_datetime = datetime.now()
# This is used by the telegram bot
# If it not enabled in config while will always be False
if not _app.isSimulation():
controlstatus = telegram_bot.checkbotcontrolstatus()
while controlstatus == "pause" or controlstatus == "paused":
if controlstatus == "pause":
text_box = TextBox(80, 22)
text_box.singleLine()
text_box.center(f"Pausing Bot {_app.getMarket()}")
text_box.singleLine()
Logger.debug("Pausing Bot.")
print(str(datetime.now()).format() + " - Bot is paused")
helper.mqtt_test_publish("status",str(datetime.now()).format() + " - Bot is paused" )
_app.notifyTelegram(f"{_app.getMarket()} bot is paused")
telegram_bot.updatebotstatus("paused")
if _app.enableWebsocket():
Logger.info("Stopping _websocket...")
_websocket.close()
time.sleep(30)
controlstatus = telegram_bot.checkbotcontrolstatus()
if controlstatus == "start":
text_box = TextBox(80, 22)
text_box.singleLine()
text_box.center(f"Restarting Bot {_app.getMarket()}")
text_box.singleLine()
Logger.debug("Restarting Bot.")
mqtt_test_publish("status", "Restarting Bot")
# print(str(datetime.now()).format() + " - Bot has restarted")
_app.notifyTelegram(f"{_app.getMarket()} bot has restarted")
telegram_bot.updatebotstatus("active")
_app.read_config(_app.getExchange())
if _app.enableWebsocket():
Logger.info("Starting _websocket...")
Logger
_websocket.start()
if controlstatus == "exit":
text_box = TextBox(80, 22)
text_box.singleLine()
text_box.center(f"Closing Bot {_app.getMarket()}")
text_box.singleLine()
Logger.debug("Closing Bot.")
mqtt_test_publish("status", "Closing Bot")
_app.notifyTelegram(f"{_app.getMarket()} bot is stopping")
telegram_bot.removeactivebot()
sys.exit(0)
if controlstatus == "reload":
text_box = TextBox(80, 22)
text_box.singleLine()
text_box.center(f"Reloading config parameters {_app.getMarket()}")
text_box.singleLine()
Logger.debug("Reloading config parameters.")
_app.read_config(_app.getExchange())
if _app.enableWebsocket():
_websocket.close()
if _app.getExchange() == Exchange.BINANCE:
_websocket = BWebSocketClient([app.getMarket()], app.getGranularity())
elif _app.getExchange() == Exchange.COINBASEPRO:
_websocket = CWebSocketClient([app.getMarket()], app.getGranularity())
elif _app.getExchange() == Exchange.KUCOIN:
_websocket = KWebSocketClient([app.getMarket()], app.getGranularity())
_websocket.start()
_app.setGranularity(_app.getGranularity())
list(map(s.cancel, s.queue))
s.enter(5, 1, execute_job, (sc, _app, _state, _technical_analysis, _websocket))
# _app.read_config(_app.getExchange())
telegram_bot.updatebotstatus("active")
# reset _websocket every 23 hours if applicable
if _app.enableWebsocket() and not _app.isSimulation():
if _websocket.getTimeElapsed() > 82800:
Logger.info("Websocket requires a restart every 23 hours!")
Logger.info("Stopping _websocket...")
_websocket.close()
Logger.info("Starting _websocket...")
_websocket.start()
Logger.info("Restarting job in 30 seconds...")
s.enter(
30, 1, execute_job, (sc, _app, _state, _technical_analysis, _websocket)
)
# 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(_state.last_df_index))
trading_data = _app.getSmartSwitchHistoricalDataChained(
_app.getMarket(),
_app.getGranularity(),
str(startDate),
str(endDate),
)
if _app.getGranularity() == Granularity.ONE_HOUR:
simDate = _app.getDateFromISO8601Str(str(simDate))
sim_rounded = pd.Series(simDate).dt.round("60min")
simDate = sim_rounded[0]
elif _app.getGranularity() == Granularity.FIFTEEN_MINUTES:
simDate = _app.getDateFromISO8601Str(str(simDate))
sim_rounded = pd.Series(simDate).dt.round("15min")
simDate = sim_rounded[0]
elif _app.getGranularity() == Granularity.FIVE_MINUTES:
simDate = _app.getDateFromISO8601Str(str(simDate))
sim_rounded = pd.Series(simDate).dt.round("5min")
simDate = sim_rounded[0]
dateFound = False
while dateFound == False:
try:
_state.iterations = trading_data.index.get_loc(str(simDate)) + 1
dateFound = True
except: # pylint: disable=bare-except
simDate += timedelta(seconds=_app.getGranularity().value[0])
if (
_app.getDateFromISO8601Str(str(simDate)).isoformat()
== _app.getDateFromISO8601Str(str(_state.last_df_index)).isoformat()
):
_state.iterations += 1
if _state.iterations == 0:
_state.iterations = 1
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
if _state.iterations == 2:
# check if bot has open or closed order
# update data.json "opentrades"
if _state.last_action == "BUY":
telegram_bot.add_open_order()
else:
telegram_bot.remove_open_order()
if (
(last_api_call_datetime.seconds > 60 or _app.isSimulation())
and _app.getSmartSwitch() == 1
and _app.getSellSmartSwitch() == 1
and _app.getGranularity() != Granularity.FIVE_MINUTES
and _state.last_action == "BUY"
):
if not _app.isSimulation() or (
_app.isSimulation() and not _app.simResultOnly()
):
Logger.info(
"*** open order detected smart switching to 300 (5 min) granularity ***"
)
mqtt_test_publish("status", "*** open order detected smart switching to 300 (5 min) granularity ***")
if not _app.telegramTradesOnly():
_app.notifyTelegram(
_app.getMarket()
+ " open order detected smart switching to 300 (5 min) granularity"
)
if _app.isSimulation():
_app.sim_smartswitch = True
_app.setGranularity(Granularity.FIVE_MINUTES)
list(map(s.cancel, s.queue))
s.enter(5, 1, execute_job, (sc, _app, _state, _technical_analysis, _websocket))
if (
(last_api_call_datetime.seconds > 60 or _app.isSimulation())
and _app.getSmartSwitch() == 1
and _app.getSellSmartSwitch() == 1
and _app.getGranularity() == Granularity.FIVE_MINUTES
and _state.last_action == "SELL"
):
if not _app.isSimulation() or (
_app.isSimulation() and not _app.simResultOnly()
):
Logger.info(
"*** sell detected smart switching to 3600 (1 hour) granularity ***"
)
if not _app.telegramTradesOnly():
_app.notifyTelegram(
_app.getMarket()
+ " sell detected smart switching to 3600 (1 hour) granularity"
)
if _app.isSimulation():
_app.sim_smartswitch = True
_app.setGranularity(Granularity.ONE_HOUR)
list(map(s.cancel, s.queue))
s.enter(5, 1, execute_job, (sc, _app, _state, _technical_analysis, _websocket))
# use actual sim mode date to check smartchswitch
if (
(last_api_call_datetime.seconds > 60 or _app.isSimulation())
and _app.getSmartSwitch() == 1
and _app.getGranularity() == Granularity.ONE_HOUR
and _app.is1hEMA1226Bull(current_sim_date, _websocket) is True
and _app.is6hEMA1226Bull(current_sim_date, _websocket) is True
):
if not _app.isSimulation() or (
_app.isSimulation() and not _app.simResultOnly()
):
Logger.info(
"*** smart switch from granularity 3600 (1 hour) to 900 (15 min) ***"
)
mqtt_test_publish("status", "*** smart switch from granularity 3600 (1 hour) to 900 (15 min) ***")
if _app.isSimulation():
_app.sim_smartswitch = True
if not _app.telegramTradesOnly():
_app.notifyTelegram(
_app.getMarket()
+ " smart switch from granularity 3600 (1 hour) to 900 (15 min)"
)
_app.setGranularity(Granularity.FIFTEEN_MINUTES)
list(map(s.cancel, s.queue))
s.enter(5, 1, execute_job, (sc, _app, _state, _technical_analysis, _websocket))
# use actual sim mode date to check smartchswitch
if (
(last_api_call_datetime.seconds > 60 or _app.isSimulation())
and _app.getSmartSwitch() == 1
and _app.getGranularity() == Granularity.FIFTEEN_MINUTES
and _app.is1hEMA1226Bull(current_sim_date, _websocket) is False
and _app.is6hEMA1226Bull(current_sim_date, _websocket) is False
):
if not _app.isSimulation() or (
_app.isSimulation() and not _app.simResultOnly()
):
Logger.info(
"*** smart switch from granularity 900 (15 min) to 3600 (1 hour) ***"
)
if _app.isSimulation():
_app.sim_smartswitch = True
if not _app.telegramTradesOnly():
_app.notifyTelegram(
f"{_app.getMarket()} smart switch from granularity 900 (15 min) to 3600 (1 hour)"
)
_app.setGranularity(Granularity.ONE_HOUR)
list(map(s.cancel, s.queue))
s.enter(5, 1, execute_job, (sc, _app, _state, _technical_analysis, _websocket))
if (
_app.getExchange() == Exchange.BINANCE
and _app.getGranularity() == Granularity.ONE_DAY
):
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, execute_job, (sc, _app, _state, _technical_analysis, _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,
execute_job,
(sc, _app, _state, _technical_analysis, _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
# If using websockets make this call every minute instead of each iteration
if _app.enableWebsocket() and not _app.isSimulation():
if last_api_call_datetime.seconds > 60:
_state.pollLastAction()
else:
_state.pollLastAction()
if last_action_current != _state.last_action:
Logger.info(
f"last_action change detected from {last_action_current} to {_state.last_action}"
)
if not _app.telegramTradesOnly():
_app.notifyTelegram(
f"{_app.getMarket} last_action change detected from {last_action_current} to {_state.last_action}"
)
# this is used to confirm last trade if error occurred during trade process
# make sure signals and telegram info is set correctly, close bot if needed on sell
if _state.action == "check_buy" and _state.last_action == "BUY":
_state.trade_error_cnt = 0
_state.trailing_buy = 0
_state.action = None
telegram_bot.add_open_order()
Logger.warning(
f"{_app.getMarket()} ({_app.printGranularity}) - {datetime.today().strftime('%Y-%m-%d %H:%M:%S')}\n"
f"Catching BUY that occurred previously. Updating signal information."
)
_app.notifyTelegram(
_app.getMarket()
+ " ("
+ _app.printGranularity()
+ ") - "
+ datetime.today().strftime("%Y-%m-%d %H:%M:%S")
+ "\n"
+ "Catching BUY that occurred previously. Updating signal information."
)
elif _state.action == "check_sell" and _state.last_action == "SELL":
_state.prevent_loss = 0
_state.tsl_triggered = 0
_state.trade_error_cnt = 0
_state.action = None
telegram_bot.remove_open_order()
Logger.warning(
f"{_app.getMarket()} ({_app.printGranularity}) - {datetime.today().strftime('%Y-%m-%d %H:%M:%S')}\n"
f"Catching SELL that occurred previously. Updating signal information."
)
_app.notifyTelegram(
_app.getMarket()
+ " ("
+ _app.printGranularity()
+ ") - "
+ datetime.today().strftime("%Y-%m-%d %H:%M:%S")
+ "\n"
+ "Catching SELL that occurred previously. Updating signal information."
)
if _app.enableexitaftersell and _app.startmethod not in (
"standard"
):
sys.exit(0)
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.000001:
raise Exception(
f"{_app.getMarket()} is unsuitable for trading, quote price is less than 0.000001!"
)
# 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])
mqtt_test_publish("technical_indicators/" + "ema12gtema26",ema12gtema26)
mqtt_test_publish("technical_indicators/" + "ema12gtema26co", ema12gtema26co )
mqtt_test_publish("technical_indicators/" + "goldencross", goldencross)
mqtt_test_publish("technical_indicators/" + "macdgtsignal", macdgtsignal)
mqtt_test_publish("technical_indicators/" + "macdgtsignalco", macdgtsignalco)
mqtt_test_publish("technical_indicators/" + "ema12ltema26", ema12ltema26)
mqtt_test_publish("technical_indicators/" + "ema12ltema26co", ema12ltema26co)
mqtt_test_publish("technical_indicators/" + "macdltsignal", macdltsignal)
mqtt_test_publish("technical_indicators/" + "macdltsignalco", macdltsignalco)
mqtt_test_publish("technical_indicators/" + "obvVVVVV", obv)
mqtt_test_publish("technical_indicators/" + "obv_pc", obv_pc)
mqtt_test_publish("technical_indicators/" + "elder_ray_buy", elder_ray_buy)
mqtt_test_publish("technical_indicators/" + "elder_ray_sell", elder_ray_sell)
# mqtt = BotConfig.config["mqtt"]
# config = PyCryptoBot.getConfig(self)
# mqtt = config["mqtt"]
# print(mqtt["mqtt_user"] + " " + mqtt["password"] + " " + mqtt["broker"] + " " + mqtt["transport"])
# 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])
mqtt_test_publish("candlestick/hammer", hammer)
mqtt_test_publish("candlestick/inverted_hammer",inverted_hammer )
mqtt_test_publish("candlestick/hanging_man", hanging_man)
mqtt_test_publish("candlestick/shooting_star", shooting_star)
mqtt_test_publish("candlestick/three_white_soldiers", three_white_soldiers)
mqtt_test_publish("candlestick/three_black_crows", three_black_crows)
mqtt_test_publish("candlestick/morning_star", morning_star)
mqtt_test_publish( "candlestick/evening_star", evening_star)
mqtt_test_publish("candlestick/three_line_strike", three_line_strike)
mqtt_test_publish("candlestick/abandoned_baby", abandoned_baby)
mqtt_test_publish("candlestick/morning_doji_star", morning_doji_star)
mqtt_test_publish("candlestick/evening_doji_star", evening_doji_star)
mqtt_test_publish("candlestick/two_black_gapping", two_black_gapping)
# Log data for Telegram Bot
telegram_bot.addindicators("EMA", ema12gtema26 or ema12gtema26co)
if not _app.disableBuyElderRay():
telegram_bot.addindicators("ERI", elder_ray_buy)
if _app.disableBullOnly():
telegram_bot.addindicators("BULL", goldencross)
if not _app.disableBuyMACD():
telegram_bot.addindicators("MACD", macdgtsignal or macdgtsignalco)
if not _app.disableBuyOBV():
telegram_bot.addindicators("OBV", float(obv_pc) > 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(_app, price, current_sim_date)
immediate_action = False
margin, profit, sell_fee, change_pcnt_high = 0, 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():
if _app.enableWebsocket():
if last_api_call_datetime.seconds > 60:
_state.exchange_last_buy = _app.getLastBuy()
else:
_state.exchange_last_buy = _app.getLastBuy()
exchange_last_buy = _state.exchange_last_buy
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() == Exchange.COINBASEPRO
or _app.getExchange() == Exchange.KUCOIN
):
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 immediate sell actions
if strategy.isSellTrigger(
_app,
_state,
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 immediate_action is not True and strategy.isWaitTrigger(_app, margin, goldencross):
_state.action = "WAIT"
immediate_action = False
if _app.enableImmediateBuy():
if _state.action == "BUY":
immediate_action = True
if not _app.isSimulation() and _app.enableTelegramBotControl():
manual_buy_sell = telegram_bot.checkmanualbuysell()
if not manual_buy_sell == "WAIT":
_state.action = manual_buy_sell
_state.last_action = "BUY" if _state.action == "SELL" else "SELL"
immediate_action = True
# If buy signal, save the price and check for decrease/increase before buying.
trailing_buy_logtext = ""
if _state.action == "BUY" and immediate_action is not True:
_state.action, _state.trailing_buy, trailing_buy_logtext, immediate_action = strategy.checkTrailingBuy(_app, _state, price)
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:
text_box = 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)
if immediate_action:
price_text = str(price)
else:
price_text = "Close: " + str(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: | "
log_text = ""
if hammer is True:
log_text = '* Candlestick Detected: Hammer ("Weak - Reversal - Bullish Signal - Up")'
if shooting_star is True:
log_text = '* Candlestick Detected: Shooting Star ("Weak - Reversal - Bearish Pattern - Down")'
if hanging_man is True:
log_text = '* Candlestick Detected: Hanging Man ("Weak - Continuation - Bearish Pattern - Down")'
if inverted_hammer is True:
log_text = '* Candlestick Detected: Inverted Hammer ("Weak - Continuation - Bullish Pattern - Up")'
if three_white_soldiers is True:
log_text = '*** Candlestick Detected: Three White Soldiers ("Strong - Reversal - Bullish Pattern - Up")'
if three_black_crows is True:
log_text = '* Candlestick Detected: Three Black Crows ("Strong - Reversal - Bearish Pattern - Down")'
if morning_star is True:
log_text = '*** Candlestick Detected: Morning Star ("Strong - Reversal - Bullish Pattern - Up")'
if evening_star is True:
log_text = '*** Candlestick Detected: Evening Star ("Strong - Reversal - Bearish Pattern - Down")'
if three_line_strike is True:
log_text = '** Candlestick Detected: Three Line Strike ("Reliable - Reversal - Bullish Pattern - Up")'
if abandoned_baby is True:
log_text = '** Candlestick Detected: Abandoned Baby ("Reliable - Reversal - Bullish Pattern - Up")'
if morning_doji_star is True:
log_text = '** Candlestick Detected: Morning Doji Star ("Reliable - Reversal - Bullish Pattern - Up")'
if evening_doji_star is True:
log_text = '** Candlestick Detected: Evening Doji Star ("Reliable - Reversal - Bearish Pattern - Down")'
if two_black_gapping is True:
log_text = '*** Candlestick Detected: Two Black Gapping ("Reliable - Reversal - Bearish Pattern - Down")'
if (
log_text != ""
and not _app.isSimulation()
or (_app.isSimulation() and not _app.simResultOnly())
):
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 existing 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
+ trailing_buy_logtext
+ " | "
+ 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
+ trailing_buy_logtext
+ " | "
+ 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
+ trailing_buy_logtext
+ " | "
+ ema_co_prefix
+ ema_text
+ ema_co_suffix
+ macd_co_prefix
+ macd_text
+ macd_co_suffix