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.
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.
- β 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
# 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# Quick analysis with optimized parameters
python quick_analysis.py
# Full analysis pipeline (all phases)
python main.py
# Interactive dashboard
streamlit run dashboard.pyBTC 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)
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)
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.
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.
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!
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 |
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
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.
- 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.txtto 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 # WindowsFeatures:
- 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_idLaunch the Streamlit dashboard for real-time analysis:
streamlit run dashboard.pyFeatures:
- π Live BTC price charts with Donchian channels
- π Strategy performance metrics
- π Individual trade analysis
- π Drawdown visualization
- π― Parameter sensitivity analysis
- π± Multi-page interface for different analyses
This simulation is optimistic. Real trading will face:
-
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
-
Execution Problems
- Order delays and partial fills
- Price gaps through stop losses
- Exchange downtime and API failures
-
Psychological Failures (90% of traders fail here)
- Panic selling during drawdowns
- Revenge trading after losses
- Parameter tweaking mid-strategy
- FOMO and emotional overrides
-
Black Swan Events
- Exchange collapses (FTX, Mt.Gox)
- Flash crashes and liquidation cascades
- Regulatory changes
- Market structure shifts
-
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.
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
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
python-binance>=1.0.19 # Binance API wrapper
requests>=2.28.0 # HTTP requests
python-dotenv>=1.0.0 # Environment variables
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
| 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 |
- 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%
| 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
# Using V1 optimized parameters
python quick_analysis.py
# Output:
# Final Equity: $9,550
# Total Return: +855%
# Max Drawdown: -39.3%
# Win Rate: 45.5%# Test 2,800 parameter combinations
python robustness_test.py
# Results saved to: results/robustness_results.csv# 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%# Start paper trading bot on Binance testnet
python paper_bot.py
# Monitor logs
tail -f paper_bot.log# What if you invested $1K + $300/month in S&P 500?
python sp500_reinvest.py
# Compares strategy performance vs traditional investingpython validate_all.pyThis runs:
- β Data integrity checks
- β Strategy logic validation
- β Parameter range verification
- β Backtest reproducibility
- β Bot state persistence
- β API connection tests
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 per trade: 1% of equity
- Max units: 4 (pyramiding on breakouts)
- Stop loss: 4.0 Γ ATR trailing stop
- 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
- Start with paper trading (testnet)
- Use only 20-30% of total capital for strategy
- Keep emergency fund outside of trading
- Set maximum drawdown threshold (e.g., -50%)
- Review and adjust parameters quarterly
# 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- β
Never commit
.envfile 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
- 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
- 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)
- Total Trades: Number of completed round trips
- Avg Trade Duration: Time from entry to exit
- Trade Frequency: Trades per day/week/month
Issue: ModuleNotFoundError: No module named 'vectorbt'
# Solution: Install missing dependencies
pip install -r requirements.txtIssue: binance.exceptions.BinanceAPIException: Invalid API-key
# Solution: Check .env file has correct keys
# Verify keys are active on binance.comIssue: Bot not executing trades
# Check logs for errors
cat paper_bot.log
# Verify data is updating
python data_fetcher.pyIssue: Dashboard won't load
# Install dashboard requirements
pip install -r requirements_dashboard.txt
# Run with verbose logging
streamlit run dashboard.py --logger.level=debugThis is a personal research project, but suggestions are welcome!
- 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
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.
- 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
- Issues: Open a GitHub issue
- Questions: Check documentation in
/docs - Updates: Watch this repository for improvements
- 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
- Multi-exchange support (Coinbase, Kraken)
- Portfolio mode (BTC, ETH, SOL)
- Machine learning parameter optimization
- Mobile app for iOS/Android
- Web-based dashboard (React)
- Advanced analytics (regime detection)
- Social trading features
- Automated tax reporting
- SYSTEM_SUMMARY.md - Complete technical overview
- BOT_GUIDE.md - How to run trading bots
- CRITICAL_WARNINGS.md - Must-read before trading
- PAPER_TRADING_CHECKLIST.md - Pre-flight checklist
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
- Ran 500 randomized simulations
- Monte Carlo shows path-dependent risk
- Important: Backtest β guaranteed future returns
- Paper trading tracker ready
- Signal generator implemented
- Deployment checklist created
-
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
-
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
-
Time underwater is VERY high (98%)
- You will be in drawdown almost constantly
- Patience and discipline are essential
-
Monte Carlo reveals path risk
- Shuffling trade order changes outcomes significantly
- Don't expect backtest returns in live trading
results/backtest_results.csv- Full backtest dataresults/backtest_optimized.csv- Optimized params backtestresults/regime_analysis.csv- Regime breakdownresults/robustness_results.csv- All parameter combinationsresults/plots/equity_curve.png- Equity chartresults/plots/trade_analysis.png- Trade statisticsresults/plots/robustness_heatmaps.png- Parameter sensitivityresults/plots/monte_carlo_optimized.png- MC distribution
- Review the robustness heatmaps to understand parameter sensitivity
- Run forward_test.py to start paper trading
- Paper trade for 3-6 months before real deployment
- Start with 10-20% of intended capital when going live
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.
python forward_test.pypython regime_analysis.pypython survivability.pypython monte_carlo.py