Skip to content

willianpinho/trading-bot

Repository files navigation

BTC Trading Bot - Clean Architecture

🚀 Overview

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.

🏗️ Architecture

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)    │
└─────────────────────────────────────────────────────┘

Key Principles

  • 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

✨ Features

📊 Trading Strategies

  • 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

🛡️ Risk Management

  • 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 Analysis

  • 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

💬 Telegram Integration

  • 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

🛠️ Installation

Prerequisites

  • 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)

Quick Start

  1. Clone the repository
git clone https://github.com/yourusername/trading-bot.git
cd trading-bot
  1. Create virtual environment
python -m venv venv
source venv/bin/activate  # On Windows: venv\Scripts\activate
  1. Install dependencies
pip install -r requirements.txt
  1. Set up database
mysql -u root -p < config/database/database_setup.sql
  1. Configure the bot
# Create config.json from the template
cp config.json.example config.json
# Edit config.json with your credentials

⚙️ Configuration

The 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]
  }
}

Important Configuration Notes

  • 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_users array

🚀 Usage

Running the Bot

python src/main.py

Command Line Options

# Use custom configuration file
python src/main.py --config production.json

# Run with specific log level
LOG_LEVEL=DEBUG python src/main.py

Telegram Commands

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

📁 Project Structure

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

🧪 Testing

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/

📊 Monitoring & Logging

Log Files

  • trading_bot_clean.log - Main application log
  • logs/trades.log - Trade execution log
  • logs/errors.log - Error tracking
  • logs/performance.log - Performance metrics

Health Monitoring

The bot includes built-in health checks:

  • Database connectivity
  • Exchange API status
  • Strategy performance
  • System resources

🔒 Security Best Practices

  1. API Security

    • Use IP whitelisting on Binance
    • Enable only required permissions
    • Rotate API keys regularly
  2. Database Security

    • Use strong passwords
    • Restrict network access
    • Regular backups
  3. Telegram Security

    • Whitelist user IDs
    • Use environment-specific tokens
    • Monitor command usage

🤝 Contributing

We welcome contributions! Please see our Contributing Guide for details.

Development Setup

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

📝 License

This project is licensed under the MIT License - see the LICENSE file for details.

⚠️ Disclaimer

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

🆘 Support

🏆 Acknowledgments

Built with inspiration from:

  • Clean Architecture by Robert C. Martin
  • Domain-Driven Design principles
  • The cryptocurrency trading community

Made with ❤️ by [Your Name]

About

Resources

License

Contributing

Stars

Watchers

Forks

Packages

No packages published