.. | ||
bot_core | ||
docker-compose.yml | ||
Dockerfile | ||
env_example | ||
main.py | ||
README.md | ||
requirements.txt |
🤖 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
git clone <repository-url>
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:
# 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
# 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:
# 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:
# 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
# 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
# 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
cp env_example .env
# Edit .env with your configuration
4. Run the Bot
# Ensure environment is activated
pyenv activate trading-bot-env
# Run the trading bot
python main.py
5. Deactivate Environment (when done)
pyenv deactivate
📊 Configuration Guide
Trading Strategies
1. Bollinger Bands + Moving Average (Default)
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
STRATEGY=BOLLINGER_ONLY
- Pure mean reversion strategy
- Buys at lower band, sells at upper band
3. Moving Average Crossover
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
STRATEGY=MEAN_REVERSION
- Combines MA, RSI, and price distance from mean
- Buys oversold conditions, sells overbought conditions
Risk Management Configuration
# 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
WS_RECONNECT_DELAY=5 # Reconnection delay in seconds
WS_PING_INTERVAL=20 # Ping interval for connection health
WS_TIMEOUT=30 # WebSocket timeout
Logging Configuration
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
# 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
# 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
- Test Extensively: Use paper trading for weeks/months
- Verify Strategy: Backtest your strategy on historical data
- Start Small: Begin with minimal position sizes
- Monitor Closely: Watch the bot's behavior carefully
- Have Exit Plan: Know how to stop the bot quickly
API Key Security
- Read-Only Testing: Start with read-only API keys
- IP Restrictions: Restrict API keys to your IP address
- No Withdrawals: Never enable withdrawal permissions
- Regular Rotation: Rotate API keys regularly
Risk Management
- Daily Limits: Set and respect daily loss limits
- Position Sizing: Never risk more than you can afford to lose
- Stop Losses: Always use stop-loss orders
- Diversification: Don't put all funds in one strategy
🐛 Troubleshooting
Common Issues
WebSocket Connection Problems
# Check network connectivity
docker-compose logs trading-bot | grep "WebSocket"
# Restart WebSocket connection
docker-compose restart trading-bot
API Permission Errors
# Verify API key permissions
# Ensure API key has spot trading enabled (if not paper trading)
# Check IP restrictions
High Memory Usage
# 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
- Fork the repository
- Create a feature branch
- Make your changes
- Add tests if applicable
- Submit a pull request
🔗 Related Projects
- CCXT - Cryptocurrency trading library
- pandas-ta - Technical analysis indicators
- Binance API - Official Binance API documentation
📄 License
This project is for educational purposes only. Use at your own risk.
🆘 Support
For questions and support:
- Check the troubleshooting section
- Review the logs for error messages
- Ensure your configuration is correct
- 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.