Skip to content

XandarSword3/Paper-Trading-Bot

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

🐒 BTC Turtle-Donchian Trading Strategy System

A comprehensive algorithmic trading system implementing a Turtle-inspired Donchian Channel breakout strategy for Bitcoin. This project includes backtesting, optimization, Monte Carlo simulation, paper trading bots, and live trading capabilities.

πŸ“Š Overview

This system transforms the classic Turtle Trading strategy into a modern cryptocurrency trading bot with extensive backtesting and risk analysis. Starting from TradingView parameters that lost 84%, we optimized to achieve 855%+ returns through rigorous testing and validation.

Key Achievements

  • βœ… 8+ years of historical backtesting (Aug 2017 - Dec 2025)
  • βœ… Multiple strategy versions (V1: 4H timeframe, V4: 1H high-frequency)
  • βœ… Parameter optimization across 2,800+ combinations
  • βœ… Monte Carlo simulations with 1,000+ paths over 20 years
  • βœ… Automated paper trading on Binance testnet
  • βœ… Live trading integration with Telegram bot notifications
  • βœ… Interactive Streamlit dashboard for real-time analysis

πŸš€ Quick Start

Installation

# Clone the repository
git clone <your-repo-url>
cd "BTC Strategy"

# Create virtual environment (recommended)
python -m venv .venv
.venv\Scripts\activate  # Windows
source .venv/bin/activate  # Linux/Mac

# Install dependencies
pip install -r requirements.txt

Run Your First Backtest

# Quick analysis with optimized parameters
python quick_analysis.py

# Full analysis pipeline (all phases)
python main.py

# Interactive dashboard
streamlit run dashboard.py

πŸ“ Project Structure

BTC Strategy/
β”œβ”€β”€ πŸ“Š Core Strategy Files
β”‚   β”œβ”€β”€ strategy.py              # V1: Core Turtle-Donchian implementation (4H)
β”‚   β”œβ”€β”€ strategy_v2.py           # V2: Enhanced version with improvements
β”‚   β”œβ”€β”€ strategy_v3.py           # V3: Fast execution variant
β”‚   β”œβ”€β”€ strategy_v4.py           # V4: High-frequency 1H version (1572% returns!)
β”‚   β”œβ”€β”€ config.py                # V1 optimized parameters
β”‚   β”œβ”€β”€ config_v2.py             # V2 configuration
β”‚   └── config_v4_optimal.py     # V4 optimal parameters
β”‚
β”œβ”€β”€ πŸ”¬ Analysis & Testing
β”‚   β”œβ”€β”€ data_fetcher.py          # Downloads BTCUSDT data from Binance
β”‚   β”œβ”€β”€ robustness_test.py       # Parameter grid optimization (2,800 combos)
β”‚   β”œβ”€β”€ regime_analysis.py       # Market regime decomposition
β”‚   β”œβ”€β”€ regime_simulation.py     # 20-year Monte Carlo (optimistic)
β”‚   β”œβ”€β”€ realistic_regime_simulation.py  # With trading costs & slippage
β”‚   β”œβ”€β”€ monte_carlo.py           # Standard Monte Carlo simulation
β”‚   β”œβ”€β”€ survivability.py         # Capital survivability analysis
β”‚   β”œβ”€β”€ detailed_analysis.py     # Deep performance metrics
β”‚   └── validate_all.py          # Full system validation suite
β”‚
β”œβ”€β”€ πŸ€– Trading Bots
β”‚   β”œβ”€β”€ paper_bot.py             # Paper trading bot (Binance testnet)
β”‚   β”œβ”€β”€ simple_paper_bot.py      # Simplified paper trading version
β”‚   β”œβ”€β”€ telegram_bot.py          # Telegram notification bot
β”‚   β”œβ”€β”€ github_bot.py            # Live trading bot (Binance mainnet)
β”‚   β”œβ”€β”€ github_bot_v4.py         # V4 live trading bot
β”‚   └── get_chat_id.py           # Get Telegram chat ID utility
β”‚
β”œβ”€β”€ πŸ“ˆ Visualization & Dashboard
β”‚   β”œβ”€β”€ dashboard.py             # Main Streamlit dashboard
β”‚   β”œβ”€β”€ visualization.py         # Plotting utilities
β”‚   └── pages/
β”‚       β”œβ”€β”€ 1_Candle_Analysis.py
β”‚       β”œβ”€β”€ 2_V1_Strategy.py
β”‚       └── 3_V4_Strategy.py
β”‚
β”œβ”€β”€ πŸ“Š Comparative Analysis
β”‚   β”œβ”€β”€ sp500_reinvest.py        # Compare: $1K + $300/mo in S&P 500
β”‚   β”œβ”€β”€ strategy_analysis.py     # Strategy comparison tools
β”‚   └── forward_test.py          # Forward testing framework
β”‚
β”œβ”€β”€ πŸ“š Documentation
β”‚   β”œβ”€β”€ README.md                # This file
β”‚   β”œβ”€β”€ SYSTEM_SUMMARY.md        # Complete system overview
β”‚   β”œβ”€β”€ BOT_GUIDE.md             # How to run trading bots
β”‚   β”œβ”€β”€ CRITICAL_WARNINGS.md     # Risk disclosures & limitations
β”‚   └── PAPER_TRADING_CHECKLIST.md
β”‚
β”œβ”€β”€ πŸ’Ύ Data & Results
β”‚   β”œβ”€β”€ data/
β”‚   β”‚   β”œβ”€β”€ BTCUSDT_4h.csv       # Historical 4H candle data
β”‚   β”‚   └── SP500.csv            # S&P 500 comparison data
β”‚   β”œβ”€β”€ results/
β”‚   β”‚   β”œβ”€β”€ all_trades.csv       # Full trade history
β”‚   β”‚   β”œβ”€β”€ backtest_results.csv
β”‚   β”‚   β”œβ”€β”€ robustness_results.csv
β”‚   β”‚   └── plots/               # Generated charts
β”‚   └── backups/
β”‚       β”œβ”€β”€ strategy_v1_winning.py
β”‚       └── config_v1_winning.py
β”‚
└── πŸ”§ Configuration Files
    β”œβ”€β”€ requirements.txt          # Python dependencies
    β”œβ”€β”€ requirements_dashboard.txt
    β”œβ”€β”€ bot_state.json           # Bot state persistence
    β”œβ”€β”€ trades.json              # Trade log
    └── .env                     # API keys (not committed)

🎯 Strategy Versions

V1: 4-Hour Optimized Strategy (855% Return)

Best for: Swing trading, lower trade frequency, easier to manage

Parameter Value Why
Timeframe 4H Filters noise, captures major trends
Entry Length 40 160-hour breakout (fewer false signals)
Exit Length 16 64-hour channel (good trend capture)
Trail Multiplier 4.0 Wide stops for volatile crypto markets
Risk % 1.0% Conservative position sizing
Direction Long Only Shorts historically unprofitable in BTC

Results (Aug 2017 - Dec 2025):

  • Total Return: +855% ($1,000 β†’ $9,550)
  • Max Drawdown: -39.3%
  • Win Rate: 45.5%
  • Profit Factor: 1.60
  • Total Trades: 442 (~0.14 trades/day)

V4: 1-Hour High-Frequency Strategy (1572% Return)

Best for: Active traders, higher capital efficiency, more opportunities

Parameter Value Difference from V1
Timeframe 1H 4x more granular
Entry Length 8 8-hour breakout (faster entries)
Exit Length 16 16-hour channel
Trail Multiplier 3.5 Slightly tighter for faster timeframe
Risk % 1.0% Same conservative sizing
Direction Long Only Same as V1

Results:

  • Total Return: +1572% ($1,000 β†’ $16,720)
  • Max Drawdown: -65% (higher volatility)
  • Win Rate: 44%
  • Profit Factor: 1.27
  • Total Trades: ~3,900 (~1.33 trades/day)

Trade-off: Higher returns but more drawdown and requires more active monitoring.

πŸ”¬ Research & Development Journey

Phase 1: Original TradingView Parameters (FAILED ❌)

Entry: 20, Exit: 10, Trail: 2.5, Risk: 1.5%
Result: -84.4% return, -90.9% max drawdown

The original parameters from TradingView lost money in every market regime.

Phase 2: Regime Decomposition βœ“

Tested strategy across 6 distinct market regimes:

  • 2017 Bull (+198% BTC): Strategy +48%
  • 2018 Bear (-72% BTC): Strategy -37%
  • 2019 Chop (+96% BTC): Strategy +24%
  • 2020-2021 Bull (+553% BTC): Strategy -42%
  • 2022 Bear (-65% BTC): Strategy -51%
  • 2023-2025 Recovery (+435% BTC): Strategy -41%

Key Finding: Original parameters failed in ALL regimes!

Phase 3: Parameter Optimization βœ“

Tested 2,800 parameter combinations:

  • 56% of combinations were profitable
  • 24.5% achieved >100% returns
  • Identified robust parameter ranges (plateaus vs cliffs)

Optimization Results:

Parameter Original Optimized Impact
Entry Length 20 40 βœ… Fewer false breakouts
Exit Length 10 16 βœ… Better trend capture
Trail Multiplier 2.5 4.0 βœ… Avoids noise volatility
Risk % 1.5% 1.0% βœ… More sustainable

Phase 4: Monte Carlo Simulation (20-Year Forward Projection) βœ“

Simulated 1,000 paths over 20 years with realistic market conditions:

Realistic Scenario (with costs):

  • Median Outcome: $220,210 (22,021% return)
  • 5th Percentile: $17,846 (worst case still profitable)
  • 95th Percentile: $4.3M (best case)

Probability Table:

  • 100% chance of profit (no paths lost money)
  • 97.9% chance of exceeding $10,000
  • 66.9% chance of exceeding $100,000
  • 18.3% chance of exceeding $1,000,000

Phase 5: Cost Modeling βœ“

Included realistic trading costs:

  • Exchange fees: 0.15% per trade
  • Slippage: 0.05% per trade
  • Annual execution errors: 1%
  • Network fees and spread costs

Impact: Realistic simulation shows ~40% lower returns than optimistic scenario.

πŸ€– Trading Bot Features

Paper Trading Bot (paper_bot.py)

  • Connects to Binance Testnet (fake money, real execution)
  • Monitors 4H BTC candles in real-time
  • Automatically executes V1 strategy
  • Logs all trades to paper_bot.log
  • Emergency Killswitch: Create KILLSWITCH.txt to stop gracefully
# Start paper trading
python paper_bot.py

# Monitor in real-time
tail -f paper_bot.log  # Linux/Mac
Get-Content paper_bot.log -Wait  # Windows

Live Trading Bot (github_bot.py)

⚠️ WARNING: Uses real money on Binance mainnet!

Features:

  • Telegram notifications for every trade
  • State persistence (bot_state.json)
  • Position tracking and P&L monitoring
  • Automatic reconnection and error handling

Required setup:

# Create .env file with:
BINANCE_API_KEY=your_api_key
BINANCE_API_SECRET=your_secret_key
TELEGRAM_BOT_TOKEN=your_bot_token
TELEGRAM_CHAT_ID=your_chat_id

πŸ“Š Interactive Dashboard

Launch the Streamlit dashboard for real-time analysis:

streamlit run dashboard.py

Features:

  • πŸ“ˆ Live BTC price charts with Donchian channels
  • πŸ“Š Strategy performance metrics
  • πŸ” Individual trade analysis
  • πŸ“‰ Drawdown visualization
  • 🎯 Parameter sensitivity analysis
  • πŸ“± Multi-page interface for different analyses

⚠️ Critical Warnings

🚨 READ BEFORE TRADING REAL MONEY

This simulation is optimistic. Real trading will face:

  1. Trading Costs (reduces returns by 20-40%)

    • Exchange fees: 0.1-0.15% per trade
    • Slippage: 0.05-0.2% per execution
    • Network fees and spread costs
  2. Execution Problems

    • Order delays and partial fills
    • Price gaps through stop losses
    • Exchange downtime and API failures
  3. Psychological Failures (90% of traders fail here)

    • Panic selling during drawdowns
    • Revenge trading after losses
    • Parameter tweaking mid-strategy
    • FOMO and emotional overrides
  4. Black Swan Events

    • Exchange collapses (FTX, Mt.Gox)
    • Flash crashes and liquidation cascades
    • Regulatory changes
    • Market structure shifts
  5. Historical Bias

    • BTC had unprecedented bull market 2017-2021
    • Past performance β‰  future results
    • Strategy optimized on limited data

See CRITICAL_WARNINGS.md for full risk disclosure.

πŸŽ“ What You'll Learn

This project demonstrates:

  • βœ… Professional backtesting methodology
  • βœ… Parameter optimization techniques
  • βœ… Monte Carlo simulation for risk assessment
  • βœ… Real-time data integration (Binance API)
  • βœ… Position sizing and risk management
  • βœ… Trade execution and order management
  • βœ… State persistence and error handling
  • βœ… Telegram bot integration
  • βœ… Interactive data visualization
  • βœ… Performance metrics and analytics

πŸ”§ Dependencies

Core Libraries

pandas>=2.0.0           # Data manipulation
numpy>=1.24.0           # Numerical computing
vectorbt>=0.26.0        # Vectorized backtesting
matplotlib>=3.7.0       # Plotting
seaborn>=0.12.0         # Statistical visualization
scipy>=1.10.0           # Scientific computing

Trading & Data

python-binance>=1.0.19  # Binance API wrapper
requests>=2.28.0        # HTTP requests
python-dotenv>=1.0.0    # Environment variables

Dashboard & Utilities

streamlit>=1.28.0       # Interactive dashboard
plotly>=5.18.0          # Interactive plots
tqdm>=4.65.0            # Progress bars
pyarrow>=14.0.0         # Fast data serialization

πŸ“š Key Files Explained

File Purpose
strategy.py Core V1 strategy class with Donchian logic
config.py Optimized V1 parameters (Entry=40, Exit=16, etc.)
data_fetcher.py Downloads historical data from Binance
robustness_test.py Grid search over 2,800 parameter combos
realistic_regime_simulation.py 20-year Monte Carlo with costs
paper_bot.py Safe testnet trading bot
github_bot.py Live trading bot (REAL MONEY)
dashboard.py Streamlit interactive interface
validate_all.py Run all tests to verify system integrity

πŸ”₯ Performance Highlights

V1 Strategy (4H Timeframe)

  • Initial Capital: $1,000
  • Final Equity: $9,550
  • Return: +855%
  • CAGR: ~30% over 8 years
  • Max Drawdown: -39.3%
  • Sharpe Ratio: 1.98
  • Profit Factor: 1.60
  • Win Rate: 45.5%

Yearly Breakdown

Year Return Status
2018 -2.9% πŸ“‰ Bear market
2019 +101.4% βœ… Best year
2020 +81.7% βœ… Strong bull
2021 -7.7% πŸ“‰ Choppy top
2022 -22.6% πŸ“‰ Bear market
2023 +74.7% βœ… Recovery
2024 +32.2% βœ… Solid growth
2025 +6.9% ⏳ Partial year

Winning Years: 5 | Losing Years: 3

🎯 Usage Examples

Run a Quick Backtest

# Using V1 optimized parameters
python quick_analysis.py

# Output:
# Final Equity: $9,550
# Total Return: +855%
# Max Drawdown: -39.3%
# Win Rate: 45.5%

Parameter Optimization

# Test 2,800 parameter combinations
python robustness_test.py

# Results saved to: results/robustness_results.csv

Monte Carlo Simulation

# 20-year forward simulation with realistic costs
python realistic_regime_simulation.py

# Output:
# Median 20-year outcome: $220,210
# 95% confidence interval: $17,846 - $4.3M
# Probability of profit: 100%

Paper Trading (Safe Testing)

# Start paper trading bot on Binance testnet
python paper_bot.py

# Monitor logs
tail -f paper_bot.log

Compare vs S&P 500

# What if you invested $1K + $300/month in S&P 500?
python sp500_reinvest.py

# Compares strategy performance vs traditional investing

πŸ§ͺ Testing & Validation

Run All Validation Tests

python validate_all.py

This runs:

  • βœ… Data integrity checks
  • βœ… Strategy logic validation
  • βœ… Parameter range verification
  • βœ… Backtest reproducibility
  • βœ… Bot state persistence
  • βœ… API connection tests

πŸ“ˆ Comparison: Strategy vs S&P 500

Scenario: $1,000 initial + $300/month for 8 years

Metric BTC Strategy (V1) S&P 500 Index
Initial Capital $1,000 $1,000
Monthly Addition $0 $300
Total Invested $1,000 $29,800
Final Value $9,550 ~$45,000
Return on Initial +855% +4,400%
Risk (Max DD) -39.3% ~-25%
Active Management Required Passive

Key Insight: Strategy outperforms on capital efficiency (no monthly additions needed), but S&P 500 wins with disciplined monthly investing.

πŸ›‘οΈ Risk Management

Position Sizing

  • Risk per trade: 1% of equity
  • Max units: 4 (pyramiding on breakouts)
  • Stop loss: 4.0 Γ— ATR trailing stop

Portfolio Protection

  • Max drawdown experienced: -39.3% (V1), -65% (V4)
  • Diversification: Single asset (BTC) - consider adding other assets
  • Capital preservation: Never risk more than can afford to lose

Recommended Safety Measures

  1. Start with paper trading (testnet)
  2. Use only 20-30% of total capital for strategy
  3. Keep emergency fund outside of trading
  4. Set maximum drawdown threshold (e.g., -50%)
  5. Review and adjust parameters quarterly

πŸ”’ Security & API Setup

Environment Variables (.env)

# Binance API (get from binance.com)
BINANCE_API_KEY=your_api_key_here
BINANCE_API_SECRET=your_secret_key_here

# Telegram Bot (get from @BotFather)
TELEGRAM_BOT_TOKEN=your_bot_token
TELEGRAM_CHAT_ID=your_chat_id

# Optional: Use testnet for paper trading
USE_TESTNET=true

Security Best Practices

  • βœ… Never commit .env file to GitHub
  • βœ… Use API keys with trade-only permissions (no withdrawals)
  • βœ… Enable IP whitelisting on Binance
  • βœ… Use 2FA on exchange account
  • βœ… Regularly rotate API keys
  • βœ… Monitor unusual activity via Telegram alerts

πŸ“Š Performance Metrics Explained

Return Metrics

  • Total Return: (Final Equity - Initial Capital) / Initial Capital
  • CAGR: Compound Annual Growth Rate
  • Sharpe Ratio: Risk-adjusted returns (>1.0 is good)
  • Profit Factor: Gross Profit / Gross Loss

Risk Metrics

  • Max Drawdown: Largest peak-to-trough decline
  • Win Rate: % of profitable trades
  • Average Win: Average profit per winning trade
  • Average Loss: Average loss per losing trade
  • Expectancy: (Win Rate Γ— Avg Win) - (Loss Rate Γ— Avg Loss)

Trade Metrics

  • Total Trades: Number of completed round trips
  • Avg Trade Duration: Time from entry to exit
  • Trade Frequency: Trades per day/week/month

πŸ› Troubleshooting

Common Issues

Issue: ModuleNotFoundError: No module named 'vectorbt'

# Solution: Install missing dependencies
pip install -r requirements.txt

Issue: binance.exceptions.BinanceAPIException: Invalid API-key

# Solution: Check .env file has correct keys
# Verify keys are active on binance.com

Issue: Bot not executing trades

# Check logs for errors
cat paper_bot.log

# Verify data is updating
python data_fetcher.py

Issue: Dashboard won't load

# Install dashboard requirements
pip install -r requirements_dashboard.txt

# Run with verbose logging
streamlit run dashboard.py --logger.level=debug

🀝 Contributing

This is a personal research project, but suggestions are welcome!

Areas for Improvement

  • Add more timeframes (15m, 1D, 1W)
  • Multi-asset portfolio version
  • Machine learning for parameter adaptation
  • Alternative entry/exit signals
  • Integration with other exchanges
  • Mobile app for monitoring
  • Advanced risk management (Kelly Criterion)
  • Tax reporting automation

πŸ“œ License

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

Disclaimer: Trading cryptocurrencies involves substantial risk of loss. Past performance does not guarantee future results. This software is provided "as is" without warranty. The author is not responsible for any financial losses.

πŸ™ Acknowledgments

  • Turtle Trading System: Original methodology by Richard Dennis
  • Donchian Channels: Indicator by Richard Donchian
  • VectorBT: Fast backtesting library
  • Binance API: Data and execution infrastructure
  • Community: TradingView, QuantConnect, Reddit r/algotrading

πŸ“ž Support & Contact

  • Issues: Open a GitHub issue
  • Questions: Check documentation in /docs
  • Updates: Watch this repository for improvements

πŸ—ΊοΈ Roadmap

βœ… Completed

  • V1 strategy optimization (4H timeframe)
  • V4 high-frequency strategy (1H timeframe)
  • Monte Carlo simulations
  • Paper trading bot (testnet)
  • Live trading bot with Telegram
  • Interactive Streamlit dashboard
  • Comprehensive documentation

🚧 In Progress

  • Multi-exchange support (Coinbase, Kraken)
  • Portfolio mode (BTC, ETH, SOL)
  • Machine learning parameter optimization

πŸ“‹ Planned

  • Mobile app for iOS/Android
  • Web-based dashboard (React)
  • Advanced analytics (regime detection)
  • Social trading features
  • Automated tax reporting

πŸ“š Additional Resources


Last Updated: December 27, 2025

Built with ❀️ for algorithmic trading education

  • Max Drawdown: 39.3% (acceptable)
  • Longest Drawdown: 2.5 years
  • Worst losing streak: 13 trades
  • PASSES stress test

Phase 5: Monte Carlo βœ“

  • Ran 500 randomized simulations
  • Monte Carlo shows path-dependent risk
  • Important: Backtest β‰  guaranteed future returns

Phase 6-7: Forward Testing Framework βœ“

  • Paper trading tracker ready
  • Signal generator implemented
  • Deployment checklist created

Critical Insights

  1. The TradingView parameters are WRONG for this strategy

    • Entry=20 is too short, catches false breakouts
    • Trail=2.5 is too tight, gets stopped out prematurely
    • Pyramid spacing=0.5 ATR is too aggressive
  2. The strategy HAS edge, but only in specific parameter regions

    • Robustness testing shows wide profitable plateaus
    • Need Entry >= 35, Trail >= 3.5 for consistent profits
  3. Time underwater is VERY high (98%)

    • You will be in drawdown almost constantly
    • Patience and discipline are essential
  4. Monte Carlo reveals path risk

    • Shuffling trade order changes outcomes significantly
    • Don't expect backtest returns in live trading

Files Generated

  • results/backtest_results.csv - Full backtest data
  • results/backtest_optimized.csv - Optimized params backtest
  • results/regime_analysis.csv - Regime breakdown
  • results/robustness_results.csv - All parameter combinations
  • results/plots/equity_curve.png - Equity chart
  • results/plots/trade_analysis.png - Trade statistics
  • results/plots/robustness_heatmaps.png - Parameter sensitivity
  • results/plots/monte_carlo_optimized.png - MC distribution

Next Steps

  1. Review the robustness heatmaps to understand parameter sensitivity
  2. Run forward_test.py to start paper trading
  3. Paper trade for 3-6 months before real deployment
  4. Start with 10-20% of intended capital when going live

Warning

This strategy will lose money with the TradingView default parameters.

You MUST use the optimized parameters or run your own robustness testing to find profitable parameter regions.

Usage

Generate current signals:

python forward_test.py

Run regime analysis only:

python regime_analysis.py

Run survivability analysis:

python survivability.py

Run Monte Carlo simulation:

python monte_carlo.py

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages