A production-ready cryptocurrency trading bot built with Clean Architecture principles and SOLID design patterns. Features adaptive trading strategies, comprehensive risk management, and real-time market analysis for Bitcoin trading on Binance.
The system follows Clean Architecture with clear separation of concerns:
┌─────────────────────────────────────────────────────┐
│ Interface Layer │
│ (CLI, Telegram Bot, Health API) │
├─────────────────────────────────────────────────────┤
│ Application Layer │
│ (Use Cases, Application Services) │
├─────────────────────────────────────────────────────┤
│ Domain Layer │
│ (Entities, Domain Services, Repositories) │
├─────────────────────────────────────────────────────┤
│ Infrastructure Layer │
│ (External APIs, Database, Messaging, Monitoring) │
└─────────────────────────────────────────────────────┘
- Dependency Inversion: Inner layers know nothing about outer layers
- Single Responsibility: Each component has one reason to change
- Interface Segregation: Small, focused interfaces
- Testability: Each layer can be tested in isolation
- Adaptive Hybrid Strategy: Automatically selects optimal strategy based on market conditions
- Grid Trading: Profits from range-bound markets
- Breakout Momentum: Captures trending movements
- DCA Safety Net: Dollar-cost averaging for risk mitigation
- Capital-based Tiers: Dynamic risk allocation
- Micro (<$500): 2.5% risk, max 3 positions
- Small ($500-$2k): 1.5% risk, max 5 positions
- Medium ($2k-$10k): 1% risk, max 8 positions
- Large (>$10k): 0.5% risk, max 12 positions
- Position Sizing: Kelly Criterion-based calculations
- Daily Loss Limits: Automatic trading halt on excessive losses
- Emergency Stop: 10% maximum drawdown protection
- Market Regime Detection:
- Bull/Bear trend identification
- Lateral market detection
- Volatility regime classification
- Technical Indicators: ADX, ATR, RSI, EMA, Bollinger Bands
- Confidence Scoring: Multi-factor weighted analysis
- Persistence Tracking: Regime stability monitoring
- Real-time Notifications: Trade alerts, errors, daily summaries
- Command Interface: Full bot control via Telegram
- Performance Reports: PnL tracking with multiple timeframes
- Position Monitoring: Live position updates
- Secure Authentication: Whitelist-based access control
- Python 3.8-3.12 (Note: Python 3.13 has compatibility issues)
- MySQL 5.7+ or MariaDB 10.3+
- Binance account with API access
- Telegram Bot token (optional)
- Clone the repository
git clone https://github.com/yourusername/trading-bot.git
cd trading-bot- Create virtual environment
python -m venv venv
source venv/bin/activate # On Windows: venv\Scripts\activate- Install dependencies
pip install -r requirements.txt- Set up database
mysql -u root -p < config/database/database_setup.sql- Configure the bot
# Create config.json from the template
cp config.json.example config.json
# Edit config.json with your credentialsThe bot uses config.json for all configuration. Here's the structure:
{
"trading": {
"symbol": "BTCUSDT",
"max_position_size": "0.1",
"max_open_positions": 5,
"stop_loss_percentage": "0.02",
"take_profit_percentage": "0.05"
},
"exchange": {
"api_key": "your_binance_api_key",
"api_secret": "your_binance_api_secret",
"testnet": false
},
"database": {
"host": "localhost",
"user": "root",
"password": "",
"database": "trading_bot"
},
"telegram": {
"token": "your_telegram_bot_token",
"allowed_users": [123456789]
}
}- API Keys: Must have trading permissions enabled
- IP Whitelist: Add your server IP to Binance API restrictions
- Database: For macOS, the system automatically uses Unix socket
- Telegram: User IDs must be added to
allowed_usersarray
python src/main.py# Use custom configuration file
python src/main.py --config production.json
# Run with specific log level
LOG_LEVEL=DEBUG python src/main.py| Command | Description |
|---|---|
/start |
Initialize the bot |
/stop |
Stop all trading activities |
/status |
Current bot and market status |
/positions |
List all open positions |
/pnl_today |
Today's profit/loss |
/pnl_month |
Current month's P&L |
/pnl_year |
Yearly performance |
/pnl_custom 7 |
Custom period P&L (days) |
/performance |
Detailed performance metrics |
/trades |
Recent trade history |
/help |
Show all available commands |
trading-bot/
├── src/
│ ├── main.py # Application entry point
│ ├── domain/ # Core business logic
│ │ ├── entities/ # Business entities
│ │ ├── repositories/ # Repository interfaces
│ │ └── services/ # Domain services
│ ├── application/ # Application business rules
│ │ ├── services/ # Application services
│ │ └── use_cases/ # Application use cases
│ ├── infrastructure/ # External interfaces
│ │ ├── adapters/ # External service adapters
│ │ ├── persistence/ # Database implementations
│ │ └── messaging/ # Telegram integration
│ └── strategies/ # Trading strategy implementations
├── tests/ # Test suite
├── config/ # Configuration files
│ └── database/ # Database setup scripts
├── docs/ # Documentation
└── logs/ # Application logs
The project includes comprehensive test coverage:
# Run all tests
pytest
# Run with coverage report
pytest --cov=src --cov-report=html
# Run specific test categories
pytest tests/unit/
pytest tests/integration/trading_bot_clean.log- Main application loglogs/trades.log- Trade execution loglogs/errors.log- Error trackinglogs/performance.log- Performance metrics
The bot includes built-in health checks:
- Database connectivity
- Exchange API status
- Strategy performance
- System resources
-
API Security
- Use IP whitelisting on Binance
- Enable only required permissions
- Rotate API keys regularly
-
Database Security
- Use strong passwords
- Restrict network access
- Regular backups
-
Telegram Security
- Whitelist user IDs
- Use environment-specific tokens
- Monitor command usage
We welcome contributions! Please see our Contributing Guide for details.
# Install development dependencies
pip install -r requirements-dev.txt
# Run code formatting
black src/ tests/
# Run linting
flake8 src/ tests/
# Run type checking
mypy src/This project is licensed under the MIT License - see the LICENSE file for details.
IMPORTANT: This software is for educational purposes only. Cryptocurrency trading carries substantial risk of loss.
- Never invest more than you can afford to lose
- Past performance does not guarantee future results
- Always do your own research
- Test thoroughly with small amounts first
- 📖 Check the documentation
- 🐛 Report issues on GitHub Issues
- 💬 Join our Discord community
Built with inspiration from:
- Clean Architecture by Robert C. Martin
- Domain-Driven Design principles
- The cryptocurrency trading community
Made with ❤️ by [Your Name]