P
PipsGrowth
OtherOpen Source – Free

Pipsgrowth EX04005 HAEA

MT5 Expert Advisor (Open Source) · XAUUSD · M1

Pipsgrowth.com EX04005 EA_candles — candlestick pattern recognition with multi-TF confirmation, full 12-layer stack.

Overview

Pipsgrowth EX04005 is a pure candlestick pattern recognizer, written in MQL5 for MT5 and designed to run on XAUUSD at the one-minute bar. Unlike the rest of the HAEA family, which leans on Heiken Ashi smoothing or alligator-style moving-average structure, this EA does the opposite: it strips everything back to the raw open-high-low-close tape and asks one question on every closed bar — does the shape of this candle, or the relationship between this candle and the previous one, look like a reversal pattern from classical Japanese candlestick analysis? If the answer is yes, the EA then asks a second question on a higher timeframe — is the prevailing trend alignment agreeing with the direction of the pattern? Only when both conditions hold does the EA open a market order.

The recognition layer exposes four toggleable patterns, all of which are enabled by default. The UseDoji flag arms the simplest of the four: any bar where the absolute body size is less than twenty percent of the total range (a relaxed threshold — the comment in the source notes this was widened from ten percent to capture more setups, at the cost of admitting more marginal indecision bars). The UseHammer flag looks for a bar whose lower wick is more than twice the body and whose upper wick is shorter than the body — a textbook hammer at a swing low, or a shooting star at a swing high. The UseEngulfing flag activates two complementary checks: a bullish engulfing when the current bar's body fully covers the prior bearish bar (current close above prior open, current open below prior close), and a bearish engulfing as the mirror. The UseHarami flag adds the inside-bar reversal: a bullish harami when the prior bar is bearish and the current bullish bar sits entirely within the prior body's range, and the bearish counterpart as the mirror. Each pattern has its own detection function — IsDoji, IsHammer, IsBullishEngulfing, IsBearishEngulfing, IsBullishHarami, IsBearishHarami — and the main ProcessTradingLogic walks them in priority order on the most recent closed one-minute bar.

The Timeframe1 and Timeframe2 inputs let the user pick which MT5 timeframes drive the two stages. By default, the EA inspects one-minute bars (Timeframe1=1) for the raw pattern and confirms on a five-minute chart (Timeframe2=4, mapping to M5 via the MapTimeframeInt switch). The confirm step is intentionally lightweight: it pulls the last closed value of two exponential moving averages on the higher timeframe — a fast EMA(10) and a slow EMA(20), both on close — and requires that the fast EMA sit above the slow EMA for any of the bullish pattern families (Hammer, Bullish Engulfing, Bullish Harami) and below it for the bearish families (Bearish Engulfing, Bearish Harami). A Doji signal falls through to a default true at the end of ConfirmOnHigherTimeframe, which means a doji on the primary timeframe never actually reaches the order path — Doji is registered as a signal name but is not handled by the buy or sell branch of ExecuteTrade, so it is effectively a no-trade detection rather than a tradable setup despite the input flag.

Position sizing has two paths. With UseAutoLotSize=false (the default), the EA simply sends TradeVolume=0.01 on every entry — a flat micro-lot suitable for testing on small accounts. With UseAutoLotSize=true, the EA calls CalculateLotSize, which multiplies the effective capital by RiskPercent=2.0% and divides by the margin required for one full lot at the current ask, then floors the result to the symbol's volume step, clamps it to the broker's min and max lot, and applies a hard ceiling of MaxLotSize=1.0 lots. GetEffectiveCapital honors InpCapitalCapAmount: when the cap is set to a non-zero value, the effective capital is the lesser of the cap and the current equity, so traders can pre-commit a fixed risk envelope to this EA and let the rest of the account stay untouched.

Each entry carries a fixed stop of StopLoss=50 points and a fixed take-profit of TakeProfit=75 points — a 1:1.5 reward-to-risk ratio, modest by trend-follower standards but reasonable for mean-reversion pattern setups where the goal is to capture a small corrective move rather than ride a sustained leg. The stops and targets are passed through Trade.Buy and Trade.Sell on every fill, with a margin check via OrderCalcMargin before the request is dispatched, three retries at 150-millisecond intervals on REQUOTE, TIMEOUT, PRICE_OFF, and PRICE_CHANGED, and Trade.SetDeviationInPoints(Slippage=3) to absorb minor slippage. The filling mode is auto-selected per symbol from FOK to IOC to RETURN.

Trailing stop management is optional and disabled by default. When the user toggles UseTrailingStop=true, the ManageTrailingStop function walks the open positions on every tick: for a long position, it sets a candidate new stop at the current bid minus TrailingStop=30 points and only modifies the order when the candidate is at least TrailingStep=10 points above the existing stop, preventing micro-adjustments. The mirror logic handles shorts using the ask. Because the trailing logic lives outside the bar cycle, a position can be tightened intra-bar even when no new pattern is detected, which is the right behavior for a fast-moving instrument like gold.

The risk scaffolding around the entry path is dense. IsTradeAllowed checks the live spread against MaxSpread=30 points and refuses to operate if the broker widens beyond that ceiling, which matters a lot on a one-minute bar where spreads on gold routinely burst during news. IsSafeToTrade adds a capital-floor guard at InpCapitalCapFloor=50 dollars, an equity-floor guard at InpMinEquityPercent=95% of the initial balance, a daily loss limit at InpDailyLossLimitPct=3% of effective capital, a weekly loss limit at InpWeeklyLossLimitPct=6%, a hard cap on InpMaxTradesPerDay=50, and a consecutive-losses cooldown that engages after InpMaxConsecLosses=3 losses for InpCooldownMinutes=30. The OnTradeTransaction handler updates g_realizedToday, g_realizedWeek, g_tradesToday, and g_consecLosses on every closing deal tagged with this EA's magic number, and rotates the daily counters at the first tick of a new server day.

Session control is the usual London-plus-New-York window translated to GMT. InActiveSession accepts signals when the GMT hour falls inside London (7 to 16) or New York (12 to 21), with InpAvoidAsia=true as the default — the EA will reject any bar whose only session overlap is the Asian window (0 to 7 GMT), which is the right call for a pattern EA that wants liquidity at the open of London or the overlap with New York. InpNewsFilter is off by default, but when turned on it skips bars within InpNewsFilterMinutes=15 of the London or New York session open. IsMarketOpen blocks the weekend gap using the universal Friday-22 and Sunday-22 GMT rules. DetectGMTOffset infers the server's GMT offset from the Monday opening gap on the H1 chart and falls back to zero if the auto-detection cannot lock on.

Because the EA runs on a one-minute bar, throughput is high — pattern detections are cheap, but the per-bar ProcessTradingLogic only runs on a new bar, not on every tick, so the CPU footprint stays modest. In backtesting, the EA's OnTester returns (net * profitFactor) / (1 + balance-DD-percent), gated on at least 30 trades; that formula rewards both raw profit and consistency, with the drawdown term in the denominator penalizing strategies that only make money by taking large risks. On a fast ECN or raw-spread account with reliable gold liquidity, a $100 deposit is enough to run the default micro-lot configuration; users who flip on auto-lotting should treat the 2% risk input as a per-trade ceiling rather than a target, and size up only after observing the backtest drawdown on a multi-month XAUUSD sample.

Strategy Deep Dive

On every new one-minute bar, the EA pulls the last ten closed candles on the primary timeframe and the last ten on the confirmation timeframe via CopyRates, then walks the four toggleable pattern checks in priority order. A directional pattern that passes the EMA(10)/EMA(20) cross-check on the higher timeframe routes through ExecuteTrade, which performs an OrderCalcMargin pre-check, dispatches Trade.Buy or Trade.Sell with the fixed 50-point stop and 75-point target, and retries the order up to three times at 150-millisecond intervals on REQUOTE, TIMEOUT, PRICE_OFF, and PRICE_CHANGED. Independent of the bar cycle, ManageTrailingStop runs on every tick when armed to ratchet open positions forward, and OnTradeTransaction updates the daily P&L, weekly P&L, trade count, and consecutive-loss counter for the safety gates in IsSafeToTrade and IsTradeAllowed — the same gates that filter out weekend bars, off-session hours, and news windows before any pattern is even considered.

Entry Signal

The EA scans the most recent closed one-minute bar for one of four classical Japanese candlestick reversal patterns: Doji (body less than 20% of total range), Hammer (lower wick greater than 2× the body with a short upper wick), Bullish Engulfing (current bullish body fully covering the prior bearish bar), Bearish Engulfing (mirror), Bullish Harami (current bullish bar sitting inside the prior bearish body), and Bearish Harami (mirror). When a directional pattern is detected, the EA confirms it on the higher timeframe (default M5) by checking whether the fast EMA(10) is above the slow EMA(20) for bullish setups or below it for bearish setups, and only then opens a market order with the configured stop and target.

Exit Signal

There is no explicit signal-based exit; positions run until the per-trade take-profit at 75 points is hit, the per-trade stop-loss at 50 points is hit, or an optional trailing stop kicks in. When UseTrailingStop=true, the EA on every tick ratchets the stop forward for longs by 30 points behind the current bid and only fires a modification when the new stop is at least 10 points beyond the existing one, with the mirror logic on shorts using the ask.

Stop Loss

Per-trade stop-loss is a fixed 50 points set on entry via Trade.Buy / Trade.Sell and applied in both directions, with an optional ratcheting trailing stop of 30 points behind price that steps forward by 10 points minimum when enabled. A global drawdown ceiling sits at InpMinEquityPercent=95% of the initial balance: if equity falls below that line, the EA stops opening new positions until the equity recovers.

Take Profit

Per-trade take-profit is a fixed 75 points set on entry, giving a 1:1.5 reward-to-risk ratio against the 50-point stop. There is no basket target, no partial close, and no break-even step in the source — the EA leaves each position to run to its configured TP or SL.

Best For

This EA is built for traders who want a rules-based, pattern-driven entry on a tight timeframe with a small per-trade risk envelope, on a low-spread ECN or raw-spread account with reliable gold liquidity. The default $100 minimum deposit and 0.01-lot micro configuration make it accessible for testing on a cent account, but auto-lot users should expect margin headroom of roughly 50–100× the per-trade risk input because XAUUSD margin requirements are substantial at the one-minute bar. The active window is the London session (7–16 GMT) and the New York session (12–21 GMT), with Asian hours blocked by default — a typical day sees the EA fire only during the London open and the London–New York overlap, with the rest of the day spent holding or flat.

Strategy Logic

Pipsgrowth EX04005 HAEA — Strategy Logic Analysis (from .mq5 source)

Family: HAEA Magic: 22204005 Version: 2.00

BRIEF: Candlestick pattern recognition EA that detects Doji, Hammer, Engulfing, and Harami patterns on the primary timeframe and confirms with EMA trend alignment on a higher timeframe. Includes auto lot sizing, trailing stop, and spread filter

INDICATOR STACK:

  • Standard MT5 indicators

KEY FUNCTIONS:

  • IsNewBar()
  • ProcessTradingLogic()
  • IsDoji()
  • IsHammer()
  • IsBullishEngulfing()
  • IsBearishEngulfing()
  • IsBullishHarami()
  • IsBearishHarami()
  • ConfirmOnHigherTimeframe()
  • ExecuteTrade()
  • CalculateLotSize()
  • GetEffectiveCapital()
  • ...and 10 more

INTERNAL CONSTANTS (0 total):

INPUT PARAMETERS (39 total across 10 groups):

  • [=== Identity ===] MagicNumber = 22204005 // Magic Number
  • [=== Identity ===] InpTradeComment = "Psgrowth.com Expert_04005" // Trade Comment
  • [=== Strategy ===] Symbol_Name = "XAUUSD" // Trading symbol (Gold)
  • [=== Strategy ===] Timeframe1 = 1 // Timeframe (1=M1,2=M5,3=M15,4=M30,5=H1,6=H4,7=D1) // Primary timeframe (1m)
  • [=== Strategy ===] Timeframe2 = 4 // Timeframe (1=M1,2=M5,3=M15,4=M30,5=H1,6=H4,7=D1) // Confirmation timeframe (5m)
  • [=== Risk Management ===] TradeVolume = 0.01 // Fixed trade size (lot)
  • [=== Risk Management ===] UseAutoLotSize = false // Calculate lot size automatically based on balance
  • [=== Risk Management ===] RiskPercent = 2.0 // Risk percentage per trade (for auto lot)
  • [=== Risk Management ===] MaxLotSize = 1.0 // Maximum allowed lot size
  • [=== Risk Management ===] StopLoss = 50 // Stop Loss (points)
  • [=== Risk Management ===] TakeProfit = 75 // Take Profit (points)
  • [=== Trade Settings ===] Slippage = 3 // Acceptable slippage (points)
  • [=== Trade Settings ===] MaxSpread = 30 // Maximum acceptable spread (points)
  • [=== Trailing Stop ===] UseTrailingStop = false // Use trailing stop
  • [=== Trailing Stop ===] TrailingStop = 30 // Trailing stop distance (points)
  • [=== Trailing Stop ===] TrailingStep = 10 // Trailing step distance (points)
  • [=== Pattern Detection ===] UseDoji = true // Enable Doji pattern
  • [=== Pattern Detection ===] UseHammer = true // Enable Hammer pattern
  • [=== Pattern Detection ===] UseEngulfing = true // Enable Engulfing pattern
  • [=== Pattern Detection ===] UseHarami = true // Enable Harami pattern
  • [=== Logging ===] EnableLogging = true // Enable logging
  • [=== Hardening: Risk Management ===] InpMaxConsecLosses = 3 // Max consecutive losses before cooldown (0=disabled)
  • [=== Hardening: Risk Management ===] InpCooldownMinutes = 30 // Cooldown minutes after consec losses (0=disabled)
  • [=== Hardening: Risk Management ===] InpMaxTradesPerDay = 50 // Maximum trades per day
  • [=== Hardening: Risk Management ===] InpMinEquityPercent = 95.0 // Stop trading if equity falls below this % of initial balance
  • [=== Hardening: Risk Management ===] InpDailyLossLimitPct = 3.0 // Daily loss limit (% of effective capital)
  • [=== Hardening: Risk Management ===] InpWeeklyLossLimitPct = 6.0 // Weekly loss limit (% of effective capital)
  • [=== Hardening: Capital Allocation Cap ===] InpCapitalCapAmount = 0.0 // Cap amount ($ real money equity)
  • [=== Hardening: Capital Allocation Cap ===] InpCapitalCapFloor = 50.0 // Floor ($); block entries below this
  • [=== Hardening: GMT Sessions ===] InpServerGMTOffset = 0 // Server GMT offset in hours (0=auto-detect via weekend gap)
  • [=== Hardening: GMT Sessions ===] InpLondonStartHour = 7 // London session start (GMT)
  • [=== Hardening: GMT Sessions ===] InpLondonEndHour = 16 // London session end (GMT)
  • [=== Hardening: GMT Sessions ===] InpNYStartHour = 12 // New York session start (GMT)
  • [=== Hardening: GMT Sessions ===] InpNYEndHour = 21 // New York session end (GMT)
  • [=== Hardening: GMT Sessions ===] InpAvoidAsia = true // Avoid Asian session
  • [=== Hardening: GMT Sessions ===] InpAsiaStartHour = 0 // Asian session start (GMT)
  • [=== Hardening: GMT Sessions ===] InpAsiaEndHour = 7 // Asian session end (GMT)
  • [=== Hardening: GMT Sessions ===] InpNewsFilter = false // Avoid trading near news session opens
  • [=== Hardening: GMT Sessions ===] InpNewsFilterMinutes = 15 // Minutes to avoid around news
Pseudocode
// Pipsgrowth EX04005 HAEA — Execution Flow (from source analysis)
// Family: HAEA
// Candlestick pattern recognition EA that detects Doji, Hammer, Engulfing, and Harami patterns on the primary timeframe and confirms with EMA trend alignment on a higher timeframe. Includes auto lot sizing, trailing stop, and spread filter

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:
M1

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 a chart matching the recommended timeframe
  7. 7Configure parameters according to the table on this page
  8. 8Enable Allow Algo Trading and click OK

EA Parameters

ParameterDefaultDescription
MagicNumber22204005Magic Number
InpTradeComment"Psgrowth.com Expert_04005"Trade Comment
Symbol_Name"XAUUSD"Trading symbol (Gold)
Timeframe11Timeframe (1=M1,2=M5,3=M15,4=M30,5=H1,6=H4,7=D1) // Primary timeframe (1m)
Timeframe24Timeframe (1=M1,2=M5,3=M15,4=M30,5=H1,6=H4,7=D1) // Confirmation timeframe (5m)
TradeVolume0.01Fixed trade size (lot)
UseAutoLotSizefalseCalculate lot size automatically based on balance
RiskPercent2.0Risk percentage per trade (for auto lot)
MaxLotSize1.0Maximum allowed lot size
StopLoss50Stop Loss (points)
TakeProfit75Take Profit (points)
Slippage3Acceptable slippage (points)
MaxSpread30Maximum acceptable spread (points)
UseTrailingStopfalseUse trailing stop
TrailingStop30Trailing stop distance (points)
TrailingStep10Trailing step distance (points)
UseDojitrueEnable Doji pattern
UseHammertrueEnable Hammer pattern
UseEngulfingtrueEnable Engulfing pattern
UseHaramitrueEnable Harami pattern
EnableLoggingtrueEnable logging
InpMaxConsecLosses3Max consecutive losses before cooldown (0=disabled)
InpCooldownMinutes30Cooldown minutes after consec losses (0=disabled)
InpMaxTradesPerDay50Maximum trades per day
InpMinEquityPercent95.0Stop trading if equity falls below this % of initial balance
InpDailyLossLimitPct3.0Daily loss limit (% of effective capital)
InpWeeklyLossLimitPct6.0Weekly loss limit (% of effective capital)
InpCapitalCapAmount0.0Cap amount ($ real money equity)
InpCapitalCapFloor50.0Floor ($); block entries below this
InpServerGMTOffset0Server GMT offset in hours (0=auto-detect via weekend gap)
InpLondonStartHour7London session start (GMT)
InpLondonEndHour16London session end (GMT)
InpNYStartHour12New York session start (GMT)
InpNYEndHour21New York session end (GMT)
InpAvoidAsiatrueAvoid Asian session
InpAsiaStartHour0Asian session start (GMT)
InpAsiaEndHour7Asian session end (GMT)
InpNewsFilterfalseAvoid trading near news session opens
InpNewsFilterMinutes15Minutes to avoid around news
Source Code (.mq5)Open Source
Pipsgrowth_com_EX04005.mq5
#property copyright "Pipsgrowth.com"
#property link      "https://pipsgrowth.com"
#property version   "2.00"
#property strict
#property description "Pipsgrowth.com EX04005 EA_candles — candlestick pattern recognition with multi-TF confirmation, full 12-layer stack."

#include <Trade/Trade.mqh>
#include <Trade/PositionInfo.mqh>

// CTrade class for opening/closing orders
CTrade         Trade;
CPositionInfo  PositionInfo;

// Input Parameters
ENUM_TIMEFRAMES MapTimeframeInt(int tf)
{
   switch(tf)
   {
      case 1: return PERIOD_M1;
      case 2: return PERIOD_M5;
      case 3: return PERIOD_M15;
      case 4: return PERIOD_M30;
      case 5: return PERIOD_H1;
      case 6: return PERIOD_H4;
      case 7: return PERIOD_D1;
      default: return PERIOD_H1;
   }
}
ENUM_TIMEFRAMES g_Timeframe1 = PERIOD_H1;
ENUM_TIMEFRAMES g_Timeframe2 = PERIOD_H1;
input group "=== Identity ==="
input int      MagicNumber = 22204005;      // Magic Number
input string   InpTradeComment = "Psgrowth.com Expert_04005"; // Trade Comment

ENUM_TIMEFRAMES MapTimeframeInt(int tf)
{
   switch(tf)
   {
      case 1: return PERIOD_M1;
      case 2: return PERIOD_M5;
      case 3: return PERIOD_M15;
      case 4: return PERIOD_M30;
      case 5: return PERIOD_H1;
      case 6: return PERIOD_H4;
      case 7: return PERIOD_D1;
      default: return PERIOD_H1;
   }
}
ENUM_TIMEFRAMES g_Timeframe1 = PERIOD_H1;
ENUM_TIMEFRAMES g_Timeframe2 = PERIOD_H1;
input group "=== Strategy ==="
input string   Symbol_Name = "XAUUSD";     // Trading symbol (Gold)
input int Timeframe1 = 1; // Timeframe (1=M1,2=M5,3=M15,4=M30,5=H1,6=H4,7=D1) // Primary timeframe (1m)
input int Timeframe2 = 4; // Timeframe (1=M1,2=M5,3=M15,4=M30,5=H1,6=H4,7=D1) // Confirmation timeframe (5m)

ENUM_TIMEFRAMES MapTimeframeInt(int tf)
{
   switch(tf)
   {
      case 1: return PERIOD_M1;

Full source code available on download

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

Tags:ex04005haeapipsgrowthfreemt5xauusd

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_EX04005.mq5
File Size31.5 KB
Versionv2.00
PlatformMetaTrader 5
File Type.mq5 Source
StrategyOther
Risk LevelMedium Risk
Timeframes
M1
Currency Pairs
XAUUSD
Min. Deposit$100