M1 Gold Hedge
A breakout and hedge recovery Expert Advisor designed for Gold (XAUUSD). The EA places directional breakout orders aligned with the H1 trend bias. When a position moves against you, a recovery position opens in the opposite direction at a larger lot size. All positions are managed as a single basket and close automatically when the profit target is reached. Fully compatible with both netting and hedging account types.
How It Works
Entry
At the start of each cycle the EA scans the last N bars for a high/low range and places a BuyStop above the high or a SellStop below the low, depending on the H1 EMA trend direction. Only one basket runs at a time. Pending orders that are not filled within the expiry window are cancelled automatically.
Hedge Recovery
When the active position moves against you by the hedge trigger distance, a new position opens in the opposite direction at a larger lot size. This repeats up to the maximum number of hedge levels. With default settings the exposure grows as follows: 0.01 → 0.02 → 0.03 → 0.05 → 0.08 → 0.12 lots.
Smart Recovery
When the basket is frozen due to drawdown, the EA can optionally open a single trend-aligned recovery position sized to cover the total loss and still reach the profit target in one move. The recovery direction is confirmed against the H1 EMA bias before entry.
Basket Exit
- Hard take-profit — closes all positions when combined profit reaches the target dollar amount.
- Trailing take-profit — activates above a configurable threshold and steps back from the peak profit.
- Minimum profit floor — no automated close executes unless basket profit exceeds this amount, ensuring every exit is in profit.
Two-Layer Protection System
- Freeze mode — when a USD loss or equity drawdown threshold is breached, no new hedge levels are placed. Existing positions remain open. The freeze lifts automatically when the basket recovers to break-even.
- Emergency close — if the account margin level drops below a configurable threshold, all positions are closed immediately to prevent a broker stop-out. This is the only automated close that can execute at a loss.
- Margin check — before every new hedge placement, free margin and equity are verified. The order is blocked if either falls below the safety threshold.
Broker-Safe Order Placement
The EA calculates minimum SL/TP distances using the broker's stops level plus the live spread, eliminating "Invalid stops" errors that affect other EAs on wide-spread instruments like Gold. When a position is within the broker's freeze zone, the EA skips forced closes and lets the position exit naturally at its TP or SL.
Trend Filter
An optional ADX and Bollinger Band filter on the M5 and M15 timeframes blocks new basket entries when the market is trending. Directional entry is further filtered by a fast/slow EMA cross on H1 — the EA only places BUY breakouts in a bullish bias and SELL breakouts in a bearish bias. Hedge recovery management continues unaffected when the filter is active.
Session Filter
Trading is restricted to a configurable daily time window. The recommended window for Gold is 08:00 – 21:00 GMT, covering the London open through the full New York session. The EA reads the symbol's actual session schedule directly so the filter works correctly in both live trading and the Strategy Tester.
Live Dashboard
A real-time on-chart panel displays balance, equity, free margin, spread, daily P&L, floating basket profit, total exposure in lots, current hedge level, active take-profit targets, pending order status, trend filter state, H1 bias direction, and recovery attempt counter. A one-click button closes all positions and stops the EA immediately.
Best Trading Sessions for Gold
| Session | GMT | Fit for This EA |
| Asian | 00:00 – 08:00 | Avoided — low volume, breakouts often fake |
| London Open | 07:00 – 09:00 | High quality breakouts |
| London | 08:00 – 12:00 | Best for EMA filter — steady directional trend |
| London / NY Overlap | 12:00 – 17:00 | Premium window — highest volume and range |
| New York | 13:00 – 20:00 | Strong momentum, good trend follow |
| NY Close | 20:00 – 22:00 | Caution — spreads widen |
| Dead Zone | 22:00 – 00:00 | Avoided — extremely thin liquidity |
Key Features
- Designed specifically for Gold (XAUUSD) — also works on major forex pairs
- Compatible with M1 and other timeframes
- Supports both netting and hedging account types — auto-detected on startup
- Broker digit normalisation for 2, 3, 4, and 5 digit brokers
- Spread-aware SL/TP calculation — eliminates "Invalid stops" errors on Gold
- Freeze-level guard — skips modification when broker blocks it, avoids "Modification failed" errors
- Magic number isolation — safe to run alongside other EAs
- Auto-restart at midnight for a clean daily cycle
- Fully tested in the MT5 Strategy Tester on XAUUSD and EURUSD
Input Parameters
Account Mode
| Parameter | Default | Description |
| InpNettingMode | false | Set to true to force netting scalper mode. The EA detects netting accounts automatically. |
Netting Scalper
| Parameter | Default | Description |
| InpNettingTPPips | 25 | Take profit distance in pips for each scalp trade. |
| InpNettingMaxBars | 8 | Maximum number of H1 bars a netting position may stay open before being closed by time. |
| InpNettingConfirmClose | true | Require the last H1 candle to close on the correct side of the fast EMA before entering. |
Entry Settings
| Parameter | Default | Description |
| InpBarLookback | 3 | Number of bars used to define the breakout high/low range. |
| InpMaxSpread | 50 | Maximum allowed spread in points. No entry is placed if the spread exceeds this value. |
| InpInitialLot | 0.01 | Lot size for the initial breakout order. |
| InpOrderExpireMins | 2 | Cancel unfilled pending breakout orders after this many minutes. Set 0 to disable expiry. |
Hedge / Recovery
| Parameter | Default | Description |
| InpLotMultiplier | 1.5 | Multiplier applied to the lot size at each new hedge level. |
| InpMaxLot | 2.0 | Hard cap on the lot size of any single position. |
| InpMaxHedgeLevels | 5 | Maximum number of hedge recovery levels allowed. Set 0 for unlimited. |
| InpHedgeDistance | 500 | Distance in points the price must move against the newest position to trigger the next hedge level. Used only when ATR distance is disabled. |
Smart Recovery
| Parameter | Default | Description |
| InpSmartRecovery | true | Enable the smart recovery system. When frozen, the EA attempts a trend-aligned recovery trade sized to cover the loss. |
| InpRecoveryPoints | 300 | Expected move in points the recovery trade needs to cover the loss and reach the profit target. |
| InpRecoveryUnfreeze | true | Allow recovery trades while the freeze is active. If false, the EA waits for the market to recover on its own. |
| InpMaxRecoveryAttempts | 3 | Maximum number of recovery trades allowed per freeze cycle. Set 0 for unlimited. |
| InpRecoveryMaxEquityPct | 5.0 | Recovery trade is aborted if its required margin exceeds this percentage of current equity. Set 0 to disable. |
Stop-Loss
| Parameter | Default | Description |
| InpPositionSL | 30 | Per-position stop loss in pips. Required on netting accounts. Set 0 to disable (hedging mode only). |
Profit Target
| Parameter | Default | Description |
| InpTargetProfit | 10.0 | Close all positions when basket profit reaches this amount in account currency. |
| InpTrailStart | 5.0 | Activate the trailing exit when basket profit reaches this amount. |
| InpTrailStep | 1.5 | Close the basket when profit pulls back this amount from the trailing peak. |
| InpMinCloseProfit | 0.50 | Minimum basket profit required for any automated close to execute. Guarantees every exit is in profit. |
Loss Freeze Levels
| Parameter | Default | Description |
| InpFreezeLossUSD | 30.0 | Freeze new hedge placements when basket loss reaches this amount. Set 0 to disable. |
| InpFreezeDrawPct | 8.0 | Freeze new hedge placements when equity drops this percentage below the balance at basket open. Set 0 to disable. |
| InpEmergencyMarginPct | 10.0 | Close all positions immediately if the account margin level falls below this percentage. Prevents broker stop-out. Set 0 to disable. |
Trend Filter
| Parameter | Default | Description |
| InpUseTrendFilter | true | Enable or disable the trend filter entirely. |
| InpFilterM5 | true | Include the M5 timeframe in the trend check. |
| InpFilterM15 | true | Include the M15 timeframe in the trend check. |
| InpADXPeriod | 14 | Period for the ADX indicator used in the trend filter. |
| InpADXThreshold | 25.0 | ADX value above which the market is considered trending and new entries are blocked. |
| InpBBPeriod | 20 | Period for the Bollinger Bands indicator used in the trend filter. |
| InpBBDeviation | 2.0 | Standard deviation multiplier for Bollinger Bands. |
| InpADXRequired | true | Require ADX to confirm a trend. When both InpADXRequired and InpBBRequired are true, both indicators must agree (AND mode). |
| InpBBRequired | true | Require a Bollinger Band breakout to confirm a trend. Set either to false for OR mode. |
Directional Entry
| Parameter | Default | Description |
| InpDirectionalEntry | true | Only place BUY breakouts in a bullish H1 bias and SELL breakouts in a bearish H1 bias. |
| InpEMAFast | 21 | Period for the fast EMA used for H1 direction bias. |
| InpEMASlow | 50 | Period for the slow EMA used for H1 direction bias. |
ATR Dynamic Distance
| Parameter | Default | Description |
| InpUseATRDist | true | Use ATR-based dynamic spacing between hedge levels instead of the fixed InpHedgeDistance. |
| InpATRPeriod | 14 | Period for the ATR indicator. |
| InpATRMult | 2.0 | ATR value is multiplied by this factor to determine the hedge spacing distance. |
Break-Even
| Parameter | Default | Description |
| InpBEPoints | 150 | Move SL to break-even when a position is this many points in profit. Set 0 to disable. |
Recovery Trend Confirm
| Parameter | Default | Description |
| InpRecoveryTrendConfirm | true | Only place a recovery trade if the H1 EMA bias aligns with the recovery direction. |
| InpRecoveryTrendTimeout | 4 | After this many H1 bars in freeze without a recovery, bypass the trend confirmation and trade anyway. |
Time Filter
| Parameter | Default | Description |
| InpStart | h08 | Hour of day when trading is allowed to begin (broker server time). |
| InpEnd | h21 | Hour of day when trading stops for the session. |
| InpAutoRestart | true | Automatically reset state variables at midnight for a fresh daily cycle. |
System
| Parameter | Default | Description |
| InpMagic | 123456 | Magic number used to identify orders and positions belonging to this EA. |
| InpAlerts | true | Enable popup alerts for key events such as take-profit hit, freeze activated, and emergency close. |
Dashboard
| Parameter | Default | Description |
| InpDashX | 20 | Horizontal position of the dashboard panel in pixels from the left edge of the chart. |
| InpDashY | 20 | Vertical position of the dashboard panel in pixels from the top edge of the chart. |
Recommended Setup
- Symbol: XAUUSD (Gold)
- Timeframe: M1
- Account type: ECN or Low spreads
- Minimum balance: $500 (recommended $1,000 or more)
- VPS: strongly recommended for 24/5 uptime
Risk Warning
This EA uses a martingale-style recovery system. Lot sizes increase with each hedge level and total exposure grows significantly in adverse market conditions. Always test thoroughly on a demo account before live trading. Ensure the freeze levels and emergency close threshold are configured appropriately for your account size. Past performance in the Strategy Tester does not guarantee future results.
Note:
- Always test on a demo account first to understand how the breakout levels and trailing stop behave during different market sessions.
- Use a Cent account if you do not have a large amount of funds.
- For recommended Gold settings, use InpNettingTPPips = 180, InpPositionSL = 350, InpMaxSpread = 40.
- Get the file set and Manual Guide inside our Telegram Group