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

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 License Status

⚑ 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

# Clone the repository
git clone <repository-url>
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
  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:

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

# 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):

curl -X POST http://localhost:8000/start/BTCUSDT

Start Trading for ETH (custom duration):

curl -X POST "http://localhost:8000/start/ETHUSDT?duration_hours=24"

Check Bot Status:

curl http://localhost:8000/status

Stop Trading:

curl -X POST http://localhost:8000/stop/BTCUSDT

5. Run Backtest

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.

curl http://localhost:8000/status

POST /start/{symbol}

Start trading session for a specific symbol.

# 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.

curl -X POST http://localhost:8000/stop/BTCUSDT

GET /sessions

Get all trading sessions (active and completed).

curl http://localhost:8000/sessions

GET /report/{session_id}

Get detailed report for a completed session.

curl http://localhost:8000/report/BTCUSDT_1703123456

POST /start_all

Start trading sessions for ALL configured pairs simultaneously.

# 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.

curl -X POST http://localhost:8000/stop_all

GET /logs/analysis

Get recent analysis logs (strategy signals, indicator values).

curl "http://localhost:8000/logs/analysis"
curl "http://localhost:8000/logs/analysis?lines=100"

GET /logs/live

Get recent live logs (all bot activities).

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.

curl "http://localhost:8000/analysis/status"

POST /emergency_stop

Emergency stop all trading sessions.

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

# 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:

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

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

# Run in background
nohup python main.py &

VPS Deployment (Recommended)

# Install dependencies
sudo apt update
sudo apt install python3 python3-pip tmux

# Clone and setup
git clone <repository-url>
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)

npm install -g pm2
pm2 start main.py --name scalper
pm2 startup
pm2 save

πŸ”§ Troubleshooting

Common Issues

API Connection Failed

# 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

# 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

# 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 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 β†’ "Create new Space"

    • Name: your-scalping-bot
    • SDK: Docker
    • Storage: Small
  2. Repository Setup:

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