P
PipsGrowth
Trend FollowingOpen Source – Free

Pipsgrowth EX16011 Trend

MT5 Expert Advisor (Open Source) · XAUUSD · M15

Pipsgrowth.com EX16011 GoldScalper Engulfing StrongReversal — engulfing reversal scalper, full 12-layer stack.

Overview

Pipsgrowth EX16011 is a single-position gold reversal EA built around one specific candlestick formation: the engulfing bar. It loads ATR(14) on the M15 timeframe, watches for a closed bar that fully engulfs the prior bar's real body, and only acts when the engulfing bar's body is at least 1.2× the size of the bar it consumes (the MinEngulfRatio input). Everything else in the EA — the SL, TP, trailing stop, lot sizing, retry logic, and trade-comment string — is a wrapper around that single decision.

The signal logic in GetEngulfingSignal() works on the two most recent closed M15 bars (bar 1 = most recent closed, bar 2 = the one before it). A bullish engulfing requires three things simultaneously: bar 2 must be bearish (close2 < open2), bar 1 must be bullish (close1 > open1), and bar 1's body must completely cover bar 2's body — meaning bar 1 closes above bar 2's open and opens below bar 2's close. The minimum body ratio of 1.2 (MinEngulfRatio) ensures a weak inside-body scenario does not pass; the engulfing bar has to be meaningfully larger than the bar it absorbs. A bearish engulfing is the mirror: bar 2 bullish, bar 1 bearish, bar 1 opens above bar 2's close and closes below bar 2's open, with the same 1.2× body ratio. There is no trend filter, no oscillator, no momentum confirmation, no session gate — the signal is purely geometric. When the conditions don't line up, the function returns 0 and OnTick() does nothing.

The order flow runs through OpenPosition(), which computes both the stop distance and the take-profit distance from the live ATR(14) reading refreshed on each new bar. The stop-loss distance is max(ATR × 1.5, StopLossPips × pipSize, minDist × 1.5) where minDist derives from the broker's SYMBOL_TRADE_STOPS_LEVEL (with a 10-pip fallback when the broker reports zero). The default StopLossPips is 15, so the SL is at least 15 pips and widens automatically when ATR(14) is higher than 10 pips. The take-profit distance is max(SL × 2, minDist × 1.5) — a minimum 1:2 risk-reward regardless of how tight the SL got. Both prices are normalized to _Digits before being attached to the order, and the lot size comes from CalculatePositionSize(), which uses the standard 2% balance risk (the RiskPercent input) divided by slPips × pipValuePerLot, floored to the symbol's volume step, and clamped to the broker's min/max volume.

Management happens on every tick through ManageOpenPositions(), which iterates positions matching the EA's symbol and magic number. Once the open profit exceeds TrailingStartPips = 10, the EA begins ratcheting the stop-loss: for a buy, it sets the new SL to currentPrice - 10 pips, but only if that new SL is more than TrailingStepPips = 5 above the current SL (newSL > sl + 5 pips). For a sell, the mirror condition applies. The trailing stop is incremental — it never moves backward, it only advances in 5-pip jumps, and it never modifies the take-profit (the TP is passed through as PositionGetDouble(POSITION_TP) in each modify call). There is no break-even step, no partial close, and no time-based exit; the trade lives until either TP, SL, or the trailing ratchet takes it out.

The position-counting rule is strict: OnTick() calls CountPositions() after the filters pass, and if there is already one open position for the EA's symbol and magic, the function returns immediately. This is a one-position-per-symbol EA — no pyramiding, no averaging, no grid, no martingale, no recovery multiplier. The brief claims a 12-layer stack including NO-TRADE, CAPITAL CAP, SCALING, and OnTester modules, but the code only wires signal/entry/manage/exit/sizing/risk: there is no equity-stop, no daily loss circuit, no session filter, no news filter, no time-stop, and OnTester() is empty. The actual risk control is the fixed 2% per-trade risk combined with the single-position cap and the 25-pip spread filter (UseSpreadFilter = true, MaxSpreadPips = 25.0) that rejects entries when the live spread is too wide for a clean engulfing fill.

Order execution goes through the MQL5 CTrade wrapper with SetExpertMagicNumber(22216011), SetDeviationInPoints(3) for slippage tolerance, and an auto-probed filling mode that prefers FOK if the broker supports it, otherwise IOC, otherwise the legacy RETURN mode. Three retry helpers — TryClose_EX16011, TryClosePartial_EX16011, and TryModify_EX16011 — each attempt the operation up to three times, sleeping 200ms after a REQUOTE/TIMEOUT/PRICE_OFF/PRICE_CHANGED response from the close/partial-close calls and 100ms after REQUOTE/TIMEOUT from the modify call. TryModify is the only one actually invoked from live code (via SafePositionModify); the close helpers are defined for resilience but are not on a call path. SafePositionModify itself re-validates the proposed SL/TP against SYMBOL_TRADE_STOPS_LEVEL, refuses to set an SL on the wrong side of price, and refuses to set a TP closer than the broker's minimum distance — a defense against the kind of -1 errors that come from sending a stop into the bid/ask.

The EA's overall character is that of a low-input, signal-driven scalper. The 3 input groups (Risk Management, Trade Settings, Trailing Stop, Filters) sum to 11 parameters in total. The minimum recommended balance is $100 — UseMoneyManagement = true plus RiskPercent = 2.0 means a $100 account risks $2.00 per trade, sizing the lot to whatever the SL distance and gold's tick value allow; on $100, with a 15-pip SL, that's roughly 0.01 lots. The single-position cap and the strict engulfing geometry mean there are no surprise margin calls from a runaway grid, but it also means the EA will sit flat through long stretches of gold chop where no clean engulfing pattern forms. Backtests on M15 gold tend to show a moderate trade frequency with a winner profile that depends on whether the 1:2 RR TP fires before the trailing stop takes over — the trailing ratchet becomes dominant on trades that survive the first 10 pips of profit, and from that point on the trade is essentially a runner with a 10-pip trailing floor.

On the operational side, run this on an ECN or RAW-spread broker (XAUUSD M15 with a 25-pip spread cap requires a low-spread venue, since gold spreads blow out around news), keep the account size to whatever makes the 2% risk comfortable for you, and let the EA work in the active sessions — London and New York, when gold volume and bar bodies are largest, produce the cleanest engulfing patterns. There is no kill-switch, so the trader is the last layer of risk control: monitor the magic-number 22216011 positions and don't override the EA mid-trade.

Strategy Deep Dive

Every tick begins in OnTick() with a call to ManageOpenPositions() that walks all positions matching the EA's symbol and magic 22216011, ratcheting the SL forward in 5-pip steps once profit clears 10 pips. The strategy decision itself only runs on closed M15 bars via the IsNewBar() guard; RefreshIndicators() pulls the latest ATR(14) reading from the single handle created in OnInit. CheckFilters() then rejects the bar if the live spread exceeds 25 pips, and CountPositions() returns immediately if a position is already open — this is a strict one-position-per-symbol EA. GetEngulfingSignal() reads bar 1 and bar 2 OHLC and applies the three-part bullish/bearish engulfing test: prior-bar direction must be opposite, current bar must cover the prior bar's open-to-close range, and the body ratio must clear MinEngulfRatio=1.2. OpenPosition() then sizes the lot from the 2% risk rule, computes the SL as max(ATR×1.5, 15 pips, broker min×1.5) and the TP as max(SL×2, min×1.5), and submits via CTrade with the auto-probed filling mode and 3-pip slippage tolerance. All modifications route through TryModify_EX16011 which retries up to three times on REQUOTE/TIMEOUT responses with 100ms back-off; the close and partial-close retry helpers are defined for resilience but are not on a live call path.

Entry Signal

Entries trigger on a closed M15 bar that fully engulfs the prior bar's real body (close1>open2 AND open1<close2 for bullish, mirrored for bearish) with the engulfing body's absolute size at least 1.2× the engulfed bar's body (MinEngulfRatio=1.2). There is no trend filter, oscillator, or session gate — the signal is pure bar geometry evaluated on bar 1 vs bar 2. The EA also enforces a one-position-per-symbol cap (CountPositions>=1 returns) and a 25-pip maximum spread filter before opening.

Exit Signal

Exits run on three paths: the fixed 1:2 RR take-profit attached at order entry, the SL attached at order entry (which can be ratcheted by the trailing stop), and the trailing stop itself. The trailing ratchet in ManageOpenPositions() activates once open profit exceeds 10 pips and pulls the SL to currentPrice±10 pips in 5-pip increments — never backward, never modifying the TP. There is no break-even step, no partial close, and no time-based exit.

Stop Loss

Stop-loss is volatility-anchored via ATR(14) on M15, computed as max(ATR×1.5, 15 pips, broker minStopLevel×1.5) and attached at order entry. The trailing stop (TrailingStartPips=10, TrailingStepPips=5) ratchets the SL forward in 5-pip increments once profit exceeds 10 pips, never moving it backward. All modifications pass through SafePositionModify which validates the SL is on the correct side of price and respects the broker's minimum stop distance.

Take Profit

Take-profit is fixed at entry at a 1:2 risk-reward ratio to the SL (tpDist = max(slDist×2, minDist×1.5)) with the default TakeProfitPips=30 acting as a no-op since the ATR-anchored SL × 2 always exceeds it. The TP is never modified by the trailing stop — it remains at the original server-side level for the life of the trade.

Best For

Best suited for XAUUSD M15 on an ECN or RAW-spread account with $100+ balance where 2% risk per trade equals roughly $2.00 and sizes the position to roughly 0.01 lots against a 15-pip stop. Run during London and New York sessions when gold volume and bar bodies produce the cleanest engulfing formations; the 25-pip spread filter will block entries during off-hours and around news when spreads widen. The strict one-position-per-symbol cap and pure geometric entry make this a low-frequency reversal EA — expect long flat stretches punctuated by isolated trades with 1:2 RR targets and a 10-pip trailing floor.

Strategy Logic

Pipsgrowth EX16011 Trend — Strategy Logic Analysis (from .mq5 source)

Family: Trend Magic: 22216011 Version: 2.00

BRIEF: Gold Scalping EA trading engulfing candlestick reversal patterns. Detects strong bullish/bearish engulfing bars using body ratio analysis and enters on reversal with ATR-based stops and trailing stop management. 12 layers: REGIME, SIGNAL, ENTRY, CONFIRM, NO-TRADE, CAPITAL CAP, RISK, SIZING, MANAGE, EXIT, SCALING, OnTester

INDICATOR STACK:

  • Standard MT5 indicators

KEY FUNCTIONS:

  • SafePositionModify()
  • RefreshIndicators()
  • GetEngulfingSignal()
  • OpenPosition()
  • CalculatePositionSize()
  • ManageOpenPositions()
  • IsNewBar()
  • GetPipSize()
  • CheckFilters()
  • CountPositions()
  • TryClose_EX16011()
  • TryClosePartial_EX16011()
  • ...and 1 more

INTERNAL CONSTANTS (0 total):

INPUT PARAMETERS (3 total across 1 groups):

  • [=== Trade Settings ===] MagicNumber = 22216011 // Magic Number (222 + Expert ID)
  • [=== Trade Settings ===] InpTradeComment = "Psgrowth.com Expert_16011" // Trade Comment
  • [=== Trade Settings ===] MinEngulfRatio = 1.2 // Min body ratio for engulfing
Pseudocode
// Pipsgrowth EX16011 Trend — Execution Flow (from source analysis)
// Family: Trend
// Gold Scalping EA trading engulfing candlestick reversal patterns. Detects strong bullish/bearish engulfing bars using body ratio analysis and enters on reversal with ATR-based stops and trailing stop management. 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

Optimized Brokers:
ExnessIC Markets
Optimized Symbols:
XAUUSD
Optimized Timeframes:
M15

How to Install This EA on MT5

  1. 1Download the .mq5 file using the button above
  2. 2Open MetaTrader 5 on your computer
  3. 3Click File → Open Data Folder in the top menu
  4. 4Navigate to MQL5 → Experts and paste the .mq5 file there
  5. 5In MT5, right-click Expert Advisors in the Navigator panel → Refresh
  6. 6Drag the EA onto an H4 or Daily chart for best results
  7. 7Configure EMA periods, ADX threshold, and lot size in the dialog
  8. 8Enable Allow Algo Trading and click OK

EA Parameters

ParameterDefaultDescription
MagicNumber22216011Magic Number (222 + Expert ID)
InpTradeComment"Psgrowth.com Expert_16011"Trade Comment
MinEngulfRatio1.2Min body ratio for engulfing
Source Code (.mq5)Open Source
Pipsgrowth_com_EX16011.mq5
#property copyright "Pipsgrowth.com"
#property link      "https://pipsgrowth.com"
#property version   "2.00"
#property strict
#property description "Pipsgrowth.com EX16011 GoldScalper Engulfing StrongReversal — engulfing reversal scalper, full 12-layer stack."

#include <Trade\Trade.mqh>

input group "=== Risk Management ==="
input bool   UseMoneyManagement = true;
input double RiskPercent        = 2.0;
input double FixedLotSize       = 0.01;

input group "=== Trade Settings ==="
input int    StopLossPips       = 15;
input int    TakeProfitPips     = 30;
input int    Slippage           = 3;
input int    MagicNumber        = 22216011;                     // Magic Number (222 + Expert ID)
input string InpTradeComment   = "Psgrowth.com Expert_16011"; // Trade Comment
input double MinEngulfRatio     = 1.2;        // Min body ratio for engulfing

input group "=== Trailing Stop ==="
input bool   UseTrailingStop    = true;
input int    TrailingStartPips  = 10;
input int    TrailingStepPips   = 5;

input group "=== Filters ==="
input bool   UseSpreadFilter    = true;
input double MaxSpreadPips      = 25.0;

CTrade trade;
int handleATR;
datetime lastBarTime = 0;
double currentATR;

ENUM_ORDER_TYPE_FILLING GetAllowedFilling()
{
   int filling_mode = (int)SymbolInfoInteger(_Symbol, SYMBOL_FILLING_MODE);
   if((filling_mode & SYMBOL_FILLING_FOK) == SYMBOL_FILLING_FOK) return ORDER_FILLING_FOK;
   else if((filling_mode & SYMBOL_FILLING_IOC) == SYMBOL_FILLING_IOC) return ORDER_FILLING_IOC;
   else return ORDER_FILLING_RETURN;
}


//+------------------------------------------------------------------+
//| Safe Position Modify - validates stops before modifying          |
//+------------------------------------------------------------------+
bool SafePositionModify(ulong ticket, double newSL, double newTP)
{
   // Select the position
   if(!PositionSelectByTicket(ticket))
   {
      return false; // Position doesn't exist, no error needed
   }
   
   // Get current price
   long type = PositionGetInteger(POSITION_TYPE);
   double price = (type == POSITION_TYPE_BUY) ? 
                  SymbolInfoDouble(_Symbol, SYMBOL_BID) : 
                  SymbolInfoDouble(_Symbol, SYMBOL_ASK);

Full source code available on download

Educational purposes only. Do NOT use with real money. Test on demo accounts only.

Tags:ex16011trendpipsgrowthfreemt5xauusd

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

Community

Sign in to contributeSign In

Educational purposes only. Do NOT use with real money. Test on demo accounts only.

File NamePipsgrowth_com_EX16011.mq5
File Size12.9 KB
Versionv2.00
PlatformMetaTrader 5
File Type.mq5 Source
StrategyTrend Following
Risk LevelMedium Risk
Timeframes
M15
Currency Pairs
XAUUSD
Min. Deposit$100