Pipsgrowth EX16027 Trend
MT5 Expert Advisor (Open Source) · XAUUSD · M5, H1
Pipsgrowth.com EX16027 BullishBearish_Engulfing_Stoch - Engulfing pattern + Stochastic confirm + MA trend filter, full 12-layer stack.
Overview
Pipsgrowth EX16027 runs the same two-candle bullish and bearish engulfing skeleton as EX16024 through EX16026, but routes the confirmation leg through a heavily smoothed Stochastic oscillator instead of CCI, MFI, or RSI. The Stochastic call is iStochastic(_Symbol, _Period, 47, 9, 13, MODE_SMA, STO_LOWHIGH) — a 47-period %K, 9-period %D, 13-bar slowing on low/high prices, with the signal line (the slower %D, not the fast %K) used for every comparison. The 47-period K is roughly four hours of M5 history, deliberately slow; the additional 13-bar slowing flattens the line so a single M5 spike no longer pokes the indicator out of the oversold band. On XAUUSD M5 the smoothed Stochastic behaves closer to a regime filter than a tick-fast momentum oscillator, which is the reason the rest of the EA still demands a real engulfing geometry before it ever asks the indicator for permission.
The pattern is detected in CheckPattern and requires five conditions per direction. A bullish engulfing needs Open(2) greater than Close(2) so the prior bar is bearish, Close(1) minus Open(1) greater than AvgBody(1) so the latest bullish body exceeds the twelve-bar average body, Close(1) greater than Open(2) so the latest close sits above the prior open (the actual engulfment), MidOpenClose(2) less than CloseAvg(2) so the prior bar midpoint sits below the 5-SMA trend line, and Open(1) less than Close(2) so the latest open sits below the prior close. The bearish mirror inverts all five. The helper MidOpenClose returns (Open + Close) divided by 2, and CloseAvg pulls CopyBuffer from ExtTrendMAHandle, which is the iMA(_Symbol, _Period, 5, 0, MODE_SMA, PRICE_CLOSE) handle created in OnInit. The 5-SMA is the only piece that converts a counter-trend pause into a directional bet — without it every pullback would qualify as a reversal.
CheckConfirmation then samples StochSignal(1) from buffer 1 of the Stochastic handle, which is the slower %D line. A bullish setup is only confirmed if the smoothed Stochastic sits below 30, and a bearish setup only if it sits above 70. The asymmetry is intentional: a bullish reversal only earns permission when momentum has already washed out into oversold, and a bearish reversal only when it has spiked into overbought. A pattern that prints in a flat, mid-range Stochastic is rejected even if the candlestick geometry is perfect, which is what keeps EX16027 from being a pure candlestick EA.
CheckCloseSignal evaluates a separate four-case cross on bars 1 and 2. A long position closes if StochSignal(1) is below 80 and StochSignal(2) is above 80 (the smoothed line exits the overbought band downward) OR if StochSignal(1) is below 20 and StochSignal(2) is above 20 (the line plunges into oversold, signalling a momentum break against the trade). A short position closes on the mirror at 20 and 80. The 80/20 close bands are wider than the 30/70 confirmation bands on purpose: by the time smoothed Stochastic rolls out of the 80/20 zone, the trend has matured enough that an exit signal carries real weight, whereas the 30/70 boundary is too close to the centre of the oscillator's range to be a useful exit trigger.
Position management runs a static 200-point stop and a static 200-point target, with the same spread-override safety that the other three siblings use. When the current spread is wider than the SL distance, the stop collapses to current price minus spread (for a buy) or plus spread (for a sell); the same collapse applies to the TP. Together with the 200/200 bracket this is a 1:1 risk-reward geometry. The OnTick pipeline then schedules a hard ten-bar M5 time stop: BarsHold walks CopyRates from open_time to TimeCurrent and forces a close once the count reaches InpDuration. CloseBySignal and CloseByTime both call TryClose_EX16027, which retries the close up to three times with a 200 ms Sleep on REQUOTE, TIMEOUT, PRICE_OFF, and PRICE_CHANGED return codes; TryClosePartial_EX16027 and TryModify_EX16027 are defined in the source but never wired into the live close or modify path.
EX16027 fits as the fourth leg of a four-way engulfing family that already includes the CCI(37) variant in EX16024, the MFI(37) variant in EX16025, and the RSI(37) variant in EX16026. Each sibling ships a different confirmation oscillator, uses a unique magic number, and shares the rest of the geometry, so all four can be deployed on the same XAUUSD M5 chart without colliding. As a stand-alone EA the Stochastic variant has the slowest entry filter of the four — the 13-bar slowing on top of the 47-period K means EX16027 takes fewer trades than its siblings and rejects more engulfings that print in the wrong Stochastic regime. The trade-off is that the trades it does take have a stronger momentum backdrop behind them. For a backtester expecting a fast turnover reversal stream this will look quiet; for a trader who wants an engulfing EA that only fires when smoothed momentum confirms, it is the right pick from the family.
Strategy Deep Dive
On each new bar, the static datetime next_bar_open anchor triggers Phase 1 of the OnTick pipeline, where CheckState chains CheckPattern, CheckConfirmation, and CheckCloseSignal. CheckPattern reads Open(1), Open(2), Close(1), Close(2) and the 12-bar AvgBody to test the 2-candle engulfing geometry with the 5-SMA trend-context filter, where MidOpenClose(2) must sit on the correct side of CloseAvg(2). CheckConfirmation then samples StochSignal(1) from buffer 1 of the iStochastic(47, 9, 13, MODE_SMA, STO_LOWHIGH) handle — the slower %D line, not %K — and only confirms when the line sits below 30 for a buy or above 70 for a sell. CheckCloseSignal independently evaluates a four-case %D cross on bar 1 versus bar 2 at the wider 80/20 bands. Phases 2 and 3 open and close on the next tick after a signal, and Phase 4 force-closes any position whose BarsHold count has reached InpDuration of 10. The two native indicator handles (iStochastic and iMA(5, MODE_SMA, PRICE_CLOSE)) are created in OnInit; OnDeinit only releases the Stochastic handle, which leaves the SMA handle to leak until the chart is reloaded.
A 2-candle bullish or bearish engulfing fires when the prior bar is opposite-coloured, the latest body exceeds the 12-bar AvgBody(1), and MidOpenClose(2) sits on the correct side of the 5-SMA trend filter. The 47-period %K, 9-period %D, 13-bar slowing Stochastic on STO_LOWHIGH then confirms the direction by reading the slower %D line: bullish setups require StochSignal(1) below 30, bearish setups require StochSignal(1) above 70. A market order is sent on the first tick after the new-bar detection.
Positions close on three triggers: a four-case smoothed-Stochastic cross where the %D line rolls out of the 80 or 20 band (bar 1 versus bar 2), a hard 10-bar M5 time stop via CloseByTime and BarsHold, and the static 200-point SL and 200-point TP bracket. CloseBySignal and CloseByTime both call TryClose_EX16027, which retries up to three closes with a 200 ms Sleep on REQUOTE, TIMEOUT, PRICE_OFF, and PRICE_CHANGED return codes.
Per-trade stop is a static 200 points with a spread-override safety in PositionOpen that collapses the stop to current price minus spread (for a buy) or current price plus spread (for a sell) when the current spread is wider than the SL distance. There is no trailing stop, no break-even, and no account-level drawdown cap — the only per-trade safety is the 10-bar time stop.
Per-trade take-profit is a static 200 points with the same spread-override safety that collapses the target to current price plus spread (for a buy) or current price minus spread (for a sell) when the spread is wider than the target distance. Combined with the 200-point SL, this is a 1:1 risk-reward bracket on every entry.
XAUUSD on M5 (H1 as the documented alternative) on a low-spread ECN or RAW-spread account. The smoothed Stochastic and the 200/200 1:1-RR bracket assume a typical XAUUSD M5 spread under 30 points. Minimum deposit 100 USD, with 500 USD as a more comfortable buffer for surviving a streak of 200-point stops on the 0.10 fixed lot. Risk is MEDIUM. Best deployed as the slowest of four parallel reversal streams on the same XAUUSD M5 chart, alongside EX16024 (CCI), EX16025 (MFI), and EX16026 (RSI) with unique magic numbers, or as a stand-alone pick when only one engulfing variant is wanted and the smoothed momentum filter is preferred over a tick-faster oscillator.
Strategy Logic
Pipsgrowth EX16027 Trend — Strategy Logic Analysis (from .mq5 source)
Family: Trend
Magic: 22216027
Version: 2.00
BRIEF:
Engulfing pattern + Stoch 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 (14 total across 4 groups):
- [=== Pattern Parameters ===]
InpAverBodyPeriod= 12 // period for calculating average candlestick size - [=== Pattern Parameters ===]
InpMAPeriod= 5 // Trend MA period - [=== Pattern Parameters ===]
InpStochK= 47 // period %K - [=== Pattern Parameters ===]
InpStochD= 9 // period %D - [=== Pattern Parameters ===]
InpStochSlow= 13 // smoothing period %K - [=== Pattern Parameters ===]
InpStochApplied=STO_LOWHIGH// calculation type - [=== Pattern Parameters ===]
InpStochMA=MODE_SMA// smoothing 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=22216027// Magic Number - [=== Identity ===]
InpTradeComment= "Psgrowth.com Expert_16027" // Trade comment
// Pipsgrowth EX16027 Trend — Execution Flow (from source analysis)
// Family: Trend
// Engulfing pattern + Stoch 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 |
| InpStochK | 47 | period %K |
| InpStochD | 9 | period %D |
| InpStochSlow | 13 | smoothing period %K |
| InpStochApplied | STO_LOWHIGH | calculation type |
| InpStochMA | MODE_SMA | smoothing 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 | 22216027 | Magic Number |
| InpTradeComment | "Psgrowth.com Expert_16027" | Trade comment |
#property copyright "Pipsgrowth.com"
#property link "https://pipsgrowth.com"
#property version "2.00"
#property strict
#property description "Pipsgrowth.com EX16027 BullishBearish_Engulfing_Stoch - Engulfing pattern + Stochastic 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 InpStochK =47; // period %K
input int InpStochD =9; // period %D
input int InpStochSlow=13; // smoothing period %K
input ENUM_STO_PRICE InpStochApplied =STO_LOWHIGH; // calculation type
input ENUM_MA_METHOD InpStochMA =MODE_SMA; // smoothing 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=22216027; // Magic Number
input string InpTradeComment = "Psgrowth.com Expert_16027"; // 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);
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.