# Bybit Scalping Bot 🤖 A production-ready cryptocurrency scalping bot that trades BTCUSDT, ETHUSDT, and SOLUSDT using multiple sophisticated strategies with 20x leverage and automated risk management. ![Python](https://img.shields.io/badge/python-3.8+-blue.svg) ![License](https://img.shields.io/badge/license-MIT-green.svg) ![Status](https://img.shields.io/badge/status-production--ready-brightgreen.svg) ## ⚡ Features - **Multi-Strategy Trading**: Three advanced scalping strategies (EMA Momentum, Breakout, Pullback) - **20x Leverage**: Configurable leverage with automatic position sizing - **Automated TP/SL**: Take profit at 2.5%, stop loss at 1% - **Real-Time Data**: WebSocket streaming for ultra-fast signal generation - **Risk Management**: Dynamic position sizing, daily loss limits, volatility filters - **Backtesting Engine**: Historical performance analysis and parameter optimization - **Comprehensive Logging**: Detailed trade logs, performance metrics, error tracking - **Telegram Notifications**: Real-time trade alerts and bot status updates - **Production Ready**: Error handling, reconnection logic, graceful shutdown ## 🚀 Quick Start ### 1. Environment Setup ```bash # Clone the repository git clone cd scalper # Install dependencies pip install -r requirements.txt # Copy environment template cp .env.example .env ``` ### 2. API Configuration 1. Create a Bybit account at [bybit.com](https://bybit.com) 2. Generate API keys in Account > API Management 3. **Required Permissions:** - ✅ **Unified Trading Account** → Read & Trade - ✅ **USDC Derivatives** → Read & Trade - ✅ **Spot** → Read & Trade 4. **Important**: Add your IP address to the whitelist Edit `.env` file: ```env BYBIT_API_KEY=your_api_key_here BYBIT_API_SECRET=your_api_secret_here BYBIT_TESTNET=false # Use false for mainnet TELEGRAM_BOT_TOKEN=your_telegram_bot_token_here # Optional TELEGRAM_CHAT_ID=your_chat_id_here # Optional ``` ### 3. Start API Server ```bash # Start the FastAPI control server python3 api_server.py ``` Server will be available at: **http://localhost:8000** ### 4. Control Trading via API #### Start Trading for BTC (18 hours default): ```bash curl -X POST http://localhost:8000/start/BTCUSDT ``` #### Start Trading for ETH (custom duration): ```bash curl -X POST "http://localhost:8000/start/ETHUSDT?duration_hours=24" ``` #### Check Bot Status: ```bash curl http://localhost:8000/status ``` #### Stop Trading: ```bash curl -X POST http://localhost:8000/stop/BTCUSDT ``` ### 5. Run Backtest ```bash python3 main.py backtest ``` ## 📡 FastAPI Control Interface The bot uses FastAPI for remote control, allowing you to start/stop trading sessions for individual pairs. ### API Endpoints #### `GET /status` Get current bot status and active sessions. ```bash curl http://localhost:8000/status ``` #### `POST /start/{symbol}` Start trading session for a specific symbol. ```bash # Default 18 hours curl -X POST http://localhost:8000/start/BTCUSDT # Custom duration curl -X POST "http://localhost:8000/start/ETHUSDT?duration_hours=24" # Limited trades curl -X POST "http://localhost:8000/start/SOLUSDT?duration_hours=12&max_trades=50" ``` #### `POST /stop/{symbol}` Stop trading session for a specific symbol. ```bash curl -X POST http://localhost:8000/stop/BTCUSDT ``` #### `GET /sessions` Get all trading sessions (active and completed). ```bash curl http://localhost:8000/sessions ``` #### `GET /report/{session_id}` Get detailed report for a completed session. ```bash curl http://localhost:8000/report/BTCUSDT_1703123456 ``` #### `POST /start_all` Start trading sessions for ALL configured pairs simultaneously. ```bash # Start all pairs (BTC, ETH, SOL) for 18 hours curl -X POST "http://localhost:8000/start_all" # Custom duration for all pairs curl -X POST "http://localhost:8000/start_all?duration_hours=24" ``` #### `POST /stop_all` Stop trading sessions for ALL pairs. ```bash curl -X POST http://localhost:8000/stop_all ``` #### `GET /logs/analysis` Get recent analysis logs (strategy signals, indicator values). ```bash curl "http://localhost:8000/logs/analysis" curl "http://localhost:8000/logs/analysis?lines=100" ``` #### `GET /logs/live` Get recent live logs (all bot activities). ```bash curl "http://localhost:8000/logs/live" curl "http://localhost:8000/logs/live?lines=50" ``` #### `GET /analysis/status` Get real-time analysis status for all active sessions. ```bash curl "http://localhost:8000/analysis/status" ``` #### `POST /emergency_stop` Emergency stop all trading sessions. ```bash curl -X POST http://localhost:8000/emergency_stop ``` ### Interactive API Documentation When the server is running, visit: **http://localhost:8000/docs** This provides an interactive Swagger UI to test all endpoints. ### Example Workflow ```bash # 1. Start API server python3 api_server.py # 2. Start BTC trading for 18 hours curl -X POST http://localhost:8000/start/BTCUSDT # 3. Check status curl http://localhost:8000/status # 4. Start ETH trading for 24 hours curl -X POST "http://localhost:8000/start/ETHUSDT?duration_hours=24" # 5. Stop BTC trading curl -X POST http://localhost:8000/stop/BTCUSDT # 6. Get final reports curl http://localhost:8000/sessions ``` ## 📊 Trading Strategies ### 1. EMA Momentum Scalping - **Entry**: EMA9 crosses above EMA21 in bullish direction - **Confirmation**: RSI oversold (<35) + bid dominance in orderbook - **Exit**: 2.5% profit or 1% stop loss ### 2. Breakout Scalper - **Entry**: Price breaks above recent highs with volume spike - **Confirmation**: Spread contraction + orderbook imbalance - **Exit**: Time-based (5-15 min) or TP/SL hit ### 3. Pullback Scalper - **Entry**: Price retraces to EMA21 in trending market - **Confirmation**: Volume decreases on pullback, increases on continuation - **Exit**: Trend continuation signal or timeout ## 🏗️ Architecture ``` scalper/ ├── main.py # Entry point ├── config/ │ ├── settings.yaml # Trading parameters │ └── pairs.yaml # Trading pairs ├── core/ │ ├── exchange.py # Bybit API wrapper │ ├── strategy.py # Trading strategies │ ├── risk.py # Risk management │ ├── data_engine.py # Data storage & indicators │ ├── trade_monitor.py # Trade monitoring loop │ └── websockets.py # Real-time data streaming ├── services/ │ ├── logger.py # Logging system │ └── telegram.py # Telegram notifications ├── backtester/ │ └── engine.py # Backtesting engine ├── logs/ # Log files ├── backtest_results/ # Backtest outputs └── requirements.txt # Dependencies ``` ## ⚙️ Configuration ### Trading Parameters | Parameter | Default | Description | |-----------|---------|-------------| | `leverage` | 20 | Trading leverage | | `tp_percent` | 0.025 | Take profit percentage | | `sl_percent` | 0.01 | Stop loss percentage | | `risk_per_trade` | 0.02 | Risk per trade (% of balance) | ### Strategy Parameters | Parameter | Default | Description | |-----------|---------|-------------| | `interval` | "1" | Candle interval (minutes) | | `rsi_period` | 14 | RSI calculation period | | `ema_fast` | 9 | Fast EMA period | | `ema_slow` | 21 | Slow EMA period | ## 🔬 Backtesting Run comprehensive backtests to evaluate strategy performance: ```bash python main.py backtest ``` ### Backtest Metrics - **Win Rate**: Percentage of profitable trades - **Profit Factor**: Gross profit / Gross loss - **Max Drawdown**: Largest peak-to-valley decline - **Sharpe Ratio**: Risk-adjusted returns - **Average Trade Duration**: Typical trade holding time ### Parameter Optimization The backtester includes grid search optimization for: - EMA periods - RSI thresholds - Risk percentages - Timeframe settings ## 📈 Risk Management ### Safety Features - **Daily Loss Limits**: Automatic stop when daily loss exceeds threshold - **Volatility Filters**: Skip trading during high volatility periods - **Spread Filters**: Avoid wide spreads that increase slippage - **Position Limits**: Maximum one position per symbol - **Emergency Stop**: Manual override capability ### Position Sizing ```python risk_amount = balance * risk_per_trade position_size = risk_amount / (sl_distance * leverage) ``` ## 🌐 WebSocket Integration Real-time data streams for ultra-fast execution: - **Tickers**: Price updates every 100ms - **Klines**: 1-minute and 5-minute candles - **Orderbook**: Top 25 bids/asks with depth - **Trades**: Recent market trades - **Auto-Reconnect**: Handles connection drops gracefully ## 📊 Monitoring & Logging ### Log Files - `logs/scalper.log`: General application logs - `logs/trades.log`: Trade execution logs - `logs/errors.log`: Error tracking - `logs/signals.json`: Trading signals - `logs/performance.jsonl`: Performance metrics ### Telegram Alerts Configure for real-time notifications: - Trade executions - Strategy signals - Error alerts - Daily performance summaries ## 🚀 Deployment ### Local Machine ```bash # Run in background nohup python main.py & ``` ### VPS Deployment (Recommended) ```bash # Install dependencies sudo apt update sudo apt install python3 python3-pip tmux # Clone and setup git clone cd scalper pip install -r requirements.txt # Run with process manager tmux new -s scalper python main.py # Ctrl+B, D to detach ``` ### Process Manager (PM2) ```bash npm install -g pm2 pm2 start main.py --name scalper pm2 startup pm2 save ``` ## 🔧 Troubleshooting ### Common Issues **API Connection Failed** ```bash # Check API keys in .env cat .env # Verify testnet setting # Check Bybit API status ``` **WebSocket Disconnection** - Automatic reconnection is built-in - Check internet connection - Verify Bybit service status **No Trading Signals** ```bash # Check market conditions python -c "from core.data_engine import DataEngine; de = DataEngine(); print(de.get_buffer_status())" # Verify strategy parameters # Check volatility filters ``` **Position Not Opening** - Verify account balance - Check risk management settings - Review API permissions ### Debug Mode ```bash # Enable debug logging export LOG_LEVEL=DEBUG python main.py ``` ## 📈 Performance Optimization ### Strategy Tuning 1. Run backtests with different parameters 2. Optimize for specific market conditions 3. Adjust risk parameters based on drawdown ### Hardware Requirements - **CPU**: 2+ cores recommended - **RAM**: 2-4 GB sufficient - **Network**: Stable internet connection - **Storage**: 1GB for logs and data ## 🤝 Contributing 1. Fork the repository 2. Create a feature branch 3. Add tests for new functionality 4. Submit a pull request ## 📜 License MIT License - see [LICENSE](LICENSE) file for details. ## ⚠️ Disclaimer **This software is for educational and research purposes only. Trading cryptocurrencies involves substantial risk of loss and is not suitable for every investor. Past performance does not guarantee future results. Please test thoroughly and use at your own risk.** ### Risk Warnings - **Leverage Trading**: 20x leverage can amplify both gains and losses - **Market Volatility**: Crypto markets can be highly volatile - **Technical Risks**: Software bugs, internet outages, API issues - **Financial Risk**: Never invest more than you can afford to lose ## 🆘 Support - **Issues**: Open a GitHub issue - **Documentation**: Check this README and inline code comments - **Community**: Join crypto trading communities for general advice --- ## 🌐 **Hugging Face Deployment** ### **Deploy to Hugging Face Spaces** 1. **Create Space**: Go to [hf.co/spaces](https://hf.co/spaces) → "Create new Space" - **Name**: `your-scalping-bot` - **SDK**: `Docker` - **Storage**: `Small` 2. **Repository Setup**: ```bash # Push your code to GitHub git add . git commit -m "Scalping bot deployment" git push origin main ``` 3. **Connect Repository**: In Space settings → "Connect Repository" - Enter your GitHub URL - Branch: `main` 4. **Public URL**: You'll get a URL like: ``` https://yourusername-your-scalping-bot.hf.space ``` **This is your public IP for remote access!** 5. **Configure API Keys**: Use the web interface to set your Bybit credentials ### **Hugging Face Features** - 🌐 **Public web dashboard** with real-time analysis - 📊 **Interactive charts** and performance metrics - 🎛️ **One-click trading** controls - 📱 **Mobile-friendly** interface - 🔄 **Auto-scaling** and uptime monitoring --- **Happy Trading! 🚀**