File size: 7,526 Bytes
96e0cc2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import streamlit as st
import subprocess
import os
import signal
import time
from threading import Thread
import requests

# Set page config
st.set_page_config(
    page_title="Scalping Bot Control",
    page_icon="πŸ€–",
    layout="wide"
)

st.title("πŸ€– Bybit Scalping Bot Control Panel")

# Sidebar
st.sidebar.header("βš™οΈ Configuration")

# Environment variables setup
st.sidebar.subheader("πŸ”‘ API Configuration")
bybit_key = st.sidebar.text_input("Bybit API Key", type="password")
bybit_secret = st.sidebar.text_input("Bybit API Secret", type="password")
bybit_testnet = st.sidebar.checkbox("Use Testnet", value=False)
telegram_token = st.sidebar.text_input("Telegram Bot Token (optional)")
telegram_chat = st.sidebar.text_input("Telegram Chat ID (optional)")

if st.sidebar.button("πŸ’Ύ Save Configuration"):
    # Save to .env file
    env_content = f"""BYBIT_API_KEY={bybit_key}
BYBIT_API_SECRET={bybit_secret}
BYBIT_TESTNET={str(bybit_testnet).lower()}
TELEGRAM_BOT_TOKEN={telegram_token}
TELEGRAM_CHAT_ID={telegram_chat}
"""
    with open('.env', 'w') as f:
        f.write(env_content)
    st.sidebar.success("Configuration saved!")

# Main content
col1, col2, col3 = st.columns(3)

with col1:
    st.subheader("πŸš€ Start Trading")
    symbol = st.selectbox("Symbol", ["BTCUSDT", "ETHUSDT", "SOLUSDT"])
    duration = st.slider("Duration (hours)", 1, 24, 18)
    max_trades = st.number_input("Max Trades (optional)", min_value=1, value=50)

    if st.button("▢️ Start Trading", key="start"):
        try:
            response = requests.post(f"http://localhost:8000/start/{symbol}",
                                   params={"duration_hours": duration, "max_trades": max_trades})
            if response.status_code == 200:
                st.success(f"βœ… Started trading {symbol} for {duration} hours")
            else:
                st.error(f"❌ Failed to start: {response.text}")
        except Exception as e:
            st.error(f"❌ Error: {e}")

with col2:
    st.subheader("πŸ›‘ Stop Trading")
    stop_symbol = st.selectbox("Symbol to Stop", ["BTCUSDT", "ETHUSDT", "SOLUSDT"], key="stop_select")

    if st.button("⏹️ Stop Trading", key="stop"):
        try:
            response = requests.post(f"http://localhost:8000/stop/{stop_symbol}")
            if response.status_code == 200:
                st.success(f"βœ… Stopped trading {stop_symbol}")
            else:
                st.error(f"❌ Failed to stop: {response.text}")
        except Exception as e:
            st.error(f"❌ Error: {e}")

with col3:
    st.subheader("🚨 Emergency")
    if st.button("🚨 EMERGENCY STOP ALL", key="emergency"):
        try:
            response = requests.post("http://localhost:8000/emergency_stop")
            if response.status_code == 200:
                st.error("🚨 ALL TRADING STOPPED!")
            else:
                st.error(f"❌ Failed: {response.text}")
        except Exception as e:
            st.error(f"❌ Error: {e}")

# Status section
st.header("πŸ“Š Bot Status")

if st.button("πŸ”„ Refresh Status"):
    try:
        response = requests.get("http://localhost:8000/status")
        if response.status_code == 200:
            status = response.json()

            # Overall status
            if status["is_running"]:
                st.success("βœ… Bot is RUNNING")
            else:
                st.warning("⏸️ Bot is STOPPED")

            st.metric("Total P&L", f"${status['total_pnl']:.2f}")
            st.metric("Trades Today", status['trades_today'])

            # Active sessions
            if status["active_sessions"]:
                st.subheader("🎯 Active Sessions")
                for session in status["active_sessions"]:
                    with st.expander(f"{session['symbol']} - {session['status'].upper()}"):
                        st.write(f"**Session ID:** {session['session_id']}")
                        st.write(f"**Started:** {session['start_time'][:19]}")
                        st.write(f"**P&L:** ${session['pnl']:.2f}")
                        st.write(f"**Trades:** {session['trades']}")
            else:
                st.info("No active sessions")

        else:
            st.error(f"❌ Failed to get status: {response.status_code}")
    except Exception as e:
        st.error(f"❌ Connection error: {e}")

# Analysis section
st.header("πŸ” Live Analysis")

if st.button("πŸ“Š Refresh Analysis"):
    try:
        response = requests.get("http://localhost:8000/analysis/status")
        if response.status_code == 200:
            analysis = response.json()

            for symbol, data in analysis["analysis_status"].items():
                with st.expander(f"πŸ“ˆ {symbol} Analysis"):
                    col1, col2 = st.columns(2)

                    with col1:
                        st.metric("Current Price", f"${data['current_price']:.2f}" if data['current_price'] else "N/A")

                        indicators = data['indicators']
                        st.write("**Indicators:**")
                        st.write(f"EMA 9: {indicators['ema_9']:.4f}" if indicators['ema_9'] else "EMA 9: N/A")
                        st.write(f"EMA 21: {indicators['ema_21']:.4f}" if indicators['ema_21'] else "EMA 21: N/A")
                        st.write(f"RSI 14: {indicators['rsi_14']:.1f}" if indicators['rsi_14'] else "RSI 14: N/A")

                    with col2:
                        conditions = data['strategy_conditions']
                        st.write("**Strategy Conditions:**")
                        st.write(f"πŸ“ˆ Trend Up: {'βœ…' if conditions['trend_up'] else '❌'}")
                        st.write(f"πŸ“Š RSI Valid: {'βœ…' if conditions['rsi_valid'] else '❌'}")
                        st.write(f"πŸ’₯ Volume Spike: {'βœ…' if conditions['volume_spike'] else '❌'}")
                        st.write(f"🎯 Orderbook OK: {'βœ…' if conditions['orderbook_aligned'] else '❌'}")

                        all_conditions = all([conditions['trend_up'], conditions['rsi_valid'],
                                            conditions['volume_spike'], conditions['orderbook_aligned']])

                        if all_conditions:
                            st.success("🎯 TRADE SIGNAL READY!")
                        else:
                            st.info("⏳ Waiting for conditions...")
        else:
            st.error(f"❌ Failed to get analysis: {response.status_code}")
    except Exception as e:
        st.error(f"❌ Connection error: {e}")

# Logs section
st.header("πŸ“‹ Recent Logs")

log_type = st.selectbox("Log Type", ["Live Logs", "Analysis Logs"])

if st.button("πŸ“– Refresh Logs"):
    try:
        if log_type == "Live Logs":
            response = requests.get("http://localhost:8000/logs/live")
        else:
            response = requests.get("http://localhost:8000/logs/analysis")

        if response.status_code == 200:
            logs_data = response.json()

            st.write(f"**Total {log_type}:** {logs_data['count']}")

            logs_text = ""
            for log_line in logs_data['logs'][-10:]:  # Show last 10
                logs_text += log_line

            st.code(logs_text, language="text")
        else:
            st.error(f"❌ Failed to get logs: {response.status_code}")
    except Exception as e:
        st.error(f"❌ Connection error: {e}")

# Footer
st.markdown("---")
st.markdown("*πŸ€– Bybit Scalping Bot - FastAPI Control Interface*")
st.markdown("*Made with ❀️ for automated crypto trading*")