File size: 10,562 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
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
# πŸš€ Deploy Scalping Bot on Hugging Face Spaces

## Prerequisites

1. **Hugging Face Account**: Create account at [huggingface.co](https://huggingface.co)
2. **API Credentials**: Your Bybit API keys ready
3. **Git Repository**: Push your code to GitHub/GitLab

## Step 1: Create Hugging Face Space

1. Go to [huggingface.co/spaces](https://huggingface.co/spaces)
2. Click "Create new Space"
3. Choose:
   - **Space name**: `your-scalping-bot`
   - **License**: Apache-2.0
   - **SDK**: **Docker** (for full control)
   - **Storage**: Small (sufficient)

## Step 2: Repository Structure

Your repository should look like:
```
your-scalping-bot/
β”œβ”€β”€ app.py              # Streamlit/FastAPI app
β”œβ”€β”€ requirements.txt    # Dependencies
β”œβ”€β”€ packages.txt        # System packages (if needed)
β”œβ”€β”€ config/
β”‚   β”œβ”€β”€ settings.yaml
β”‚   └── pairs.yaml
β”œβ”€β”€ core/
β”‚   β”œβ”€β”€ exchange.py
β”‚   β”œβ”€β”€ strategy.py
β”‚   └── ...
β”œβ”€β”€ services/
β”‚   └── ...
└── README.md
```

## Step 3: Create app.py

```python
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*")
```

## Step 4: Create requirements.txt

```txt
fastapi==0.104.1
uvicorn[standard]==0.24.0
streamlit==1.28.1
requests==2.31.0
python-dotenv==1.0.0
pybit==5.7.0
pyyaml==6.0.1
pandas==2.1.3
numpy==1.26.2
websockets==12.0
```

## Step 5: Create packages.txt (Optional)

```
# No system packages needed
```

## Step 6: Deploy to Hugging Face

1. **Push to Git**: Commit and push your code to a Git repository
2. **Connect Space**: In your Hugging Face Space settings:
   - Go to "Settings" β†’ "Connect Repository"
   - Enter your repository URL
   - Set branch to `main`
3. **Auto-deploy**: Hugging Face will automatically build and deploy

## Step 7: Access Your Bot

Once deployed, you'll get a public URL like:
```
https://yourusername-your-scalping-bot.hf.space
```

This will be your **public IP/URL** for accessing the bot remotely!

## Step 8: Start the Bot

In your Hugging Face Space:
1. βœ… Configure API keys in the sidebar
2. βœ… Click "Start Trading" for your desired pairs
3. βœ… Monitor analysis in real-time
4. βœ… View logs and performance

## πŸ”’ Security Notes

- **Never expose real API keys** in public repositories
- **Use environment variables** for sensitive data
- **Consider IP restrictions** on your Bybit API keys
- **Monitor your bot regularly** via the web interface

## 🌐 Public Access

Your bot will be accessible worldwide via:
```
https://[your-username]-[space-name].hf.space
```

This serves as your **public IP address** for remote access!

## πŸ’‘ Usage Examples

```bash
# Direct API calls (replace with your HF Space URL)
curl -X POST "https://your-bot.hf.space/start/BTCUSDT"
curl "https://your-bot.hf.space/status"
curl "https://your-bot.hf.space/analysis/status"
```

## πŸŽ‰ You're Done!

Your scalping bot is now hosted on Hugging Face with:
- 🌐 **Public web interface**
- πŸ“Š **Real-time analysis dashboard**
- πŸŽ›οΈ **Remote control via API**
- πŸ“± **Mobile-friendly interface**

**Happy trading!** πŸš€πŸ€–