-
Notifications
You must be signed in to change notification settings - Fork 746
/
Copy pathPyCryptoBot.py
3241 lines (2824 loc) · 152 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
import os
import sys
import time
import json
import random
import sched
import signal
import functools
import pandas as pd
import numpy as np
from regex import R
from rich.console import Console
from rich.table import Table
from rich.text import Text
from rich import box
from datetime import datetime, timedelta
from os.path import exists as file_exists
from urllib3.exceptions import ReadTimeoutError
from models.BotConfig import BotConfig
from models.exchange.ExchangesEnum import Exchange
from models.exchange.Granularity import Granularity
from models.exchange.coinbase_pro import WebSocketClient as CWebSocketClient
from models.exchange.coinbase_pro import AuthAPI as CAuthAPI, PublicAPI as CPublicAPI
from models.exchange.kucoin import AuthAPI as KAuthAPI, PublicAPI as KPublicAPI
from models.exchange.kucoin import WebSocketClient as KWebSocketClient
from models.exchange.binance import AuthAPI as BAuthAPI, PublicAPI as BPublicAPI
from models.exchange.binance import WebSocketClient as BWebSocketClient
from models.exchange.coinbase import AuthAPI as CBAuthAPI
from models.exchange.coinbase import WebSocketClient as CBWebSocketClient
from models.helper.TelegramBotHelper import TelegramBotHelper
from models.helper.MarginHelper import calculate_margin
from models.TradingAccount import TradingAccount
from models.Stats import Stats
from models.AppState import AppState
from models.helper.TextBoxHelper import TextBox
from models.Strategy import Strategy
from views.TradingGraphs import TradingGraphs
from views.PyCryptoBot import RichText
from utils.PyCryptoBot import truncate as _truncate
from utils.PyCryptoBot import compare as _compare
try:
if file_exists("models/Trading_myPta.py"):
from models.Trading_myPta import TechnicalAnalysis # pyright: ignore[reportMissingImports]
trading_myPta = True
pandas_ta_enabled = True
else:
from models.Trading import TechnicalAnalysis
trading_myPta = False
pandas_ta_enabled = False
except ModuleNotFoundError:
from models.Trading import TechnicalAnalysis
trading_myPta = False
pandas_ta_enabled = False
except ImportError:
from models.Trading import TechnicalAnalysis
trading_myPta = False
pandas_ta_enabled = False
pd.set_option("display.float_format", "{:.8f}".format)
def signal_handler(signum):
if signum == 2:
print("Please be patient while websockets terminate!")
return
class PyCryptoBot(BotConfig):
def __init__(self, config_file: str = None, exchange: Exchange = None):
self.config_file = config_file or "config.json"
super(PyCryptoBot, self).__init__(filename=self.config_file, exchange=exchange)
self.console_term = Console(no_color=(not self.term_color), width=self.term_width) # logs to the screen
self.console_log = Console(file=open(self.logfile, "w"), no_color=True, width=self.log_width) # logs to file
self.table_console = Table(title=None, box=None, show_header=False, show_footer=False)
self.s = sched.scheduler(time.time, time.sleep)
self.price = 0
self.takerfee = -1.0
self.makerfee = 0.0
self.account = None
self.state = None
self.technical_analysis = None
self.websocket_connection = None
self.ticker_self = None
self.df_last = pd.DataFrame()
self.trading_data = pd.DataFrame()
self.telegram_bot = TelegramBotHelper(self)
self.trade_tracker = pd.DataFrame(
columns=[
"Datetime",
"Market",
"Action",
"Price",
"Base",
"Quote",
"Margin",
"Profit",
"Fee",
"DF_High",
"DF_Low",
]
)
if trading_myPta is True and pandas_ta_enabled is True:
self.enable_pandas_ta = True
else:
self.enable_pandas_ta = False
def execute_job(self):
"""Trading bot job which runs at a scheduled interval"""
if self.is_live:
self.state.account.mode = "live"
else:
self.state.account.mode = "test"
# This is used to control some API calls when using websockets
last_api_call_datetime = datetime.now() - self.state.last_api_call_datetime
if last_api_call_datetime.seconds > 60:
self.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 self.is_sim and not self.disabletelegram:
control_status = self.telegram_bot.check_bot_control_status()
while control_status == "pause" or control_status == "paused":
if control_status == "pause":
RichText.notify("Pausing bot", self, "normal")
self.notify_telegram(f"{self.market} bot is paused")
self.telegram_bot.update_bot_status("paused")
if self.websocket:
RichText.notify("Closing websocket...", self, "normal")
self.websocket_connection.close()
time.sleep(30)
control_status = self.telegram_bot.check_bot_control_status()
if control_status == "start":
RichText.notify("Restarting bot", self, "normal")
self.notify_telegram(f"{self.market} bot has restarted")
self.telegram_bot.update_bot_status("active")
self.read_config(self.exchange)
if self.websocket:
RichText.notify("Starting websocket...", self, "normal")
self.websocket_connection.start()
if control_status == "exit":
RichText.notify("Closing Bot {self.market}", self, "normal")
self.notify_telegram(f"{self.market} bot is stopping")
self.telegram_bot.remove_active_bot()
sys.exit(0)
if control_status == "reload":
RichText.notify(f"Reloading config parameters {self.market}", self, "normal")
self.read_config(self.exchange)
if self.websocket:
self.websocket_connection.close()
if self.exchange == Exchange.BINANCE:
self.websocket_connection = BWebSocketClient([self.market], self.granularity, app=self)
elif self.exchange == Exchange.COINBASE:
self.websocket_connection = CBWebSocketClient([self.market], self.granularity, app=self)
elif self.exchange == Exchange.COINBASEPRO:
self.websocket_connection = CWebSocketClient([self.market], self.granularity, app=self)
elif self.exchange == Exchange.KUCOIN:
self.websocket_connection = KWebSocketClient([self.market], self.granularity, app=self)
self.websocket_connection.start()
list(map(self.s.cancel, self.s.queue))
self.s.enter(
5,
1,
self.execute_job,
(),
)
# self.read_config(self.exchange)
self.telegram_bot.update_bot_status("active")
else:
# runs once at the start of a simulation
if self.app_started:
if self.simstartdate is not None:
try:
self.state.iterations = self.trading_data.index.get_loc(str(self.get_date_from_iso8601_str(self.simstartdate)))
except KeyError:
RichText.notify("Simulation data is invalid, unable to locate interval using date key.", self, "error")
sys.exit(0)
self.app_started = False
# reset self.websocket_connection every 23 hours if applicable
if self.websocket and not self.is_sim:
if self.websocket_connection.time_elapsed > 82800:
RichText.notify("Websocket requires a restart every 23 hours!", self, "normal")
RichText.notify("Stopping websocket...", self, "normal")
self.websocket_connection.close()
RichText.notify("Starting websocket...", self, "normal")
self.websocket_connection.start()
RichText.notify("Restarting job in 30 seconds...", self, "normal")
self.s.enter(
30,
1,
self.execute_job,
(),
)
# increment self.state.iterations
self.state.iterations = self.state.iterations + 1
if not self.is_sim:
# check if data exists or not and only refresh at candle close.
if len(self.trading_data) == 0 or (
len(self.trading_data) > 0
and (
datetime.timestamp(datetime.utcnow()) - self.granularity.to_integer
>= datetime.timestamp(
self.trading_data.iloc[
self.state.closed_candle_row,
self.trading_data.columns.get_loc("date"),
]
)
)
):
self.trading_data = self.get_historical_data(self.market, self.granularity, self.websocket_connection)
self.state.closed_candle_row = -1
self.price = float(self.trading_data.iloc[-1, self.trading_data.columns.get_loc("close")])
else:
# set time and price with ticker data and add/update current candle
ticker = self.get_ticker(self.market, self.websocket_connection)
# if 0, use last close value as self.price
self.price = self.trading_data["close"].iloc[-1] if ticker[1] == 0 else ticker[1]
self.ticker_date = ticker[0]
self.ticker_price = ticker[1]
if self.state.closed_candle_row == -2:
self.trading_data.iloc[-1, self.trading_data.columns.get_loc("low")] = (
self.price if self.price < self.trading_data["low"].iloc[-1] else self.trading_data["low"].iloc[-1]
)
self.trading_data.iloc[-1, self.trading_data.columns.get_loc("high")] = (
self.price if self.price > self.trading_data["high"].iloc[-1] else self.trading_data["high"].iloc[-1]
)
self.trading_data.iloc[-1, self.trading_data.columns.get_loc("close")] = self.price
self.trading_data.iloc[-1, self.trading_data.columns.get_loc("date")] = datetime.strptime(ticker[0], "%Y-%m-%d %H:%M:%S")
tsidx = pd.DatetimeIndex(self.trading_data["date"])
self.trading_data.set_index(tsidx, inplace=True)
self.trading_data.index.name = "ts"
else:
# not sure what this code is doing as it has a bug.
# i've added a websocket check and added a try..catch block
if self.websocket:
try:
self.trading_data.loc[len(self.trading_data.index)] = [
datetime.strptime(ticker[0], "%Y-%m-%d %H:%M:%S"),
self.trading_data["market"].iloc[-1],
self.trading_data["granularity"].iloc[-1],
(self.price if self.price < self.trading_data["close"].iloc[-1] else self.trading_data["close"].iloc[-1]),
(self.price if self.price > self.trading_data["close"].iloc[-1] else self.trading_data["close"].iloc[-1]),
self.trading_data["close"].iloc[-1],
self.price,
self.trading_data["volume"].iloc[-1],
]
tsidx = pd.DatetimeIndex(self.trading_data["date"])
self.trading_data.set_index(tsidx, inplace=True)
self.trading_data.index.name = "ts"
self.state.closed_candle_row = -2
except Exception:
pass
else:
self.df_last = self.get_interval(self.trading_data, self.state.iterations)
if len(self.df_last) > 0 and "close" in self.df_last:
self.price = self.df_last["close"][0]
if len(self.trading_data) == 0:
return None
# analyse the market data
if self.is_sim and len(self.trading_data.columns) > 8:
df = self.trading_data
# if smartswitch then get the market data using new granularity
if self.sim_smartswitch:
self.df_last = self.get_interval(df, self.state.iterations)
if len(self.df_last.index.format()) > 0:
if self.simstartdate is not None:
start_date = self.get_date_from_iso8601_str(self.simstartdate)
else:
start_date = self.get_date_from_iso8601_str(str(df.head(1).index.format()[0]))
if self.simenddate is not None:
if self.simenddate == "now":
end_date = self.get_date_from_iso8601_str(str(datetime.now()))
else:
end_date = self.get_date_from_iso8601_str(self.simenddate)
else:
end_date = self.get_date_from_iso8601_str(str(df.tail(1).index.format()[0]))
simDate = self.get_date_from_iso8601_str(str(self.state.last_df_index))
trading_data = self.get_smart_switch_historical_data_chained(
self.market,
self.granularity,
str(start_date),
str(end_date),
)
if self.granularity == Granularity.ONE_HOUR:
simDate = self.get_date_from_iso8601_str(str(simDate))
sim_rounded = pd.Series(simDate).dt.round("60min")
simDate = sim_rounded[0]
elif self.granularity == Granularity.FIFTEEN_MINUTES:
simDate = self.get_date_from_iso8601_str(str(simDate))
sim_rounded = pd.Series(simDate).dt.round("15min")
simDate = sim_rounded[0]
elif self.granularity == Granularity.FIVE_MINUTES:
simDate = self.get_date_from_iso8601_str(str(simDate))
sim_rounded = pd.Series(simDate).dt.round("5min")
simDate = sim_rounded[0]
dateFound = False
while dateFound is False:
try:
self.state.iterations = trading_data.index.get_loc(str(simDate)) + 1
dateFound = True
except Exception:
simDate += timedelta(seconds=self.granularity.value[0])
if self.get_date_from_iso8601_str(str(simDate)).isoformat() == self.get_date_from_iso8601_str(str(self.state.last_df_index)).isoformat():
self.state.iterations += 1
if self.state.iterations == 0:
self.state.iterations = 1
trading_dataCopy = trading_data.copy()
_technical_analysis = TechnicalAnalysis(trading_dataCopy, self.adjusttotalperiods, app=self)
# if 'bool(self.df_last["morning_star"].values[0])' not in df:
_technical_analysis.add_all()
df = _technical_analysis.get_df()
self.sim_smartswitch = False
elif self.smart_switch == 1 and _technical_analysis is None:
trading_dataCopy = trading_data.copy()
_technical_analysis = TechnicalAnalysis(trading_dataCopy, self.adjusttotalperiods, app=self)
if "morning_star" not in df:
_technical_analysis.add_all()
df = _technical_analysis.get_df()
else:
_technical_analysis = TechnicalAnalysis(self.trading_data, len(self.trading_data), app=self)
_technical_analysis.add_all()
df = _technical_analysis.get_df()
if self.is_sim:
self.df_last = self.get_interval(df, self.state.iterations)
else:
self.df_last = self.get_interval(df)
# Don't want index of new, unclosed candle, use the historical row setting to set index to last closed candle
if self.state.closed_candle_row != -2 and len(self.df_last.index.format()) > 0:
current_df_index = str(self.df_last.index.format()[0])
else:
current_df_index = self.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 self.state.iterations == 2:
# check if bot has open or closed order
# update data.json "opentrades"
if not self.disabletelegram:
if self.state.last_action == "BUY":
self.telegram_bot.add_open_order()
else:
self.telegram_bot.remove_open_order()
if (
(last_api_call_datetime.seconds > 60 or self.is_sim)
and self.smart_switch == 1
and self.sell_smart_switch == 1
and self.granularity != Granularity.FIVE_MINUTES
and self.state.last_action == "BUY"
):
if not self.is_sim or (self.is_sim and not self.simresultonly):
RichText.notify(
"Open order detected smart switching to 300 (5 min) granularity.",
self,
"normal",
)
if not self.telegramtradesonly:
self.notify_telegram(self.market + " open order detected smart switching to 300 (5 min) granularity")
if self.is_sim:
self.sim_smartswitch = True
self.granularity = Granularity.FIVE_MINUTES
list(map(self.s.cancel, self.s.queue))
self.s.enter(5, 1, self.execute_job, ())
if (
(last_api_call_datetime.seconds > 60 or self.is_sim)
and self.smart_switch == 1
and self.sell_smart_switch == 1
and self.granularity == Granularity.FIVE_MINUTES
and self.state.last_action == "SELL"
):
if not self.is_sim or (self.is_sim and not self.simresultonly):
RichText.notify(
"Sell detected smart switching to 3600 (1 hour) granularity.",
self,
"normal",
)
if not self.telegramtradesonly:
self.notify_telegram(self.market + " sell detected smart switching to 3600 (1 hour) granularity")
if self.is_sim:
self.sim_smartswitch = True
self.granularity = Granularity.ONE_HOUR
list(map(self.s.cancel, self.s.queue))
self.s.enter(5, 1, self.execute_job, ())
# use actual sim mode date to check smartchswitch
if (
(last_api_call_datetime.seconds > 60 or self.is_sim)
and self.smart_switch == 1
and self.granularity == Granularity.ONE_HOUR
and self.is_1h_ema1226_bull(current_sim_date) is True
and self.is_6h_ema1226_bull(current_sim_date) is True
):
if not self.is_sim or (self.is_sim and not self.simresultonly):
RichText.notify(
"Smart switch from granularity 3600 (1 hour) to 900 (15 min).",
self,
"normal",
)
if self.is_sim:
self.sim_smartswitch = True
if not self.telegramtradesonly:
self.notify_telegram(self.market + " smart switch from granularity 3600 (1 hour) to 900 (15 min)")
self.granularity = Granularity.FIFTEEN_MINUTES
list(map(self.s.cancel, self.s.queue))
self.s.enter(5, 1, self.execute_job, ())
# use actual sim mode date to check smartchswitch
if (
(last_api_call_datetime.seconds > 60 or self.is_sim)
and self.smart_switch == 1
and self.granularity == Granularity.FIFTEEN_MINUTES
and self.is_1h_ema1226_bull(current_sim_date) is False
and self.is_6h_ema1226_bull(current_sim_date) is False
):
if not self.is_sim or (self.is_sim and not self.simresultonly):
RichText.notify(
"Smart switch from granularity 900 (15 min) to 3600 (1 hour).",
self,
"normal",
)
if self.is_sim:
self.sim_smartswitch = True
if not self.telegramtradesonly:
self.notify_telegram(f"{self.market} smart switch from granularity 900 (15 min) to 3600 (1 hour)")
self.granularity = Granularity.ONE_HOUR
list(map(self.s.cancel, self.s.queue))
self.s.enter(5, 1, self.execute_job, ())
if self.exchange == Exchange.BINANCE and self.granularity == Granularity.ONE_DAY:
if len(df) < 250:
# data frame should have 250 rows, if not retry
RichText.notify(f"Data frame length is < 250 ({str(len(df))})", self, "error")
list(map(self.s.cancel, self.s.queue))
self.s.enter(300, 1, self.execute_job, ())
else:
# verify 300 rows - subtract 34% to allow small buffer if API is acting up.
adjusted_periods = self.adjusttotalperiods - (self.adjusttotalperiods * 0.30)
if len(df) < adjusted_periods: # If 300 is required, set adjusttotalperiods in config to 300 * 30%.
if not self.is_sim:
# data frame should have 300 rows or equal to adjusted total rows if set, if not retry
RichText.notify(
f"error: data frame length is < {str(int(adjusted_periods))} ({str(len(df))})",
self,
"error",
)
# pause for 10 seconds to prevent multiple calls immediately
time.sleep(10)
list(map(self.s.cancel, self.s.queue))
self.s.enter(
300,
1,
self.execute_job,
(),
)
if len(self.df_last) > 0:
# last_action polling if live
if self.is_live:
last_action_current = self.state.last_action
# If using websockets make this call every minute instead of each iteration
if self.websocket and not self.is_sim:
if last_api_call_datetime.seconds > 60:
self.state.poll_last_action()
else:
self.state.poll_last_action()
if last_action_current != self.state.last_action:
RichText.notify(
f"Last action change detected from {last_action_current} to {self.state.last_action}.",
self,
"normal",
)
if not self.telegramtradesonly:
self.notify_telegram(f"{self.market} last_action change detected from {last_action_current} to {self.state.last_action}")
# this is used to reset variables if error occurred during trade process
# make sure signals and telegram info is set correctly, close bot if needed on sell
if self.state.action == "check_action" and self.state.last_action == "BUY":
self.state.trade_error_cnt = 0
self.state.trailing_buy = False
self.state.action = None
self.state.trailing_buy_immediate = False
if not self.disabletelegram:
self.telegram_bot.add_open_order()
if not self.ignorepreviousbuy:
RichText.notify(f"{self.market} ({self.print_granularity()}) - {datetime.today().strftime('%Y-%m-%d %H:%M:%S')}", self, "warning")
RichText.notify("Catching BUY that occurred previously. Updating signal information.", self, "warning")
if not self.telegramtradesonly and not self.disabletelegram:
self.notify_telegram(
self.market
+ " ("
+ self.print_granularity()
+ ") - "
+ datetime.today().strftime("%Y-%m-%d %H:%M:%S")
+ "\n"
+ "Catching BUY that occurred previously. Updating signal information."
)
elif self.state.action == "check_action" and self.state.last_action == "SELL":
self.state.prevent_loss = False
self.state.trailing_sell = False
self.state.trailing_sell_immediate = False
self.state.tsl_triggered = False
self.state.tsl_pcnt = float(self.trailing_stop_loss)
self.state.tsl_trigger = float(self.trailing_stop_loss_trigger)
self.state.tsl_max = False
self.state.trade_error_cnt = 0
self.state.action = None
self.telegram_bot.remove_open_order()
if not self.ignoreprevioussell:
RichText.notify(f"{self.market} ({self.print_granularity()}) - {datetime.today().strftime('%Y-%m-%d %H:%M:%S')}", self, "warning")
RichText.notify("Catching SELL that occurred previously. Updating signal information.", self, "warning")
if not self.telegramtradesonly:
self.notify_telegram(
self.market
+ " ("
+ self.print_granularity()
+ ") - "
+ datetime.today().strftime("%Y-%m-%d %H:%M:%S")
+ "\n"
+ "Catching SELL that occurred previously. Updating signal information."
)
self.telegram_bot.close_trade(
str(self.get_date_from_iso8601_str(str(datetime.now()))),
0,
0,
)
if self.exitaftersell:
RichText.notify("Exit after sell! (\"exitaftersell\" is enabled)", self, "warning")
sys.exit(0)
if self.price < 0.000001:
raise Exception(f"{self.market} is unsuitable for trading, quote self.price is less than 0.000001!")
try:
# technical indicators
ema12gtema26 = bool(self.df_last["ema12gtema26"].values[0])
ema12gtema26co = bool(self.df_last["ema12gtema26co"].values[0])
goldencross = bool(self.df_last["goldencross"].values[0])
macdgtsignal = bool(self.df_last["macdgtsignal"].values[0])
macdgtsignalco = bool(self.df_last["macdgtsignalco"].values[0])
ema12ltema26co = bool(self.df_last["ema12ltema26co"].values[0])
macdltsignalco = bool(self.df_last["macdltsignalco"].values[0])
obv_pc = float(self.df_last["obv_pc"].values[0])
elder_ray_buy = bool(self.df_last["eri_buy"].values[0])
elder_ray_sell = bool(self.df_last["eri_sell"].values[0])
closegtbb20_upperco = bool(self.df_last["closegtbb20_upperco"].values[0])
closeltbb20_lowerco = bool(self.df_last["closeltbb20_lowerco"].values[0])
# if simulation, set goldencross based on actual sim date
if self.is_sim:
if self.adjusttotalperiods < 200:
goldencross = False
else:
goldencross = self.is_1h_sma50200_bull(current_sim_date)
except KeyError as err:
RichText.notify(err, self, "error")
sys.exit()
# Log data for Telegram Bot
self.telegram_bot.add_indicators("EMA", ema12gtema26 or ema12gtema26co)
if not self.disablebuyelderray:
self.telegram_bot.add_indicators("ERI", elder_ray_buy)
if self.disablebullonly:
self.telegram_bot.add_indicators("BULL", goldencross)
if not self.disablebuymacd:
self.telegram_bot.add_indicators("MACD", macdgtsignal or macdgtsignalco)
if not self.disablebuyobv:
self.telegram_bot.add_indicators("OBV", float(obv_pc) > 0)
if self.is_sim:
# 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(self.adjusttotalperiods)
strategy = Strategy(self, self.state, sdf, sdf.index.get_loc(str(current_sim_date)) + 1)
else:
strategy = Strategy(self, self.state, df)
trailing_action_logtext = ""
# determine current action, indicatorvalues will be empty if custom Strategy are disabled or it's debug is False
self.state.action, indicatorvalues = strategy.get_action(self.state, self.price, current_sim_date, self.websocket_connection)
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 self.is_sim:
trading_dataCopy = self.trading_data[self.trading_data["date"] <= current_sim_date].tail(self.adjusttotalperiods).copy()
_technical_analysis = TechnicalAnalysis(trading_dataCopy, self.adjusttotalperiods, app=self)
if self.state.last_buy_size > 0 and self.state.last_buy_price > 0 and self.price > 0 and self.state.last_action == "BUY":
# update last buy high
if self.price > self.state.last_buy_high:
self.state.last_buy_high = self.price
if self.state.last_buy_high > 0:
change_pcnt_high = ((self.price / self.state.last_buy_high) - 1) * 100
else:
change_pcnt_high = 0
# buy and sell calculations
self.state.last_buy_fee = round(self.state.last_buy_size * self.get_taker_fee(), 8)
self.state.last_buy_filled = round(
((self.state.last_buy_size - self.state.last_buy_fee) / self.state.last_buy_price),
8,
)
# if not a simulation, sync with exchange orders
if not self.is_sim:
if self.websocket:
if last_api_call_datetime.seconds > 60:
self.state.exchange_last_buy = self.get_last_buy()
else:
self.state.exchange_last_buy = self.get_last_buy()
exchange_last_buy = self.state.exchange_last_buy
if exchange_last_buy is not None:
if self.state.last_buy_size != exchange_last_buy["size"]:
self.state.last_buy_size = exchange_last_buy["size"]
if self.state.last_buy_filled != exchange_last_buy["filled"]:
self.state.last_buy_filled = exchange_last_buy["filled"]
if self.state.last_buy_price != exchange_last_buy["price"]:
self.state.last_buy_price = exchange_last_buy["price"]
if self.exchange == Exchange.COINBASE or self.exchange == Exchange.COINBASEPRO or self.exchange == Exchange.KUCOIN:
if self.state.last_buy_fee != exchange_last_buy["fee"]:
self.state.last_buy_fee = exchange_last_buy["fee"]
margin, profit, sell_fee = calculate_margin(
buy_size=self.state.last_buy_size,
buy_filled=self.state.last_buy_filled,
buy_price=self.state.last_buy_price,
buy_fee=self.state.last_buy_fee,
sell_percent=self.get_sell_percent(),
sell_price=self.price,
sell_taker_fee=self.get_taker_fee(),
app=self,
)
# handle immediate sell actions
if self.manual_trades_only is False and strategy.is_sell_trigger(
self.state, self.price, _technical_analysis.get_trade_exit(self.price), margin, change_pcnt_high
):
self.state.action = "SELL"
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, manual trades only)
if self.manual_trades_only is True or (self.state.action != "WAIT" and strategy.is_wait_trigger(margin, goldencross)):
self.state.action = "WAIT"
immediate_action = False
# If buy signal, save the self.price and check for decrease/increase before buying.
if self.state.action == "BUY" and immediate_action is not True:
(
self.state.action,
self.state.trailing_buy,
trailing_action_logtext,
immediate_action,
) = strategy.check_trailing_buy(self.state, self.price)
# If sell signal, save the self.price and check for decrease/increase before selling.
if self.state.action == "SELL" and immediate_action is not True:
(
self.state.action,
self.state.trailing_sell,
trailing_action_logtext,
immediate_action,
) = strategy.check_trailing_sell(self.state, self.price)
if self.enableimmediatebuy:
if self.state.action == "BUY":
immediate_action = True
if not self.is_sim and self.telegrambotcontrol:
manual_buy_sell = self.telegram_bot.check_manual_buy_sell()
if not manual_buy_sell == "WAIT":
self.state.action = manual_buy_sell
immediate_action = True
# polling is every 5 minutes (even for hourly intervals), but only process once per interval
if immediate_action is True or self.state.last_df_index != current_df_index:
precision = 4
if self.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)
def _candlestick(candlestick_status: str = "") -> None:
if candlestick_status == "":
return
self.table_console = Table(title=None, box=None, show_header=False, show_footer=False)
self.table_console.add_row(
RichText.styled_text("Bot1", "magenta"),
RichText.styled_text(formatted_current_df_index, "white"),
RichText.styled_text(self.market, "yellow"),
RichText.styled_text(self.print_granularity(), "yellow"),
RichText.styled_text(candlestick_status, "violet"),
)
self.console_term.print(self.table_console)
if self.disablelog is False:
self.console_log.print(self.table_console)
self.table_console = Table(title=None, box=None, show_header=False, show_footer=False) # clear table
def _notify(notification: str = "", level: str = "normal") -> None:
if notification == "":
return
if level == "warning":
color = "dark_orange"
elif level == "error":
color = "red1"
elif level == "critical":
color = "red1 blink"
elif level == "info":
color = "yellow blink"
else:
color = "violet"
self.table_console = Table(title=None, box=None, show_header=False, show_footer=False)
self.table_console.add_row(
RichText.styled_text("Bot1", "magenta"),
RichText.styled_text(formatted_current_df_index, "white"),
RichText.styled_text(self.market, "yellow"),
RichText.styled_text(self.print_granularity(), "yellow"),
RichText.styled_text(notification, color),
)
self.console_term.print(self.table_console)
if self.disablelog is False:
self.console_log.print(self.table_console)
self.table_console = Table(title=None, box=None, show_header=False, show_footer=False) # clear table
if not self.is_sim:
df_high = df[df["date"] <= current_sim_date]["close"].max()
df_low = df[df["date"] <= current_sim_date]["close"].min()
range_start = str(df.iloc[0, 0])
range_end = str(df.iloc[len(df) - 1, 0])
else:
df_high = df["close"].max()
df_low = df["close"].min()
if len(df) > self.adjusttotalperiods:
range_start = str(df.iloc[self.state.iterations - self.adjusttotalperiods, 0]) # noqa: F841
else:
# RichText.notify(f"Trading dataframe length {len(df)} is greater than expected {self.adjusttotalperiods}", self, "warning")
range_start = str(df.iloc[self.state.iterations - len(df), 0]) # noqa: F841
range_end = str(df.iloc[self.state.iterations - 1, 0]) # noqa: F841
df_swing = round(((df_high - df_low) / df_low) * 100, 2)
df_near_high = round(((self.price - df_high) / df_high) * 100, 2)
if self.state.last_action == "BUY":
if self.state.last_buy_size > 0:
margin_text = truncate(margin) + "%"
else:
margin_text = "0%"
if self.is_sim:
# save margin for summary if open trade
self.state.open_trade_margin_float = margin
self.state.open_trade_margin = margin_text
else:
margin_text = ""
args = [
arg
for arg in [
RichText.styled_text("Bot1", "magenta"),
RichText.styled_text(formatted_current_df_index, "white"),
RichText.styled_text(self.market, "yellow"),
RichText.styled_text(self.print_granularity(), "yellow"),
RichText.styled_text(str(self.price), "white"),
RichText.bull_bear(goldencross),
RichText.number_comparison(
"EMA12/26:",
round(self.df_last["ema12"].values[0], 2),
round(self.df_last["ema26"].values[0], 2),
ema12gtema26co or ema12ltema26co,
self.disablebuyema,
),
RichText.number_comparison(
"MACD:",
round(self.df_last["macd"].values[0], 2),
round(self.df_last["signal"].values[0], 2),
macdgtsignalco or macdltsignalco,
self.disablebuymacd,
),
RichText.styled_text(trailing_action_logtext),
RichText.on_balance_volume(
self.df_last["obv"].values[0],
self.df_last["obv_pc"].values[0],
self.disablebuyobv,
),
RichText.elder_ray(elder_ray_buy, elder_ray_sell, self.disablebuyelderray),
RichText.number_comparison(
"BBU:",
round(self.df_last["close"].values[0], 2),
round(self.df_last["bb20_upper"].values[0], 2),
closegtbb20_upperco or closeltbb20_lowerco,
self.disablebuybbands_s1,
),
RichText.number_comparison(
"BBL:",
round(self.df_last["bb20_lower"].values[0], 2),
round(self.df_last["close"].values[0], 2),
closegtbb20_upperco or closeltbb20_lowerco,
self.disablebuybbands_s1,
),
RichText.action_text(self.state.action),
RichText.last_action_text(self.state.last_action),
RichText.styled_label_text(
"DF-H/L",
"white",
f"{str(df_high)} / {str(df_low)} ({df_swing}%)",
"cyan",
),
RichText.styled_label_text("Near-High", "white", f"{df_near_high}%", "cyan"), # price near high
RichText.styled_label_text("Range", "white", f"{range_start} <-> {range_end}", "cyan") if (self.term_width > 120) else None,
RichText.margin_text(margin_text, self.state.last_action),
RichText.delta_text(
self.price,
self.state.last_buy_price,
precision,
self.state.last_action,
),
]
if arg
]
if not self.is_sim or (self.is_sim and not self.simresultonly):
self.table_console.add_row(*args)
self.console_term.print(self.table_console)
if self.disablelog is False:
self.console_log.print(self.table_console)
self.table_console = Table(title=None, box=None, show_header=False, show_footer=False) # clear table
if self.state.last_action == "BUY":
# display support, resistance and fibonacci levels
if not self.is_sim:
_notify(_technical_analysis.print_support_resistance_fibonacci_levels(self.price))
# if a buy signal
if self.state.action == "BUY":
self.state.last_buy_price = self.price
self.state.last_buy_high = self.state.last_buy_price
# if live
if self.is_live:
self.insufficientfunds = False
try:
self.account.quote_balance_before = self.account.get_balance(self.quote_currency)
self.state.last_buy_size = float(self.account.quote_balance_before)
if self.buymaxsize and self.buylastsellsize and self.state.minimum_order_quote(quote=self.state.last_sell_size, balancechk=True):
self.state.last_buy_size = self.state.last_sell_size
elif self.buymaxsize and self.state.last_buy_size > self.buymaxsize:
self.state.last_buy_size = self.buymaxsize
if self.account.quote_balance_before < self.state.last_buy_size:
self.insufficientfunds = True
except Exception:
pass
if not self.insufficientfunds and self.buyminsize < self.account.quote_balance_before:
if not self.is_live:
if not self.is_sim or (self.is_sim and not self.simresultonly):
_notify(f"*** Executing SIMULATION Buy Order at {str(self.price)} ***", "info")
else:
_notify("*** Executing LIVE Buy Order ***", "info")
# display balances
_notify(f"{self.base_currency} balance before order: {str(self.account.base_balance_before)}", "debug")
_notify(f"{self.quote_currency} balance before order: {str(self.account.quote_balance_before)}", "debug")
# place the buy order
resp_error = 0
try:
self.market_buy(
self.market,
self.state.last_buy_size,
self.get_buy_percent(),
)
except Exception as err:
_notify(f"Trade Error: {err}", "error")
resp_error = 1
if resp_error == 0:
self.account.base_balance_after = 0
self.account.quote_balance_after = 0
try:
ac = self.account.get_balance()
df_base = ac[ac["currency"] == self.base_currency]["available"]
self.account.base_balance_after = 0.0 if len(df_base) == 0 else float(df_base.values[0])
df_quote = ac[ac["currency"] == self.quote_currency]["available"]
self.account.quote_balance_after = 0.0 if len(df_quote) == 0 else float(df_quote.values[0])
bal_error = 0
except Exception as err:
bal_error = 1
_notify(
f"Error: Balance not retrieved after trade for {self.market}",
"warning",
)
_notify(f"API Error Msg: {err}", "warning")
if bal_error == 0:
self.state.trade_error_cnt = 0
self.state.trailing_buy = False
self.state.last_action = "BUY"
self.state.action = "DONE"
self.state.trailing_buy_immediate = False
self.telegram_bot.add_open_order()
if not self.disabletelegram:
self.notify_telegram(
self.market
+ " ("
+ self.print_granularity()
+ ") - "
+ datetime.today().strftime("%Y-%m-%d %H:%M:%S")
+ "\n"