**A trend-harvesting EA built to capture momentum on Gold — and survive the months it doesn't.**
---
## The Problem with Most Gold EAs:
Most Gold EAs look great on a rising market. They pile on long trades, rack up impressive equity curves during bull runs — then bleed dry the moment Gold goes sideways or drops. When you look closer, you'll find they rely on tight stops that get clipped by Gold's wild intraday swings, or they hold trades with no stop at all and pray for recovery.
We spent months testing dozens of approaches across multiple years of XAUUSD data — trending markets, choppy ranges, and sharp corrections. We weren't looking for the most profitable system on paper. We were looking for the one that **survived every condition** while still growing the account. This EA is the result: a disciplined breakout system that enters only when the market proves it's ready to move, then trails profits with an adaptive mechanism calibrated to Gold's actual volatility.
---
## How It Works
This EA reads the **H4 timeframe internally** to identify breakout conditions, while you attach it to an **M5 chart** for precise trailing execution. You don't need to set up multiple charts or timeframes — the EA handles everything.
**Entry logic:**
The EA uses a proprietary breakout detection algorithm on the H4 chart. It monitors price structure over a configurable lookback window, waiting for price to convincingly break beyond a defined boundary. Multiple independent confirmations must align before any trade is taken — a single condition alone is never enough.
**Both directions:** The EA trades both long and short. It doesn't assume Gold will always go up. When the market breaks down, it sells. When it breaks up, it buys.
**Exit management:**
Every trade is born with a fixed Stop Loss calibrated to the market's current volatility — not an arbitrary pip count. Once the trade moves in your favor, an **adaptive trailing mechanism** kicks in: it follows price at a distance proportional to volatility, tightening as profits grow. This lets winners breathe during strong moves while protecting gains when momentum fades. A wide Take Profit acts as a safety ceiling, but in practice, most profitable trades are closed by the trailing system.
**One position at a time.** No grid, no averaging, no pyramiding. You always know your exact exposure.
---
## Backtest Performance
[See Screenshot 1: Equity Curve]
Starting with $10,000 and risking just 0.5% per trade, the EA grew the account to **$32,066** (+221%) over 2.7 years of XAUUSD data with a maximum drawdown of only **9.7%**.
**Key Numbers:**
| Metric | Value |
|---------------------|--------------------------------|
| Backtest Period | Oct 2023 -- Jun 2026 (2.7 yrs) |
| Total Trades | 204 (~76/year, ~6/month) |
| Profit Factor | **2.18** |
| Win Rate | 53.4% |
| Avg Reward/Risk | **+0.27R** per trade |
| Avg Win / Avg Loss | $374 / $-197 (1.9 : 1 ratio) |
| Best Trade | +4.0R |
| Worst Trade | -1.0R (SL always respected) |
| Max Drawdown | 9.7% |
| Max Consecutive Losses| 6 |
**Winners are nearly 2x larger than losers on average.** Combined with a 53% win rate, this creates a strong positive expectancy on every single trade.
[See Screenshot 2: Yearly Performance]
**Year-by-year results:**
| Year | Trades | Avg R/Trade | PF | Result |
|------|--------|-------------|------|----------------|
| 2023 | 19 | -0.02R | 0.86 | Breakeven (partial year, only 3 months) |
| 2024 | 66 | +0.08R | 1.65 | Profitable |
| 2025 | 76 | +0.23R | 1.96 | Profitable |
| 2026 | 43 | +0.76R | 2.81 | Profitable |
Three out of four years profitable. The 2023 result covers only October--December (a partial year with 19 trades) and was essentially flat — not a real loss year.
[See Screenshot 3: Monthly Heatmap]
The monthly pattern is classic trend-following: many small flat or mildly negative months, punctuated by strong green months that drive overall profitability. **76% of all months were profitable** (25 out of 33).
[See Screenshot 4: Trade Analysis]
The return distribution confirms healthy positive skew — losses are consistently capped at -1R (by the fixed Stop Loss), while winners extend to +4R thanks to the trailing system. No outlier losses, no blow-ups.
---
## Cost Sensitivity
[See Screenshot 5: Cost Sensitivity]
We tested the EA across spread levels from $0.50 to $5.00 per trade. **Profit Factor stays above 1.9 at every level tested**, confirming the edge is robust and not dependent on ultra-low execution costs.
| Spread/Trade | Profit Factor | End Equity |
|-------------|---------------|-------------|
| $0.50 | 2.29 | $33,195 |
| $1.50 | 2.18 | $32,066 |
| $3.00 | 2.03 | $30,353 |
| $5.00 | 1.91 | $28,694 |
Even on a Standard account with wide spreads, the EA remains clearly profitable.
---
## Capital and Risk Recommendations
**Minimum capital by account type:**
| Account Type | Minimum | Comfortable |
|-------------|-----------|-------------|
| Standard | $5,000 | $10,000+ |
| Mini | $500 | $1,000+ |
| Micro | $100 | $200+ |
**Risk levels and expected drawdown:**
| Risk per Trade | Expected Max DD | Growth Rate | Recommendation |
|---------------|----------------|-------------|---------------------|
| 0.25% | ~5% | Slow | Conservative |
| 0.50% | ~10% | Moderate | **Recommended** |
| 1.00% | ~20% | Fast | Experienced traders |
| >1.50% | >30% | Very fast | Not recommended |
The EA includes **built-in position sizing** — it automatically calculates the correct lot size based on your chosen risk percentage and current equity. No manual lot calculation needed. You can also set a fixed lot size if you prefer full control.
**Advanced: Kelly Criterion sizing** is available as an optional module. After 30 closed trades, the EA can automatically calculate the mathematically optimal risk percentage based on its own live performance history. This is disabled by default — enable it only if you understand Kelly sizing.
---
## Account Type Recommendations
**Best: ECN / Raw Spread / Pro accounts**
Lowest total trading cost. This is the account type used in our backtest ($1.50 spread). Commission-based accounts with tight spreads give the best results.
**Acceptable: Standard / Classic accounts**
Higher spreads but no commission. The EA remains profitable with spreads up to $5.00 per trade (see Cost Sensitivity above). Make sure your broker's typical Gold spread is under 400 points ($4.00) during active hours.
**Avoid:** Fixed-spread brokers with Gold spreads above 500 points ($5.00), or brokers with frequent requotes and poor execution on Gold.
---
## Safety Features
Every feature below is designed to protect your capital:
- **Every trade has a Stop Loss from the moment it opens** — calculated from real market volatility, not an arbitrary number. No exceptions, no "virtual SL", no hidden risk.
- **No martingale, no grid, no averaging down — ever.** The EA does not increase lot size after losses. Each trade is independent.
- **One position at a time.** You always know exactly how much is at risk. No hidden exposure from multiple open trades.
- **Cooldown between trades.** After a trade closes, the EA waits before taking the next signal — preventing revenge trading during choppy conditions.
- **Spread filter.** If the spread is abnormally wide (news events, low liquidity), the EA skips the signal entirely. Better to miss a trade than enter at a bad price.
- **Friday cutoff.** No new trades are opened Friday evening, avoiding weekend gap risk on new positions.
- **Crash-safe state recovery.** If your VPS reboots or MT5 restarts, the EA recovers its exact state — trailing distance, entry volatility, everything — without missing a beat. Uses GlobalVariables that survive terminal restarts.
- **No DLL, no external connections.** The EA runs entirely on your terminal. It doesn't send your data anywhere and doesn't depend on any external service.
- **Full MQL5 Market compliance.** Pre-trade margin check, volume validation, stops level and freeze level respect, and proper error logging. Passes all Market review requirements.
---
## What to Expect (Honest Talk)
This is a **trend-following breakout system.** Here's what that means in practice:
- **Most months will be small.** You'll see months with $100--$300 profit on a $10,000 account at 0.5% risk. That's normal.
- **A few months will be large.** When Gold catches a strong trend, the trailing system rides it. Single months of +$1,000 to +$5,000 are not uncommon — and that's where most of the annual profit comes from.
- **You will have losing months.** Roughly 1 in 4 months will be negative. Maximum observed monthly loss was about $700 on a $10,000 account. If you can't tolerate occasional red months, trend-following is not for you.
- **The EA will sit idle during ranging markets.** No breakout = no trade. This is a feature, not a bug. The EA's edge is knowing when NOT to trade.
- **Win rate is 53%, not 90%.** Almost half of trades lose. The system makes money because **winners are nearly twice the size of losers**, not because it wins all the time. This is how all successful trend-following systems work.
- **The backtest covers 2023-2026** — predominantly an uptrend in Gold. Long trades contributed more than shorts during this period. In a prolonged bear market, the system would rely more heavily on short entries. We recommend backtesting with your broker's extended data (2018+) to verify performance across different regimes.
**Past performance does not guarantee future results.** We strongly recommend running the EA on a demo account for 4--8 weeks before committing real capital.
---
## Ongoing Development and Updates
- **Regular stability checks.** We re-run the full backtest suite after every update to ensure nothing is broken.
- **Backtest-to-live verification.** We compare live fills against backtest expectations to catch any divergence early.
- **Broker compatibility monitoring.** We track spread patterns and execution quality across major brokers and adjust recommendations as needed.
- **Free lifetime updates** for all buyers. Strategy refinements, new features, and compatibility fixes — all included.
- **Direct support.** Message us on MQL5 anytime with questions about setup, risk management, or broker selection. We're traders ourselves and happy to help.
---
## Quick Setup
1. Attach the EA to a **XAUUSD M5** chart (the EA reads H4 internally — you only need M5).
2. Set your risk: `Risk per trade = 0.5` (recommended) or choose your own level.
3. Leave all other parameters at default — they are already optimized.
4. Enable **Allow Algo Trading** in MT5.
5. Done. The EA will monitor H4 breakouts and manage trades automatically.
**Tip:** Use a VPS for 24/5 uptime. The EA needs to run continuously to catch all H4 bar closes. If your terminal is offline when a breakout occurs, you'll miss the trade.
---
## Key Parameters
| Parameter | Default | Description |
|---------------------|---------|-----------------------------------------------------|
| Risk per trade (%) | 0.5 | Percentage of equity risked on each trade |
| Fixed lot size | 0.0 | Set > 0 to use fixed lots instead of risk-based |
| Trailing enabled | true | Adaptive trailing stop (recommended ON) |
| Initial stop-loss | 2.5x | Stop-loss distance as multiple of volatility |
| Trailing distance | 1.5x | Trailing stop distance as multiple of volatility |
| Trail activation | 0.5x | Profit threshold before trailing activates |
| Max hold time | 72h | Auto-close trades held longer than this |
| Max spread | 250 pts | Skip signals when spread exceeds this ($2.50) |
| Friday cutoff | true | No new entries Friday after 20:00 broker time |
| Magic number | 251004 | Change if running multiple EAs on same symbol |
| Kelly enabled | false | Enable auto Kelly position sizing (advanced) |
| Enable logging | false | Turn on for debugging, keep off for normal operation |
All strategy-specific parameters (breakout lookback, volatility periods) are internal and pre-optimized. Advanced users can access them, but we recommend leaving them at default values.
---
## Screenshots
1. **Equity Curve** — Compounded equity growth with 0.5% risk per trade over 2.7 years. Starting capital $10,000 grows to $32,066 with maximum drawdown of only 9.7%. All trades include spread costs.
2. **Yearly Performance** — Year-by-year results showing profitable performance in 3 out of 4 years (2023 was a partial 3-month year at breakeven).
3. **Monthly Heatmap** — Monthly returns showing the classic trend-following pattern: many small months, occasional large winning months that drive profitability. 76% of months profitable.
4. **Trade Analysis** — Trade distribution, win rate, and key statistics. Average winner is 1.9x larger than average loser, creating consistent positive expectancy.
5. **Cost Sensitivity** — Profit Factor remains above 1.9 across all tested spread levels from $0.50 to $5.00, confirming the edge is robust and not dependent on ultra-low spreads.
---
Questions? Message us anytime. We're traders ourselves and happy to discuss strategy expectations, broker recommendations, or risk management in detail.
--------------------
# Donchian H4 XAUUSD EA v3 — Setup Guide
## Mapping Backtest Results to EA Inputs
Best configuration with trailing stop:
| Backtest Config | EA Input | Value |
|---|---|---|
| Donchian period = 25 | `InpBreakoutLen` | **25** |
| ATR period = 14 | `InpVolPeriod` | **14** |
| SL = 2.5 x ATR_H4 | `InpInitSL` | **2.5** |
| TP = 10 x ATR_H4 (wide) | `InpTPMult` | **10.0** |
| Trail activation = 0.5 x ATR_H4 | `InpTrailActivate` | **0.5** |
| Trail distance = 1.5 x ATR_H4 | `InpTrailMult` | **1.5** |
| Max hold 48-72h | `InpMaxHoldHours` | **72** |
| Trailing ON | `InpTrailEnabled` | **true** |
## Important Setup Notes
### 1. Attach EA to M5 Chart (NOT H4)
This EA:
- Calculates signals on **H4** (hard-coded `PERIOD_H4` in all indicator functions)
- Trails SL on **the chart timeframe** the EA is attached to
For the trailing stop to react as fast as in the backtest (every 5 minutes), **attach the EA to an M5 chart**. If attached to H4, trailing only updates once every 4 hours — far too slow.
### 2. Money Management Settings
Default: **Fixed Risk 0.5% per trade**, Kelly disabled.
- Increase to `InpRiskPct = 1.0` for faster growth (drawdown roughly doubles).
- Or use a fixed lot: `InpFixedLot = 0.10` for accounts of $10,000+.
- After the EA has closed **30 trades**, you can enable `InpKellyEnabled = true` — the EA will automatically calculate the Kelly percentage from its own trade history (filtered by magic number) and use it instead of `InpRiskPct`.
### 3. Spread Filter
`InpMaxSpread = 250` points = $2.50. If your broker's spread regularly exceeds 200 points, increase this to 350-400.
### 4. Magic Number
Default is `251004`. If running multiple EAs on the same symbol, each EA must have a unique magic number.
## Deployment Procedure
1. **Copy** the file `Donchian_H4_XAUUSD_EA_v3.mq5` into the `MQL5/Experts/` folder of MetaTrader 5.
2. **Compile** in MetaEditor (F7) — there should be no warnings or errors.
3. **Enable Algo Trading** in MT5 (button on the toolbar).
4. **Open a XAUUSD M5 chart**, then drag and drop the EA onto it.
5. **Configure inputs** according to the table above.
6. **Run Strategy Tester before going live**:
- Settings: XAUUSD, M5, "Every tick based on real ticks"
- Period: 01/01/2018 to present (to verify with extended data)
- Deposit: $10,000
- Leverage: 1:100 or higher
7. **Demo trade for 2-3 months** before going live.
8. **Start live with small size** (minimum lot or 0.25% risk) for 1-2 months.
## Post-Installation Checklist
- [ ] Experts tab: confirm the message `"Donchian H4 EA v3 loaded. Symbol=XAUUSD, magic=251004"` appears
- [ ] Enable `InpEnableLog = true` for one day to review logs, then disable it.
- [ ] Strategy Tester runs without errors.
- [ ] When a position is open: SL must be clearly set away from price, no broker rejection ("Invalid stops").
- [ ] When price moves favorably beyond 0.5 x ATR_H4: SL begins trailing (visible in Experts tab if logging is enabled).
- [ ] After the EA closes a trade: cooldown of 12 M5 bars (60 minutes) before opening a new position.
## Warnings
- **Spread**: The backtest uses a fixed spread of $1.50 (Pro account). If your broker has high spreads ($3+), profitability may decrease by 30-50%.
- **News**: Gold is highly sensitive to FOMC, NFP, and CPI events. The EA does not include a news filter — consider reducing risk during weeks with major economic releases.
- **Weekend gaps**: The `InpFridayCutoff` setting prevents new entries on Fridays after 20:00, but open positions are still held over the weekend. If you are concerned about large gaps, manually close positions before the weekend.
- **Backtest data (2023-2026)** covers a predominantly bullish market — Long trades outperformed Shorts. Run the Strategy Tester with data from 2018-2026 to verify that Short trades also perform well.
## Performance Expectations
With default settings (0.5% risk per trade) on a $10,000 account:
| Metric | Expected Range |
|---|---|
| Trades per month | ~7 |
| Win rate | ~53-57% |
| Avg monthly P/L | $300-800 (3-8%) |
| Maximum expected drawdown | $2,000-3,000 (20-30%) |
| Max consecutive losses | 6-7 |
| Average hold time | 18-22 hours |
This is a long-horizon trend-following EA — expect periods of 1-2 months with mild losses during sideways markets, followed by strong trend captures that more than compensate. Do not disable the EA during losing periods unless there is a clear and permanent change in market regime.