# Binance StochRSI Volume Trading Bot A cryptocurrency trading bot implementing a **StochRSI + Volume momentum reversal strategy** for spot trading on Binance. The bot targets liquid pairs (BTCUSDT, ETHUSDT) using 15-minute timeframes with built-in backtesting and strategy scanning capabilities. ## Features - **Momentum Reversal Strategy**: StochRSI crossover signals with volume confirmation - **Trend Filtering**: 200 EMA to trade only with the trend - **Risk Management**: Position sizing, stop-loss, take-profit, daily trade limits - **Backtesting Engine**: Test strategies on historical data with detailed metrics - **Multi-Symbol Scanner**: Evaluate all USDT pairs and rank by performance - **Trade Logging**: SQLite database for trade history and backtest results - **Docker Support**: Containerized deployment ready ## Strategy Overview ### Entry Conditions (ALL must be true at candle close) 1. **Previous candle**: StochRSI %K < %D AND %K ≤ 20 (oversold) 2. **Current candle**: %K crosses above %D AND %K ≤ 30 3. **Volume**: Current volume > 1.5× 20-period Volume SMA 4. **Trend**: Close price > 200 EMA (uptrend confirmation) ### Exit Conditions - **Take Profit**: 2:1 Risk-to-Reward ratio - **Stop Loss**: Lowest low of last 5 candles minus 0.1% buffer - **Early Exit**: StochRSI %K crosses below %D above 70 (overbought) ### Risk Management | Parameter | Value | |-----------|-------| | Risk per trade | 1% of account | | Max open positions | 1 per pair | | Max trades per day | 4 | | Cooldown after loss | 2 candles | | Trading fee | 0.1% per side | ## Project Structure ``` BinancePythonBot/ ├── main.py # CLI entry point (backtest & scan commands) ├── config/ │ └── settings.py # Centralized configuration ├── src/ │ ├── indicators/ │ │ └── technical.py # RSI, StochRSI, EMA, Volume SMA │ ├── strategy/ │ │ └── stochrsi_volume.py # Entry/exit signal generation │ ├── risk/ │ │ └── manager.py # Position sizing & risk controls │ ├── data/ │ │ └── fetcher.py # Binance API data retrieval │ ├── backtest/ │ │ └── engine.py # Backtesting simulation engine │ └── trading/ # (Future) Live trading module ├── database/ │ └── models.py # SQLite schema & CRUD operations ├── requirements.txt ├── Dockerfile ├── docker-compose.yml └── .env.example ``` ## Installation ### Prerequisites - Python 3.11+ - Binance account (optional for backtesting, required for live trading) ### Setup 1. **Clone the repository** ```bash git clone cd BinancePythonBot ``` 2. **Create virtual environment** ```bash python -m venv venv # Windows venv\Scripts\activate # Linux/macOS source venv/bin/activate ``` 3. **Install dependencies** ```bash pip install -r requirements.txt ``` 4. **Configure environment variables** ```bash cp .env.example .env ``` Edit `.env` with your Binance API credentials: ``` BINANCE_API_KEY=your_api_key_here BINANCE_API_SECRET=your_api_secret_here BINANCE_TESTNET=false ``` ## Usage ### Backtest a Single Symbol ```bash python main.py backtest --symbol BTCUSDT --start 2024-01-01 --end 2024-12-31 ``` **Options:** - `--symbol`: Trading pair (default: BTCUSDT) - `--start`: Start date in YYYY-MM-DD format (required) - `--end`: End date in YYYY-MM-DD format (default: today) **Example Output:** ``` ============================================================ BACKTEST REPORT: BTCUSDT (15m) ============================================================ Period: 2024-01-01 to 2024-12-31 PERFORMANCE METRICS ------------------------------------------------------------ Total Trades: 45 Winning Trades: 28 Losing Trades: 17 Win Rate: 62.22% [PASS] >= 40% Total PnL: $1,847.32 PnL %: 18.47% Profit Factor: 2.15 [PASS] >= 1.6 Max Drawdown: 8.73% [PASS] < 15% Final Balance: $11,847.32 ============================================================ ``` ### Scan Multiple Symbols Evaluate all USDT trading pairs and rank by performance: ```bash python main.py scan --start 2024-01-01 --min-volume 100000 --top 20 ``` **Options:** - `--start`: Start date for backtesting (required) - `--end`: End date (default: today) - `--min-volume`: Minimum 24h volume in USDT (default: 100,000,000) - `--top`: Number of top results to display (default: 10) **Example Output:** ``` Scanning 150 USDT pairs... TOP 20 PERFORMING SYMBOLS ============================================================ Rank Symbol Win Rate Profit Factor Max DD Total PnL ------------------------------------------------------------ 1 SOLUSDT 68.42% 2.87 6.21% $2,341.56 2 BTCUSDT 62.22% 2.15 8.73% $1,847.32 3 ETHUSDT 58.33% 1.92 9.45% $1,523.18 ... ``` ### Docker Deployment **Using Docker Compose:** ```bash # Run scanner docker-compose up # Run with custom command docker-compose run bot python main.py backtest --symbol ETHUSDT --start 2024-01-01 ``` **Using Docker directly:** ```bash docker build -t binance-bot . docker run -v $(pwd)/database:/app/database binance-bot backtest --symbol BTCUSDT --start 2024-01-01 ``` ## Configuration All strategy parameters are centralized in `config/settings.py`: ### Indicator Parameters | Parameter | Value | Description | |-----------|-------|-------------| | RSI_LENGTH | 14 | RSI calculation period | | STOCH_LENGTH | 14 | Stochastic period | | STOCH_K_SMOOTH | 3 | %K smoothing factor | | STOCH_D_SMOOTH | 3 | %D smoothing factor | | EMA_PERIOD | 200 | Trend filter EMA | | VOLUME_SMA_PERIOD | 20 | Volume average period | | VOLUME_MULTIPLIER | 1.5 | Volume threshold multiplier | ### Signal Thresholds | Parameter | Value | Description | |-----------|-------|-------------| | STOCHRSI_OVERSOLD | 20 | Previous candle K must be at or below | | STOCHRSI_ENTRY_MAX | 30 | Current candle K must be at or below | | STOCHRSI_OVERBOUGHT | 80 | Early exit threshold | ## Technical Indicators ### StochRSI Calculation 1. Calculate 14-period RSI 2. Apply 14-period Stochastic formula to RSI values 3. Smooth %K with 3-period SMA 4. Calculate %D as 3-period SMA of %K ### Volume Confirmation - 20-period Simple Moving Average of volume - Entry requires current volume > 1.5× Volume SMA ### Trend Filter - 200-period Exponential Moving Average - Only take LONG entries when price > 200 EMA ## Database Schema Trade and backtest data are stored in SQLite (`database/trades.db`): **trades table:** - entry_time, entry_price, stop_loss, take_profit - position_size, exit_time, exit_price, exit_reason - pnl, symbol **backtest_runs table:** - symbol, timeframe, start_date, end_date - initial_capital, total_trades, winning_trades - win_rate, profit_factor, max_drawdown, total_pnl ## API Security - **Never enable withdrawal permissions** on your API keys - Store credentials in `.env` file (excluded from git) - Use testnet (`BINANCE_TESTNET=true`) for development - API keys require only **Read** and **Trade** permissions ## Performance Validation The backtest report includes pass/fail indicators: | Metric | Threshold | Reasoning | |--------|-----------|-----------| | Win Rate | ≥ 40% | Minimum viable with 2:1 R:R | | Profit Factor | ≥ 1.6 | Gross profit / gross loss | | Max Drawdown | < 15% | Capital preservation | ## Roadmap - [ ] Live trading module with WebSocket streaming - [ ] Real-time signal alerts (Telegram/Discord) - [ ] Web dashboard for monitoring - [ ] Additional strategy variations - [ ] Unit tests and CI/CD pipeline ## Disclaimer This software is for educational purposes only. Cryptocurrency trading involves substantial risk of loss. Past performance does not guarantee future results. Always: - Paper trade on testnet before using real funds - Never risk more than you can afford to lose - Understand the strategy before deploying - Monitor positions and be prepared to intervene ## License MIT License - See LICENSE file for details