You will learn
- What should and shouldn't be automated in a price action strategy
- The 5-module architecture of a professional EA: events, filters, signal, risk, execution
- MQL5 code for new-bar detection, D1 swing zones, indecision candles, tick-volume filter, % risk lot sizing, expiring pending orders, daily loss limit, breakeven/partial close
- Four deadly traps: lookahead, repainting, broker-dependent tick volume, over-optimisation
- Taking an EA from the Strategy Tester to a live account and VPS
Who it's for
Traders with basic programming knowledge who want to build their own EA, or who want to understand and properly evaluate the EA they use.
Read first
PRO-01, PRO-02, PRO-03
Once a strategy is written as testable rules (PRO-01), measured (PRO-03) and risk-managed (PRO-02), the natural next step is to let a computer execute it: no fatigue, no tilt, no "just this once". This document does not teach programming from scratch; it gives you the standard architecture of a price action Expert Advisor on MetaTrader 5, skeleton source code for the most important modules, and a list of the mistakes the BMR Master Trade team has met (and paid for) while building EAs for clients.
01 What to automate, and what not to
Not everything in the playbook should become code. Principle: automate what the machine does better than you (discipline, calculation, watching orders 24/5, emotionless execution) and keep what you do better than the machine (reading macro context, noticing a regime change, deciding to switch the EA off before an unusual event).
| Component | Automate? | Notes |
|---|---|---|
| Detecting D1 zones | ✅ Yes | Swing/cluster algorithm: less "refined" than the human eye but consistent |
| Indecision candle + volume | ✅ Yes | Defined by body/range ratio and % of the 20-bar average |
| New high/low confirmation (pending orders) | ✅ Yes | The machine does it better than a person |
| Lot, SL, TP, R:R calculation | ✅ Yes | Eliminates calculation errors entirely |
| Daily/weekly/drawdown limits | ✅ Yes | Machines don't "revenge trade" |
| News filter | ⚠️ Partly | Use the MT5 economic calendar (MQL5 Economic Calendar) or fixed no-trade windows |
| D1 volume phase | ⚠️ Partly | Codeable, but thresholds need tuning per pair |
| "Look left" to judge zone strength | ❌ Not yet | Replace with touch count and zone age |
| Deciding to switch the EA off in abnormal markets | ❌ No | That is your job: check every day |
02 The 5-module architecture

Figure 1. Processing flow on each new bar. Each module is a separate function that can be switched on/off via inputs for "ablation" testing (removing one filter at a time to see how performance changes).
A professional EA keeps five modules clearly separate. Benefits: each part is easy to test, the risk module can be reused in other EAs, and bugs are easier to find.
ReversalPA_EA.mq5
├── Inputs // every parameter in one place, grouped
├── OnInit // indicator handles, symbol checks, version log
├── OnTick
│ ├── IsNewBar() // run logic only when a bar closes
│ ├── ManageOpenPositions() // breakeven, trailing, time-stop
│ ├── PassFilters() // session, news, spread, daily limit, D1
│ ├── DetectSignal() // zone + indecision + volume → score
│ ├── CalcLot() + CalcSLTP()// risk
│ └── PlacePending() // pending order with expiry
└── OnDeinit // release handles
03 Module 1: events, work only on bar close
Most logic bugs in EAs come from processing signals on the running candle (index 0). Its high/low/volume are still changing: anything you calculate can "disappear" a few minutes later. Rule: signals are always computed on index 1 and older, and only once when a new bar appears.
#include <Trade\Trade.mqh>
CTrade trade;
input group "=== General ==="
input ulong InpMagic = 20261105;
input ENUM_TIMEFRAMES InpTF = PERIOD_H4; // signal timeframe
input ENUM_TIMEFRAMES InpTFCtx = PERIOD_D1; // context / zone timeframe
datetime g_lastBar = 0;
bool IsNewBar()
{
datetime t = iTime(_Symbol, InpTF, 0);
if(t == g_lastBar) return false;
g_lastBar = t;
return true;
}
void OnTick()
{
ManageOpenPositions(); // every tick: trailing needs the current price
if(!IsNewBar()) return; // everything else: once per bar
if(!PassFilters()) return;
int dir = 0; double score = 0;
if(!DetectSignal(dir, score)) return;
if(score < InpMinScore) return;
PlacePending(dir, score);
}
04 Module 2: filters
Order the filters from cheap to expensive (computationally), and from "definitely no trade" to "maybe a trade":
input group "=== Filters ==="
input int InpStartHour = 7; // server hour to start (London)
input int InpEndHour = 20; // server hour to stop
input double InpMaxSpreadPts = 350; // max spread (points), XAUUSD ~35 pips
input double InpMaxDailyLoss = 2.0; // max daily loss %
input int InpMaxTradesDay = 3;
bool PassFilters()
{
MqlDateTime dt; TimeToStruct(TimeCurrent(), dt);
if(dt.day_of_week == 0 || dt.day_of_week == 6) return false;
if(dt.hour < InpStartHour || dt.hour >= InpEndHour) return false;
double spread = (SymbolInfoDouble(_Symbol, SYMBOL_ASK)
- SymbolInfoDouble(_Symbol, SYMBOL_BID)) / _Point;
if(spread > InpMaxSpreadPts) return false;
if(DailyPnLPercent() <= -InpMaxDailyLoss) return false; // Module 4
if(TradesToday() >= InpMaxTradesDay) return false;
if(CountOurPositions() > 0) return false; // 1 trade per symbol
return true;
}
News filter: the simplest and most reliable approach is fixed no-trade windows for scheduled releases (NFP on the first Friday, FOMC, CPI), entered as an input string such as "2026.11.06 13:30;2026.11.13 13:30" in server time. The advanced approach uses MQL5's CalendarValueHistory() to fetch high-impact events automatically, but test it carefully: the MT5 calendar does not run in the Strategy Tester.
05 Module 3: signal
D1 zones from swings
The way the human eye draws zones (CB-02) is approximated by: finding D1 swing highs/lows (local extremes within a window of n candles on each side), then clustering swings whose closes fall within ± tol (in D1 ATR). A cluster with ≥ 2 swings is a zone; its edges are the min/max of the swing candle bodies in the cluster.
input group "=== Zones ==="
input int InpSwingN = 3; // n candles each side to define a swing
input int InpLookback = 120; // D1 candles to scan
input double InpZoneTolATR = 0.35; // clustering tolerance (x D1 ATR)
input int InpMinTouches = 2;
struct Zone { double lo, hi; int touches; datetime last; };
Zone g_zones[]; int g_nZones = 0;
int g_hATRd1 = INVALID_HANDLE;
bool IsSwingHigh(int i) // i: closed D1 index
{
double h = iHigh(_Symbol, InpTFCtx, i);
for(int k = 1; k <= InpSwingN; k++)
if(iHigh(_Symbol, InpTFCtx, i-k) >= h || iHigh(_Symbol, InpTFCtx, i+k) >= h) return false;
return true;
}
// IsSwingLow: same with iLow and <=
void BuildZones()
{
double atr[1]; if(CopyBuffer(g_hATRd1, 0, 1, 1, atr) < 1) return;
double tol = atr[0] * InpZoneTolATR;
double pts[]; ArrayResize(pts, 0);
for(int i = InpSwingN + 1; i < InpLookback; i++) // i >= n+1: n closed candles on the right
{
double o = iOpen(_Symbol, InpTFCtx, i), c = iClose(_Symbol, InpTFCtx, i);
if(IsSwingHigh(i)) { int s = ArraySize(pts); ArrayResize(pts, s+1); pts[s] = MathMax(o, c); }
if(IsSwingLow(i)) { int s = ArraySize(pts); ArrayResize(pts, s+1); pts[s] = MathMin(o, c); }
}
ArraySort(pts); // linear clustering
ArrayResize(g_zones, 0); g_nZones = 0;
int i = 0;
while(i < ArraySize(pts))
{
int j = i; while(j + 1 < ArraySize(pts) && pts[j+1] - pts[i] <= tol) j++;
int touches = j - i + 1;
if(touches >= InpMinTouches)
{
ArrayResize(g_zones, g_nZones + 1);
g_zones[g_nZones].lo = pts[i]; g_zones[g_nZones].hi = pts[j];
g_zones[g_nZones].touches = touches; g_nZones++;
}
i = j + 1;
}
}
Call BuildZones() once per new D1 bar (not every H4 bar) to save computation, and only use swings that already have n closed candles on their right: this is the single most important anti-lookahead point.
Indecision candles with a volume filter
input group "=== Signal candle ==="
input double InpMaxBodyRatio = 0.35; // body / range
input double InpMinWickRatio = 0.50; // wick towards the zone / range
input double InpVolMult = 1.20; // volume >= 1.2 x 20-bar average
input int InpVolPeriod = 20;
// dir = +1: indecision at support (lower wick); -1: at resistance (upper wick)
bool IsIndecision(int i, int dir)
{
double o = iOpen(_Symbol, InpTF, i), c = iClose(_Symbol, InpTF, i);
double h = iHigh(_Symbol, InpTF, i), l = iLow(_Symbol, InpTF, i);
double range = h - l; if(range <= 0) return false;
double body = MathAbs(c - o);
double wick = (dir > 0) ? (MathMin(o, c) - l) : (h - MathMax(o, c));
return (body / range <= InpMaxBodyRatio) && (wick / range >= InpMinWickRatio);
}
bool VolumeOK(int i)
{
long v[]; if(CopyTickVolume(_Symbol, InpTF, i, InpVolPeriod + 1, v) < InpVolPeriod + 1) return false;
// v[InpVolPeriod] is bar i (newest in the array), v[0..InpVolPeriod-1] are the 20 bars before
double sum = 0; for(int k = 0; k < InpVolPeriod; k++) sum += (double)v[k];
return (double)v[InpVolPeriod] >= InpVolMult * sum / InpVolPeriod;
}
bool DetectSignal(int &dir, double &score)
{
double c1 = iClose(_Symbol, InpTF, 1);
for(int z = 0; z < g_nZones; z++)
{
bool inZone = (c1 >= g_zones[z].lo - ZoneBuffer()) && (c1 <= g_zones[z].hi + ZoneBuffer());
if(inZone && PriorTrend(-1) && IsIndecision(1, +1)) { dir = +1; score = Score(z, +1); return true; }
if(inZone && PriorTrend(+1) && IsIndecision(1, -1)) { dir = -1; score = Score(z, -1); return true; }
}
return false;
}
PriorTrend(sign) checks for ≥ 3 candles in one direction before the signal candle (or 1 candle with a body ≥ 1.5 ATR). Score() adds points per the PRO-01 card: touches ≥ 2 (+1), VolumeOK(1) (+1), agreement with D1 structure (+2), R:R ≥ 1.5 (+1)… All scoring logic lives in one function so you can run ablation tests: switch each criterion off and compare E.
06 Module 4: risk
Lot from % risk and stop distance
input group "=== Risk ==="
input double InpRiskPct = 1.0; // % of account per trade
input double InpMinRR = 1.5;
input double InpSLBufATR = 0.10; // SL buffer (x signal-timeframe ATR)
double CalcLot(double slDistancePrice)
{
double balance = AccountInfoDouble(ACCOUNT_BALANCE);
double riskMoney = balance * InpRiskPct / 100.0;
double tickVal = SymbolInfoDouble(_Symbol, SYMBOL_TRADE_TICK_VALUE);
double tickSize = SymbolInfoDouble(_Symbol, SYMBOL_TRADE_TICK_SIZE);
if(tickVal <= 0 || tickSize <= 0 || slDistancePrice <= 0) return 0;
double lossPerLot = slDistancePrice / tickSize * tickVal; // loss at SL for 1 lot
double lot = riskMoney / lossPerLot;
double step = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_STEP);
lot = MathFloor(lot / step) * step; // round DOWN
lot = MathMax(SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MIN), lot);
lot = MathMin(SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MAX), lot);
return lot;
}
Two important details: round down (never risk more than planned) and check whether lot == VOLUME_MIN pushes real risk above plan. On a small XAUUSD account, 0.01 lot with an 8 USD stop = 8 USD of risk; on a 300 USD account that is 2.7%, so the EA must reject the trade instead of silently exceeding the limit.
Daily loss limit from trade history
double DailyPnLPercent()
{
datetime dayStart = iTime(_Symbol, PERIOD_D1, 0); // 00:00 server time
if(!HistorySelect(dayStart, TimeCurrent())) return 0;
double pnl = 0;
for(int i = HistoryDealsTotal() - 1; i >= 0; i--)
{
ulong t = HistoryDealGetTicket(i);
if(HistoryDealGetInteger(t, DEAL_MAGIC) != InpMagic) continue;
if(HistoryDealGetInteger(t, DEAL_ENTRY) != DEAL_ENTRY_OUT) continue;
pnl += HistoryDealGetDouble(t, DEAL_PROFIT) + HistoryDealGetDouble(t, DEAL_SWAP)
+ HistoryDealGetDouble(t, DEAL_COMMISSION);
}
// include open P&L so the limit can't be "dodged" by holding losers
for(int i = PositionsTotal() - 1; i >= 0; i--)
if(PositionGetTicket(i) > 0 && PositionGetInteger(POSITION_MAGIC) == InpMagic)
pnl += PositionGetDouble(POSITION_PROFIT);
return pnl / AccountInfoDouble(ACCOUNT_BALANCE) * 100.0;
}
07 Module 5: execution and management
Pending orders with expiry
input int InpExpireBars = 3; // pending order expires after 3 bars
void PlacePending(int dir, double score)
{
double atr[1]; CopyBuffer(g_hATR, 0, 1, 1, atr);
double buf = atr[0] * InpSLBufATR;
double h1 = iHigh(_Symbol, InpTF, 1), l1 = iLow(_Symbol, InpTF, 1);
double entry, sl, tp;
if(dir > 0) { entry = h1 + buf; sl = WallLow() - buf; tp = NextZoneAbove(entry) - buf; }
else { entry = l1 - buf; sl = WallHigh() + buf; tp = NextZoneBelow(entry) + buf; }
double risk = MathAbs(entry - sl), reward = MathAbs(tp - entry);
if(risk <= 0 || reward / risk < InpMinRR) { Print("Skip: R:R=", reward/risk); return; }
double lot = CalcLot(risk);
double realRisk = lot * risk / SymbolInfoDouble(_Symbol, SYMBOL_TRADE_TICK_SIZE)
* SymbolInfoDouble(_Symbol, SYMBOL_TRADE_TICK_VALUE);
if(lot <= 0 || realRisk > AccountInfoDouble(ACCOUNT_BALANCE) * InpRiskPct / 100.0 * 1.2)
{ Print("Skip: minimum lot exceeds risk"); return; }
datetime expiry = iTime(_Symbol, InpTF, 0) + InpExpireBars * PeriodSeconds(InpTF);
trade.SetExpertMagicNumber(InpMagic);
trade.SetDeviationInPoints(30);
string cmt = StringFormat("RevPA s=%.0f", score);
bool ok = (dir > 0)
? trade.BuyStop (lot, NormalizeDouble(entry, _Digits), _Symbol, NormalizeDouble(sl, _Digits),
NormalizeDouble(tp, _Digits), ORDER_TIME_SPECIFIED, expiry, cmt)
: trade.SellStop(lot, NormalizeDouble(entry, _Digits), _Symbol, NormalizeDouble(sl, _Digits),
NormalizeDouble(tp, _Digits), ORDER_TIME_SPECIFIED, expiry, cmt);
if(!ok) Print("Order error: ", trade.ResultRetcode(), " ", trade.ResultRetcodeDescription());
}
Extra checks: the distance from entry to the current price must be ≥ SYMBOL_TRADE_STOPS_LEVEL; if price has already passed the entry when the new bar opens (a gap), switch to a market order only if the recalculated R:R is still ≥ InpMinRR.
Breakeven and partial close in R
input double InpBE_R = 1.0; // move SL to breakeven at +1R
input double InpPartial_R = 1.5; // close 50% at +1.5R
input int InpTimeStop = 15; // close if held 15 bars without reaching +0.5R
void ManageOpenPositions()
{
for(int i = PositionsTotal() - 1; i >= 0; i--)
{
ulong tk = PositionGetTicket(i);
if(tk == 0 || PositionGetInteger(POSITION_MAGIC) != InpMagic) continue;
double open = PositionGetDouble(POSITION_PRICE_OPEN), sl = PositionGetDouble(POSITION_SL);
double cur = PositionGetDouble(POSITION_PRICE_CURRENT);
long type = PositionGetInteger(POSITION_TYPE);
double r0 = MathAbs(open - InitialSL(tk)); // original 1R, stored at entry
if(r0 <= 0) continue;
double rNow = (type == POSITION_TYPE_BUY) ? (cur - open) / r0 : (open - cur) / r0;
if(rNow >= InpBE_R && ((type == POSITION_TYPE_BUY && sl < open) || (type == POSITION_TYPE_SELL && sl > open)))
trade.PositionModify(tk, NormalizeDouble(open, _Digits), PositionGetDouble(POSITION_TP));
if(rNow >= InpPartial_R && !PartialDone(tk))
{
double half = NormalizeDouble(PositionGetDouble(POSITION_VOLUME) / 2, 2);
if(half >= SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MIN)) { trade.PositionClosePartial(tk, half); MarkPartial(tk); }
}
if(BarsSinceOpen(tk) >= InpTimeStop && rNow < 0.5) trade.PositionClose(tk);
}
}
Where to store the "original 1R"? The SL may have moved, so it cannot be derived from POSITION_SL. Durable options: write it into the order comment ("RevPA s=9 r=8.40") or use GlobalVariableSet("RevPA_R_" + ticket, r0). Only GlobalVariables survive a terminal restart.
08 Four deadly traps
| Trap | Symptom | How to avoid it |
|---|---|---|
| Lookahead | Beautiful backtest, poor live results. Uses iHigh(..., 0), iClose(..., 0) of an unclosed bar; uses swings whose n right-hand candles don't exist yet | All signal logic uses index ≥ 1; swings require i ≥ n + 1; check by running the EA in "Open prices only" and "Every tick": results should be close |
| Repainting | ZigZag, Fractals and some "arrow" indicators redraw the past | Write your own swings as above; if using an external indicator, compare its buffer at time T and T+50 bars |
| Broker-dependent tick volume | EA optimised on broker A, run on broker B with 30% lower tick volume → the 120% filter never passes | Use ratios to the 20-bar average (as done), not absolute thresholds; re-test on the data of the broker that will run live |
| Over-optimisation | PF 4.0 with parameters (0.37 / 1.23 / 0.08), but (0.35 / 1.2 / 0.1) loses | Optimise ≤ 3 parameters, coarse steps, pick a region where all neighbouring points are profitable (PRO-03) |
A less-discussed fifth trap: spread when placing the pending order vs when it fills. A Buy Stop fills at the Ask; if the spread widens on news, the fill is further than planned and the SL (set on the Bid) is closer. Check InpMaxSpreadPts at placement too, and consider cancelling the pending order if the current spread exceeds the threshold as price approaches entry.
09 From the Strategy Tester to a live account
- Unit-test each module. Run the EA with
InpMinScore = 0and only one filter on, to make sure each function does its job. Print detailed logs for the first 20 signals and check them by eye on the chart. - Backtest to the PRO-03 standard. Real ticks, real spread + 20%, ≥ 3 years, forward 1/3. Write the system evaluation report.
- Ablation. Switch each criterion in
Score()off. If turning off the volume filter doesn't lower E, that filter adds no value in this market; simplify. - Demo for 4–8 weeks on the real broker that will run it. Compare each demo trade with the backtest signal at the same time. A mismatch on > 10% of trades → there is a lookahead/repaint/spread trap.
- Live at 0.25–0.5%. At least 30 trades. Compare E with the backtest. Only raise to 1% when live E ≥ 60% of backtest E.
- VPS and monitoring. A VPS near the broker's server (latency < 10 ms), automatic terminal restart, a Telegram alert when the EA stops sending an hourly "heartbeat". Every morning, 5 minutes: is the EA running? any unusual trades? daily loss?
An EA executes a strategy; it does not execute judgement. When something abnormal happens (a surprise central-bank intervention, a broker changing conditions, a system that has lost for 3 weeks beyond the Monte Carlo P95), the operator must switch the EA off. Write the switch-off conditions into your playbook (PRO-04) from day one.
10 Extending this framework
The EA skeleton above is the base for many variants you can build from the library:
- Breakout with retest (NC-05): replace
IsIndecisionwith a body closing outside the zone +VolumeOKat a 1.5 threshold; a Limit order at the zone edge. - Fade the Break (NC-05): wick pierces the zone, closes back; market order at the next bar open; SL beyond the wick + 5 pips.
- Session box (NC-05): compute the 00:00–08:00 box, OCO Buy/Sell Stops, cancel after 12:00.
- D1 4-phase filter (NC-03): compare the average tick volume of 10 bars with the 10 before, combined with the sign of
Close[1] − Close[11].
Each variant only replaces Module 3; Modules 2, 4 and 5 are shared. That is the value of a modular architecture.
An EA is like an automatic coffee machine: it repeats a good recipe thousands of times without tiring. But the recipe is still written by the barista, the beans are still chosen by a person, and when the machine makes a strange noise, a person has to switch it off. Automation doesn't replace understanding; it multiplies it.
11 Summary
- Automate discipline, calculation and order-watching; keep contextual judgement and the switch-off decision.
- 5-module architecture: Events → Filters → Signal → Risk → Execution; one function per module, toggled by inputs.
- Signals always on closed bars (index ≥ 1); swings need n closed bars on the right: anti-lookahead.
- Lot: round down; reject the trade if the minimum lot exceeds risk. Daily limit from deal history + open P&L.
- Pending orders expire; manage by the original R stored in a GlobalVariable.
- Four traps: lookahead, repainting, broker-dependent tick volume, over-optimisation. A 6-step path from Tester to VPS.
You have completed all 15 documents. The next step is practice: one strategy, one journal, 100 trades.
References
- MetaQuotes, MQL5 Reference: CTrade, CopyTickVolume, HistoryDealGet*, Strategy Tester (mql5.com/docs).
- Andrew R. Young, Expert Advisor Programming for MetaTrader 5.
- Forex Strategies Resources: MT5 Directory Strategies, Indicators, EA and Metatrader Trading System MT5 (forexstrategiesresources.com).
- Robert Pardo, The Evaluation and Optimization of Trading Strategies: walk-forward and ablation.
- BMR Master Trade EA source code and testing standards.
Study with a community
Questions on this document? Join the BMR trader community on Telegram to discuss the exercises and keep each other accountable. Trading costs matter too: our cashback pays you back on every lot.
Join on TelegramEducational content, not investment advice. Trading forex, gold, indices and CFDs on margin carries a high risk of losing capital; past or simulated results do not guarantee future results. You are fully responsible for your trading decisions. Part of the BMR Trader Library (© BMR Master Trade), compiled from the references listed in each document.