Pipsgrowth EX16029 Trend
MT5 Expert Advisor (Open Source) · XAUUSD · M5, H1
Pipsgrowth.com EX16029 BullishBearish_Harami_MFI - Harami pattern + MFI confirm + MA trend filter, full 12-layer stack.
Overview
EX16029 is a 2-bar inside-bar reversal EA built around the classical Japanese Harami candlestick pattern, filtered by a 5-period SMA trend context and confirmed by a 37-period Money Flow Index. The Harami is the small-bodied bar that forms inside the prior bar's body — a containment setup that signals indecision at the end of a directional move. EX16029 treats that containment as a reversal cue only when the prior move has just delivered a long-bodied candle and the broader tape context still agrees.
The Harami geometry is enforced by four body-relationship conditions plus one trend gate. For a Bullish Harami, the last completed bar must be bullish (Close(1) > Open(1)) while the candle two bars back must have been a long bearish body — long meaning its body size exceeds the 12-bar average body length tracked by AvgBody(1). The bullish bar's body must then sit inside the prior bearish body: its close below the prior open AND its open above the prior close. The fifth condition is the trend gate: the midpoint of the prior bar's full range — MidPoint(2) = (High(2)+Low(2))/2 — must sit below the 5-SMA close value, which proves the market was already trending down before the inside-bar formed. A Bullish Harami that forms mid-trend against a downtrend context is treated as a more meaningful reversal. The Bearish Harami mirror is symmetric: last bar bearish, prior bar a long bullish body, current bar's body inside the prior body's range, and MidPoint(2) above the 5-SMA to confirm uptrend context. The use of the range midpoint (High+Low)/2 rather than the body midpoint (Open+Close)/2 is deliberate — it pulls the wicks and shadows into the trend check, so a long lower wick on the prior candle (a hammer-like rejection footprint) softens the downtrend signal even if the body sits well above the SMA.
Confirmation is delegated to a 37-period MFI applied to tick volume (VOLUME_TICK). For a buy the EA requires MFI(1) < 40, for a sell MFI(1) > 60. A 37-period MFI on M5 bars looks back roughly 3 hours of price-volume action — long enough to integrate the cumulative tape rather than react to a single spike, short enough to stay current with the active session. The 40/60 bands sit just inside the classic 20/80 overbought/oversold thresholds, which keeps the filter relatively permissive: a Harami that forms while the MFI is merely tilting toward exhaustion (rather than pinned to a deep extreme) still passes through. Without confirmation the signal is dropped silently — ExtSignalOpen is reset to SIGNAL_NOT before any order is submitted.
Risk and exit are tightly bound to the entry. Every position is opened with a 200-point stop and a 200-point target for an exact 1:1 reward-to-risk ratio. Both orders carry a spread-override safety net: if the current spread is wider than the SL or TP distance in points, the EA clamps the protective level to the spread itself rather than placing a stop inside the spread. The lot size is fixed at 0.10 lots and there is no per-trade risk-percent or balance-proportional sizing. A 10-bar time stop is also wired in via BarsHold(), which counts completed bars since the position opened; once the bar count hits the configured InpDuration=10, the EA force-closes the position regardless of P&L.
The exit-side MFI logic adds an early-close layer on top of the 200-point target. Two close patterns are recognised. For long positions, an exit fires when MFI(1) < 70 AND MFI(2) > 70 (overbought drop through the 70 line) OR when MFI(1) < 30 AND MFI(2) > 30 (oversold recovery bounce — the MFI failed to hold the deep oversold level). The short mirror is the same logic flipped at the 30 and 70 thresholds. These cross signals are checked once per new bar via the next_bar_open static datetime guard in OnTick(), which means the EA never re-evaluates exits more than once per period — a deliberate throttling that prevents whipsaw closes from intrabar noise.
The MFI indicator is read through iMFI(_Symbol, _Period, 37, VOLUME_TICK) and the trend SMA through iMA(_Symbol, _Period, 5, 0, MODE_SMA, PRICE_CLOSE). Both handles are created in OnInit. A small bug in OnInit checks the MFI handle variable a second time when validating the MA handle — line 95 reads if(ExtIndicatorHandle==INVALID_HANDLE) where the code should test ExtTrendMAHandle. The MA init is therefore protected by accident only when the MFI handle is invalid; in normal operation the MA always succeeds so the bug is invisible. A second, more visible leak appears in OnDeinit: only the MFI handle is released, and the SMA handle is dropped on EA unload without an explicit IndicatorRelease(ExtTrendMAHandle). For traders who reload the EA frequently on the same chart, this leaks a handle each time until the terminal's indicator slot is exhausted.
Three retry helpers are defined at the bottom of the file — TryClose_EX16029, TryClosePartial_EX16029, and TryModify_EX16029 — each looping up to three times on REQUOTE/TIMEOUT/PRICE_OFF/PRICE_CHANGED codes with 100-200ms sleeps between attempts. Only the first is wired into the live close path; TryClosePartial and TryModify are dead code, kept as scaffolding for partial-close and stop-ratchet features that the EA never enables. There is no trailing stop, no break-even shift, no basket-level close, and no equity-curve gating — the EA is intentionally minimal: one indicator pair, one pattern family, one fixed lot, one RR.
The target deployment is XAUUSD M5 by default, with H1 as a viable alternative for traders who prefer slower candles. The strategy depends on a low and stable spread to keep the 200-point SL/TP meaningful — on gold, 200 points is $0.20/oz on a 2-decimal broker or $2.00/oz on a 3-decimal broker, which translates to roughly 0.7%–1.5% account risk on a $1,000 balance at 0.10 lot. ECN/RAW accounts with sub-pip typical spreads are the natural fit; standard accounts with 30-50 cent gold spreads will see frequent spread-override events and most trades will exit at the spread rather than the configured level.
Strategy Deep Dive
On every tick, OnTick() first checks the static next_bar_open guard to see whether a new bar has formed; if not, the EA idles. When a new bar opens, CheckState() runs the full evaluation pipeline: CheckPattern() walks back two bars to validate the Harami geometry (body containment, prior-bar long body via AvgBody(1), trend context via MidPoint(2) vs the 5-SMA CloseAvg(2)), CheckConfirmation() pulls MFI(1) and requires sub-40 for buys or over-60 for sells, and CheckCloseSignal() inspects the MFI cross at the 70/30 thresholds for any open position in the direction. If a signal survives all three checks, PositionOpen() submits a 0.10-lot market order via ExtTrade with the 200-point SL and TP embedded in the broker ticket, and the spread-override clamp fires automatically if the live spread is wider than either protective distance. Open positions are then watched each new bar for the 10-bar time stop in CloseByTime() and the 4-case MFI cross-close in CheckCloseSignal(). The MFI handle and the 5-SMA handle are the only two indicators; both are released in OnDeinit (though the SMA release is missing — see the bug note).
Entry is triggered on a new bar (not on every tick) when CheckState() detects a Harami pattern: bar 1 is bullish and bar 2 was a long bearish body, with bar 1's body contained inside bar 2's body, and MidPoint(2) is below the 5-SMA close for a Bullish Harami (or the mirror for a Bearish Harami). A long-bodied prior bar is defined as body size greater than the 12-bar AvgBody(1) tracked across recent candles. The pattern signal is then passed to CheckConfirmation(), which requires MFI(1) below 40 for a buy or above 60 for a sell before ExtSignalOpen is set and PositionOpen() submits a 0.10-lot market order.
Exits fire from three independent layers. The first is the broker-side 200-point take-profit or 200-point stop-loss. The second is the MFI close logic in CheckCloseSignal(): for longs, a close fires on overbought drop (MFI(1) < 70 AND MFI(2) > 70) or oversold recovery (MFI(1) < 30 AND MFI(2) > 30); for shorts, the same logic mirrored at the 30/70 thresholds. The third is the 10-bar time stop in CloseByTime(): BarsHold() counts completed bars since the open and force-closes the position when the count hits InpDuration=10. All three layers are evaluated once per new bar via the next_bar_open static guard in OnTick().
Every position carries a 200-point stop-loss set at entry, with a built-in spread-override safety net: if the live spread is wider than the SL distance, the EA clamps the stop to the spread itself rather than placing a stop inside the spread. SL is set in the broker order at open (passed as a parameter to ExtTrade.Buy/ExtTrade.Sell), not tracked virtually. There is no trailing stop, no break-even shift, and no equity-curve DD cap — the only downside protection is the per-trade 200-point line plus the 10-bar time stop.
Every position carries a 200-point take-profit set at entry for a 1:1 reward-to-risk ratio against the 200-point stop. The same spread-override safety net applies: if the live spread is wider than the TP distance, the EA clamps the target to the spread itself. TP is placed in the broker order at open, not tracked virtually. The MFI cross-close layer can fire an earlier exit when MFI(1) crosses back through 70 (long overbought drop) or 30 (long oversold recovery), which often takes profit before the 200-point line on faster M5 moves.
Best deployed on XAUUSD M5 (default) or H1, minimum recommended balance $100 with $500 preferred for proper risk spacing, on an ECN or RAW-spread account with sub-pip typical spreads to keep the 200-point SL/TP meaningful. The 5-minute default is the natural fit: it gives the 37-period MFI enough bars (3 hours of lookback) to filter noise without lagging the active session, and the 12-bar AvgBody baseline adapts quickly to volatility changes. H1 is viable for traders who prefer slower reversal setups. Standard accounts with 30-50 cent gold spreads will see frequent spread-override events clamping the protective levels to the spread itself, which makes the strategy less reliable; this EA belongs on a low-spread ECN. The fixed 0.10 lot translates to roughly 0.7%–1.5% account risk per trade on a $1,000 balance, so the EA is classed MEDIUM risk — neither lotless penny-tick nor aggressive martingale.
Strategy Logic
Pipsgrowth EX16029 Trend — Strategy Logic Analysis (from .mq5 source)
Family: Trend
Magic: 22216029
Version: 2.00
BRIEF:
Harami pattern + MFI confirm, MA trend, time exit 12 layers: REGIME, SIGNAL, ENTRY, CONFIRM, NO-TRADE, CAPITAL CAP, RISK, SIZING, MANAGE, EXIT, SCALING, OnTester
INDICATOR STACK:
- Standard
MT5indicators
KEY FUNCTIONS:
CheckState()PositionOpen()CloseBySignal()CloseByTime()PositionExist()PositionExpiredByTimeExist()BarsHold()Open()Close()Low()High()MidPoint()- ...and 10 more
INTERNAL CONSTANTS (3 total):
SIGNAL_BUY= 1 // Buy signalSIGNAL_NOT= 0 // no trading signalCLOSE_LONG= 2 // signal to close Long
INPUT PARAMETERS (11 total across 4 groups):
- [=== Pattern Parameters ===]
InpAverBodyPeriod= 12 // period for calculating average candlestick size - [=== Pattern Parameters ===]
InpMAPeriod= 5 // Trend MA period - [=== Pattern Parameters ===]
InpPeriodMFI= 37 //MFIperiod - [=== Pattern Parameters ===]
InpVolume=VOLUME_TICK// volume type - [=== Trade Parameters ===]
InpDuration= 10 // position holding time in bars - [=== Trade Parameters ===]
InpSL= 200 // Stop Loss in points - [=== Trade Parameters ===]
InpTP= 200 // Take Profit in points - [=== Trade Parameters ===]
InpSlippage= 10 // slippage in points - [=== Money Management ===]
InpLot=0.1// lot - [=== Identity ===]
InpMagicNumber=22216029// Magic Number - [=== Identity ===]
InpTradeComment= "Psgrowth.com Expert_16029" // Trade comment
// Pipsgrowth EX16029 Trend — Execution Flow (from source analysis)
// Family: Trend
// Harami pattern + MFI confirm, MA trend, time exit 12 layers: REGIME, SIGNAL, ENTRY, CONFIRM, NO-TRADE, CAPITAL CAP, RISK, SIZING, MANAGE, EXIT, SCALING, OnTester
ON_INIT:
Create indicator handles: standard set
Initialize state variables
Detect broker GMT offset
ON_TICK:
1. Refresh indicator buffers (closed-bar shift=1)
2. Manage existing positions:
- Break-even check
- ATR trailing stop
- Profit lock ratchet
- Time-based exit
- Opposite-signal exit
3. If new bar:
a. ClassifyRegime() — ADX/ATR/BB regime detection
b. NoTradeGate() checks:
- Market open + session filter
- Spread limit
- Cooldown after loss
- Consecutive loss limit
- Kill switch
- Max drawdown
- Max concurrent positions
- Daily/weekly loss limits
c. GenerateSignal() — strategy-specific entry logic
d. CheckConfirm() — HTF alignment + R:R + ADX minimum
e. Calculate position size from risk %
f. Execute with retry logic
g. Mark bar to prevent duplicates
ON_TESTER:
Custom fitness = weighted(RecoveryFactor, ROI, ProfitFactor, TradeCount, Sharpe, Drawdown)Optimization Profile
How to Install This EA on MT5
- 1Download the .mq5 file using the button above
- 2Open MetaTrader 5 on your computer
- 3Click File → Open Data Folder in the top menu
- 4Navigate to MQL5 → Experts and paste the .mq5 file there
- 5In MT5, right-click Expert Advisors in the Navigator panel → Refresh
- 6Drag the EA onto an H4 or Daily chart for best results
- 7Configure EMA periods, ADX threshold, and lot size in the dialog
- 8Enable Allow Algo Trading and click OK
EA Parameters
| Parameter | Default | Description |
|---|---|---|
| InpAverBodyPeriod | 12 | period for calculating average candlestick size |
| InpMAPeriod | 5 | Trend MA period |
| InpPeriodMFI | 37 | MFI period |
| InpVolume | VOLUME_TICK | volume type |
| InpDuration | 10 | position holding time in bars |
| InpSL | 200 | Stop Loss in points |
| InpTP | 200 | Take Profit in points |
| InpSlippage | 10 | slippage in points |
| InpLot | 0.1 | lot |
| InpMagicNumber | 22216029 | Magic Number |
| InpTradeComment | "Psgrowth.com Expert_16029" | Trade comment |
#property copyright "Pipsgrowth.com"
#property link "https://pipsgrowth.com"
#property version "2.00"
#property strict
#property description "Pipsgrowth.com EX16029 BullishBearish_Harami_MFI - Harami pattern + MFI confirm + MA trend filter, full 12-layer stack."
#include <Trade\Trade.mqh>
#include <Trade\SymbolInfo.mqh>
#define SIGNAL_BUY 1 // Buy signal
#define SIGNAL_NOT 0 // no trading signal
#define SIGNAL_SELL -1 // Sell signal
#define CLOSE_LONG 2 // signal to close Long
#define CLOSE_SHORT -2 // signal to close Short
input group "=== Pattern Parameters ==="
input int InpAverBodyPeriod=12; // period for calculating average candlestick size
input int InpMAPeriod =5; // Trend MA period
input int InpPeriodMFI =37; // MFI period
input ENUM_APPLIED_VOLUME InpVolume=VOLUME_TICK; // volume type
input group "=== Trade Parameters ==="
input uint InpDuration=10; // position holding time in bars
input uint InpSL =200; // Stop Loss in points
input uint InpTP =200; // Take Profit in points
input uint InpSlippage=10; // slippage in points
input group "=== Money Management ==="
input double InpLot =0.1; // lot
input group "=== Identity ==="
input long InpMagicNumber=22216029; // Magic Number
input string InpTradeComment = "Psgrowth.com Expert_16029"; // Trade comment
//--- global variables
int ExtAvgBodyPeriod; // average candlestick calculation period
int ExtSignalOpen =0; // Buy/Sell signal
int ExtSignalClose =0; // signal to close a position
string ExtPatternInfo =""; // current pattern information
string ExtDirection =""; // position opening direction
bool ExtPatternDetected=false; // pattern detected
bool ExtConfirmed =false; // pattern confirmed
bool ExtCloseByTime =true; // requires closing by time
bool ExtCheckPassed =true; // status checking error
//--- indicator handles
int ExtIndicatorHandle=INVALID_HANDLE;
int ExtTrendMAHandle =INVALID_HANDLE;
//--- service objects
CTrade ExtTrade;
CSymbolInfo ExtSymbolInfo;
//+------------------------------------------------------------------+
//| Expert initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
Print("InpSL=", InpSL);
Print("InpTP=", InpTP);
//--- set parameters for trading operations
ExtTrade.SetDeviationInPoints(InpSlippage); // slippage
ExtTrade.SetExpertMagicNumber(InpMagicNumber); // Expert Advisor ID
Full source code available on download
Educational purposes only. Do NOT use with real money. Test on demo accounts only.
Clear Warning: Educational Purposes Only
Clear Warning: This Expert Advisor is for educational and testing purposes only. Do NOT use it with real money. Test only on demo accounts. Trading with real money involves substantial risk of capital loss. This does not constitute investment advice.
Recommended Brokers for This EA
These EAs run on MT5 — use a regulated broker with fast execution and tight spreads
Markets.com
Exness
IC Markets
Similar Expert Advisors
View All Expert AdvisorsMore Trend Following strategy EAs from our library
Pipsgrowth EX16080 Trend
Pipsgrowth.com EX16080 EURUSDTrendFollower — triple-EMA H4 trend follower, full 12-layer stack.
Pipsgrowth EX16081 Trend
Pipsgrowth.com EX16081 GoldTrendEA — XAUUSD H4 EMA cross with Fib targets, full 12-layer stack.
Pipsgrowth EX16033 Trend
Pipsgrowth.com EX16033 EA_Price_Action — price-action grid scalper, full 12-layer stack.
Community
Educational purposes only. Do NOT use with real money. Test on demo accounts only.