# 🤖 Binance Trading Bot Advanced automated cryptocurrency trading bot for Binance exchange with real-time WebSocket connectivity, technical indicators, and comprehensive risk management. ## 🚀 Features ### Core Trading Features - **Real-time Data**: WebSocket connection to Binance for live market data - **Technical Indicators**: Bollinger Bands, Moving Averages (SMA/EMA), RSI, MACD - **Multiple Strategies**: Bollinger Bands + MA, Mean Reversion, MA Crossover - **Automated Execution**: Buy/sell orders with configurable position sizing - **Paper Trading**: Safe testing mode without real money ### Risk Management - **Stop-Loss & Take-Profit**: Configurable risk/reward ratios - **Position Sizing**: Dynamic position sizing based on risk parameters - **Daily Loss Limits**: Automatic trading halt on daily loss thresholds - **Maximum Drawdown Protection**: Portfolio-level risk controls - **Emergency Stop**: Manual and automatic trading halt capabilities ### Monitoring & Analytics - **Performance Tracking**: Comprehensive trade and portfolio analytics - **Real-time Logging**: Structured logging with multiple log levels - **Health Monitoring**: WebSocket connection health and reconnection logic - **Trade History**: Persistent storage of all trading activities ### Deployment & Operations - **Docker Support**: Containerized deployment with docker-compose - **Environment Configuration**: Flexible configuration via environment variables - **Database Integration**: SQLite and PostgreSQL support - **Optional Monitoring**: Prometheus and Grafana integration ## 📋 Prerequisites - Docker and Docker Compose (recommended) - OR Python 3.11+ with pip - Binance account with API keys - Basic understanding of cryptocurrency trading ## 🛠️ Quick Setup (Docker - Recommended) ### 1. Clone and Setup ```bash git clone cd trading_bot # Copy and configure environment file cp env_example .env nano .env # Edit with your configuration ``` ### 2. Configure Environment Edit `.env` file with your settings: ```bash # Essential Settings BINANCE_API_KEY=your_api_key_here BINANCE_SECRET_KEY=your_secret_key_here BINANCE_TESTNET=true # Start with testnet! # Trading Configuration TRADING_SYMBOL=BTCUSDT POSITION_SIZE=0.001 PAPER_TRADING=true # Keep this true for testing! ENABLE_TRADING=false # Set to true only when ready # Risk Management STOP_LOSS_PERCENT=2.0 TAKE_PROFIT_PERCENT=3.0 MAX_DAILY_LOSS=5.0 ``` ### 3. Start the Bot ```bash # Start in paper trading mode docker-compose up -d # View logs docker-compose logs -f trading-bot # Stop the bot docker-compose down ``` ## 🐍 Manual Setup (Python) ### 1. Setup Python Environment with pyenv #### Install pyenv (if not already installed) **On Linux/macOS:** ```bash # Install pyenv curl https://pyenv.run | bash # Add to your shell profile (~/.bashrc, ~/.zshrc, etc.) export PYENV_ROOT="$HOME/.pyenv" export PATH="$PYENV_ROOT/bin:$PATH" eval "$(pyenv init -)" eval "$(pyenv virtualenv-init -)" # Reload your shell source ~/.bashrc # or ~/.zshrc ``` **On Windows:** ```powershell # Install pyenv-win using git git clone https://github.com/pyenv-win/pyenv-win.git %USERPROFILE%\.pyenv # Add to your PATH (in PowerShell) $env:PYENV = "$env:USERPROFILE\.pyenv\pyenv-win" $env:PATH = "$env:PYENV\bin;$env:PYENV\shims;$env:PATH" # Or set permanently in system environment variables ``` #### Install and Configure Python ```bash # Install Python 3.11 (recommended) pyenv install 3.11.0 # Create virtual environment for the trading bot pyenv virtualenv 3.11.0 trading-bot-env # Activate the environment pyenv activate trading-bot-env # OR set it as local environment for this directory pyenv local trading-bot-env ``` ### 2. Install Dependencies ```bash # Make sure you're in the trading bot environment pyenv activate trading-bot-env # if not already activated # Install required packages pip install -r requirements.txt ``` ### 3. Configure Environment ```bash cp env_example .env # Edit .env with your configuration ``` ### 4. Run the Bot ```bash # Ensure environment is activated pyenv activate trading-bot-env # Run the trading bot python main.py ``` ### 5. Deactivate Environment (when done) ```bash pyenv deactivate ``` ## 📊 Configuration Guide ### Trading Strategies #### 1. Bollinger Bands + Moving Average (Default) ```bash STRATEGY=BOLLINGER_MA BOLLINGER_PERIOD=20 BOLLINGER_STD=2.0 MA_PERIOD=50 ``` - Buys when price touches lower Bollinger Band and is above MA - Sells when price touches upper Bollinger Band and is below MA #### 2. Bollinger Bands Only ```bash STRATEGY=BOLLINGER_ONLY ``` - Pure mean reversion strategy - Buys at lower band, sells at upper band #### 3. Moving Average Crossover ```bash STRATEGY=MA_CROSSOVER ``` - Buys on golden cross (fast MA crosses above slow MA) - Sells on death cross (fast MA crosses below slow MA) #### 4. Mean Reversion ```bash STRATEGY=MEAN_REVERSION ``` - Combines MA, RSI, and price distance from mean - Buys oversold conditions, sells overbought conditions ### Risk Management Configuration ```bash # Position Sizing POSITION_SIZE=0.001 # Size per trade MAX_POSITIONS=1 # Maximum concurrent positions # Risk Limits STOP_LOSS_PERCENT=2.0 # 2% stop loss TAKE_PROFIT_PERCENT=3.0 # 3% take profit MAX_DAILY_LOSS=5.0 # 5% daily loss limit MAX_PORTFOLIO_RISK=10.0 # 10% max portfolio exposure ``` ## 🔧 Advanced Configuration ### WebSocket Settings ```bash WS_RECONNECT_DELAY=5 # Reconnection delay in seconds WS_PING_INTERVAL=20 # Ping interval for connection health WS_TIMEOUT=30 # WebSocket timeout ``` ### Logging Configuration ```bash LOG_LEVEL=INFO # DEBUG, INFO, WARNING, ERROR, CRITICAL LOG_FILE=logs/trading_bot.log LOG_MAX_SIZE=10485760 # 10MB log rotation LOG_BACKUP_COUNT=5 # Keep 5 backup files ``` ### Database Options ```bash # SQLite (default) DATABASE_URL=sqlite:///data/trading_bot.db # PostgreSQL (advanced) DATABASE_URL=postgresql://user:password@localhost:5432/trading_bot ``` ## 📈 Monitoring ### Health Checks - WebSocket connection status - Order execution monitoring - Risk limit monitoring - Performance tracking ### Log Analysis ```bash # View real-time logs docker-compose logs -f trading-bot # Search for specific events docker-compose logs trading-bot | grep "SIGNAL" docker-compose logs trading-bot | grep "TRADE" docker-compose logs trading-bot | grep "ERROR" ``` ### Performance Metrics The bot tracks: - Total trades and win rate - PnL and portfolio value - Risk metrics and drawdown - Trade execution statistics ## 🚨 Safety Guidelines ### Before Live Trading 1. **Test Extensively**: Use paper trading for weeks/months 2. **Verify Strategy**: Backtest your strategy on historical data 3. **Start Small**: Begin with minimal position sizes 4. **Monitor Closely**: Watch the bot's behavior carefully 5. **Have Exit Plan**: Know how to stop the bot quickly ### API Key Security 1. **Read-Only Testing**: Start with read-only API keys 2. **IP Restrictions**: Restrict API keys to your IP address 3. **No Withdrawals**: Never enable withdrawal permissions 4. **Regular Rotation**: Rotate API keys regularly ### Risk Management 1. **Daily Limits**: Set and respect daily loss limits 2. **Position Sizing**: Never risk more than you can afford to lose 3. **Stop Losses**: Always use stop-loss orders 4. **Diversification**: Don't put all funds in one strategy ## 🐛 Troubleshooting ### Common Issues #### WebSocket Connection Problems ```bash # Check network connectivity docker-compose logs trading-bot | grep "WebSocket" # Restart WebSocket connection docker-compose restart trading-bot ``` #### API Permission Errors ```bash # Verify API key permissions # Ensure API key has spot trading enabled (if not paper trading) # Check IP restrictions ``` #### High Memory Usage ```bash # Check container resources docker stats trading-bot # Adjust log levels LOG_LEVEL=WARNING # In .env file ``` ### Log Levels - **DEBUG**: Detailed technical information - **INFO**: General operational information - **WARNING**: Important warnings and issues - **ERROR**: Error conditions that need attention - **CRITICAL**: Critical errors requiring immediate action ## 📝 Contributing 1. Fork the repository 2. Create a feature branch 3. Make your changes 4. Add tests if applicable 5. Submit a pull request ## 🔗 Related Projects - [CCXT](https://github.com/ccxt/ccxt) - Cryptocurrency trading library - [pandas-ta](https://github.com/twopirllc/pandas-ta) - Technical analysis indicators - [Binance API](https://binance-docs.github.io/apidocs/) - Official Binance API documentation ## 📄 License This project is for educational purposes only. Use at your own risk. ## 🆘 Support For questions and support: 1. Check the troubleshooting section 2. Review the logs for error messages 3. Ensure your configuration is correct 4. Test with paper trading first ## ⚠️ Final Warning **Cryptocurrency trading is extremely risky. This bot is provided as-is for educational purposes. The developers are not responsible for any financial losses. Always trade responsibly and never invest more than you can afford to lose.**