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.
- 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
- Python 3.8+
- Chrome browser (for Selenium web scraping)
- Internet connection for API calls
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
-
Clone the repository:
git clone <repository-url> cd btc_trading_bot
-
Install dependencies:
pip install -r requirements.txt
-
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/
Fetches and logs Bitcoin prices from CoinGecko API.
Basic Usage:
python btc_price_tracker.pyAdvanced 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.logParameters:
--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)
Scrapes BTC prediction markets from Polymarket using Selenium.
Basic Usage:
python polymarket_fetcher_selenium.pyFeatures:
- JavaScript-rendered content handling
- Automatic market filtering (removes markets without price data)
- CSV output with timestamps
- Error handling and retry logic
Fetches and analyzes orderbook data from major exchanges.
python orderbook_analyzer.py- Change exchange with
--exchange binance|coinbase|kraken(if supported)
Simulates automated trading with risk management and detailed reporting.
Basic Usage:
python strategy_simulator.pyAdvanced 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 1000Parameters:
--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)
Uses orderbook, volatility, and trend for smarter entries/exits.
python enhanced_strategy_simulator.py --use-orderbook --exchange binance- See
--helpfor all options (entry delay, min delta, volatility, etc)
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
--helpfor all options (drawdown, session interval, etc)
# 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 -vThe 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
btc_prices.csv: Historical BTC price data with timestampspolymarket_markets.csv: Scraped prediction market dataautomated_trading_results.csv: Detailed trading simulation resultssession_*_results.csv: Automated trading session resultsauto_trader_results_*.json: Automated trading session logsorderbook_data.csv: Orderbook analytics (if run)btc_price_tracker.log: Application logs with rotationmock_btc_prices.csv: Mock data for testing
BTC Prices (btc_prices.csv):
timestamp,btc_price_usd
2025-06-24T20:03:25.618412,106044.0
2025-06-24T20:06:07.244765,106070.0Polymarket 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.7091Trading 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.0Conservative 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
The system implements multiple risk controls:
- Entry Delay: Prevents immediate reactions to market noise
- Minimum Price Delta: Ensures sufficient movement before trading
- Trailing Stops: Limits losses on adverse price movements
- Profit Targets: Secures gains at predetermined levels
- Meltdown Protection: Emergency exit for extreme price movements
- Position Sizing: Controls exposure per trade
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
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
- 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
- Real-time status updates during long operations
- Progress bars for data processing
- Performance metrics display
- Error count and retry statistics
- 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
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-
ChromeDriver not found:
# Install ChromeDriver brew install chromedriver # macOS sudo apt-get install chromium-chromedriver # Ubuntu
-
API rate limiting:
# Increase retry delay python btc_price_tracker.py --retry-delay 30 -
Selenium timeout:
# Increase timeout python btc_price_tracker.py --timeout 60 -
CSV file corruption:
# Backup and recreate mv btc_prices.csv btc_prices.csv.backup python btc_price_tracker.py
# Enable debug logging
python btc_price_tracker.py --log-level DEBUG
python strategy_simulator.py --log-level DEBUGbtc_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
- Write unit tests first
- Implement feature with proper error handling
- Add logging and monitoring
- Update documentation
- Run integration tests
This project is for educational and research purposes. Use at your own risk.
- Fork the repository
- Create a feature branch
- Add tests for new functionality
- Ensure all tests pass
- Submit a pull request
For issues and questions:
- Check the troubleshooting section
- Review the logs for error details
- Run tests to verify system integrity
- 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.
__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_*.jsonThis system is modular and extensible. For advanced use, tune the enhanced strategy, integrate more data sources, or add a dashboard.