P
PipsGrowth
Mean ReversionOpen Source – Free

Pipsgrowth EX09006 MeanReversion

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

Pipsgrowth.com EX09006 HangingManHammer CCI — candlestick reversal + CCI confirm, full 12-layer stack.

Overview

Pipsgrowth EX09006 is a candlestick-pattern mean-reversion EA. Rather than relying on moving-average crossovers or oscillator thresholds alone, the entire entry thesis is built around a single geometric bar shape — the Hammer for buy setups and its bearish twin the Hanging Man for sells — with a Commodity Channel Index confirmation standing in as the momentum filter. The pattern is detected on the most recent fully closed bar (shift = 1) using straightforward ohlc geometry, not pattern-recognition libraries. The bar's body has to sit inside the upper third of the range, and the lower wick has to be at least twice as long as the body and longer than the upper wick. The MAVal(1) gate then forces a context dependency: a Hammer is only valid when the closed bar's close is below the SMA(5) — i.e. the reversal is forming in a short-term dip, not after the trend has already turned. The Hanging Man mirror fires only when the close is above the SMA(5).

With the pattern shape verified, the EA looks at CCI(37) — a longer period than the typical 14, which means fewer signals and more weight on the most recent 37 closes. A buy requires CCI <= -100; a sell requires CCI >= 100. The further CCI sits past those thresholds, the higher the confidence score: 50 + |CCI - threshold| × 0.4, capped at 100. The score is logged but does not gate entries — the thresholds alone are the binary filter. The raw pattern direction (+1 buy, -1 sell, 0 none) is what propagates forward.

The regime classifier in ClassifyRegime() runs on every tick and bucketizes the market into one of seven states: STRONG_TREND, WEAK_TREND, RANGE, BREAKOUT, COMPRESS, EXPAND, or CHOPPY. The decision tree uses ADX(14), a Bollinger Bands width z-score (period 20, deviation 2.0, computed by hand over a 30-bar window), and an ATR(14) percentile rank (100-bar lookback). Mean reversion is only allowed in three of the seven states — RANGE, COMPRESS, and WEAK_TREND — which the source comment makes explicit: 'Block in StrongTrend/Breakout/Expand.' This is the single most consequential guardrail: it prevents the EA from fading trends it cannot win against.

Three confirmation checks must pass before a SendOrder call: HTF agreement, spread cap, and minimum R:R. The HTF filter pulls an EMA(50) on H1 and requires the signal bar's close to sit on the opposite side of it from the trade direction — a Hammer buy wants the close below the H1 EMA, meaning the higher timeframe is in a downtrend phase where a counter-trend bounce is more likely to be the start of a pullback, not the resumption of a move. The spread filter accepts the bar if current spread is below MAX_SPREAD_POINTS (35) or, if InpMaxSpreadOverAvg > 0, below three times a rolling average spread. R:R is enforced at MIN_RR_RATIO = 1.2, so even when a 1.67:1 nominal setup is in play (TP_ATR_MULT 3.0 / SL_ATR_MULT 1.8), the broker's stops-level can sometimes squeeze the actual R:R below the floor and block the trade.

SL and TP are ATR-driven: SL distance = ATR(14) of the closed bar × 1.8, TP distance = ATR(14) × 3.0, giving roughly 1.67:1. Lot sizing uses the standard risk formula in CalcLotByRisk(): riskMoney = effective_capital × InpRiskPercent / 100, divided by perLotRisk = slPriceDistance × tick_value / tick_size, then clamped to volume step / min / max and capped at InpMaxLots. With InpRiskPercent at 0.5 and a typical 200-point XAUUSD SL on M5, a $100 account is sized at the broker's minimum lot, which is why the recommended minimum deposit sits at $100 — anything below that and the position simply will not size up.

The management layer runs on every tick once a position is open. ManageOpenPosition() implements three independent exit mechanisms that can all fire. First, a one-shot break-even at 1R — when unrealized profit reaches 1× the original stop distance, the SL is moved to entry + 2 points and locked there, no further ratcheting. Second, a 50% partial close at 1R, which only fires if the remaining volume is at least twice the broker's minimum lot so the residual position stays tradeable. Third, an ATR(14) × 2.5 trailing stop with a 10-point step that only ever moves the stop in the favorable direction. The exit stack also includes an opposite-signal exit (Hanging Man while long, or Hammer while short), a 60-bar time stop on M5, and a hard regime-change close when the market flips into STRONG_TREND, BREAKOUT, or EXPAND — the mean-reversion thesis is considered invalidated in those states.

Capital and risk are gated by a stack of guards. The no-trade check evaluates: kill switch, broker trade mode, terminal connection, capital cap floor ($50 default), effective capital floor, server-time session (7:00–20:00), weekend block (Sun=0, Sat=6 in MQL day-of-week), spread cap, a ±30-minute news window around each hour boundary, regime permission, daily trade cap (5), 5-bar cooldown after the last loss, and the InpMaxConcurrent = 1 limit. Daily realized PnL is computed in RealizedPnLToday() from the deal history filtered by magic and symbol, and if it breaches -3% of effective capital, any open position is force-closed and new entries are blocked for the rest of the day. The weekly limit is 6% with the same mechanism.

The capital cap is the most under-appreciated input. InpCapitalCapAmount = 0 disables it (uses full equity); setting it to e.g. 5000 means the EA will never risk more than 0.5% of $5000 — useful for traders running multiple EAs on one account. The effective capital is recomputed on every tick in UpdateEffectiveCapital() as MathMin(cap, equity).

InpDryRun defaults to true. The EA will log '[DRYRUN] BUY lots=0.01 sl=... tp=... reason=SIGNAL' on every entry attempt and not place a real order until you flip this to false. This is a safe default for first-time deployment but a footgun for anyone who copies the EA onto a chart and walks away. InpKillSwitch is a one-click hard stop — when true, every entry is blocked and the reason printed is 'KILL_SWITCH.'

The OnTester() function returns a custom fitness of (net profit × profit factor) / (1 + drawdown%), with a minimum 30-trade floor. Zero trades, zero profit factor, or zero drawdown all return 0.0, so the optimizer is rewarded for net profitability, penalized for drawdown, and refuses to score under-sampled backtests. This is a quality-weighted criterion, not a net-profit-only one — a 2,000-trade sample with 1.3 PF and 12% DD will outrank a 50-trade sample with 3.0 PF and 4% DD in the optimizer's ranking.

TryClose_EX09006, TryClosePartial_EX09006, and TryModify_EX09006 each retry three times on REQUOTE / TIMEOUT / PRICE_OFF / PRICE_CHANGED with 200ms (or 100ms on modify) backoff, and the trade-send loop retries once on the same transient set with a 150ms sleep and a symbol refresh. The fills path is auto-detected via SetTypeFillingBySymbol in OnInit. The EA does not implement any MQL5 built-in news filter or any external feed — the ±30 minute news guard is a generic hour-boundary window that will fire even when no news is scheduled.

In a backtest, the EA's behavior on XAUUSD M5 should be characterized by low trade frequency — the pattern + CCI double filter is restrictive — and tight, fast winners. The partial-close at 1R typically resolves a third to half the position quickly when the bar bounces as expected; the trailing stop takes over from there. Losing trades usually exit on the opposite-signal rule or the 60-bar time stop rather than the original SL, which means the realized loss distribution is narrower than the SL would suggest, but the win rate is also lower than a typical trend-following EA. Run the Strategy Tester with 'Every tick based on real ticks' and tick-value confirmation for the lot sizing to match live behavior.

Strategy Deep Dive

Every tick the EA reclassifies the market into one of seven regimes (ADX 14, BB-width z, ATR 14 percentile) and blocks mean-reversion trades whenever the state is STRONG_TREND, BREAKOUT, EXPAND, or CHOPPY. On each new bar it inspects the last closed candle's geometry — body position, wick ratios — to identify a Hammer or Hanging Man shape, then reads CCI(37) and MA(5) close to require a context-aware momentum extreme. SL and TP are ATR(14) multiples (1.8× and 3.0×), lot size is risk-percent of effective capital, and the management loop chains break-even, partial TP, ATR trail, opposite-pattern exit, regime-flip exit, and a 60-bar time stop. The 0.5% risk with a 200-point XAUUSD M5 SL sizes a $100 account at the broker minimum lot, so the recommended minimum deposit is exactly that floor.

Entry Signal

Entries are triggered by a Hanging Man / Hammer candlestick pattern on the most recent fully closed bar (shift = 1) — body in the upper third of the range, lower wick ≥ 2× the body, and longer than the upper wick. The MA(5) gates the trade context (close below SMA = Hammer buy, close above SMA = Hanging Man sell), and CCI(37) confirms momentum with a ≤ -100 / ≥ +100 threshold. The seven-state regime classifier must be in RANGE, COMPRESS, or WEAK_TREND; STRONG_TREND, BREAKOUT, EXPAND, and CHOPPY block entries outright.

Exit Signal

Exits run on every tick via ManageOpenPosition and follow a four-path stack. A one-shot break-even at 1R moves the SL to entry + 2 points, a 50% partial close fires at 1R when remaining volume is at least 2× the broker minimum, an ATR(14) × 2.5 trailing stop with a 10-point step ratchets forward only, and a hard close fires on an opposite pattern signal or a regime flip into STRONG_TREND / BREAKOUT / EXPAND. A 60-bar time stop covers the rest.

Stop Loss

SL is set to ATR(14) of the closed bar × 1.8 below the entry on buys (above on sells), then snapped outward by RespectStops() to honor the broker's stops-level minimum. With a 200-point typical XAUUSD M5 ATR, the SL lands around 360 points. The break-even logic moves SL to entry + 2 points at 1R and freezes it there.

Take Profit

TP is set to ATR(14) × 3.0 above the entry on buys (below on sells), giving a nominal 1.67:1 R:R against the SL. A 50% partial close fires at 1R; the residual position runs under the ATR(14) × 2.5 trail. A 1.2 R:R minimum is enforced by ComputeConfirm, which can block the entry if the broker's stops-level squeezes the realized R:R below the floor.

Best For

Best on XAUUSD M5 for short-horizon reversal scalping where pattern frequency and ATR-based stops align cleanly; the H1 HTF filter means the higher-timeframe context matters more here than on the M1 ECN scalps. Recommended minimum balance is $100 — the 0.5% risk × 1.8 ATR SL × typical 200-point M5 ATR sizes a $100 account at the broker minimum lot, and any smaller account cannot reach a position. Use an ECN or low-spread account; the spread cap (35 points absolute or 3× rolling average) is the single most likely rejection reason on XAUUSD during the London/New York overlap when spreads widen on news.

Strategy Logic

Pipsgrowth EX09006 MeanReversion — Strategy Logic Analysis (from .mq5 source)

Family: MeanReversion Magic: 22209006 Version: 2.00

BRIEF: Hanging Man (bearish) / Hammer (bullish) candlestick on last CLOSED bar + CCI confirmation (CCI<-100 Buy / CCI>+100 Sell). 12 layers: REGIME, SIGNAL, ENTRY, CONFIRM, NO-TRADE, CAPITAL CAP, RISK, SIZING, MANAGE, EXIT, SCALING, OnTester

INDICATOR STACK:

  • Standard MT5 indicators

KEY FUNCTIONS:

  • Norm()
  • ClampVolume()
  • PointsToPrice()
  • StopsLevelPrice()
  • CopyBuf()
  • CCIVal()
  • MAVal()
  • ATRVal()
  • ADXVal()
  • HTFEMAVal()
  • GetBBWidthZ()
  • GetATRPctile()
  • ...and 28 more

INTERNAL CONSTANTS (36 total):

  • ATR_REG_PERIOD = 14 // ATR period for regime
  • ATR_PCTILE_LOOKBACK = 100 // ATR percentile window
  • BB_REG_PERIOD = 20 // Bollinger Band period (regime)
  • BB_REG_DEV = 2.0 // Bollinger Band deviation
  • ADX_REG_PERIOD = 14 // ADX period (regime)
  • HTF_TREND_PERIOD = 50 // HTF EMA period
  • HTF_TIMEFRAME = PERIOD_H1 // HTF timeframe for trend agreement
  • AVG_BODY_PERIOD = 12 // candle avg body period (pattern)
  • MA_TREND_PERIOD = 5 // short SMA for pattern trend context
  • CCI_PERIOD_DEFAULT = 37 // CCI oscillator period (default)
  • CCI_APPLIED_PRICE = PRICE_CLOSE // CCI applied price
  • REG_STRONG_ADX = 28 // ADX >= this => StrongTrend
  • REG_RANGE_ADX = 20 // ADX <= this => range-ish
  • REG_COMP_BBZ = 0.8 // BB-width zscore <= => Compress
  • REG_EXP_BBZ = 1.5 // BB-width zscore >= => Expand
  • ...and 21 more

INPUT PARAMETERS (21 total across 7 groups):

  • [=== Identity ===] InpMagic = 22209006 // Magic number (unique per EA)
  • [=== Identity ===] InpTradeComment = "Psgrowth.com Expert_09006" // Trade comment
  • [=== Risk & Sizing ===] InpRiskPercent = 0.5 // Risk per trade, % of effective capital
  • [=== Risk & Sizing ===] InpDailyLossLimitPct = 3.0 // Daily loss limit, % of effective capital
  • [=== Risk & Sizing ===] InpWeeklyLossLimitPct = 6.0 // Weekly loss limit, % of effective capital
  • [=== Risk & Sizing ===] InpMaxLots = 5.0 // Hard cap on lot size per trade
  • [=== Risk & Sizing ===] InpMaxConcurrent = 1 // Max concurrent positions (this symbol/magic)
  • [=== Risk & Sizing ===] InpSlippagePoints = 20 // Max slippage in points
  • [=== Capital Allocation Cap ===] InpCapitalCapAmount = 0.0 // Cap amount in REAL equity $
  • [=== Capital Allocation Cap ===] InpCapitalCapFloor = 50.0 // Floor below which entries are blocked
  • [=== Signal (Pattern + CCI) ===] InpCCIPeriod = 37 // CCI oscillator period
  • [=== Signal (Pattern + CCI) ===] InpCCIBuyMax = -100.0 // CCI must be <= this to confirm Hammer (Buy)
  • [=== Signal (Pattern + CCI) ===] InpCCISellMin = 100.0 // CCI must be >= this to confirm HangMan (Sell)
  • [=== Regime / Confirm ===] InpHTFBarAgree = 1 // 1=require HTF-EMA side agreement, 0=skip
  • [=== Regime / Confirm ===] InpMaxSpreadOverAvg = 3 // Max spread multiple over rolling avg (x), 0=off
  • [=== Exit / Manage ===] InpUseBreakEven = true // Enable break-even at BE_TRIGGER_R
  • [=== Exit / Manage ===] InpUsePartialTP = true // Enable partial TP at PARTIAL_TP_R
  • [=== Exit / Manage ===] InpUseATRTrail = true // Enable ATR trailing stop
  • [=== Exit / Manage ===] InpExitOnOppSignal = true // Exit on opposite candlestick pattern
  • [=== Dry-Run / Kill Switch ===] InpDryRun = true // Dry-run mode (no live orders)
  • [=== Dry-Run / Kill Switch ===] InpKillSwitch = false // Emergency kill switch (block all trading)
Pseudocode
// Pipsgrowth EX09006 MeanReversion — Execution Flow (from source analysis)
// Family: MeanReversion
// Hanging Man (bearish) / Hammer (bullish) candlestick on last CLOSED bar + CCI confirmation (CCI<-100 Buy / CCI>+100 Sell). 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 H1 or H4 chart
  7. 7Set Bollinger Band period, deviation, RSI levels, and lot size
  8. 8Enable Allow Algo Trading and click OK

EA Parameters

ParameterDefaultDescription
InpMagic22209006Magic number (unique per EA)
InpTradeComment"Psgrowth.com Expert_09006"Trade comment
InpRiskPercent0.5Risk per trade, % of effective capital
InpDailyLossLimitPct3.0Daily loss limit, % of effective capital
InpWeeklyLossLimitPct6.0Weekly loss limit, % of effective capital
InpMaxLots5.0Hard cap on lot size per trade
InpMaxConcurrent1Max concurrent positions (this symbol/magic)
InpSlippagePoints20Max slippage in points
InpCapitalCapAmount0.0Cap amount in REAL equity $
InpCapitalCapFloor50.0Floor below which entries are blocked
InpCCIPeriod37CCI oscillator period
InpCCIBuyMax-100.0CCI must be <= this to confirm Hammer (Buy)
InpCCISellMin100.0CCI must be >= this to confirm HangMan (Sell)
InpHTFBarAgree11=require HTF-EMA side agreement, 0=skip
InpMaxSpreadOverAvg3Max spread multiple over rolling avg (x), 0=off
InpUseBreakEventrueEnable break-even at BE_TRIGGER_R
InpUsePartialTPtrueEnable partial TP at PARTIAL_TP_R
InpUseATRTrailtrueEnable ATR trailing stop
InpExitOnOppSignaltrueExit on opposite candlestick pattern
InpDryRuntrueDry-run mode (no live orders)
InpKillSwitchfalseEmergency kill switch (block all trading)
Source Code (.mq5)Open Source
Pipsgrowth_com_EX09006.mq5
#property copyright "Pipsgrowth.com"
#property link      "https://pipsgrowth.com"
#property version   "2.00"
#property strict
#property description "Pipsgrowth.com EX09006 HangingManHammer CCI — candlestick reversal + CCI confirm, full 12-layer stack."

#include <Trade\Trade.mqh>
#include <Trade\PositionInfo.mqh>
#include <Trade\SymbolInfo.mqh>
#include <Trade\AccountInfo.mqh>
#include <Trade\OrderInfo.mqh>
#include <Trade\DealInfo.mqh>

//================== TUNABLE CONSTANTS (NOT inputs) =================
#define ATR_REG_PERIOD        14              // ATR period for regime
#define ATR_PCTILE_LOOKBACK   100             // ATR percentile window
#define BB_REG_PERIOD         20              // Bollinger Band period (regime)
#define BB_REG_DEV            2.0             // Bollinger Band deviation
#define ADX_REG_PERIOD        14              // ADX period (regime)
#define HTF_TREND_PERIOD      50              // HTF EMA period
#define HTF_TIMEFRAME         PERIOD_H1       // HTF timeframe for trend agreement
#define AVG_BODY_PERIOD       12              // candle avg body period (pattern)
#define MA_TREND_PERIOD       5               // short SMA for pattern trend context
#define CCI_PERIOD_DEFAULT    37              // CCI oscillator period (default)
#define CCI_APPLIED_PRICE     PRICE_CLOSE     // CCI applied price
#define REG_STRONG_ADX        28               // ADX >= this => StrongTrend
#define REG_RANGE_ADX         20               // ADX <= this => range-ish
#define REG_COMP_BBZ          0.8              // BB-width zscore <= => Compress
#define REG_EXP_BBZ           1.5              // BB-width zscore >= => Expand
#define ATR_PCTILE_STRONG     80               // ATR percentile >= => high vol
#define ATR_PCTILE_LOW        20               // ATR percentile <= => low vol
#define SL_ATR_MULT           1.8              // SL = ATR(closed bar) * mult
#define TP_ATR_MULT           3.0              // TP = ATR(closed bar) * mult
#define TRAIL_ATR_MULT        2.5              // ATR trailing distance
#define TRAIL_STEP_POINTS     10               // trail step (points)
#define BE_TRIGGER_R          1.0              // break-even trigger at 1.0R
#define PARTIAL_TP_R          1.0              // partial TP at 1.0R
#define PARTIAL_FRACTION      0.5              // partial close 50%
#define MAX_BARS_IN_TRADE     60               // time-based exit (bars)
#define MAX_SPREAD_POINTS     35               // spread cap (points)
#define MAX_DAILY_TRADES      5                // max entries per day
#define COOLDOWN_BARS_AFTER_LOSS 5            // cooldown after loss
#define MIN_RR_RATIO          1.2              // min reward:risk
#define SESSION_START_HOUR    7                // server-time session start
#define SESSION_END_HOUR      20               // server-time session end
#define NEWS_WINDOW_MIN       30               // manual news window (min around HH:00)
#define PYRAMID_MAX_LEVELS    5                // pyramid hard cap
#define PYRAMID_ATR_SPACING   1.5              // pyramid ATR spacing
#define PORTFOLIO_HEAT_CAP    0.06             // max portfolio heat 6%
#define MAX_TRADE_RETRIES     1                // trade-send retry on transient
#define INP_VERSION_TAG       "v2.00 MeanRev HangHam/CCI"  // version tag (log only)

//================== INPUTS (18 total) ==============================
input group "=== Identity ==="
input long   InpMagic           = 22209006;                       // Magic number (unique per EA)
input string InpTradeComment    = "Psgrowth.com Expert_09006";    // Trade comment

input group "=== Risk & Sizing ==="
input double InpRiskPercent       = 0.5;    // Risk per trade, % of effective capital
input double InpDailyLossLimitPct = 3.0;    // Daily loss limit, % of effective capital

Full source code available on download

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

Tags:ex09006meanreversionpipsgrowthfreemt5xauusd

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_EX09006.mq5
File Size38.3 KB
Versionv2.00
PlatformMetaTrader 5
File Type.mq5 Source
StrategyMean Reversion
Risk LevelMedium Risk
Timeframes
M5H1
Currency Pairs
XAUUSD
Min. Deposit$100