scalperBot / test /huggingface_README.md
nexusbert's picture
Upload 36 files
96e0cc2 verified

πŸš€ Deploy Scalping Bot on Hugging Face Spaces

Prerequisites

  1. Hugging Face Account: Create account at 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
  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

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

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

# 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! πŸš€πŸ€–