Fresh MQL5 code release – perfect for enhancing your MT4/MT5 strategies.
Strategy Logic
Typology
- Trend-following EMA crossover system on closed M30 bars, distributed for XAUUSD.
- Single-position design ("one trade at a time"): a new signal is ignored while any strategy position or pending order is still open — no pyramiding.
- Intraday: entries are restricted to a broker server-time window (07:00–19:00 by default).
Entries
Recover from drawdowns intelligently with the Auto Recovery Expert Advisor for MT4/MT5. Perfect for hedging strategies. Learn more.
- Signals are evaluated once per new bar ( IsNewBar ), using only completed bars ( CopyBuffer at shifts 1 and 2) — entries never repaint.
- Buy: the fast EMA (20) crosses above the slow EMA (50) between the last two closed bars, and the latest close is above both the fast EMA and the 200 EMA trend line.
- Sell: the exact mirror image (cross below, close below fast EMA and below EMA 200).
- Executed as market orders at the current ask/bid.
Exits
- Every position carries a stop-loss at a fixed percentage of the entry price (1% by default).
- No take-profit (TP = 0) and no signal-based exit: a trade runs until its stop-loss or the daily close.
- Once per day at a configurable server time (20:00 by default), all strategy positions are closed and all pending orders deleted.
Capital Protection
- Risk-based position sizing: a fixed percentage of the balance (1% by default) is risked per trade; lot size is derived from the stop-loss distance using tick size, tick value and lot step, then clamped to the broker's min/max volume.
- Preflight OrderCheck on every order: new orders are rejected when free margin is insufficient and no-change SL/TP modifications are rejected, while position-reducing and closing orders are always allowed.
- MagicNumber + comment ownership tags ensure the EA only scans and manages its own positions and orders.
What Beginners Can Learn
- How to subclass CTrade and route every order through a preflight ( OrderCheck ) that rejects no-change SL/TP modifications, blocks new orders on insufficient free margin, yet still allows position-reducing and closing requests when margin is short.
- How to use MagicNumber + comment tags as ownership guards so the EA only manages its own positions and pending orders.
- How to compute position size from a fixed stop-loss percentage and a per-trade account risk percentage using tick size, tick value, and lot step.
- How to restrict entries to a broker server-time window (including windows that wrap past midnight) and to run a once-per-day exit schedule.
- How to detect an EMA crossover on closed bars only ( CopyBuffer starting at shift 1 and 2) so signals never repaint.
- How to delete leftover pending orders after a fill using OnTradeTransaction .
Inputs
- FastEmaPeriod — fast EMA period (20).
- SlowEmaPeriod — slow EMA period (50); must be greater than FastEmaPeriod .
- TrendEmaPeriod — trend filter EMA period (200).
- EntryStartHour / EntryStartMinute — entry window open, server time (7:00).
- EntryEndHour / EntryEndMinute — entry window close, server time (19:00).
- ExitHour / ExitMinute — daily close-all time, server time (20:00).
- RiskPercent — account risk per trade, in percent (1.0 = 1% of balance).
- StopLossPercent — stop-loss distance as a percent of the entry price (1%).
Constants (Not User Inputs)
- MagicNumber: 568330 .
- Strategy comment: "EmaTrendCross_V1__XAUUSD_M30" .
- One strategy position at a time; take-profit is not used (TP = 0).
- Symbol and timeframe follow the chart the EA is attached to ( _Symbol / PERIOD_CURRENT ); the product is distributed for XAUUSD M30.
Setup
- Attach to an XAUUSD M30 chart (the EA trades whatever symbol and timeframe the chart provides).
- Works on both hedging and netting accounts; the preflight detects position-reducing orders in either margin mode.
- Recommended broker: any broker with XAUUSD M30 history available (e.g., IC Markets).
- Backtest with "Every tick" on XAUUSD M30 — the report below covers 2020.01.01 – 2026.10.01.
Backtest Results — XAUUSD M30, 2020.01.01 – 2026.10.01
Broker: IC Markets (EU) Ltd · USD account · initial deposit 1,000.00 · leverage 1:50 · "Every tick" model · history quality 99% (79,801 bars / 9,542,122 ticks) · all inputs at defaults.
| Metric | Value |
|---|---|
| Total net profit | +1,107.33 USD (+110.73% on the 1,000 USD deposit) |
| Profit factor | 1.46 (gross profit 3,522.91 vs gross loss −2,415.58) |
| Win rate | 52.80% — 264 of 500 trades (longs 51.45% won, shorts 54.46% won) |
| Expected payoff | +2.21 USD per trade |
| Max drawdown | Balance: 136.08 USD (8.07%) · Equity: 145.25 USD (8.59%) |
| Recovery factor / Sharpe ratio | 7.62 / 4.13 |
| Largest win / largest loss | +105.28 / −51.81 USD (avg win +13.34 vs avg loss −10.24) |
| Max consecutive losses | 8 trades (−28.41 USD total) |
| Average holding time | 6h 08m (min 5m 40s, max 34h 30m) |
| Margin level at end | 1,046.29% (low margin usage thanks to 1% risk sizing) |
What the numbers show:
- Positive expectancy: profit factor 1.46 with average win (+13.34) clearly larger than average loss (−10.24) — the edge comes from payoff asymmetry, not from a high win rate.
- Balanced long/short activity (276 long / 224 short trades, both ~52–54% winners) — the logic is not a one-directional curve-fit.
- Drawdown stayed in single digits (max 8.59% of equity) over ~6.8 years — consistent with the 1%-per-trade risk sizing and the daily close-all.
- AHPR 1.0016 / GHPR 1.0015 with LR correlation 0.96: the equity curve grows steadily hour-by-hour and day-by-day, not from one lucky spike.
Note: these results come from one broker, one symbol, one period and one set of inputs, on a 1,000 USD demo-style backtest. They show how the code behaves in the Strategy Tester — they are not a promise of future results (see Risk Warning below). Equity curve image at the bottom of this post.
Risk Warning This is an educational code sample, not a production-ready signal service. Past backtest performance does not guarantee future results. No trading system wins every trade. Use demo accounts first. The author assumes no liability for live trading losses.

Thanks for reading. Discover premium MetaTrader solutions at RobotFX.
78968