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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# XAUUSD ML Trading System πͺπ
|
| 2 |
+
|
| 3 |
+
A comprehensive ML-based Gold (XAUUSD) trading system implementing 5 institutional-grade strategies with online learning, Walk-Forward Optimization (WFO) backtesting, and Probability of Best Fit analysis.
|
| 4 |
+
|
| 5 |
+
## β οΈ Disclaimer
|
| 6 |
+
|
| 7 |
+
**This is an educational/research project. This is NOT financial advice. Trading Gold (XAUUSD) involves substantial risk of loss. Past performance (including backtests) is NOT indicative of future results. Never trade with money you can't afford to lose.**
|
| 8 |
+
|
| 9 |
+
---
|
| 10 |
+
|
| 11 |
+
## ποΈ Architecture
|
| 12 |
+
|
| 13 |
+
```
|
| 14 |
+
xauusd_trader/
|
| 15 |
+
βββ data_loader.py # XAUUSD data loading (yfinance + synthetic)
|
| 16 |
+
βββ main.py # Main orchestrator - ties everything together
|
| 17 |
+
βββ strategies/
|
| 18 |
+
β βββ smc_strategy.py # Strategy 1: Smart Money Concepts (Order Blocks, BOS, FVG)
|
| 19 |
+
β βββ ict_power_of_3.py # Strategy 2: ICT Power of 3 (AMD phases)
|
| 20 |
+
β βββ momentum_strategy.py # Strategy 3: RSI Divergence & Stochastics
|
| 21 |
+
β βββ sentiment_strategy.py # Strategy 4: Fundamental/Sentiment Alignment
|
| 22 |
+
β βββ risk_management.py # Strategy 5: Volatility-aware Risk Management
|
| 23 |
+
βββ ml/
|
| 24 |
+
β βββ ensemble_model.py # XGBoost ensemble with online learning & drift detection
|
| 25 |
+
βββ backtesting/
|
| 26 |
+
βββ wfo_engine.py # Walk-Forward Optimization backtesting
|
| 27 |
+
βββ probability_best_fit.py # Distribution fitting & strategy selection
|
| 28 |
+
```
|
| 29 |
+
|
| 30 |
+
## π 5 Trading Strategies
|
| 31 |
+
|
| 32 |
+
### 1. Smart Money Concepts (SMC) - Order Block Tap Entry
|
| 33 |
+
The most profitable strategy in our analysis. Detects institutional footprints:
|
| 34 |
+
- **Break of Structure (BOS)**: Identifies when price breaks key swing highs/lows
|
| 35 |
+
- **Order Blocks**: Last opposing candle before a displacement that broke structure
|
| 36 |
+
- **Liquidity Sweeps**: Wick-through of swing points (stop hunts)
|
| 37 |
+
- **Fair Value Gaps (FVG)**: Imbalance zones in 3-candle patterns
|
| 38 |
+
- **50% Equilibrium Entry**: Limit orders at OB midpoint with tight stops behind the wick
|
| 39 |
+
|
| 40 |
+
### 2. ICT Power of 3 (AMD)
|
| 41 |
+
Session-based institutional movement detection:
|
| 42 |
+
- **Accumulation (Asian session)**: Tight consolidation range detection
|
| 43 |
+
- **Manipulation (London open)**: False breakout / liquidity sweep identification
|
| 44 |
+
- **Distribution (NY session)**: True directional move after manipulation
|
| 45 |
+
- Entry only during Distribution phase after Manipulation confirmation
|
| 46 |
+
|
| 47 |
+
### 3. RSI Divergence & Stochastics
|
| 48 |
+
Momentum oscillator confluence:
|
| 49 |
+
- **Standard RSI Divergence**: Price/RSI divergence for reversal signals
|
| 50 |
+
- **Hidden RSI Divergence**: Trend continuation signals
|
| 51 |
+
- **Stochastic Crossovers**: Precise timing in trending markets
|
| 52 |
+
- **Moving Average Alignment**: EMA 9/21/50/100/200 crossover confirmation
|
| 53 |
+
- **Bollinger Bands + MACD**: Additional confluence factors
|
| 54 |
+
|
| 55 |
+
### 4. Fundamental/Sentiment Alignment
|
| 56 |
+
Macro-driven directional bias:
|
| 57 |
+
- **Risk-On/Risk-Off Score**: Composite of VIX, DXY, SPY, TLT
|
| 58 |
+
- **Dollar Index (DXY)** inverse correlation
|
| 59 |
+
- **VIX Fear Gauge** positive correlation during crises
|
| 60 |
+
- **Bond Yields** inverse correlation proxy
|
| 61 |
+
- Falls back to price-action derived sentiment when macro data unavailable
|
| 62 |
+
|
| 63 |
+
### 5. Strict Risk Management
|
| 64 |
+
Gold-specific volatility protection:
|
| 65 |
+
- **ATR-based Dynamic Stops**: Min/max stop distance in ATR multiples
|
| 66 |
+
- **Volatility-adjusted Position Sizing**: Smaller positions in high-vol regimes
|
| 67 |
+
- **Drawdown-based Risk Scaling**: Progressive reduction at 1%/2%/3%/5% DD levels
|
| 68 |
+
- **Session-aware Risk**: Lower exposure during Asian session and off-hours
|
| 69 |
+
- **Daily Loss Limit**: 3% daily cap, 10% total DD halt
|
| 70 |
+
- **Guaranteed Stop Logic**: Buffer for gap protection
|
| 71 |
+
|
| 72 |
+
## π€ ML Engine
|
| 73 |
+
|
| 74 |
+
### XGBoost Ensemble with Online Learning
|
| 75 |
+
- **3-model ensemble** with diverse random seeds and subsampling
|
| 76 |
+
- **86 features** across all 5 strategy groups
|
| 77 |
+
- **Hedge algorithm** for dynamic model weighting based on recent performance
|
| 78 |
+
- **ADWIN drift detection** for market regime changes
|
| 79 |
+
- **Incremental warm-start retraining** after every N closed trades
|
| 80 |
+
- **RobustScaler** preprocessing for outlier resilience
|
| 81 |
+
|
| 82 |
+
### Feature Groups (86 total)
|
| 83 |
+
| Group | Features | Key Indicators |
|
| 84 |
+
|-------|----------|---------------|
|
| 85 |
+
| SMC | 16 | BOS, OB strength, FVG, liquidity sweeps, structure code |
|
| 86 |
+
| AMD | 14 | Accumulation tightness, manipulation direction/strength, distribution |
|
| 87 |
+
| Momentum | 31 | RSI (7/14/21), Stochastics, MACD, BBands, EMA crossovers, divergences |
|
| 88 |
+
| Sentiment | 5 | Risk sentiment score, trend, regime code |
|
| 89 |
+
| Volatility | 11 | HV, Parkinson, Yang-Zhang, vol ratio, gap detection |
|
| 90 |
+
| Price Action | 8 | Returns, candle body/wicks, ATR |
|
| 91 |
+
| Session | 1 | Trading session code |
|
| 92 |
+
|
| 93 |
+
## π Walk-Forward Optimization (WFO)
|
| 94 |
+
|
| 95 |
+
Rolling temporal cross-validation that prevents look-ahead bias:
|
| 96 |
+
|
| 97 |
+
```
|
| 98 |
+
Fold 0: [====TRAIN====][=TEST=]
|
| 99 |
+
Fold 1: [======TRAIN======][=TEST=]
|
| 100 |
+
Fold 2: [=========TRAIN=========][=TEST=]
|
| 101 |
+
```
|
| 102 |
+
|
| 103 |
+
### Key Metrics Tracked
|
| 104 |
+
- **WFO Efficiency** = OOS Sharpe / IS Sharpe (measures overfitting)
|
| 105 |
+
- **Sharpe Stability** = Mean(OOS Sharpe) / Std(OOS Sharpe)
|
| 106 |
+
- **% Profitable Folds**: Consistency across market conditions
|
| 107 |
+
- Per-fold: Win Rate, Profit Factor, Max Drawdown, R-multiple
|
| 108 |
+
|
| 109 |
+
## π― Probability of Best Fit
|
| 110 |
+
|
| 111 |
+
Statistical strategy selection using:
|
| 112 |
+
|
| 113 |
+
1. **Distribution Fitting**: Fits Normal, Skew-Normal, Student-t, Laplace, Logistic to each strategy's P&L series. Ranked by BIC.
|
| 114 |
+
2. **Monte Carlo Simulation**: 10,000 resampled forward paths β probability of positive P&L
|
| 115 |
+
3. **OOS Consistency**: % of WFO folds where strategy was profitable
|
| 116 |
+
4. **Sharpe Stability**: Risk-adjusted return consistency
|
| 117 |
+
5. **Hedge Ensemble Weights**: Distribution-free exponential weighting that provably converges to best strategy
|
| 118 |
+
|
| 119 |
+
### Composite Score
|
| 120 |
+
```
|
| 121 |
+
Score = 0.25 Γ Normalized_Expected_Return
|
| 122 |
+
+ 0.25 Γ Pct_Positive_Folds
|
| 123 |
+
+ 0.25 Γ Sharpe_Stability
|
| 124 |
+
+ 0.25 Γ MC_Probability
|
| 125 |
+
```
|
| 126 |
+
|
| 127 |
+
## π Quick Start
|
| 128 |
+
|
| 129 |
+
### Installation
|
| 130 |
+
```bash
|
| 131 |
+
pip install numpy pandas scikit-learn xgboost scipy yfinance river joblib
|
| 132 |
+
```
|
| 133 |
+
|
| 134 |
+
### Run Full Pipeline
|
| 135 |
+
```python
|
| 136 |
+
from xauusd_trader.main import XAUUSDTradingSystem, ModelConfig, BacktestConfig
|
| 137 |
+
from xauusd_trader.strategies.risk_management import RiskConfig
|
| 138 |
+
|
| 139 |
+
system = XAUUSDTradingSystem(
|
| 140 |
+
model_config=ModelConfig(
|
| 141 |
+
n_estimators=300,
|
| 142 |
+
max_depth=6,
|
| 143 |
+
learning_rate=0.08,
|
| 144 |
+
n_models=3,
|
| 145 |
+
online_batch_size=30,
|
| 146 |
+
),
|
| 147 |
+
risk_config=RiskConfig(
|
| 148 |
+
initial_capital=100000.0,
|
| 149 |
+
max_risk_per_trade=0.01, # 1% risk per trade
|
| 150 |
+
max_daily_loss_pct=0.03, # 3% daily loss limit
|
| 151 |
+
max_total_drawdown_pct=0.10, # 10% total DD halt
|
| 152 |
+
),
|
| 153 |
+
backtest_config=BacktestConfig(
|
| 154 |
+
n_folds=5,
|
| 155 |
+
forward_bars=10,
|
| 156 |
+
min_confidence=0.35,
|
| 157 |
+
),
|
| 158 |
+
)
|
| 159 |
+
|
| 160 |
+
# Run everything: load data β features β train β WFO β Best Fit β Online trading
|
| 161 |
+
results = system.full_pipeline(use_real_data=True)
|
| 162 |
+
```
|
| 163 |
+
|
| 164 |
+
### Use Individual Components
|
| 165 |
+
```python
|
| 166 |
+
# Just run SMC analysis
|
| 167 |
+
from xauusd_trader.data_loader import load_xauusd, add_atr
|
| 168 |
+
from xauusd_trader.strategies.smc_strategy import compute_smc_features
|
| 169 |
+
|
| 170 |
+
df = load_xauusd(period="1y", interval="1h")
|
| 171 |
+
df = add_atr(df)
|
| 172 |
+
df = compute_smc_features(df)
|
| 173 |
+
|
| 174 |
+
# See Order Block signals
|
| 175 |
+
signals = df[df['smc_signal'] != 0]
|
| 176 |
+
print(signals[['close', 'smc_signal', 'smc_entry', 'smc_sl', 'smc_tp', 'smc_confidence']])
|
| 177 |
+
```
|
| 178 |
+
|
| 179 |
+
## π Sample Backtest Results
|
| 180 |
+
|
| 181 |
+
Results from 5000-bar test (your results will vary with real data):
|
| 182 |
+
|
| 183 |
+
```
|
| 184 |
+
WFO BACKTEST (3 folds, all profitable):
|
| 185 |
+
Total OOS Trades: 1260
|
| 186 |
+
Win Rate: 52.2%
|
| 187 |
+
Profit Factor: 2.09
|
| 188 |
+
Sharpe Ratio: 5.34
|
| 189 |
+
WFO Efficiency: 0.54
|
| 190 |
+
Sharpe Stability: 3.07
|
| 191 |
+
|
| 192 |
+
STRATEGY RANKING (Probability of Best Fit):
|
| 193 |
+
1. SMC_OrderBlock Score=0.823 WinRate=81.8% Sharpe=18.2 BestFit=Laplace
|
| 194 |
+
2. ML_Ensemble Score=0.782 WinRate=52.2% Sharpe=5.36 BestFit=Normal
|
| 195 |
+
3. Momentum Score=0.490 WinRate=27.1% Sharpe=0.37 BestFit=Student-t
|
| 196 |
+
|
| 197 |
+
ONLINE TRADING (with learning):
|
| 198 |
+
Trades: 1621, WinRate: 51.3%, PF: 2.03, Sharpe: 4.98
|
| 199 |
+
Drift events detected: 2, Model adapted successfully
|
| 200 |
+
```
|
| 201 |
+
|
| 202 |
+
## π§ Configuration
|
| 203 |
+
|
| 204 |
+
### Model Hyperparameters
|
| 205 |
+
| Parameter | Default | Description |
|
| 206 |
+
|-----------|---------|-------------|
|
| 207 |
+
| `n_estimators` | 300 | XGBoost trees per model |
|
| 208 |
+
| `max_depth` | 6 | Max tree depth |
|
| 209 |
+
| `learning_rate` | 0.08 | Boosting learning rate |
|
| 210 |
+
| `n_models` | 3 | Ensemble size |
|
| 211 |
+
| `online_batch_size` | 50 | Trades before incremental retrain |
|
| 212 |
+
| `online_boost_rounds` | 10 | Boost rounds per online update |
|
| 213 |
+
|
| 214 |
+
### Risk Parameters
|
| 215 |
+
| Parameter | Default | Description |
|
| 216 |
+
|-----------|---------|-------------|
|
| 217 |
+
| `max_risk_per_trade` | 1% | Max capital risk per trade |
|
| 218 |
+
| `max_daily_loss_pct` | 3% | Daily loss limit |
|
| 219 |
+
| `max_total_drawdown_pct` | 10% | Total DD halt threshold |
|
| 220 |
+
| `min_sl_atr_mult` | 0.5Γ ATR | Minimum stop loss distance |
|
| 221 |
+
| `max_sl_atr_mult` | 3.0Γ ATR | Maximum stop loss distance |
|
| 222 |
+
|
| 223 |
+
## π References
|
| 224 |
+
|
| 225 |
+
- Smart Money Concepts (SMC) / Inner Circle Trader (ICT) methodology
|
| 226 |
+
- [Neural Network-Based Algorithmic Trading Systems](https://arxiv.org/abs/2508.02356)
|
| 227 |
+
- [Orchestration Framework for Financial Agents](https://arxiv.org/abs/2512.02227) - XGBoost + Rolling WFO
|
| 228 |
+
- [Ensembling Portfolio Strategies](https://arxiv.org/abs/2406.03652) - Universal Covers / Hedge algorithm
|
| 229 |
+
- [River: ML for Streaming Data](https://arxiv.org/abs/2012.04740) - Online learning framework
|
| 230 |
+
- [QTMRL](https://arxiv.org/abs/2508.20467) - RL for trading with technical indicators
|
| 231 |
+
|
| 232 |
+
## License
|
| 233 |
+
|
| 234 |
+
MIT License - See LICENSE file for details.
|