Skip to content

harshareddy832/btc-trading-bot

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

1 Commit
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

Bitcoin Trading Bot System

A comprehensive prototype trading bot system that fetches Bitcoin prices, scrapes prediction markets, simulates automated trading with risk management, and now includes orderbook analytics, enhanced strategy logic, and automated multi-session trading.

πŸš€ Features

  • Real-time BTC Price Tracking: Fetches live Bitcoin prices from CoinGecko API
  • Prediction Market Scraping: Scrapes Polymarket BTC prediction markets using Selenium
  • Orderbook Analysis: Fetches and analyzes orderbook data from major exchanges (Binance, Coinbase, Kraken)
  • Enhanced Strategy Simulator: Multi-factor entry/exit logic using orderbook, volatility, and trend
  • Automated Trading Bot: Runs multiple trading sessions, tracks PnL, and manages risk
  • Risk Management: Trailing stops, profit targets, meltdown protection, and emergency stop
  • Comprehensive Logging: Detailed logging with rotation and multiple levels
  • CLI Interface: Command-line interface with parameter validation
  • Unit & Integration Tests: Complete test suite for all components
  • Performance Monitoring: Progress tracking and status updates

πŸ“‹ Requirements

System Requirements

  • Python 3.8+
  • Chrome browser (for Selenium web scraping)
  • Internet connection for API calls

Python Dependencies

requests>=2.31.0
pandas>=2.0.0
numpy>=1.24.0
beautifulsoup4>=4.12.0
selenium>=4.15.0
webdriver-manager>=4.0.0
schedule>=1.2.0
lxml>=4.9.0

πŸ› οΈ Installation

  1. Clone the repository:

    git clone <repository-url>
    cd btc_trading_bot
  2. Install dependencies:

    pip install -r requirements.txt
  3. Install Chrome WebDriver (for Selenium):

    # macOS (using Homebrew)
    brew install chromedriver
    
    # Ubuntu/Debian
    sudo apt-get install chromium-chromedriver
    
    # Windows
    # Download from https://chromedriver.chromium.org/

πŸ“– Usage

1. BTC Price Tracker

Fetches and logs Bitcoin prices from CoinGecko API.

Basic Usage:

python btc_price_tracker.py

Advanced Options:

# Continuous tracking with custom interval
python btc_price_tracker.py --continuous --interval 30

# Debug logging
python btc_price_tracker.py --log-level DEBUG

# Custom retry settings
python btc_price_tracker.py --max-retries 5 --retry-delay 10

# Custom file paths
python btc_price_tracker.py --csv-file custom_prices.csv --log-file custom.log

Parameters:

  • --continuous: Run continuous price tracking (default: single fetch)
  • --interval SECONDS: Tracking interval in seconds (default: 60)
  • --max-retries N: Maximum retry attempts (default: 3)
  • --retry-delay SECONDS: Delay between retries (default: 5)
  • --log-level LEVEL: Logging level (DEBUG, INFO, WARNING, ERROR, CRITICAL)
  • --log-file PATH: Log file path
  • --csv-file PATH: CSV output file path
  • --timeout SECONDS: API request timeout (default: 30)

2. Polymarket Fetcher

Scrapes BTC prediction markets from Polymarket using Selenium.

Basic Usage:

python polymarket_fetcher_selenium.py

Features:

  • JavaScript-rendered content handling
  • Automatic market filtering (removes markets without price data)
  • CSV output with timestamps
  • Error handling and retry logic

3. Orderbook Analyzer

Fetches and analyzes orderbook data from major exchanges.

python orderbook_analyzer.py
  • Change exchange with --exchange binance|coinbase|kraken (if supported)

4. Strategy Simulator

Simulates automated trading with risk management and detailed reporting.

Basic Usage:

python strategy_simulator.py

Advanced Options:

# Conservative strategy
python strategy_simulator.py --entry-delay 10 --min-delta 50 --trailing-stop 100

# Aggressive strategy
python strategy_simulator.py --entry-delay 2 --min-delta 5 --trailing-stop 25

# Custom position sizing
python strategy_simulator.py --position-size 500 --meltdown-threshold 1000

Parameters:

  • --entry-delay MINUTES: Delay before entering positions (default: 5)
  • --min-delta DOLLARS: Minimum BTC price movement to trade (default: 10.0)
  • --trailing-stop DOLLARS: Trailing stop loss amount (default: 50.0)
  • --profit-target RATIO: Profit target ratio (default: 0.998)
  • --meltdown-threshold DOLLARS: Meltdown protection threshold (default: 200.0)
  • --position-size DOLLARS: Position size per trade (default: 100.0)

5. Enhanced Strategy Simulator

Uses orderbook, volatility, and trend for smarter entries/exits.

python enhanced_strategy_simulator.py --use-orderbook --exchange binance
  • See --help for all options (entry delay, min delta, volatility, etc)

6. Automated Trading Bot

Runs the full system for multiple sessions, tracks PnL, and manages risk.

python auto_trader.py --total-sessions 6 --entry-delay 5 --min-delta 10.0
  • See --help for all options (drawdown, session interval, etc)

πŸ§ͺ Testing

Run All Tests

# Unit tests
python -m unittest test_btc_price_tracker.py -v
python -m unittest test_polymarket_fetcher.py -v
python -m unittest test_strategy_simulator.py -v

# Integration tests
python -m unittest test_integration.py -v

# Run all tests
python -m unittest discover -v

Test Coverage

The test suite covers:

  • βœ… API interactions and error handling
  • βœ… Web scraping and data parsing
  • βœ… Trading logic and risk management
  • βœ… CSV file operations
  • βœ… CLI parameter validation
  • βœ… Integration workflows
  • βœ… Error scenarios and edge cases

πŸ“Š Output Files

Generated Files

  • btc_prices.csv: Historical BTC price data with timestamps
  • polymarket_markets.csv: Scraped prediction market data
  • automated_trading_results.csv: Detailed trading simulation results
  • session_*_results.csv: Automated trading session results
  • auto_trader_results_*.json: Automated trading session logs
  • orderbook_data.csv: Orderbook analytics (if run)
  • btc_price_tracker.log: Application logs with rotation
  • mock_btc_prices.csv: Mock data for testing

CSV File Formats

BTC Prices (btc_prices.csv):

timestamp,btc_price_usd
2025-06-24T20:03:25.618412,106044.0
2025-06-24T20:06:07.244765,106070.0

Polymarket Markets (polymarket_markets.csv):

market_id,market_name,start_time,end_time,yes_price,no_price,status,scraped_at
bitcoinhit,bitcoin-hit,00:00 (resolution time),00:05 (resolution time),0.5,0.5,Active,2025-06-24T20:05:46.7091

Trading Results (automated_trading_results.csv):

market_id,start_time,end_time,entry_time,exit_time,btc_entry_price,btc_exit_price,price_delta,simulated_position,exit_reason,realized_pnl,cumulative_pnl
market_1,2025-06-24 13:00:00,2025-06-24 14:00:00,2025-06-24 13:05:00,2025-06-24 14:00:00,105000.0,105200.0,200.0,YES,meltdown_protection,66.67,0.0

πŸ”§ Configuration

Trading Parameters

Conservative Settings (Lower risk, lower returns):

  • Entry delay: 10 minutes
  • Minimum delta: $50
  • Trailing stop: $100
  • Position size: $50

Moderate Settings (Balanced risk/reward):

  • Entry delay: 5 minutes
  • Minimum delta: $10
  • Trailing stop: $50
  • Position size: $100

Aggressive Settings (Higher risk, higher returns):

  • Entry delay: 2 minutes
  • Minimum delta: $5
  • Trailing stop: $25
  • Position size: $200

Risk Management

The system implements multiple risk controls:

  1. Entry Delay: Prevents immediate reactions to market noise
  2. Minimum Price Delta: Ensures sufficient movement before trading
  3. Trailing Stops: Limits losses on adverse price movements
  4. Profit Targets: Secures gains at predetermined levels
  5. Meltdown Protection: Emergency exit for extreme price movements
  6. Position Sizing: Controls exposure per trade

πŸ“ˆ Performance Metrics

The simulator tracks comprehensive performance metrics:

  • Total Trades: Number of executed trades
  • Win Rate: Percentage of profitable trades
  • Total PnL: Cumulative profit/loss
  • Max Drawdown: Largest peak-to-trough decline
  • Exit Reasons: Breakdown of trade closure reasons
  • Risk Metrics: Trailing stop, profit target, meltdown threshold usage

🚨 Error Handling

The system includes robust error handling:

  • API Failures: Automatic retries with exponential backoff
  • Network Issues: Graceful degradation and fallback options
  • Data Validation: Input sanitization and format checking
  • File Operations: Safe CSV handling with backups
  • Web Scraping: Selenium error recovery and alternative strategies

πŸ” Monitoring

Log Levels

  • DEBUG: Detailed execution flow and data processing
  • INFO: General operational information
  • WARNING: Potential issues that don't stop execution
  • ERROR: Errors that affect functionality
  • CRITICAL: Fatal errors requiring immediate attention

Progress Tracking

  • Real-time status updates during long operations
  • Progress bars for data processing
  • Performance metrics display
  • Error count and retry statistics

πŸ›‘οΈ Security Considerations

  • API Rate Limiting: Respects CoinGecko API limits
  • Data Validation: Sanitizes all inputs and outputs
  • Error Logging: Avoids sensitive data in logs
  • File Permissions: Secure CSV file handling
  • Network Security: HTTPS for all API communications

πŸ”„ Continuous Operation

For long-running operations:

# Continuous price tracking
python btc_price_tracker.py --continuous --interval 60

# Monitor logs
tail -f btc_price_tracker.log

# Check system status
ps aux | grep python

πŸ› Troubleshooting

Common Issues

  1. ChromeDriver not found:

    # Install ChromeDriver
    brew install chromedriver  # macOS
    sudo apt-get install chromium-chromedriver  # Ubuntu
  2. API rate limiting:

    # Increase retry delay
    python btc_price_tracker.py --retry-delay 30
  3. Selenium timeout:

    # Increase timeout
    python btc_price_tracker.py --timeout 60
  4. CSV file corruption:

    # Backup and recreate
    mv btc_prices.csv btc_prices.csv.backup
    python btc_price_tracker.py

Debug Mode

# Enable debug logging
python btc_price_tracker.py --log-level DEBUG
python strategy_simulator.py --log-level DEBUG

πŸ“ Development

Code Structure

btc_trading_bot/
β”œβ”€β”€ btc_price_tracker.py          # BTC price fetching and logging
β”œβ”€β”€ polymarket_fetcher_selenium.py # Market scraping with Selenium
β”œβ”€β”€ strategy_simulator.py         # Trading simulation engine
β”œβ”€β”€ test_*.py                     # Unit and integration tests
β”œβ”€β”€ requirements.txt              # Python dependencies
β”œβ”€β”€ README.md                     # This documentation
└── *.csv                         # Data files

Adding New Features

  1. Write unit tests first
  2. Implement feature with proper error handling
  3. Add logging and monitoring
  4. Update documentation
  5. Run integration tests

πŸ“„ License

This project is for educational and research purposes. Use at your own risk.

🀝 Contributing

  1. Fork the repository
  2. Create a feature branch
  3. Add tests for new functionality
  4. Ensure all tests pass
  5. Submit a pull request

πŸ“ž Support

For issues and questions:

  1. Check the troubleshooting section
  2. Review the logs for error details
  3. Run tests to verify system integrity
  4. Create an issue with detailed information

Disclaimer: This is a prototype trading system for educational purposes. Do not use with real money without proper testing and risk assessment.

🧹 Unnecessary/Generated Files

  • __pycache__/: Python bytecode cache, can be deleted
  • *.log, *.csv, auto_trader_results_*.json: Output/log files, can be deleted for a clean repo

To clean up:

rm -rf __pycache__ *.log *.csv auto_trader_results_*.json

This system is modular and extensible. For advanced use, tune the enhanced strategy, integrate more data sources, or add a dashboard.

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages