Skip to content

michaelandrewrm/py-binance-bot

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

59 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

πŸ€– Py-Binance-Bot: Cryptocurrency Trading Bot

A sophisticated, enterprise-grade AI-powered cryptocurrency trading bot built with Python. This system combines advanced grid trading strategies, machine learning optimization, and comprehensive risk management to deliver professional-level automated trading capabilities for the Binance exchange.

✨ Features

  • πŸ”— Grid Trading: Automated grid trading with manual and AI-assisted parameter optimization
  • 🧠 Machine Learning: Bayesian optimization for strategy parameter tuning
  • πŸ›‘οΈ Risk Management: Multi-layer safety systems with circuit breakers and position limits
  • πŸ“Š Data Management: Efficient data loading with Parquet caching and validation
  • πŸ–₯️ Web Interface: Real-time monitoring dashboard and command-line interface
  • πŸ” Secure Storage: Encrypted credential management and hybrid data persistence
  • πŸ“ˆ Backtesting: Comprehensive strategy testing with walk-forward validation

πŸ—οΈ Architecture Overview

graph TB
    subgraph "User Interface Layer"
        CLI[ui/cli.py - Command Interface]
        DASH[ui/dashboard.py - Web Dashboard]
        SEC[ui/security.py - Security]
        SESS[ui/session_manager.py - Sessions]
    end
    
    subgraph "Core Trading Engine"
        EXEC[core/executor.py - Trading Executor]
        SAFETY[core/safety.py - Safety Manager]
        STATE[core/state.py - State Management]
        GRID[core/grid_engine.py - Grid Engine]
    end
    
    subgraph "AI & Strategy Layer"
        BASE[ai/baseline.py - Strategy Engine]
        BO[ai/bo_suggester.py - Bayesian Optimizer]
        VALID[ai/validation.py - Model Validation]
    end
    
    subgraph "Simulation & Reporting"
        ENGINE[sim/engine.py - Backtest Engine]
        EVAL[sim/evaluation.py - Performance Analysis]
        REPORTS[reports/end_of_run.py - Report Generation]
        HODL[reports/hodl_benchmark.py - Benchmarks]
    end
    
    subgraph "Data Layer"
        SCHEMA[data/schema.py - Data Structures]
        LOADER[data/loader.py - Data Loading]
    end
    
    subgraph "Storage Layer"
        REPO[storage/repo.py - Data Repository]
        ARTIFACTS[storage/artifacts.py - ML Artifacts]
    end
    
    subgraph "Exchange Integration"
        BINANCE[exec/binance.py - Binance API]
        PAPER[exec/paper_broker.py - Paper Trading]
    end
    
    CLI --> EXEC
    DASH --> REPO
    EXEC --> SAFETY
    EXEC --> STATE
    EXEC --> GRID
    EXEC --> BINANCE
    BASE --> BO
    BASE --> VALID
    ENGINE --> EVAL
    EVAL --> REPORTS
    REPORTS --> HODL
    LOADER --> SCHEMA
    REPO --> SCHEMA
    ARTIFACTS --> VALID
    SAFETY --> STATE
Loading

πŸ—οΈ System Architecture

This trading bot is built with a modular, enterprise-grade architecture that separates concerns and ensures reliability, testability, and maintainability.

py-binance-bot/
β”œβ”€β”€ 🎯 core/                    # Core Trading Engine
β”‚   β”œβ”€β”€ executor.py             # Main trading execution coordinator
β”‚   β”œβ”€β”€ safety.py               # Risk management & circuit breakers
β”‚   β”œβ”€β”€ sizing.py               # Position sizing & fee calculations
β”‚   β”œβ”€β”€ flatten.py              # Emergency position flattening
β”‚   β”œβ”€β”€ grid_engine.py          # Grid trading strategy engine
β”‚   └── state.py                # State persistence & management
β”œβ”€β”€ πŸ”Œ exec/                    # Exchange Interface Layer
β”‚   β”œβ”€β”€ binance.py              # Binance API client with retry logic
β”‚   β”œβ”€β”€ rate_limit.py           # Smart rate limiting & request throttling
β”‚   └── paper_broker.py         # Paper trading simulation
β”œβ”€β”€ πŸ€– ai/                      # AI & Machine Learning
β”‚   β”œβ”€β”€ baseline.py             # Technical indicators & baseline strategies  
β”‚   β”œβ”€β”€ bo_suggester.py         # Bayesian optimization for hyperparameters
β”‚   β”œβ”€β”€ validation.py           # Model validation & walk-forward analysis
β”‚   └── README.md               # AI module documentation
β”œβ”€β”€ πŸ“Š data/                    # Data Management
β”‚   β”œβ”€β”€ loader.py               # Historical data fetching & caching
β”‚   └── schema.py               # Data models & validation schemas
β”œβ”€β”€ πŸ§ͺ sim/                     # Simulation & Backtesting
β”‚   β”œβ”€β”€ engine.py               # Backtesting simulation engine
β”‚   β”œβ”€β”€ evaluation.py           # Performance metrics & analysis
β”‚   └── slippage.py             # Realistic slippage modeling
β”œβ”€β”€ πŸ’Ύ storage/                 # Data Persistence
β”‚   β”œβ”€β”€ artifacts.py            # Model & config artifact management
β”‚   └── repo.py                 # Data repository layer
β”œβ”€β”€ πŸ“ˆ reports/                 # Analytics & Reporting
β”‚   β”œβ”€β”€ end_of_run.py           # Comprehensive trading reports
β”‚   └── hodl_benchmark.py       # Buy-and-hold benchmark comparison
β”œβ”€β”€ πŸ–₯️ ui/                      # User Interface
β”‚   β”œβ”€β”€ cli.py                  # Command-line interface
β”‚   └── dashboard.py            # Web dashboard (future)
β”œβ”€β”€ πŸ§ͺ tests/                   # Comprehensive Test Suite (167+ tests)
β”‚   β”œβ”€β”€ test_safety.py          # Risk management tests (78% coverage)
β”‚   β”œβ”€β”€ test_executor.py        # Trading execution tests
β”‚   β”œβ”€β”€ test_sizing.py          # Position sizing tests (86% coverage)
β”‚   β”œβ”€β”€ test_rate_limiting.py   # Rate limiting tests (69% coverage)
β”‚   β”œβ”€β”€ test_binance_client.py  # API client tests (68% coverage)
β”‚   β”œβ”€β”€ test_safety_clean.py    # Additional safety system tests
β”‚   └── test_executor_simple.py # Simplified executor tests
β”œβ”€β”€ main.py                     # Application entry point
β”œβ”€β”€ config.py                   # Configuration management
β”œβ”€β”€ GLOSSARY.md                 # Technical terms and definitions
└── requirements.txt            # Python dependencies

πŸ“¦ Installation

πŸ“‹ Requirements

  • Python 3.10+: Modern Python version for optimal performance
  • API Access: Binance account with API credentials (or compatible exchange)
  • Optional: GPU for accelerated ML training and optimization

πŸš€ Setup

  1. Clone the repository:
git clone https://github.com/michaelandrewrm/py-binance-bot.git
cd py-binance-bot
  1. Set up virtual environment:
# Create virtual environment
python -m venv trading_bot_env

# Activate (Linux/macOS)
source trading_bot_env/bin/activate

# Activate (Windows)
trading_bot_env\Scripts\activate
  1. Install dependencies:
pip install -r requirements.txt
# Or for minimal installation
pip install -r requirements-minimal.txt
  1. Configure credentials:
python -m ui.cli config init
python -m ui.cli config show
  1. Validate configuration:
python -m ui.cli config validate

πŸš€ Quick Start

πŸ“ Paper Trading (Recommended for beginners)

Start with risk-free paper trading to familiarize yourself with the system:

# Start grid trading with manual parameters
python -m ui.cli grid start BTCUSDC --mode manual

# Check trading status
python -m ui.cli grid status

# View dashboard
python -m ui.dashboard

πŸ’° Live Trading (Advanced users)

⚠️ Warning: Only proceed with live trading after thorough testing in paper mode.

# AI-assisted parameter selection
python -m ui.cli grid start BTCUSDC --mode ai --confirm-live

# Monitor with web dashboard
streamlit run ui/dashboard.py

πŸ“Š Backtesting

Test and optimize your strategies using historical data:

# Run backtest on historical data
python -m ui.cli backtest run --strategy grid --symbol BTCUSDC --days 30

# Optimize parameters
python -m ui.cli model optimize --strategy baseline --symbol BTCUSDC

πŸ“ Directory Structure

The following table provides an overview of the project's modular architecture:

Directory Purpose Key Features
πŸ€– ai/ Machine learning and strategy intelligence Bayesian optimization, baseline strategies, model validation
🎯 core/ Core trading infrastructure Trading executor, safety systems, grid engine, state management
πŸ“Š data/ Data structures and loading Market data schemas, caching, validation
πŸ”Œ exec/ Exchange integration Binance API client, paper trading, rate limiting
πŸ“ˆ reports/ Performance analysis and reporting Comprehensive reports, HODL benchmarks, chart generation
πŸ§ͺ sim/ Backtesting and simulation Event-driven backtesting, performance evaluation, slippage models
πŸ’Ύ storage/ Data persistence and ML artifacts SQLite repository, ML model storage, hybrid data management
πŸ–₯️ ui/ User interfaces CLI, web dashboard, session management, security

βš™οΈ Configuration

🌍 Environment Variables

Create a .env file in the project root with your API credentials:

# API Configuration
BINANCE_API_KEY=your_api_key_here
BINANCE_API_SECRET=your_api_secret_here
BINANCE_TESTNET=true  # Use testnet for testing

Update the config.yaml file with your trading preferences:

trading:
    default_symbol: "BTCUSDC"
    default_timeframe: "5m"
    max_position_size: 1000.0
    risk_per_trade: 0.02

grid:
    n_grids: 12
    invest_per_grid: 50.0
    grid_spacing_pct: 0.01
    upper_price: null
    lower_price: null

πŸ›‘οΈ Risk Management

Configure risk limits in the risk_limits.json file to protect your capital:

{
    "max_daily_loss": 100.0,
    "max_position_size": 1000.0,
    "max_open_orders": 20,
    "circuit_breaker_threshold": 0.05
}

πŸ›‘οΈ Safety Features

The trading bot includes multiple layers of protection to safeguard your investments:

  • 🚨 Multi-layer Risk Management: Position limits, daily loss limits, and automated circuit breakers
  • ⚑ Emergency Flatten: Instant position closure with python -m ui.cli trade flatten
  • πŸ“ Paper Trading Default: All operations default to paper trading mode for safety
  • πŸ’Ύ State Persistence: Automatic state saving and recovery for system continuity
  • βœ… Input Validation: Comprehensive validation of all user inputs and commands

πŸ› οΈ Development

πŸ§ͺ Running Tests

Ensure code quality and reliability with our comprehensive test suite:

# Run all tests
python -m pytest

# Run specific test category
python -m pytest tests/test_core/

# Run with coverage
python -m pytest --cov=. --cov-report=html

πŸ” Code Quality

Maintain high code standards with automated tools:

# Format code
python -m black .

# Type checking
python -m mypy .

# Linting
python -m flake8 .

πŸ“š Documentation

  • πŸ‘¨β€πŸ’» Developer Docs: Detailed API documentation and development guides
  • πŸ“– Full Glossary: Complete terminology reference for trading and technical terms
  • πŸ“ Directory READMEs: See individual directory documentation for module-specific information

🀝 Contributing

We welcome contributions from the community! To contribute:

  1. Fork the repository on GitHub
  2. Create a feature branch: git checkout -b feature-name
  3. Make your changes and add comprehensive tests
  4. Run the test suite: python -m pytest to ensure everything works
  5. Submit a pull request with a clear description of your changes

πŸ“„ License

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

⚠️ Disclaimer

This software is for educational and research purposes only. Cryptocurrency trading involves significant financial risk. The authors are not responsible for any financial losses incurred through the use of this software. Always test thoroughly with paper trading before using real funds.

πŸ†˜ Support

  • πŸ› Issues: Report bugs and feature requests on GitHub Issues
  • πŸ“– Documentation: See directory-specific READMEs for detailed information
  • πŸ”’ Security: Report security vulnerabilities privately to the maintainers

About

No description, website, or topics provided.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages