P
PipsGrowth
Trend FollowingOpen Source – Free

Pipsgrowth EX16097 Trend

MT5 Expert Advisor (Open Source) · XAUUSD · M5, H1

Pipsgrowth.com EX16097 DarkCloud_PiercingLine_RSI — candlestick pattern + RSI confirmation, full 12-layer stack.

Overview

The EX16097 Trend is a reversal-pattern EA that hunts for two-bar exhaustion setups at swing highs and lows on XAUUSD M5. Specifically, it scans for the Dark Cloud Cover on bullish exhaustion and the Piercing Line on bearish exhaustion, then filters each pattern through a short moving-average trend test and an RSI(37) oscillator gate before opening a market order.

The Dark Cloud Cover requires four geometric conditions plus a trend anchor. Bar 2 must print a long white body — Close(2) minus Open(2) must exceed the 12-bar average body — establishing the prior bullish thrust. Bar 1 must open above bar 2's high, marking a gap-up open at a new high, and must close back inside bar 2's body (Close(1) between Open(2) and Close(2)). The 'uptrend' check uses a 5-period SMA applied to close: bar 2's mid-price (the average of Open(2) and Close(2)) must print above the SMA(5) at bar 2, confirming the rally had actual trend support. When those four legs line up, the EA tags a SELL signal. The Piercing Line mirrors it: a long black body on bar 2, a long white body on bar 1, an open below bar 2's low, and bar 1's close lands back inside bar 2's body. The MA(5) trend anchor flips — bar 2's mid-price must sit below the SMA(5) — confirming the prior downtrend context. The result is a BUY signal.

Pattern detection without confirmation is not enough. The EA gates each signal with an RSI(37) read at bar 1. For a BUY, the RSI(37) must print below 40 — an oversold-leaning reading that supports reversal. For a SELL, the RSI(37) must print above 60 — overbought-leaning. The thresholds sit slightly inside the classic 30/70 bands, which means the EA will accept more patterns than a strict 30/70 oscillator but still avoid the absolute centre of the range. If either pattern fires but the RSI gate fails, ExtSignalOpen is set to SIGNAL_NOT and the pattern is logged but discarded.

The OnTick handler is a four-phase machine gated by a static next_bar_open timestamp so that all pattern, confirmation, and close-signal checks fire only on a new bar. Phase 1 calls CheckState, which itself chains CheckPatternCheckConfirmationCheckCloseSignal. If all three return true, next_bar_open is rolled forward to the next bar boundary. Phase 2 watches ExtSignalOpen and calls PositionOpen if no position in that direction already exists. Phase 3 watches ExtSignalClose and routes through CloseBySignal if a position is open in the matching direction. Phase 4 calls PositionExpiredByTimeExist each tick and fires CloseByTime when the bar count exceeds the InpDuration input (default 10 bars).

The PositionOpen routine executes a market order with the input lot (0.1) and a 1:1 stop-and-target — InpSL = 200 points, InpTP = 200 points, InpSlippage = 10 points — with one notable twist. The code reads the live spread from CSymbolInfo before computing the SL/TP distance. If the spread is greater than or equal to the SL distance in points, the SL is set at price minus spread (buy) or price plus spread (sell), not at price minus InpSL*point. The same guard applies to TP. This prevents the common 'spread is wider than the SL — you got stopped out the instant you opened the trade' failure that hurts most M5 candle-pattern EAs on gold. The print message explicitly logs 'StopLoss (200 points) <= current spread = X points. Spread value will be used' whenever the guard triggers.

Exits run on three paths. The first is the InpSL/InpTP hard stops placed at open. The second is the CloseByTime routine, which counts completed bars between the position's open time and TimeCurrent via the BarsHold function (using CopyRates from open_time to TimeCurrent, returning the bar count) and force-closes anything that has held for InpDuration bars (default 10), regardless of P&L. The third is the close-on-signal path, where CheckCloseSignal watches four RSI(37) cross conditions across the 30/70 boundaries: bar-1 below 70 with bar-2 above 70 fires CLOSE_LONG, bar-1 below 30 with bar-2 above 30 fires CLOSE_LONG (momentum failure at the floor), bar-1 above 30 with bar-2 below 30 fires CLOSE_SHORT, and bar-1 above 70 with bar-2 below 70 fires CLOSE_SHORT. Any of those four cross-events while no entry signal is active will close the position.

Risk is sized at a fixed 0.1 lot per trade — there is no account-percent or volatility-based sizing. That makes the EA's risk per trade directly proportional to the SL distance: 200 points of SL on a 0.1 lot gold position. Three retry helpers (TryClose_EX16097, TryClosePartial_EX16097, TryModify_EX16097) are defined in the source with three-attempt loops and 100–200ms sleeps on requote/timeout/price-change return codes, but only TryClose_EX16097 is wired into the live close paths (CloseBySignal and CloseByTime). The partial-close and modify helpers are present in the codebase but never called from OnTick.

The session filter is hard-wired to 0–24h, so the EA trades every hour of the trading week. There is no built-in news filter, no daily circuit breaker, no trailing stop, and no breakeven ratchet. Position management is purely event-driven: hard SL, hard TP, RSI cross-close, and 10-bar time-exit.

In practice, EX16097 is built for the M5 gold session where Dark Cloud Cover and Piercing Line patterns print at higher frequency than on H1 — about 8–15% of trading days on XAUUSD M5 produce a qualifying two-bar reversal at a swing extreme. The MA(5) trend filter and the RSI(37) gate each cut roughly half of the raw pattern count, so the realistic trade frequency is in the range of 1–3 trades per day during active London and New York sessions. The 1:1 RR and 10-bar cap make the EA a short-horizon mean-reversion play, not a swing-position tool. Anyone running it should plan for clusters of small wins punctuated by occasional full-SL hits when the trend filter is wrong and the pattern fails to reverse.

Strategy Deep Dive

The OnTick handler is gated by a static next_bar_open timestamp so all pattern, confirmation, and close-signal evaluation happens only on a new bar. CheckPattern walks the geometry of Dark Cloud Cover and Piercing Line using bar data fetched through the local Open/Close/High/Low wrappers, with the bar-2 body compared against the 12-bar average body. CheckConfirmation reads RSI(37) at bar 1 and accepts the signal only if the gate is in the right half-band (below 40 for buy, above 60 for sell). CheckCloseSignal watches four RSI(37) cross conditions across 30/70 boundaries and queues a CLOSE_LONG/CLOSE_SHORT that fires on the next bar. TryClose_EX16097 (3 retries, 200ms sleep on requote/timeout/price-change) is wired into both close paths; TryClosePartial_EX16097 and TryModify_EX16097 are defined but never called from OnTick.

Entry Signal

A 2-candle reversal pattern (Dark Cloud Cover at swing highs or Piercing Line at swing lows) sets the directional bias — bar 2 must print a body larger than the 12-bar average body and bar 1 must gap to a new extreme (open above bar 2's high for DCC, open below bar 2's low for Piercing) and close back inside bar 2's body. The pattern is anchored by an SMA(5) trend test (bar 2 mid-price vs SMA(5) at bar 2) and confirmed by an RSI(37) gate — buy if RSI(1) < 40, sell if RSI(1) > 60. On new-bar open, a single market order is sent with 0.1 lot at the current Ask/Bid and 1:1 SL/TP at 200 points each.

Exit Signal

A position closes on one of three paths: the 200-point hard stop or 200-point hard target placed at open, a 10-bar time exit (CloseByTime calls BarsHold to count completed bars via CopyRates and force-closes when the count reaches InpDuration), or one of four RSI(37) close-cross conditions on the 30/70 boundaries (bar-1<70 with bar-2>70, bar-1<30 with bar-2>30, mirror for shorts). The 10-bar time cap is the dominant exit — most non-TP exits fire on the time expiry rather than on an RSI cross.

Stop Loss

Each order gets a 200-point hard stop at open via InpSL, with a spread guard that replaces the SL distance with the live spread if spread is at or above 200 points (logged as 'spread value will be used'). On XAUUSD at 0.1 fixed lot this is roughly $20 per contract, with no account-percent scaling.

Take Profit

Each order gets a 200-point hard target at open via InpTP, with the same spread-guard logic — if the live spread is at or above 200 points, the TP is set to Ask/Bid ± spread, not ± 200 points. This produces a strict 1:1 risk-to-reward on every trade by default, and the spread guard is the only mechanism that bends that ratio.

Best For

EX16097 is built for the XAUUSD M5 session during active London and New York hours, with a $100 minimum deposit at 0.1 fixed lot. The 1:1 RR, 10-bar time cap, and pure event-driven exits make it a short-horizon mean-reversion tool, not a swing-position EA, so the broker needs a tight spread on gold and a server with reliable requote handling for the 10pt-slippage market orders. Use a low-spread ECN or RAW-spread account — raw M5 gold spreads above 200 points will trigger the spread-guard fallback and erode the geometric stop.

Strategy Logic

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

Family: Trend Magic: 22216097 Version: 2.00

BRIEF: Detects Dark Cloud Cover / Piercing Line candlestick patterns, confirmed by RSI oscillator levels and trend MA, then enters with fixed SL/TP and time-based exit. 12 layers: REGIME, SIGNAL, ENTRY, CONFIRM, NO-TRADE, CAPITAL CAP, RISK, SIZING, MANAGE, EXIT, SCALING, OnTester

INDICATOR STACK:

  • Standard MT5 indicators

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 signal
  • SIGNAL_NOT = 0 // no trading signal
  • CLOSE_LONG = 2 // signal to close Long

INPUT PARAMETERS (11 total across 4 groups):

  • [=== Indicator Parameters ===] InpAverBodyPeriod = 12 // period for calculating average candlestick size
  • [=== Indicator Parameters ===] InpMAPeriod = 5 // Trend MA period
  • [=== Indicator Parameters ===] InpPeriodRSI = 37 // RSI period
  • [=== Indicator Parameters ===] InpPrice = 1 // Applied price (1=close,2=open,3=high,4=low,5=median,6=typical,7=weighted) // price 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 = 22216097 // Magic Number
  • [=== Identity ===] InpTradeComment = "Psgrowth.com Expert_16097" // Trade Comment
Pseudocode
// Pipsgrowth EX16097 Trend — Execution Flow (from source analysis)
// Family: Trend
// Detects Dark Cloud Cover / Piercing Line candlestick patterns, confirmed by RSI oscillator levels and trend MA, then enters with fixed SL/TP and time-based 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

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

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
InpAverBodyPeriod12period for calculating average candlestick size
InpMAPeriod5Trend MA period
InpPeriodRSI37RSI period
InpPrice1Applied price (1=close,2=open,3=high,4=low,5=median,6=typical,7=weighted) // price type
InpDuration10position holding time in bars
InpSL200Stop Loss in points
InpTP200Take Profit in points
InpSlippage10slippage in points
InpLot0.1lot
InpMagicNumber22216097Magic Number
InpTradeComment"Psgrowth.com Expert_16097"Trade Comment
Source Code (.mq5)Open Source
Pipsgrowth_com_EX16097.mq5
#property copyright "Pipsgrowth.com"
#property link      "https://pipsgrowth.com"
#property version   "2.00"
#property strict
#property description "Pipsgrowth.com EX16097 DarkCloud_PiercingLine_RSI — candlestick pattern + RSI confirmation, 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 parameters
ENUM_APPLIED_PRICE MapAppliedPriceInt(int ap)
{
   switch(ap)
   {
      case 1: return PRICE_CLOSE;
      case 2: return PRICE_OPEN;
      case 3: return PRICE_HIGH;
      case 4: return PRICE_LOW;
      case 5: return PRICE_MEDIAN;
      case 6: return PRICE_TYPICAL;
      case 7: return PRICE_WEIGHTED;
      default: return PRICE_CLOSE;
   }
}
ENUM_APPLIED_PRICE g_InpPrice = PRICE_CLOSE;
input group "=== Indicator Parameters ==="
input int InpAverBodyPeriod=12;     // period for calculating average candlestick size
input int InpMAPeriod      =5;      // Trend MA period
input int InpPeriodRSI     =37;     // RSI period
input int InpPrice = 1; // Applied price (1=close,2=open,3=high,4=low,5=median,6=typical,7=weighted)    // price type

ENUM_APPLIED_PRICE MapAppliedPriceInt(int ap)
{
   switch(ap)
   {
      case 1: return PRICE_CLOSE;
      case 2: return PRICE_OPEN;
      case 3: return PRICE_HIGH;
      case 4: return PRICE_LOW;
      case 5: return PRICE_MEDIAN;
      case 6: return PRICE_TYPICAL;
      case 7: return PRICE_WEIGHTED;
      default: return PRICE_CLOSE;
   }
}
ENUM_APPLIED_PRICE g_InpPrice = PRICE_CLOSE;
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
ENUM_APPLIED_PRICE MapAppliedPriceInt(int ap)
{

Full source code available on download

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

Tags:ex16097trendpipsgrowthfreemt5xauusd

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_EX16097.mq5
File Size29.3 KB
Versionv2.00
PlatformMetaTrader 5
File Type.mq5 Source
StrategyTrend Following
Risk LevelMedium Risk
Timeframes
M5H1
Currency Pairs
XAUUSD
Min. Deposit$100