-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstreamlit_app.py
173 lines (139 loc) · 7.55 KB
/
streamlit_app.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
import streamlit as st
import logging
from datetime import datetime, timedelta
from typing import Dict, Any
from config import config_manager, kucoin_client_manager
from trading_bot import TradingBot
from chart_utils import ChartCreator
from trading_loop import initialize_trading_loop, stop_trading_loop
# Import explicitly
from ui_components import UIManager, StatusTable
# Set up logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)
def initialize_bot(is_simulation: bool, liquid_ratio: float, initial_balance: float) -> TradingBot:
logger.info("Initializing bot...")
bot = st.session_state.get('bot')
if bot is None:
logger.info("Creating a new bot instance.")
bot = TradingBot(config_manager.get_config('bot_config')['update_interval'], liquid_ratio)
st.session_state['bot'] = bot
else:
logger.info("Using existing bot instance.")
bot.is_simulation = is_simulation
bot.initialize()
logger.info("Bot initialized successfully.")
return bot
def main():
logger.info("Starting main function...")
st.set_page_config(layout="wide")
st.title("Cryptocurrency Trading Bot")
error_container = st.empty()
# Manually initialize session state
if 'trade_messages' not in st.session_state:
st.session_state.trade_messages = []
try:
# Explicitly remove any initialize method call
logger.info("Initializing KuCoin client...")
is_simulation = st.sidebar.checkbox("Simulation Mode", value=config_manager.get_config('simulation_mode')['enabled'], key='is_simulation')
if not is_simulation:
perso_key = st.sidebar.text_input("Enter your personal key:", type="password")
if not perso_key:
st.warning("Please enter your personal key to use live trading mode.")
return
if not config_manager.verify_live_trading_access(perso_key):
st.error("Invalid personal key. Please enter the correct key to proceed.")
return
st.sidebar.warning("WARNING: This bot will use real funds on the live KuCoin exchange.")
st.sidebar.warning("Only proceed if you understand the risks and are using funds you can afford to lose.")
proceed = st.sidebar.checkbox("I understand the risks and want to proceed", key="proceed_checkbox")
if not proceed:
logger.info("User did not proceed with live trading.")
st.sidebar.error("Please check the box to proceed with live trading.")
return
config_manager.initialize_kucoin_client()
if 'is_trading' not in st.session_state:
st.session_state.is_trading = False
if 'stop_event' not in st.session_state:
st.session_state.stop_event = None
if 'trading_task' not in st.session_state:
st.session_state.trading_task = None
if 'user_inputs' not in st.session_state:
st.session_state.user_inputs = {}
# Create UI manager
ui_manager = UIManager(None)
# Sidebar controls
initial_balance, liquid_ratio, profit_margin_percentage, max_total_orders = ui_manager.display_component('sidebar_controls', is_simulation=is_simulation)
# Initialize bot
bot = initialize_bot(is_simulation, liquid_ratio, initial_balance)
ui_manager.bot = bot # Update UI manager with the initialized bot
ui_manager.components['status_table'] = StatusTable(bot)
# Symbol selector
if not kucoin_client_manager.client:
config_manager.initialize_kucoin_client()
available_symbols = config_manager.get_available_trading_symbols()
if not available_symbols:
st.warning("No available trading symbols found. Please check your KuCoin API connection.")
return
user_selected_symbols = ui_manager.display_component('symbol_selector', available_symbols=available_symbols, default_symbols=config_manager.get_config('trading_symbols'))
if not user_selected_symbols:
st.warning("Please select at least one symbol to trade.")
return
# Save user inputs
st.session_state.user_inputs = {
'user_selected_symbols': user_selected_symbols,
'profit_margin_percentage': profit_margin_percentage,
'max_total_orders': max_total_orders,
'liquid_ratio': liquid_ratio,
}
# Update bot configuration
bot.max_total_orders = max_total_orders
bot.update_allocations(user_selected_symbols)
bot.wallet.set_currency_allocations({symbol: 1/len(user_selected_symbols) for symbol in user_selected_symbols})
# Trading controls
start_button, stop_button = ui_manager.display_component('trading_controls')
if start_button and not st.session_state.is_trading:
st.session_state.is_trading = True
bot.profit_margin = profit_margin_percentage
st.session_state.stop_event, st.session_state.trading_task = initialize_trading_loop(
bot, user_selected_symbols
)
st.sidebar.success("Trading started.")
# Update charts and status
chart_creator = ChartCreator(bot)
charts = chart_creator.create_charts()
ui_manager.display_component('chart_display', charts=charts)
current_prices = config_manager.fetch_real_time_prices(user_selected_symbols)
current_status = bot.get_current_status(current_prices)
ui_manager.display_component('status_table', current_status=current_status)
ui_manager.display_component('trade_messages')
if stop_button or (not st.session_state.is_trading and st.session_state.stop_event):
st.session_state.is_trading = False
if st.session_state.stop_event and st.session_state.trading_task:
stop_trading_loop(st.session_state.stop_event, st.session_state.trading_task)
st.session_state.stop_event = None
st.session_state.trading_task = None
st.sidebar.success("Trading stopped.")
ui_manager.display_component('chart_display', charts={})
ui_manager.display_component('status_table', current_status={})
# Main area
if st.session_state.is_trading:
st.subheader("Trading Status")
current_prices = config_manager.fetch_real_time_prices(user_selected_symbols)
current_status = bot.get_current_status(current_prices)
ui_manager.display_component('status_table', current_status=current_status)
st.subheader("Trade Messages")
ui_manager.display_component('trade_messages')
st.subheader("Trading Charts")
chart_creator = ChartCreator(bot)
charts = chart_creator.create_charts()
ui_manager.display_component('chart_display', charts=charts)
else:
st.info("Click 'Start Trading' to begin trading.")
# Display simulation indicator
ui_manager.display_component('simulation_indicator', is_simulation=is_simulation)
except Exception as e:
logger.error(f"An error occurred in the main function: {e}")
st.error(f"An error occurred: {e}")
if __name__ == "__main__":
main()