-
-
Notifications
You must be signed in to change notification settings - Fork 16
/
dashboard.py
1729 lines (1446 loc) · 77 KB
/
dashboard.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 pandas as pd
import time
import os
import calendar
from datetime import datetime
import streamlit as st
from millify import millify
import streamlit_authenticator as stauth
import altair as alt
import utils.config as config
import utils.database as database
import exchanges.binance as binance
import utils.general as general
from symbol_by_market_phase import main as force_run_backtest
from my_backtesting import FOLDER_BACKTEST_RESULTS
import update
st.set_page_config(
page_title="Bot Dashboard App",
page_icon="random",
layout="wide",
initial_sidebar_state="collapsed",
menu_items={
'Get Help': 'https://github.com/jptsantossilva/BEC#readme',
'Report a bug': "https://github.com/jptsantossilva/BEC/issues/new",
'About': """# My name is BEC \n I am a Trading Bot and I'm trying to be an *extremely* cool app!
\n This is my dad's 🐦 Twitter: [@jptsantossilva](https://twitter.com/jptsantossilva).
"""
}
)
# for testing purposes
# st.session_state
# Initialization
if "name" not in st.session_state:
st.session_state.name = ""
if "username" not in st.session_state:
st.session_state.username = ""
if "user_password" not in st.session_state:
st.session_state.user_password = "None"
if "reset_form_open" not in st.session_state:
st.session_state.reset_form_open = False
if "reset_password_submitted" not in st.session_state:
st.session_state.reset_password_submitted = False
if "authentication_status" not in st.session_state:
st.session_state.authentication_status = False
def get_chart_daily_balance(asset):
if asset not in ["USD", "BTC"]:
return
expander_total_balance = st.expander(label=f"Daily Balance Snapshot - {asset}", expanded=False)
with expander_total_balance:
period_selected_balances = st.radio(
label='Choose Period',
options=('Last 7 days','Last 30 days', 'Last 90 days', 'YTD', 'All Time'),
index=1,
horizontal=True,
label_visibility='collapsed',
key=f'period_selected_balances_{asset}'
)
if period_selected_balances == 'Last 7 days':
n_days = 7
source = database.get_total_balance_last_n_days(connection, n_days, asset=asset)
elif period_selected_balances == 'Last 30 days':
n_days = 30
source = database.get_total_balance_last_n_days(connection, n_days, asset=asset)
elif period_selected_balances == 'Last 90 days':
n_days = 90
source = database.get_total_balance_last_n_days(connection, n_days, asset=asset)
elif period_selected_balances == 'YTD':
source = database.get_total_balance_ytd(connection, asset=asset)
elif period_selected_balances == 'All Time':
source = database.get_total_balance_all_time(connection, asset=asset)
if source.empty:
st.warning('No data on Balances yet! Click Refresh.')
current_total_balance = 0
else:
if asset == "USD":
current_total_balance = source.Total_Balance_USD.iloc[-1]
elif asset == "BTC":
current_total_balance = source.Total_Balance_BTC.iloc[-1]
col1, col2 = st.columns([10, 1])
with col1:
st.caption(f'Last Daily Balance: {current_total_balance}')
# with col2:
# refresh_balance = st.button("Refresh", key=f"refresh_balance_{asset}")
# if refresh_balance:
# with st.spinner("Creating balance snapshot. It can take a few minutes..."):
# exchange.create_balance_snapshot(telegram_prefix="")
# # dasboard refresh
# st.rerun()
# exit if there is no data to display on chart
if source.empty:
return
hover = alt.selection_single(
fields=["Date"],
nearest=True,
on="mouseover",
empty="none",
)
if asset == "USD":
lines = (
alt.Chart(source,
# title="Total Balance USD Last 30 Days"
)
.mark_line()
.encode(
x="Date",
y=alt.Y(f"Total_Balance_{asset}", title=f"Balance_{asset}",scale=alt.Scale(domain=[source.Total_Balance_USD.min(),source.Total_Balance_USD.max()])),
# color="Total_Balance_USD",
)
)
elif asset == "BTC":
lines = (
alt.Chart(source,
# title="Total Balance USD Last 30 Days"
)
.mark_line()
.encode(
x="Date",
y=alt.Y(f"Total_Balance_{asset}", title=f"Balance_{asset}",scale=alt.Scale(domain=[source.Total_Balance_BTC.min(),source.Total_Balance_BTC.max()])),
# color="Total_Balance_USD",
)
)
# Draw points on the line, and highlight based on selection
points = lines.transform_filter(hover).mark_circle(size=70)
# Draw a rule at the location of the selection
tooltips = (
alt.Chart(source)
.mark_rule()
.encode(
x="Date",
y=f"Total_Balance_{asset}",
opacity=alt.condition(hover, alt.value(0.3), alt.value(0)),
tooltip=[
alt.Tooltip("Date", title="Date"),
alt.Tooltip(f"Total_Balance_{asset}", title=f"Balance_{asset}"),
],
)
.add_selection(hover)
)
chart = (lines + points + tooltips).interactive()
st.altair_chart(chart, use_container_width=True)
def get_chart_daily_asset_balances():
expander_asset_balances = st.expander(label="Daily Asset Balances", expanded=False)
with expander_asset_balances:
period_selected_asset = st.radio(
label='Choose Period',
options=('Last 7 days','Last 30 days', 'Last 90 days', 'YTD', 'All Time'),
index=1,
horizontal=True,
label_visibility='collapsed',
key='period_selected_asset')
if period_selected_asset == 'Last 7 days':
n_days = 7
source = database.get_asset_balances_last_n_days(connection, n_days)
elif period_selected_asset == 'Last 30 days':
n_days = 30
source = database.get_asset_balances_last_n_days(connection, n_days)
elif period_selected_asset == 'Last 90 days':
n_days = 90
source = database.get_asset_balances_last_n_days(connection, n_days)
elif period_selected_asset == 'YTD':
source = database.get_asset_balances_ytd(connection)
elif period_selected_asset == 'All Time':
source = database.get_asset_balances_all_time(connection)
if source.empty:
st.warning('No data on Balances yet!')
# exit - there is no data to display on chart
return
hover = alt.selection_single(
fields=["Date"],
nearest=True,
on="mouseover",
empty="none",
)
lines = (
alt.Chart(source,
# title="Asset Balances Last 30 Days"
)
.mark_line()
.encode(
x="Date",
y=alt.Y("Balance_USD", scale=alt.Scale(domain=[source.Balance_USD.min(),source.Balance_USD.max()])),
color="Asset",
)
)
# Draw points on the line, and highlight based on selection
points = lines.transform_filter(hover).mark_circle(size=70)
# Draw a rule at the location of the selection
tooltips = (
alt.Chart(source)
.mark_rule()
.encode(
x="Date",
y="Balance_USD",
opacity=alt.condition(hover, alt.value(0.3), alt.value(0)),
tooltip=[
alt.Tooltip("Date", title="Date"),
alt.Tooltip("Asset", title="Asset"),
alt.Tooltip("Balance_USD", title="Balance_USD"),
],
)
.add_selection(hover)
)
# chart = (lines + points + tooltips).properties(height=800).interactive()
chart = (lines + points + tooltips).interactive()
st.altair_chart(chart, use_container_width=True)
def realized_pnl():
with tab_rpnl:
# get years
years = get_years(bot_selected)
# years empty list
if len(years) == 0:
st.warning('There are no closed positions yet! 🤞')
col1, col2, col3 = st.columns(3)
# years selectbox
year = col1.selectbox(
'Year',
(years)
)
# get months
# months_dict = get_orders_by_month(year, bot_selected)
months_dict = get_orders_by_month(year)
month_names = list(months_dict.values())
# months selectbox
month_selected_name = col2.selectbox(
'Month',
(month_names)
)
disable_full_year = month_selected_name == None
if month_selected_name == None:
month_number = 1
else: # get month number from month name using months dictionary
month_number = list(months_dict.keys())[list(months_dict.values()).index(month_selected_name)]
if col2.checkbox('Full Year', disabled=disable_full_year):
month_number = 13
result_closed_positions, trades_month_1d, trades_month_4h, trades_month_1h = calculate_realized_pnl(str(year), str(month_number))
# print("\nPnL - Total")
# print(result_closed_positions)
st.header("Realized PnL - Total")
result_closed_positions = result_closed_positions.style.applymap(set_pnl_color, subset=['PnL_Perc','PnL_Value'])
st.dataframe(result_closed_positions)
# print("Realized PnL - Detail")
# print(trades_month_1d)
# print(trades_month_4h)
# print(trades_month_1h)
st.header(f"Realized PnL - Detail")
st.subheader("Bot 1d")
st.dataframe(
trades_month_1d.style.applymap(set_pnl_color, subset=['PnL_Perc','PnL_Value']),
column_config = {
"PnL_Perc": st.column_config.NumberColumn(format="%.2f"),
"PnL_Value": st.column_config.NumberColumn(format=f"%.{num_decimals}f"),
"Exit_Reason": st.column_config.TextColumn(width="large")
}
)
st.subheader("Bot 4h")
st.dataframe(
trades_month_4h.style.applymap(set_pnl_color, subset=['PnL_Perc','PnL_Value']),
column_config = {
"PnL_Perc": st.column_config.NumberColumn(format="%.2f"),
"PnL_Value": st.column_config.NumberColumn(format=f"%.{num_decimals}f"),
"Exit_Reason": st.column_config.TextColumn(width="large")
}
)
st.subheader("Bot 1h")
st.dataframe(
trades_month_1h.style.applymap(set_pnl_color, subset=['PnL_Perc','PnL_Value']),
column_config = {
"PnL_Perc": st.column_config.NumberColumn(format="%.2f"),
"PnL_Value": st.column_config.NumberColumn(format=f"%.{num_decimals}f"),
"Exit_Reason": st.column_config.TextColumn(width="large")
}
)
# print('\n----------------------------\n')
@st.dialog("Delete Position")
def delete_position(symbol, timeframe):
st.warning("If you delete position the sell price will be set to 0.", icon="⚠️")
st.write("As an example, this feature is useful for clearing a position when a symbol is delisted from the exchange and you have no way to sell it.")
st.write(f"Are you sure you want to delete **{symbol}** from **{timeframe}** timeframe?")
if st.button("Delete", key="delete_position"):
binance.delete_position(
symbol=symbol,
bot=timeframe
)
st.rerun()
def unrealized_pnl():
with tab_upnl:
result_open_positions, positions_df_1d, positions_df_4h, positions_df_1h = calculate_unrealized_pnl()
# print("\nUnrealized PnL - Total")
# print('-------------------------------')
# print(result_open_positions)
if positions_df_1d.empty and positions_df_4h.empty and positions_df_1h.empty:
st.warning('There are no open positions yet! 🤞')
st.header("Unrealized PnL - Total")
result_open_positions = result_open_positions.style.applymap(set_pnl_color, subset=['PnL_Perc','PnL_Value'])
st.dataframe(result_open_positions)
st.header(f"Unrealized PnL - Detail")
st.subheader("Bot 1d")
col_config = {
"Id": None,
"PnL_Perc": st.column_config.NumberColumn(format="%.2f"),
"PnL_Value": st.column_config.NumberColumn(format=f"%.{num_decimals}f"),
"TP1": st.column_config.CheckboxColumn(),
"TP2": st.column_config.CheckboxColumn(),
"TP3": st.column_config.CheckboxColumn(),
"TP4": st.column_config.CheckboxColumn(),
"RPQ%": st.column_config.NumberColumn(help="Remaining Position Qty %",
# format="%.2f",
)
}
event_positions_1d = st.dataframe(
positions_df_1d.style.applymap(set_pnl_color, subset=['PnL_Perc','PnL_Value']),
key="positions_df_1d",
column_config=col_config,
hide_index=True,
on_select="rerun",
selection_mode=["single-row", "multi-column"],
)
# event_positions_1d.selection
row_1d_selected = len(event_positions_1d.selection.rows) > 0
# Check if there's a selection
if row_1d_selected:
selected_row_index = event_positions_1d.selection.rows[0] # Get the index of the selected row
selected_symbol = positions_df_1d.loc[selected_row_index, 'Symbol']
selected_bot = positions_df_1d.loc[selected_row_index, 'Bot']
# Show the selected Name
# st.write(f"Selected Symbol {selected_symbol} and bot {selected_bot}")
if st.button("Delete", key="delete_1d"):
delete_position(symbol=selected_symbol, timeframe=selected_bot)
#########################
st.subheader("Bot 4h")
event_positions_4h = st.dataframe(
positions_df_4h.style.applymap(set_pnl_color, subset=['PnL_Perc','PnL_Value']),
key="positions_df_4h",
column_config=col_config,
hide_index=True,
on_select="rerun",
selection_mode=["single-row", "multi-column"],
)
# event_positions_1d.selection
row_4h_selected = len(event_positions_4h.selection.rows) > 0
# Check if there's a selection
if row_4h_selected:
selected_row_index = event_positions_4h.selection.rows[0] # Get the index of the selected row
selected_symbol = positions_df_4h.loc[selected_row_index, 'Symbol']
selected_bot = positions_df_4h.loc[selected_row_index, 'Bot']
# Show the selected Name
# st.write(f"Selected Symbol {selected_symbol} and bot {selected_bot}")
if st.button("Delete", key="delete_4h"):
delete_position(symbol=selected_symbol, timeframe=selected_bot)
#########################
st.subheader("Bot 1h")
event_positions_1h = st.dataframe(
positions_df_1h.style.applymap(set_pnl_color, subset=['PnL_Perc','PnL_Value']),
key="positions_df_1h",
column_config=col_config,
hide_index=True,
on_select="rerun",
selection_mode=["single-row", "multi-column"],
)
# event_positions_1d.selection
row_1h_selected = len(event_positions_1h.selection.rows) > 0
# Check if there's a selection
if row_1h_selected:
selected_row_index = event_positions_1h.selection.rows[0] # Get the index of the selected row
selected_symbol = positions_df_1h.loc[selected_row_index, 'Symbol']
selected_bot = positions_df_1h.loc[selected_row_index, 'Bot']
# Show the selected Name
# st.write(f"Selected Symbol {selected_symbol} and bot {selected_bot}")
if st.button("Delete", key="delete_1h"):
delete_position(symbol=selected_symbol, timeframe=selected_bot)
#----------------------
# Force Close Position
st.header("Force Selling")
sell_expander = st.expander("Choose position to sell")
with sell_expander:
# bots
bots = ["1d", "4h", "1h"]
if "sell_bot" not in st.session_state:
st.session_state.sell_bot = None
# def sell_bot_change():
sell_bot = st.selectbox(
label="Bot",
options=(bots),
# label_visibility="collapsed",
key="sell_bot",
# on_change=sell_bot_change
)
if st.session_state.sell_bot == "1d":
list_positions = positions_df_1d.Symbol.to_list()
elif st.session_state.sell_bot == "4h":
list_positions = positions_df_4h.Symbol.to_list()
elif st.session_state.sell_bot == "1h":
list_positions = positions_df_1h.Symbol.to_list()
else:
list_positions = []
if "sell_symbol" not in st.session_state:
st.session_state.sell_symbol = None
sell_symbol = st.selectbox(
label="Symbol",
options=(list_positions),
# label_visibility="collapsed",
key="sell_symbol",
disabled=len(list_positions) == 0
)
disable_sell_confirmation1 = sell_symbol == None
# get balance
if not disable_sell_confirmation1:
sell_amount_perc = st.slider(
label='Amount',
min_value=10,
max_value=100,
value=25,
step=5,
format="%d%%",
disabled=disable_sell_confirmation1
)
# get current position balance
df_pos = database.get_positions_by_bot_symbol_position(database.conn, bot=sell_bot, symbol=sell_symbol, position=1)
if not df_pos.empty:
balance_qty = df_pos['Qty'].iloc[0]
else:
balance_qty = 0
# symbol_only, symbol_stable = general.separate_symbol_and_trade_against(sell_symbol)
# balance_qty = exchange.get_symbol_balance(symbol=symbol_only, bot=sell_bot)
sell_amount = balance_qty*(sell_amount_perc/100)
st.text_input(
label='Sell Amount / Position Balance',
value=f'{sell_amount} / {balance_qty}',
disabled=True
)
# sell_expander.write(disable_sell_confirmation1)
sell_reason = f"Forced Selling of {sell_amount_perc}%"
sell_reason_input = st.text_input("Reason")
if sell_reason_input:
sell_reason = f"{sell_reason} - {sell_reason_input}"
sell_confirmation1 = st.checkbox(f"I confirm the Sell of **{sell_amount_perc}%** of **{sell_symbol}** from **{sell_bot}** bot", disabled=disable_sell_confirmation1)
# if button pressed then sell position
if sell_confirmation1:
def sell_click():
result, msg = binance.create_sell_order(
symbol=sell_symbol,
bot=sell_bot,
reason=f"Forced Selling of {sell_amount_perc}%",
percentage=sell_amount_perc
)
if result:
sell_expander.success(f"SOLD **{sell_amount_perc}%** of {sell_symbol} from **{sell_bot}** bot!")
else:
sell_expander.error(msg)
# time.sleep(3)
st.session_state.sell_bot = None
# dasboard refresh
# st.rerun()
sell_confirmation2 = sell_expander.button(label="SELL", on_click=sell_click)
def top_performers():
with tab_top_perf:
top_perf = config.get_setting("trade_top_performance")
st.subheader(f"Top {top_perf} Performers")
st.caption("The top performers are those in accumulation phase (Price > 50DSMA and Price > 200DSMA and 50DSMA < 200DSMA) and bullish phase (Price > 50DSMA and Price > 200DSMA and 50DSMA > 200DSMA) and then sorted by the price above the 200-day moving average (DSMA) in percentage terms. [Click here for more details](https://twitter.com/jptsantossilva/status/1539976855469428738?s=20).")
df_mp = database.get_all_symbols_by_market_phase(connection)
df_mp['Price'] = df_mp['Price'].apply(lambda x:f'{{:.{8}f}}'.format(x))
df_mp['DSMA50'] = df_mp['DSMA50'].apply(lambda x:f'{{:.{8}f}}'.format(x))
df_mp['DSMA200'] = df_mp['DSMA200'].apply(lambda x:f'{{:.{8}f}}'.format(x))
df_mp['Perc_Above_DSMA50'] = df_mp['Perc_Above_DSMA50'].apply(lambda x:'{:.2f}'.format(x))
df_mp['Perc_Above_DSMA200'] = df_mp['Perc_Above_DSMA200'].apply(lambda x:'{:.2f}'.format(x))
st.dataframe(df_mp)
filename = "Top_performers_"+trade_against+".txt"
if os.path.exists(filename):
with open(filename, "rb") as file:
st.download_button(
label="Download as TradingView List",
data=file,
file_name=filename,
mime='text/csv',
)
st.subheader(f"Historical Top Performers")
st.caption("Symbols that spend the most number of days in the bullish or accumulating phases")
df_symbols_days_at_top = database.symbols_by_market_phase_Historical_get_symbols_days_at_top(connection)
st.dataframe(df_symbols_days_at_top)
def signals():
with tab_signals:
st.subheader(f"Signals Log")
st.caption("These signals are just informative. They do not automatically trigger buy and sell orders. You can use these to help you make decisions about when to force a manual exit from an unrealized position.")
expander_signals = st.expander(label="Signals", expanded=False)
with expander_signals:
st.write("""**SUPER-RSI** - Triggered when all time-frames are below or above a defined level.
\n RSI(14) 1d / 4h / 1h / 30m / 15m <= 25
\n RSI(14) 1d / 4h / 1h / 30m / 15m >= 80""")
# st.divider() # Draws a horizontal line
df_s = database.get_all_signals_log(connection, num_rows=100)
st.dataframe(df_s)
def blacklist():
with tab_blacklist:
st.subheader("Blacklist")
df_blacklist = database.get_symbol_blacklist(connection)
edited_blacklist = st.data_editor(df_blacklist, num_rows="dynamic")
blacklist_apply_changes = st.button("Save")
if blacklist_apply_changes:
edited_blacklist.to_sql(name='Blacklist',con=connection, index=True, if_exists="replace")
st.success("Blacklist changes saved")
def backtesting_results():
with tab_backtesting_results:
st.subheader("Backtesting Results")
col_br1, col_br2, col_br3 = st.columns(3)
with col_br1:
# search by strategy
search_strategy = st.multiselect(
'Strategy',
options=list(dict_strategies.keys()),
format_func=format_func_strategies
)
# st.write('You selected:', search_strategy)
df_bt_results = database.get_all_backtesting_results(connection)
with col_br3:
pass
with col_br2:
list_timeframe = ["1d", "4h", "1h"]
search_timeframe = st.multiselect(label='Time-Frame',options=list_timeframe)
# search by symbol
# get distinct symbols
list_symbols = df_bt_results['Symbol'].unique().tolist()
col_br_symbol1, col_br_symbol2 = st.columns([0.66, 0.33])
with col_br_symbol2:
# add sapce above the checkbox to align with the symbol multiselect
st.write('<div style="height: 35px;"></div>', unsafe_allow_html=True)
default_symbols = None
if st.checkbox("Use Top Performers"):
df_top_perf = database.get_all_symbols_by_market_phase(connection)
top_perf_symbol_list = df_top_perf["Symbol"].to_list()
default_symbols = top_perf_symbol_list
with col_br_symbol1:
search_symbol = st.multiselect(label='Symbol', default=default_symbols, options=list_symbols)
# st.write('You selected:', search_symbol)
col_br4, col_br5, col_br6 = st.columns(3)
today = datetime.now()
four_years_ago = today.replace(year=today.year - 4)
with col_br4:
col_br41, col_br42 = st.columns(2)
with col_br41:
search_date_ini = st.date_input(
label="Start date",
value=four_years_ago,
min_value=four_years_ago,
max_value=today,
format="DD.MM.YYYY",
)
with col_br42:
search_date_end = st.date_input(
label="End date",
value=today,
min_value=search_date_ini,
max_value=today,
format="DD.MM.YYYY",
)
search_return_pct = st.checkbox("Return Percentage > 0", value=True)
# Convert 'Backtest_Start_Date' and 'Backtest_End_Date' columns to datetime objects
df_bt_results['Backtest_Start_Date'] = pd.to_datetime(df_bt_results['Backtest_Start_Date'])
df_bt_results['Backtest_End_Date'] = pd.to_datetime(df_bt_results['Backtest_End_Date'])
# if (not search_strategy) and (not search_symbol):
# st.dataframe(df_bt_results)
if search_strategy:
df_bt_results = df_bt_results[df_bt_results['Strategy_Id'].isin(search_strategy)]
if search_symbol:
df_bt_results = df_bt_results[df_bt_results['Symbol'].isin(search_symbol)]
if search_timeframe:
df_bt_results = df_bt_results[df_bt_results['Time_Frame'].isin(search_timeframe)]
if search_return_pct:
df_bt_results = df_bt_results[df_bt_results['Return_Perc'] > 0]
if search_date_ini and search_date_end:
# Convert search_dates tuple to datetime objects
start_date = datetime(search_date_ini.year, search_date_ini.month, search_date_ini.day)
end_date = datetime(search_date_end.year, search_date_end.month, search_date_end.day)
# Now perform the search
df_bt_results = df_bt_results[(df_bt_results['Backtest_Start_Date'] >= start_date) & (df_bt_results['Backtest_End_Date'] <= end_date)]
# df_bt_results = database.get_all_backtesting_results(database.conn)
# add backtest link
# Function to generate backtest link
def generate_backtest_link(row, type):
strategy_id = str(row['Strategy_Id'])
time_frame = row['Time_Frame']
symbol = row['Symbol']
filename = f'{strategy_id} - {time_frame} - {symbol}.{type}'
file_path = os.path.join(FOLDER_BACKTEST_RESULTS, filename)
if os.path.exists(file_path):
file_path = os.path.join("app", FOLDER_BACKTEST_RESULTS, filename)
backtest_link = file_path
else:
backtest_link = ""
return backtest_link
# Apply the function to create the "Backtest_Link" column
df_bt_results['Backtest_HTML'] = df_bt_results.apply(lambda row: generate_backtest_link(row, "html"), axis=1)
df_bt_results['Backtest_CSV'] = df_bt_results.apply(lambda row: generate_backtest_link(row, "csv"), axis=1)
st.dataframe(
df_bt_results,
column_config={
"Strategy_Id": None,
"Backtest_HTML": st.column_config.LinkColumn(
display_text="Open",
help="Backtesting results in HTML",
),
"Backtest_CSV": st.column_config.LinkColumn(
display_text="Open",
help="Backtesting results in CSV",
)
}
)
st.subheader("Backtesting Trades")
get_trades = st.button("Get Trades", key="get_trades")
if get_trades:
df_bt_trades = database.get_all_backtesting_trades(connection)
# Convert 'Backtest_Start_Date' and 'Backtest_End_Date' columns to datetime objects
df_bt_trades['EntryTime'] = pd.to_datetime(df_bt_trades['EntryTime'])
df_bt_trades['ExitTime'] = pd.to_datetime(df_bt_trades['ExitTime'])
if search_strategy:
df_bt_trades = df_bt_trades[df_bt_trades['Strategy_Id'].isin(search_strategy)]
if search_symbol:
df_bt_trades = df_bt_trades[df_bt_trades['Symbol'].isin(search_symbol)]
if search_timeframe:
df_bt_trades = df_bt_trades[df_bt_trades['Time_Frame'].isin(search_timeframe)]
# if search_return_pct:
# df_bt_trades = df_bt_trades[df_bt_trades['ReturnPct'] > 0]
if search_date_ini and search_date_end:
# Convert search_dates tuple to datetime objects
start_date = datetime(search_date_ini.year, search_date_ini.month, search_date_ini.day)
end_date = datetime(search_date_end.year, search_date_end.month, search_date_end.day)
# Now perform the search
df_bt_trades = df_bt_trades[(df_bt_trades['EntryTime'] >= start_date) & (df_bt_trades['ExitTime'] <= end_date)]
st.dataframe(df_bt_trades)
# Count the number of trades with ReturnPct below 0
trades_below_minus20 = df_bt_trades[df_bt_trades['ReturnPct'] < 20].shape[0]
# Count the number of trades with ReturnPct above 100
trades_above_100 = df_bt_trades[df_bt_trades['ReturnPct'] > 100].shape[0]
trades_minus20_minus10 = df_bt_trades[(df_bt_trades['ReturnPct'] >= -20) & (df_bt_trades['ReturnPct'] < -10)].shape[0]
trades_minus10_0 = df_bt_trades[(df_bt_trades['ReturnPct'] >= -10) & (df_bt_trades['ReturnPct'] < 0)].shape[0]
trades_0_10 = df_bt_trades[(df_bt_trades['ReturnPct'] >= 0) & (df_bt_trades['ReturnPct'] < 10)].shape[0]
trades_10_20 = df_bt_trades[(df_bt_trades['ReturnPct'] >= 10) & (df_bt_trades['ReturnPct'] < 20)].shape[0]
trades_20_30 = df_bt_trades[(df_bt_trades['ReturnPct'] >= 20) & (df_bt_trades['ReturnPct'] < 30)].shape[0]
trades_30_40 = df_bt_trades[(df_bt_trades['ReturnPct'] >= 30) & (df_bt_trades['ReturnPct'] < 40)].shape[0]
trades_40_50 = df_bt_trades[(df_bt_trades['ReturnPct'] >= 40) & (df_bt_trades['ReturnPct'] < 50)].shape[0]
trades_50_60 = df_bt_trades[(df_bt_trades['ReturnPct'] >= 50) & (df_bt_trades['ReturnPct'] < 60)].shape[0]
trades_60_70 = df_bt_trades[(df_bt_trades['ReturnPct'] >= 60) & (df_bt_trades['ReturnPct'] < 70)].shape[0]
trades_70_80 = df_bt_trades[(df_bt_trades['ReturnPct'] >= 70) & (df_bt_trades['ReturnPct'] < 80)].shape[0]
trades_80_90 = df_bt_trades[(df_bt_trades['ReturnPct'] >= 80) & (df_bt_trades['ReturnPct'] < 90)].shape[0]
trades_90_100 = df_bt_trades[(df_bt_trades['ReturnPct'] >= 90) & (df_bt_trades['ReturnPct'] < 100)].shape[0]
# Trades in % terms
trades_total = trades_below_minus20 + trades_minus20_minus10 + trades_minus10_0 + trades_0_10 + trades_10_20 + trades_20_30 + trades_30_40 + trades_40_50 + trades_50_60 + trades_60_70 + trades_70_80 + trades_80_90 + trades_90_100 + trades_above_100
round_num = 2
if trades_total != 0:
trades_below_minus20_perc = round(trades_below_minus20/trades_total,round_num)*100
trades_minus20_minus10_perc = round(trades_minus20_minus10/trades_total,round_num)*100
trades_minus10_0_perc = round(trades_minus10_0/trades_total,round_num)*100
trades_0_10_perc = round(trades_0_10/trades_total,round_num)*100
trades_10_20_perc = round(trades_10_20/trades_total,round_num)*100
trades_20_30_perc = round(trades_20_30/trades_total,round_num)*100
trades_30_40_perc = round(trades_30_40/trades_total,round_num)*100
trades_40_50_perc = round(trades_40_50/trades_total,round_num)*100
trades_50_60_perc = round(trades_50_60/trades_total,round_num)*100
trades_60_70_perc = round(trades_60_70/trades_total,round_num)*100
trades_70_80_perc = round(trades_70_80/trades_total,round_num)*100
trades_80_90_perc = round(trades_80_90/trades_total,round_num)*100
trades_90_100_perc = round(trades_90_100/trades_total,round_num)*100
trades_above_100_perc = round(trades_above_100/trades_total,round_num)*100
else:
trades_below_minus20_perc = 0
trades_minus20_minus10_perc = 0
trades_minus10_0_perc = 0
trades_0_10_perc = 0
trades_10_20_perc = 0
trades_20_30_perc = 0
trades_30_40_perc = 0
trades_40_50_perc = 0
trades_50_60_perc = 0
trades_60_70_perc = 0
trades_70_80_perc = 0
trades_80_90_perc = 0
trades_90_100_perc = 0
trades_above_100_perc = 0
trades_by_Return_perc = {
'Category': ['< -20%', '-20-10%','-10-0%','0-10%', '10-20%', '20-30%', '30-40%', '40-50%', '50-60%', '60-70%', '70-80%', '80-90%', '90-100%', '> 100%'],
'Number of Trades': [trades_below_minus20] + [trades_minus20_minus10] + [trades_minus10_0] + [trades_0_10] + [trades_10_20] + [trades_20_30] + [trades_30_40] + [trades_40_50] + [trades_50_60] + [trades_60_70] + [trades_70_80] + [trades_80_90] + [trades_90_100] + [trades_above_100]
}
df_tbrp = pd.DataFrame(trades_by_Return_perc)
df_tbrp["Perc of Trades"] = [
trades_below_minus20_perc,
trades_minus20_minus10_perc,
trades_minus10_0_perc,
trades_0_10_perc,
trades_10_20_perc,
trades_20_30_perc,
trades_30_40_perc,
trades_40_50_perc,
trades_50_60_perc,
trades_60_70_perc,
trades_70_80_perc,
trades_80_90_perc,
trades_90_100_perc,
trades_above_100_perc
]
# Define the order of categories
category_order = ['< -20%', '-20-10%', '-10-0%', '0-10%', '10-20%', '20-30%', '30-40%', '40-50%', '50-60%', '60-70%', '70-80%', '80-90%', '90-100%', '> 100%']
# Plotting the cheese chart using Altair
chart_tbrp = alt.Chart(df_tbrp).mark_bar().encode(
x=alt.X("Category", title="Return %", scale=alt.Scale(domain=category_order)),
# y=alt.Y("Number of Trades", title="Number of Trades"),
y=alt.Y("Perc of Trades", title="Percentage of Trades"),
color=alt.Color("Number of Trades")
).properties(
title="Distribution of Trades"
)
st.altair_chart(chart_tbrp, use_container_width=True)
# Display the results in a table
st.dataframe(
df_tbrp,
hide_index=True,
height=(len(df_tbrp) + 1) * 35 + 3)
def settings():
col1_cfg, col2_cfg = tab_settings.columns(2)
with col2_cfg:
container_main_strategy = st.container(border=True)
with container_main_strategy:
st.write("**Main Strategy**")
if "main_strategy" not in st.session_state:
st.session_state.main_strategy = config.get_setting("main_strategy")
def main_strategy_change():
config.set_setting("main_strategy", st.session_state.main_strategy)
main_strategy = st.selectbox(
label='Main Strategy',
options=list(dict_strategies_main.keys()),
key="main_strategy",
on_change=main_strategy_change,
format_func=format_func_strategies_main,
label_visibility="collapsed"
)
container_btc_strategy = st.container(border=True)
with container_btc_strategy:
st.write("**BTC Strategy**")
if "btc_strategy" not in st.session_state:
st.session_state.btc_strategy = config.get_setting("btc_strategy")
def btc_strategy_change():
config.set_setting("btc_strategy", st.session_state.btc_strategy)
btc_strategy = st.selectbox(
label='BTC Strategy',
options=list(dict_strategies_btc.keys()),
key="btc_strategy",
on_change=btc_strategy_change,
format_func=format_func_strategies_btc,
label_visibility="collapsed"
)
if "trade_against_switch" not in st.session_state:
st.session_state.trade_against_switch = config.get_setting("trade_against_switch")
def trade_against_switch_change():
config.set_setting("trade_against_switch", st.session_state.trade_against_switch)
trade_against_switch = st.checkbox(
label="Auto switch between trade against USDT/USDC or BTC",
key="trade_against_switch",
on_change=trade_against_switch_change,
help="""Considering the chosen Bitcoin strategy will decide whether it is a Bull or Bear market. If Bull then will convert USDT/USDC to BTC and trade against BTC. If Bear will convert BTC into USDT/USDC and trade against USDT/USDC."""
)
run_backtesting = st.button("Run Backtesting", help="Please be patient, as it could take a few hours to complete.")
if run_backtesting:
with st.spinner('This task is taking a leisurely stroll through the digital landscape (+/- 1h). Why not do the same? Stretch those legs, grab a snack, or contemplate the meaning of life.'):
trade_against = config.get_setting("trade_against")
force_run_backtest(time_frame="1d")
container_bot_prefix = st.container(border=True)
with container_bot_prefix:
if "bot_prefix" not in st.session_state:
st.session_state.bot_prefix = config.get_setting("bot_prefix")
def bot_prefix_change():
config.set_setting("bot_prefix", st.session_state.bot_prefix)
bot_prefix = st.text_input(
label="Telegram Messages Prefix",
key="bot_prefix",
on_change=bot_prefix_change,
help="When there are multiple instances of BEC running, the prefix is useful to distinguish which BEC the telegram message belongs to."
)
with col1_cfg:
container_bots = st.container(border=True)
with container_bots:
st.write("**Trading by Time Frame**")
if "bot_1d" not in st.session_state:
st.session_state.bot_1d = config.get_setting("bot_1d")
def bot_1d_change():
config.set_setting("bot_1d", st.session_state.bot_1d)
bot_1d = st.toggle(
label='Enable 1d',
key="bot_1d",
on_change=bot_1d_change,
help="""
**:green[Enabled]**: Buy new positions and sell existing ones based on the daily timeframe.
**:red[Disabled]**: Will not buy new positions but will continue to attempt to sell existing positions based on sell strategy conditions.
"""
)
if "bot_4h" not in st.session_state:
st.session_state.bot_4h = config.get_setting("bot_4h")
def bot_4h_change():
config.set_setting("bot_4h", st.session_state.bot_4h)
bot_4h = st.toggle(
label='Enable 4h',
key="bot_4h",
on_change=bot_4h_change,
help="""
**:green[Enabled]**: Buy new positions and sell existing ones based on the 4h timeframe.
**:red[Disabled]**: Will not buy new positions but will continue to attempt to sell existing positions based on sell strategy conditions.
"""
)
if "bot_1h" not in st.session_state:
st.session_state.bot_1h = config.get_setting("bot_1h")
def bot_1h_change():
config.set_setting("bot_1h", st.session_state.bot_1h)
bot_1h = st.toggle(
label='Enable 1h',
key="bot_1h",
on_change=bot_1h_change,
help="""
**:green[Enabled]**: Buy new positions and sell existing ones based on the 1h timeframe.
**:red[Disabled]**: Will not buy new positions but will continue to attempt to sell existing positions based on sell strategy conditions.
"""
)
# try:
# prev_stake_amount_type = config.get_setting("stake_amount_type")
# stake_amount_type = st.selectbox('Stake Amount Type', ['unlimited'],
# help="""Stake_amount is the amount of stake the bot will use for each trade.
# \nIf stake_amount = "unlimited" the increasing/decreasing of stakes will depend on the performance of the bot. Lower stakes if the bot is losing, higher stakes if the bot has a winning record since higher balances are available and will result in profit compounding.
# \nIf stake amount = static number, that is the amount per trade
# """)
# if stake_amount_type != prev_stake_amount_type:
# config.set_setting("stake_amount_type", stake_amount_type)
# except KeyError:
# st.warning('Invalid or missing configuration: stake_amount_type')
# st.stop()
container_others = st.container(border=True)
with container_others:
if "trade_against" not in st.session_state:
st.session_state.trade_against = config.get_setting("trade_against")
def trade_against_change():
config.set_setting("trade_against", st.session_state.trade_against)
min_position_size_change()
trade_against = st.selectbox(
label='Trade Against',
options=['USDC','USDT', 'BTC'],
key="trade_against",
on_change=trade_against_change,
help="""Trade against USDT/USDC or BTC