Automated trading bot for Gold (XAUUSD) and Crypto (BTC/ETH) using a two-candle pattern strategy with adaptive sizing, grid recovery, and comprehensive risk management.
- Features
- Strategy Overview
- Quick Start
- Installation
- Strategy Configuration
- Optimizer Tool
- Project Structure
- Performance Metrics
- Best Practices
- Troubleshooting
- Roadmap
- ๐ Two-Candle Pattern Recognition - Detects small setup candle followed by big trigger candle
- ๐ Adaptive Candle Sizing - ATR-based OR percentile-based dynamic thresholds
- ๐ Trend Filter - EMA/SMA-based trend confirmation
- โฐ Time Filter - Trade only during optimal hours (5 AM - 12 PM default)
- ๐ฐ Flexible TP/SL - ATR-based (dynamic) or fixed points (static)
- ๐ฏ Position Stop Loss - Static or trailing per-position stops
- ๐ Equity Protection - Hard drawdown limits and trailing equity stops
- ๐ Position Sizing - Validates positions against account equity limits
- ๐ Spread Filter - Avoids trades during high-spread conditions
- ๐ ATR-Based Spacing - Dynamic grid level placement
- ๐ Lot Multiplier - Progressive position sizing for recovery
- ๐ฏ Basket Management - Shared TP/SL for grid positions
- ๐ฆ Max Positions Limit - Prevents over-exposure
- ๐ Profitability Testing - Find most profitable TP/SL ratios
- ๐ฒ Candle Size Optimization - Test hundreds of threshold combinations
- ๐ Performance Metrics - Win rate, profit factor, drawdown, Sharpe ratio
- ๐ Time Filter Testing - Match your strategy's trading hours
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ Bar -2 (Setup) Bar -1 (Trigger) Bar 0 (Entry) โ
โ โ
โ ๐ข Small ๐ข๐ข Big โฌ๏ธ BUY โ
โ Candle Candle โ
โ โ
โ Setup: Range โค Small Threshold (20th percentile) โ
โ Trigger: Range โฅ Big Threshold (90th percentile) โ
โ Direction: Bullish setup + trend up = BUY โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
ATR Method (Dynamic - Updates Every Bar)
Small Candle = 0.8 ร ATR(14)
Big Candle = 1.1 ร ATR(14)Percentile Method (Rolling Window - Updates Every 100 Bars)
Small Candle = 20th percentile of last 200 candles
Big Candle = 90th percentile of last 200 candlesgraph TD
A[New Bar] --> B{Pattern Detected?}
B -->|No| A
B -->|Yes| C{Time Filter?}
C -->|Failed| A
C -->|Passed| D{Spread OK?}
D -->|No| A
D -->|Yes| E{Trend Filter?}
E -->|Failed| A
E -->|Passed| F[OPEN POSITION]
# Set your API key (one time)
export POLYGON_API_KEY="your_api_key_here"
# Run a single backtest on Gold (IMPORTANT: Use C:XAUUSD for forex)
python backtest_runner.py \
--ticker C:XAUUSD \
--start-date 2024-09-01 \
--end-date 2024-09-15 \
--timeframe 1 \
--timespan minute \
--initial-cash 10000
# Test configuration consistency across multiple 2-week periods
./test_multiple_periods.sh
# Run batch tests with different configurations
python backtest_runner.py --batch-test
# Test specific configuration
python backtest_runner.py \
--ticker C:XAUUSD \
--enable-counter-trend \
--tp-atr-mult 3.5 \
--sl-atr-mult 0.3 \
--run-name "Counter-Trend Test"Note: Always use C:XAUUSD (not X:XAUUSD) for gold forex data. The C: prefix is required by Polygon.io for forex pairs.
import backtrader as bt
from ken_gold_candle import GoldCandleKenStrategy, run_backtest
# Load your data
data = bt.feeds.GenericCSVData(
dataname='xauusd_1min.csv',
dtformat='%Y-%m-%d %H:%M:%S',
timeframe=bt.TimeFrame.Minutes
)
# Run backtest
results = run_backtest(data)# Find most profitable TP/SL ratios (using uv)
uv run strategy_optimizer.py \
--api-key YOUR_POLYGON_API_KEY \
--symbol XAUUSD \
--asset-class forex \
--start 2025-05-01 \
--end 2025-09-30 \
--start-hour 5 \
--end-hour 12 \
--optimize-tp-sl
# Or using python
python strategy_optimizer.py \
--api-key YOUR_POLYGON_API_KEY \
--symbol XAUUSD \
--asset-class forex \
--start 2025-05-01 \
--end 2025-09-30 \
--start-hour 5 \
--end-hour 12 \
--optimize-tp-slEdit ken_gold_candle.py:
# From optimizer output
USE_ATR_TP_SL = True
TP_ATR_MULTIPLIER = 3.0 # Best from optimization
SL_ATR_MULTIPLIER = 2.0 # Best from optimization- Python 3.8+
- Polygon.io API Key (Get Free Key)
uv is a blazingly fast Python package installer and resolver:
# Install uv (Mac/Linux)
curl -LsSf https://astral.sh/uv/install.sh | sh
# Install uv (Windows)
powershell -c "irm https://astral.sh/uv/install.ps1 | iex"
# Or install via pip
pip install uv# Using uv (recommended - much faster)
uv pip install -e .
# Or using traditional pip
pip install -r requirements.txt- Sign up at Polygon.io
- Free tier: 5 API calls/min (sufficient for testing)
- Basic plan: $29/month (recommended for extensive optimization)
# Account Configuration
LOT_SIZE = 0.01 # Minimum position size
CONTRACT_SIZE = 100 # XAUUSD: 1 lot = 100 oz
MAX_POSITION_SIZE_PERCENT = 100.0 # Max % of equity per position
# Pattern Detection (Choose ONE)
USE_ATR_CALCULATION = True # โ
Dynamic (ATR-based)
USE_PERCENTILE_CALCULATION = False # โ Rolling window (percentile)
ATR_SMALL_MULTIPLIER = 0.8 # Small = 0.8x ATR
ATR_BIG_MULTIPLIER = 1.1 # Big = 1.1x ATR
# Take Profit / Stop Loss (Choose ONE)
USE_ATR_TP_SL = False # โ Use fixed points
TP_ATR_MULTIPLIER = 3.0 # TP = 3.0x ATR (if enabled)
SL_ATR_MULTIPLIER = 2.0 # SL = 2.0x ATR (if enabled)
TAKE_PROFIT_POINTS = 150 # Fixed TP in points
POSITION_SL_POINTS = 50 # Fixed SL in points# Position Stop Loss (Choose ONE)
ENABLE_POSITION_SL = False # โ Static SL per position
ENABLE_TRAILING_POSITION_SL = True # โ
Trailing SL (locks in profits)
TRAILING_POSITION_SL_POINTS = 50 # Trail distance
# Account Protection (Choose ONE)
ENABLE_EQUITY_STOP = False # โ Hard drawdown limit
ENABLE_TRAILING_EQUITY_STOP = False # โ Trailing equity protection
MAX_DRAWDOWN_PERCENT = 1.0 # Max account drawdown %ENABLE_GRID = False # โ Grid disabled by default
ATR_MULTIPLIER_STEP = 3.5 # Grid spacing (3.5x ATR)
LOT_MULTIPLIER = 1.05 # Position size multiplier
MAX_OPEN_TRADES = 2 # Limit grid depth
GRID_PROFIT_POINTS = 150 # Basket TP# Trend Filter
ENABLE_TREND_FILTER = True # โ
Use MA for trend
MA_PERIOD = 100
MA_METHOD = 1 # 1=EMA, 0=SMA
# Time Filter
ENABLE_TIME_FILTER = True # โ
Trade 5 AM - 12 PM
START_HOUR = 5
END_HOUR = 12
# Spread Filter
MAX_SPREAD_POINTS = 20 # Reject high spread entriesThe backtest_runner.py script provides automated backtesting with comprehensive performance metrics.
- ๐ Automated Data Fetching - Downloads historical data from Polygon.io
- ๐ Comprehensive Metrics - Sharpe ratio, drawdown, win rate, profit factor, SQN, VWR
- ๐ Batch Testing - Test multiple configurations in one run
- ๐พ JSON Output - Save results for later analysis
- ๐ฏ Strategy Overrides - Test different parameters without editing code
# Set API key (one time)
export POLYGON_API_KEY="your_key_here"
# Run backtest on Gold (last 1 year, hourly data)
uv run backtest_runner.py
# Or without uv
python backtest_runner.pyuv run backtest_runner.py \
--ticker X:XAUUSD \
--start-date 2024-01-01 \
--end-date 2024-12-31 \
--timeframe 1 \
--timespan hour \
--initial-cash 10000# Test 8 different configurations automatically
uv run backtest_runner.py --batch-test
# Output includes comparison table:
# Run Name Return % Sharpe DD % Win % PF
# Default Strategy 5.23% 1.45 -8.50% 42.50% 1.32
# Grid Enabled 8.91% 1.67 -12.30% 38.20% 1.45
# Counter-Trend Fade 3.12% 0.98 -6.20% 48.10% 1.18uv run backtest_runner.py \
--run-name "Aggressive Setup" \
--enable-counter-trend \
--tp-atr-mult 4.0 \
--sl-atr-mult 0.5 \
--lot-size 0.05Each backtest provides:
๐ PORTFOLIO PERFORMANCE
Starting Value: $10,000.00
Ending Value: $10,523.45
Total Return: $523.45
Return %: 5.23%
๐ PERFORMANCE METRICS
Sharpe Ratio: 1.45
Max Drawdown: 8.50% ($850.00)
Avg Daily Return: 0.0023
SQN: 1.89
VWR: 85.3%
๐ฏ TRADE STATISTICS
Total Trades: 156
Won: 68 (43.59%)
Lost: 88
Win Streak: 7
Loss Streak: 5
Avg Duration: 12.3 bars
๐ฐ PROFIT & LOSS
Net P&L: $523.45
Avg Trade: $3.35
Profit Factor: 1.32
Avg Win: $15.67
Avg Loss: -$8.45
Largest Win: $89.23
Largest Loss: -$45.12
| Flag | Description | Default |
|---|---|---|
--api-key |
Polygon.io API key | $POLYGON_API_KEY |
--ticker |
Symbol to backtest | X:XAUUSD |
--start-date |
Start date (YYYY-MM-DD) | 1 year ago |
--end-date |
End date (YYYY-MM-DD) | Today |
--timeframe |
Timeframe multiplier | 1 |
--timespan |
Timespan (minute/hour/day) | hour |
--initial-cash |
Starting capital | 10000.0 |
--output |
Results JSON file | backtest_results.json |
--batch-test |
Run multiple configs | False |
--enable-grid |
Enable grid trading | False |
--enable-counter-trend |
Enable fade strategy | False |
--lot-size |
Override lot size | Strategy default |
--tp-atr-mult |
Override TP multiplier | Strategy default |
--sl-atr-mult |
Override SL multiplier | Strategy default |
| Feature | Description |
|---|---|
| ๐ Signal Count Analysis | Test percentile/ATR combinations for signal frequency |
| ๐ฐ TP/SL Optimization | Find most profitable take profit and stop loss levels |
| ๐ฏ Candle Size Testing | Identify which thresholds generate highest profits |
| ๐ Performance Metrics | Win rate, profit factor, drawdown, Sharpe ratio |
| โฐ Time Filter Support | Match your strategy's trading hours |
uv run strategy_optimizer.py \
--api-key YOUR_KEY \
--symbol XAUUSD \
--asset-class forex \
--start 2025-09-01 \
--end 2025-09-30 \
--start-hour 5 \
--end-hour 12uv run strategy_optimizer.py \
--api-key YOUR_KEY \
--symbol XAUUSD \
--asset-class forex \
--start 2025-09-01 \
--end 2025-09-30 \
--start-hour 5 \
--end-hour 12 \
--optimize-tp-slOutput:
๐ BEST TP/SL CONFIG:
TP: 3.0x ATR
SL: 2.0x ATR
Risk:Reward: 1.5
Total P&L: $278.74
Win Rate: 42.06%
Profit Factor: 1.15
uv run strategy_optimizer.py \
--api-key YOUR_KEY \
--symbol XAUUSD \
--asset-class forex \
--start 2025-09-01 \
--end 2025-09-30 \
--start-hour 5 \
--end-hour 12 \
--optimize-candle-profitabilityuv run strategy_optimizer.py \
--api-key YOUR_KEY \
--symbol XAUUSD \
--asset-class forex \
--start 2025-09-01 \
--end 2025-09-30 \
--start-hour 5 \
--end-hour 12 \
--optimize-all \
--output results.json| Flag | Description | Example |
|---|---|---|
--api-key |
Polygon.io API key (required) | YOUR_KEY |
--symbol |
Trading symbol | XAUUSD, BTCUSD |
--asset-class |
Asset type | forex, crypto |
--start |
Start date (YYYY-MM-DD) | 2025-09-01 |
--end |
End date (YYYY-MM-DD) | 2025-09-30 |
--start-hour |
Trading start hour (0-23) | 5 |
--end-hour |
Trading end hour (0-23) | 12 |
--optimize-tp-sl |
Optimize TP/SL ratios | - |
--optimize-candle-profitability |
Find best candle sizes | - |
--optimize-all |
Run all optimizations | - |
--use-atr-method |
Use ATR-based detection | - |
--output |
Output file name | results.json |
ken_gold_candle/
โโโ ๐ README.md # This file
โโโ ๐ CLAUDE.md # Claude Code guidance
โโโ ๐ OPTIMIZER_README.md # Detailed optimizer docs
โโโ ๐ requirements.txt # Python dependencies
โ
โโโ ๐ ken_gold_candle.py # Main strategy implementation
โ โโโ GoldCandleKenStrategy # Strategy class
โ โโโ run_backtest() # Convenience runner
โ
โโโ ๐งช backtest_runner.py # Automated backtesting with Polygon API
โ โโโ PolygonDataFetcher # Historical data fetcher
โ โโโ BacktestRunner # Comprehensive metrics engine
โ
โโโ ๐ฌ strategy_optimizer.py # Parameter optimization tool
โ โโโ PolygonDataDownloader # Historical data fetcher
โ โโโ StrategyAnalyzer # Optimization engine
โ
โโโ ๐ optimization_results.json # Pre-run XAUUSD results
| File | Purpose |
|---|---|
ken_gold_candle.py |
Backtrader strategy with all trading logic |
backtest_runner.py |
NEW Automated backtesting with detailed metrics |
strategy_optimizer.py |
Historical analysis and parameter tuning |
optimization_results.json |
Example results (XAUUSD May-Sept 2025) |
requirements.txt |
Python package dependencies |
OPTIMIZER_README.md |
Complete optimizer documentation |
CLAUDE.md |
Development guidelines for AI assistants |
| Metric | Description | Good Range |
|---|---|---|
| Win Rate | % of winning trades | 40-60% (with 2:1 R:R) |
| Profit Factor | Gross profit รท Gross loss | > 1.5 |
| Max Drawdown | Largest equity decline | < 30% of total P&L |
| Sharpe Ratio | Risk-adjusted returns | > 1.0 |
| Expectancy | Avg P&L per trade | Positive |
From optimization_results.json (May-Sept 2025):
๐ Best Configuration:
TP: 3.0x ATR | SL: 2.0x ATR
Total P&L: $278.74
Trades: 1,367
Win Rate: 42.06%
Profit Factor: 1.15
Max Drawdown: $84.38
- โ
Always use time filter - Match optimizer to strategy hours (
--start-hour 5 --end-hour 12) - โ Test multiple periods - Validate on different months/quarters
- โ Walk-forward analysis - Optimize on training period, validate on test period
- โ Demo test first - Never go live without demo account testing
- โ Use ATR-based TP/SL - Adapts to changing volatility automatically
- โ Monitor equity stops - Enable once contract multiplier is verified
- โ Over-optimize - Don't chase highest P&L on single period
- โ Skip validation - Always test on out-of-sample data
- โ Mix incompatible settings - Check mutually exclusive flags
- โ Ignore drawdown - High profit with high drawdown = risky
- โ Trade without spread filter - High spreads eat profits
1. Download Data โ 2. Run Optimizer โ 3. Analyze Results
โ โ โ
4. Validate OOS โ 5. Update Strategy โ 6. Demo Test
โ โ โ
7. Monitor Live โ 8. Re-optimize โ 9. Adjust Parameters
# Check date format
--start 2025-09-01 # โ
Correct
--start 09/01/2025 # โ Wrong
# Verify symbol format
--symbol BTCUSD # โ
Correct
--symbol BTC/USD # โ Wrong
# For Gold, use forex asset class
--symbol XAUUSD --asset-class forex # โ
CorrectRate limit hit (5 calls/min on free tier)
Solutions:
- Wait 1 minute and retry
- Use smaller date ranges
- Upgrade Polygon.io plan ($29/mo)
# Check filters aren't too restrictive
ENABLE_TREND_FILTER = False # Temporarily disable
ENABLE_TIME_FILTER = False # Temporarily disable
# Loosen candle thresholds
BIG_CANDLE_PERCENTILE = 70 # Lower threshold
SMALL_CANDLE_PERCENTILE = 30 # Raise threshold# Increase position size limit
MAX_POSITION_SIZE_PERCENT = 150.0 # From 100.0
# Or decrease lot size
LOT_SIZE = 0.005 # From 0.01The strategy includes extensive logging:
LOG_LEVEL = logging.DEBUG # Enable detailed logs
LOG_FILE = "trading.log" # Save to fileKey log messages:
POSITION SIZE VALIDATION CHECK:- Shows equity and position limitsEQUITY DIAGNOSTIC:- Shows P&L calculationsBROKER POSITION STATE:- Shows current positions
- Two-candle pattern detection
- ATR and percentile-based adaptive sizing
- Comprehensive optimizer with P&L tracking
- Grid trading support
- Multiple risk management modes
- Time filter support
- Full grid backtesting (multi-position tracking)
- Spread filter implementation (requires bid/ask data)
- Web dashboard for results visualization
- Machine learning for pattern recognition
- Multi-timeframe analysis
- Portfolio optimization across symbols
- Real-time alerting system
- TradeLocker API integration
- ๐ OPTIMIZER_README.md - Detailed optimizer documentation
- ๐ค CLAUDE.md - AI assistant development guide
- ๐ Backtrader Docs - Framework documentation
- ๐ Polygon.io API - Historical data API
MIT License - See LICENSE file for details
Contributions welcome! Please:
- Fork the repository
- Create a feature branch (
git checkout -b feature/amazing-feature) - Commit changes (
git commit -m 'Add amazing feature') - Push to branch (
git push origin feature/amazing-feature) - Open a Pull Request
This software is for educational purposes only. Trading financial instruments carries risk. Past performance does not guarantee future results. Always test on demo accounts before live trading. The authors are not responsible for any financial losses incurred using this software.
Built with โค๏ธ using Python and Backtrader