Pipsgrowth EX04004 HAEA
MT5 Expert Advisor (Open Source) · XAUUSD · M5
Pipsgrowth.com EX04004 HASmoothed_XAUUSD_5M — smoothed Heiken Ashi + EMA trend EA, full 12-layer stack.
Overview
Pipsgrowth EX04004 HAEA is a bar-by-bar trend-following EA for XAUUSD on the 5-minute chart. It looks for two things to line up on the same closed bar: a clean Heiken Ashi candle color and price sitting on the correct side of a slow exponential moving average. When both confirm in the same direction, the EA fires one market order and steps out of the market until that position is closed. There is no scaling in, no martingale, no re-entry on the next tick — the next decision waits for the next bar.
The signal is built from raw OHLC, not from a custom indicator. On every new bar the EA pulls the open, high, low, and close of the just-closed bar (index 1) plus the open and close of the bar before that (index 2). It then computes two smoothed Heiken Ashi values inline: haOpen = (open[2] + close[2]) / 2 and haClose = (open[1] + high[1] + low[1] + close[1]) / 4. A green HA candle is haClose > haOpen; a red HA candle is haClose < haOpen. That colour is the momentum vote. A 200-period exponential moving average on close prices, requested via a single iMA handle during OnInit, supplies the trend vote. A long entry needs a green HA bar with the actual close of bar 1 sitting above the EMA; a short entry needs a red HA bar with the close below the EMA. The bar's true close is the price being compared — not the smoothed HA close — so the trend filter is anchored to the real market, not to the smoothed candle.
Risk is sized off the stop loss, not off a fixed lot. CalculateLotSize() divides the effective capital by the configured InpRiskPercent (default 1.0%) and translates that dollar risk into a lot count using the symbol's tick value, tick size, and point. The result is floored to the symbol's lot step and clamped to the broker's minimum and maximum lot. If the trader sets InpRiskPercent to 0, the EA falls back to InpFixedLot (0.01). Effective capital is normally the account equity; if InpCapitalCapAmount is non-zero, the EA sizes off the smaller of equity and that cap, which lets a user pre-commit a fixed dollar amount to the strategy. Before any order is sent, OrderCalcMargin checks that the required margin fits inside free margin; if it does not, the order is dropped silently.
The stop loss is 400 points and the take profit is 800 points — a fixed 1:2 reward-to-risk ratio. The EA does not move the stop to break-even, does not trail it, and does not take partial closes. The TryClose, TryClosePartial, and TryModify helpers in the source wrap trade.PositionClose, trade.PositionClosePartial, and trade.PositionModify with three retries spaced 200ms apart on REQUOTE, TIMEOUT, PRICE_OFF, and PRICE_CHANGED return codes, but those helpers are not actually wired into the bar logic — the trade management is just SL and TP at open. A position that survives the SL/TP and stays in the market can only exit when price hits one of those two levels or the broker forcibly closes it.
The position accounting is one trade at a time. CheckSignal() short-circuits and returns immediately if PositionsTotal() > 0. There is no basket logic, no opposite-signal close, and no pending-order queue. When the current position closes, the EA waits for the next bar to form before it re-evaluates — the static datetime lastBar and iTime check in OnTick enforce this. That is by design: the EA is a swing-style trend follower, not a scalper. Trades that close at a loss feed OnTradeTransaction, which increments a running counter of consecutive losses; the moment that counter hits 3 (the default for InpMaxConsecLosses), the EA sets g_cooldownUntil = TimeCurrent() + InpCooldownMinutes * 60 and refuses any new entries for the next 30 minutes. A winning trade resets the counter to zero, so a single green bar breaks the streak.
The capital-protection stack is six layers deep and runs on every tick. IsSafeToTrade() first checks the optional capital cap and floor (InpCapitalCapAmount and InpCapitalCapFloor); then an equity floor at 95% of the initial balance; then a 3% daily realised-loss cap and a 6% weekly realised-loss cap, both expressed as a percentage of effective capital; then the consec-loss cooldown; then a hard cap of 50 trades per day; then IsMarketOpen() which blocks Saturday and the first 22 hours of Sunday plus the last hour of Friday in GMT. On top of that, InActiveSession() only allows trading during London 7–16 GMT or New York 12–21 GMT, and the InpAvoidAsia flag is on by default, so the Asian session (0–7 GMT) is excluded entirely. IsNewsTime() watches the start of London and New York and can pause entries for 15 minutes around those opens, but InpNewsFilter is off by default — the trader opts in.
The 200 EMA is the only indicator the EA actually attaches (hMA = iMA(_Symbol, _Period, InpTrendEMA, 0, MODE_EMA, PRICE_CLOSE)); Heiken Ashi values are calculated inline and never get their own handle. The session machinery is purely time-based: DetectGMTOffset() walks the last 100 H1 bars looking for the weekend gap, then picks the broker's GMT offset by testing each candidate in -12..+12 against the Friday 22:00 close. InpServerGMTOffset lets the trader override the auto-detection with a manual hour offset if the heuristic gets it wrong. Filling mode is also broker-driven: the EA checks SYMBOL_FILLING_MODE at init and uses FOK if the broker supports it, otherwise IOC, otherwise RETURN. Slippage is fixed at 3 points. New entries are placed with up to 3 retries on REQUOTE, TIMEOUT, or PRICE_OFF separated by 150ms each.
OnTester returns (net × profit factor) / (1 + relative balance drawdown), gated on a minimum of 30 closed trades in the optimisation pass. Below 30 trades the fitness is 0, which keeps the optimiser from selecting results on tiny samples. The result is a single-number score that rewards profit and consistency while penalising drawdown.
Backtest expectations: with the defaults (1% risk, 400-point stop, 800-point target, 1 trade at a time, new-bar only, 95% equity floor, 3% daily loss cap, 30-minute cooldown after 3 losses), the EA will produce a low-to-moderate number of trades per day on XAUUSD M5 because it has to wait for HA color to agree with the 200 EMA on a closed bar, and it is only allowed to look during the London or New York sessions. The fixed 1:2 RR means winners are double the size of losers in points, but the win rate has to clear roughly 34% before expectancy turns positive after spread and slippage. Set InpRiskPercent higher and the absolute P&L scales up; set it to 0 to switch to fixed 0.01 lots, which is the safer mode for forward testing. The 200 EMA in particular should be checked against the broker's data — if the broker truncates history, the EMA will be colder and the trend vote will be wrong for the first few weeks of trading.
Strategy Deep Dive
Each M5 close, EX04004 rebuilds a smoothed Heiken Ashi bar from raw OHLC (haOpen from the prior bar's mid, haClose from the current bar's typical price) and compares it to a 200-period EMA. The two votes have to agree — green HA with close above EMA for longs, red HA with close below for shorts — before OpenBuy or OpenSell runs. OrderCalcMargin confirms free margin first, then trade.Buy/trade.Sell fires with a 400-point SL, an 800-point TP, and a lot sized off InpRiskPercent of effective capital; the order loop retries three times on REQUOTE/TIMEOUT/PRICE_OFF. IsSafeToTrade() is the gatekeeper: it enforces the capital cap and floor, the 95% equity floor, the 3% daily and 6% weekly loss limits, the 50-trade-per-day cap, the 3-consecutive-losses cooldown, the weekend hours, the London 7-16 / New York 12-21 GMT session window with Asia blocked, and the optional news filter around session opens. OnTradeTransaction tallies the realised P&L and trip-wires the cooldown when 3 losses land in a row. There is no scaling, no break-even, and no opposite-signal close — every entry is a one-shot trend bet.
On every new M5 bar, the EA computes a smoothed Heiken Ashi candle from the closed bar (haOpen = (open[2]+close[2])/2, haClose = (open[1]+high[1]+low[1]+close[1])/4) and pulls a 200-period EMA. A long fires when the HA bar is green (haClose > haOpen) AND the real close of bar 1 is above the EMA; a short fires when HA is red AND the real close is below. Only one position can be open at a time — CheckSignal() returns immediately if PositionsTotal() > 0.
There is no active exit logic — trades stay open until the fixed 400-point stop loss or the fixed 800-point take profit is hit by price. The EA does not move to break-even, does not trail, does not take partial closes, and does not close on an opposite signal. Once the position closes, the EA waits for the next new bar before re-evaluating.
Fixed stop loss of 400 points (InpStopLoss) attached at order open via mysymbol.Ask()/Bid() minus InpStopLoss * mysymbol.Point(). Sized through CalculateLotSize so that the dollar risk equals InpRiskPercent (1.0% default) of effective capital, floored to the symbol's lot step and clamped to min/max lot. There is no break-even move and no trailing.
Fixed take profit of 800 points (InpTakeProfit) attached at order open — exactly 2x the stop loss for a 1:2 reward-to-risk ratio. Hit either the SL or the TP first and the position closes; no partials, no scaling out, no time-based exit.
Best for XAUUSD M5 traders who want a single-shot HA colour + 200 EMA trend filter with a fixed 1:2 RR and zero in-trade management. Minimum recommended balance: $100 (one micro lot per 1% risk against a 400-point stop). Run it on a low-spread gold feed during London or New York only — the InpAvoidAsia flag is on by default and the session gate blocks everything outside 7-16 / 12-21 GMT. Pick an ECN-style broker with FOK or IOC filling (the EA auto-selects) and at least 30 days of tick history so the 200 EMA is fully seeded.
Strategy Logic
Pipsgrowth EX04004 HAEA — Strategy Logic Analysis (from .mq5 source)
Family: HAEA
Magic: 22204004
Version: 2.00
BRIEF:
Heiken Ashi Smoothed trend EA for XAUUSD. Uses smoothed Heiken Ashi candle color combined with an EMA trend filter to generate entries. Includes risk-based position sizing and spread filter
INDICATOR STACK:
- Standard
MT5indicators
KEY FUNCTIONS:
CheckSignal()OpenBuy()OpenSell()CalculateLotSize()GetEffectiveCapital()OnTradeTransaction()DetectGMTOffset()ServerToGMT()IsMarketOpen()InActiveSession()IsNewsTime()IsSafeToTrade()- ...and 4 more
INTERNAL CONSTANTS (0 total):
INPUT PARAMETERS (28 total across 7 groups):
- [=== Identity ===]
InpMagicNumber=22204004// Magic Number - [=== Identity ===]
InpTradeComment= "Psgrowth.com Expert_04004" // TradeComment - [=== Strategy Parameters ===]
InpPeriod= 14 // Smoothed Period - [=== Strategy Parameters ===]
InpTrendEMA= 200 // TrendFilter(EMA) - [=== Money Management ===]
InpRiskPercent=1.0// Risk Percent per Trade - [=== Money Management ===]
InpFixedLot=0.01// FixedLot(if Risk=0) - [=== Money Management ===]
InpStopLoss= 400 // StopLoss(points) - [=== Money Management ===]
InpTakeProfit= 800 // TakeProfit(points) - [=== Trade Management ===]
InpMaxSpread= 250 // MaxSpread(points) - [=== Trade Management ===]
InpSlippage= 3 // Slippage - [=== 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:
GMTSessions ===]InpServerGMTOffset= 0 // ServerGMToffset in hours (0=auto-detect via weekend gap) - [=== Hardening:
GMTSessions ===]InpLondonStartHour= 7 // London session start (GMT) - [=== Hardening:
GMTSessions ===]InpLondonEndHour= 16 // London session end (GMT) - [=== Hardening:
GMTSessions ===]InpNYStartHour= 12 // New York session start (GMT) - [=== Hardening:
GMTSessions ===]InpNYEndHour= 21 // New York session end (GMT) - [=== Hardening:
GMTSessions ===]InpAvoidAsia=true// Avoid Asian session - [=== Hardening:
GMTSessions ===]InpAsiaStartHour= 0 // Asian session start (GMT) - [=== Hardening:
GMTSessions ===]InpAsiaEndHour= 7 // Asian session end (GMT) - [=== Hardening:
GMTSessions ===]InpNewsFilter=false// Avoid trading near news session opens - [=== Hardening:
GMTSessions ===]InpNewsFilterMinutes= 15 // Minutes to avoid around news
// Pipsgrowth EX04004 HAEA — Execution Flow (from source analysis)
// Family: HAEA
// Heiken Ashi Smoothed trend EA for XAUUSD. Uses smoothed Heiken Ashi candle color combined with an EMA trend filter to generate entries. Includes risk-based position sizing 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
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 a chart matching the recommended timeframe
- 7Configure parameters according to the table on this page
- 8Enable Allow Algo Trading and click OK
EA Parameters
| Parameter | Default | Description |
|---|---|---|
| InpMagicNumber | 22204004 | Magic Number |
| InpTradeComment | "Psgrowth.com Expert_04004" | Trade Comment |
| InpPeriod | 14 | Smoothed Period |
| InpTrendEMA | 200 | Trend Filter (EMA) |
| InpRiskPercent | 1.0 | Risk Percent per Trade |
| InpFixedLot | 0.01 | Fixed Lot (if Risk=0) |
| InpStopLoss | 400 | Stop Loss (points) |
| InpTakeProfit | 800 | Take Profit (points) |
| InpMaxSpread | 250 | Max Spread (points) |
| InpSlippage | 3 | Slippage |
| InpMaxConsecLosses | 3 | Max consecutive losses before cooldown (0=disabled) |
| InpCooldownMinutes | 30 | Cooldown minutes after consec losses (0=disabled) |
| InpMaxTradesPerDay | 50 | Maximum trades per day |
| InpMinEquityPercent | 95.0 | Stop trading if equity falls below this % of initial balance |
| InpDailyLossLimitPct | 3.0 | Daily loss limit (% of effective capital) |
| InpWeeklyLossLimitPct | 6.0 | Weekly loss limit (% of effective capital) |
| InpCapitalCapAmount | 0.0 | Cap amount ($ real money equity) |
| InpCapitalCapFloor | 50.0 | Floor ($); block entries below this |
| InpServerGMTOffset | 0 | Server GMT offset in hours (0=auto-detect via weekend gap) |
| InpLondonStartHour | 7 | London session start (GMT) |
| InpLondonEndHour | 16 | London session end (GMT) |
| InpNYStartHour | 12 | New York session start (GMT) |
| InpNYEndHour | 21 | New York session end (GMT) |
| InpAvoidAsia | true | Avoid Asian session |
| InpAsiaStartHour | 0 | Asian session start (GMT) |
| InpAsiaEndHour | 7 | Asian session end (GMT) |
| InpNewsFilter | false | Avoid trading near news session opens |
| InpNewsFilterMinutes | 15 | Minutes to avoid around news |
#property copyright "Pipsgrowth.com"
#property link "https://pipsgrowth.com"
#property version "2.00"
#property strict
#property description "Pipsgrowth.com EX04004 HASmoothed_XAUUSD_5M — smoothed Heiken Ashi + EMA trend EA, full 12-layer stack."
#include <Trade\Trade.mqh>
#include <Trade\PositionInfo.mqh>
#include <Trade\SymbolInfo.mqh>
#include <Trade\AccountInfo.mqh>
CTrade trade;
CPositionInfo position;
CSymbolInfo mysymbol;
CAccountInfo account;
//--- Input Groups
input group "=== Identity ==="
input int InpMagicNumber = 22204004; // Magic Number
input string InpTradeComment = "Psgrowth.com Expert_04004"; // Trade Comment
input group "=== Strategy Parameters ==="
input int InpPeriod = 14; // Smoothed Period
input int InpTrendEMA = 200; // Trend Filter (EMA)
input group "=== Money Management ==="
input double InpRiskPercent = 1.0; // Risk Percent per Trade
input double InpFixedLot = 0.01; // Fixed Lot (if Risk=0)
input int InpStopLoss = 400; // Stop Loss (points)
input int InpTakeProfit = 800; // Take Profit (points)
input group "=== Trade Management ==="
input int InpMaxSpread = 250; // Max Spread (points)
input int InpSlippage = 3; // Slippage
input group "=== Hardening: Risk Management ==="
input int InpMaxConsecLosses = 3; // Max consecutive losses before cooldown (0=disabled)
input int InpCooldownMinutes = 30; // Cooldown minutes after consec losses (0=disabled)
input int InpMaxTradesPerDay = 50; // Maximum trades per day
input double InpMinEquityPercent = 95.0; // Stop trading if equity falls below this % of initial balance
input double InpDailyLossLimitPct= 3.0; // Daily loss limit (% of effective capital)
input double InpWeeklyLossLimitPct= 6.0; // Weekly loss limit (% of effective capital)
input group "=== Hardening: Capital Allocation Cap ==="
// InpCapitalCapEnabled removed — use InpCapitalCapAmount=0 to disable // Enable capital allocation cap
input double InpCapitalCapAmount = 0.0; // Cap amount ($ real money equity)
input double InpCapitalCapFloor = 50.0; // Floor ($); block entries below this
input group "=== Hardening: GMT Sessions ==="
input int InpServerGMTOffset = 0; // Server GMT offset in hours (0=auto-detect via weekend gap)
input int InpLondonStartHour = 7; // London session start (GMT)
input int InpLondonEndHour = 16; // London session end (GMT)
input int InpNYStartHour = 12; // New York session start (GMT)
input int InpNYEndHour = 21; // New York session end (GMT)
input bool InpAvoidAsia = true; // Avoid Asian session
input int InpAsiaStartHour = 0; // Asian session start (GMT)
input int InpAsiaEndHour = 7; // Asian session end (GMT)
input bool InpNewsFilter = false; // Avoid trading near news session opens
input int InpNewsFilterMinutes= 15; // Minutes to avoid around news
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 Other strategy EAs from our library
Pipsgrowth EX01007 Adaptive
Pipsgrowth.com EX01007 Adaptive XAUUSD 5M — multi-indicator signal scorer with regime filter, full 12-layer stack, configurable timeframe, trailing/BE/profit-lock toggles, pyramid gate, spread filter, new-bar gate, filling mode detection.
Pipsgrowth EX01019 Adaptive
Pipsgrowth.com EX01019 Self-Adaptive Market EA Fixed — multi-regime adaptive EA, full 12-layer stack.
Pipsgrowth EX15029 SMC-OrderBlock
Pipsgrowth.com EX15029 SMCBreakoutEA — SMC breakout CHOCH/liquidity sweep EA, full 12-layer stack.
Community
Educational purposes only. Do NOT use with real money. Test on demo accounts only.