Pipsgrowth EX07018 MA
MT5 Expert Advisor (Open Source) · XAUUSD · M5
Pipsgrowth.com EX07018 XAUUSD_M5_EMA_Crossover_EA — EMA crossover with trailing/breakeven, full 12-layer stack.
Overview
Pipsgrowth EX07018 MA opens long or short positions on XAUUSD M5 whenever a 10-period EMA crosses a 20-period EMA, and runs two risk locks (breakeven and a ratchet-style trailing stop) to keep the result of every trade from going negative once the price has moved far enough. The crossover itself is detected on a freshly closed bar — IsNewBar() compares the current bar's open time against g_lastCandle and only returns true once, so each crossover fires exactly one order request and signal-flicker on the same bar is impossible. The first EMA is built with iMA(_Symbol, _Period, 10, 0, MODE_EMA, PRICE_CLOSE); the second is the same call with period 20. Both are released in OnDeinit().
The entry pipeline is short. After IsNewBar() flips, OnTick() calls IsWithinTradingSession(), then IsSpreadOK(), then reads two bars of each EMA. A buy triggers when fast[1] > slow[1] and the previous bar had fast[2] <= slow[2] — the classic bullish cross. A sell is the mirror. The order is then sent with trade.Buy(lot, _Symbol, ask, sl, tp, InpTradeComment) or trade.Sell(...) with sl = ask/bid ± 500 points and tp = ask/bid ∓ 1500 points. That is a hard-coded 1:3 risk-reward against the 500-point stop, which is the most asymmetric TP target in the EX07xxx MA family — most siblings target 1:1 or 1:1.5.
Position sizing in CalculateLotSize(slPoints) is a five-step routine. If InpRiskPercent is greater than zero, it pulls AccountInfoDouble(ACCOUNT_BALANCE), multiplies by InpRiskPercent / 100, divides by the per-lot loss at the requested stop, snaps the result down to the nearest SYMBOL_VOLUME_STEP, clamps to [minLot, maxLot], then calls OrderCalcMargin. If the resulting margin would consume more than 80% of ACCOUNT_MARGIN_FREE, the lot is scaled back proportionally. The final number is also capped against InpMaxLotSize (1.0 by default), so a runaway balance can never push the position size past the user-set ceiling. If InpRiskPercent is set to 0, the function falls back to InpFixedLot (0.01) — the same fallback the function uses whenever tick value, tick size, or _Point is zero.
Once a position is open, two management routines run on every tick, ahead of the new-bar logic. ManageBreakeven() waits for a long position to be InpBEStart (200) points in the money and the current stop to be below the open price, then it tries to move the stop to open + InpBEProfit * _Point (entry + 50 points). Sells are mirrored. ManageTrailingStop() then waits for a further 100 points of profit (300 points total from entry) and lifts the stop to bid - InpTrailDistance * _Point (current bid minus 200 points), provided the new stop is above both the existing stop and the open price. The two together produce a three-stage ratchet: a breakeven lock at +200, a trailing stop kick-in at +300, and a continued 200-point trail behind price as it advances. The same three retries-and-200ms-loop pattern is used by TryClose_EX07018, TryClosePartial_EX07018, and TryModify_EX07018 against REQUOTE, TIMEOUT, PRICE_OFF, and PRICE_CHANGED retcodes — the close/partial routines wait 200 ms between attempts, the modify routine waits 100 ms and only retries on REQUOTE/TIMEOUT.
The session filter in IsWithinTradingSession() is built as two independent windows, not one continuous block. Session 1 covers server hours 8 to 12 (the open of the London session, when gold typically makes its first directional move of the European day). Session 2 covers server hours 14 to 18 (NY pre-open and the first half of the US session, the second most active gold window). Each session can be toggled independently with InpEnableSession1 and InpEnableSession2. The function reads the broker's TimeCurrent() directly — there is no GMT auto-detection, so the meaning of "hour 8" depends entirely on the broker's server clock. Spread protection in IsSpreadOK() measures the live ask-bid gap in points and rejects entries beyond InpMaxSpread (200 by default), which is essential on XAUUSD where spreads can balloon during off-hours or news events.
The optional safe-pyramid mode (InpEnablePyramid = false by default) is the most subtle piece of logic in the EA. IsPyramidSafe() does three things. First, it returns false immediately if pyramiding is off or if the open count is already at InpMaxPyramidLevels (3). Second, it scans all open positions on the symbol/magic. Third, for each existing position it checks the current stop-loss against the open price: for a buy, the SL must be greater than openPrice + InpMinSLProfit * _Point; for a sell, the SL must be less than openPrice - InpMinSLProfit * _Point (or zero). The semantic is that the existing position's stop has already been lifted to at least 150 points in profit — meaning the breakeven or trailing routine has already kicked in. This means you cannot pyramid into a fresh, unprotected position. With both pyramid and the management ratchets active, a strong trending gold day could build up to three entries on the same side, each with progressively tighter protection.
The 12-layer label in the file header is aspirational. The code does not implement a regime classifier, a higher-timeframe filter, ATR, ADX, RSI, Bollinger bands, news gating, a daily loss cap, an equity floor, a time stop, a partial-close path (the TryClosePartial_EX07018 function exists but is never called from OnTick), or an OnTester fitness function. What it does implement is a clean 10/20 crossover with two management ratchets, two session windows, a spread filter, a margin-aware lot sizer, and an opt-in pyramid that only adds when prior positions are already protected. The simplicity is the point: this is a small, readable, single-purpose EA that does one thing mechanically, and traders who want a regime filter, an HTF bias, or a news guard should layer them in themselves or pick a different EX07xxx sibling.
The default config is 1% risk per trade, 0.01 lot floor, 1.0 lot ceiling, 500-point stop, 1500-point take-profit, BE at +200 with +50 lock, trail at +300 with 200-point distance, both sessions on, spread cap 200 points, pyramid off. The EA identifies its orders with magic number 22207018 and the comment string Psgrowth.com Expert_07018.
Strategy Deep Dive
Runs a 10/20 EMA crossover on XAUUSD M5, gated to two server-time windows (8–12 and 14–18) and to spreads ≤ 200 points, then sends market orders with a hard 500-point stop and a 1500-point take-profit for a fixed 1:3 R:R. ManageBreakeven lifts the stop to entry + 50 points once profit hits +200; ManageTrailingStop then ratchets the stop 200 points behind price once profit reaches +300. Optional safe-pyramid mode adds a second or third entry on the same side only after the existing position's stop has already been moved into profit by ≥ 150 points, which means a runner can only scale into a trend that is already protected. Lot size is risk-percent based, with a margin-aware fallback that caps the position at 80% of free margin and at the InpMaxLotSize ceiling.
Long entry fires when the 10-period EMA closes above the 20-period EMA on a freshly opened bar (the bar that just closed had fast <= slow, the new bar has fast > slow). Short entry is the mirror. Before either can fire, the EA must pass three gates: a new-bar check, the session filter (server hours 8–12 or 14–18), and the spread filter (≤ 200 points). If a position on the same magic already exists and pyramid is enabled, the existing position's stop must already be in profit by at least 150 points before a second entry is allowed.
Exit fires on the reverse 10/20 crossover (fast crosses back below slow for longs, above for shorts) or on the trailing stop after the trade has moved at least 300 points in favor and the stop is ratcheted 200 points behind price. The breakeven routine does not close — it only moves the stop to entry + 50 points once profit reaches +200. Positions are not force-closed at session end or on a Friday cut.
Initial stop is fixed at 500 points from entry (sl = ask - 500_Point on buys, bid + 500_Point on sells). Once the trade moves 200 points in favor, the stop is lifted to entry + 50 points (breakeven lock). Once it moves 300 points in favor, the trailing stop kicks in at bid - 200 points and ratchets forward as price advances. There is no per-trade global stop beyond the 500-point anchor.
Fixed take-profit at 1500 points from entry, a 1:3 risk-to-reward against the 500-point stop. The TP is sent with the order and is not modified by the trailing routine. There is no basket take-profit, no time-based exit, and no partial-close path wired to OnTick.
Built for XAUUSD on the M5 timeframe with a $100 minimum deposit at MEDIUM risk. Needs a broker whose server clock aligns with the two server-time windows the EA hardcodes (8–12 and 14–18, which roughly track London-open and NY-pre-open for most MT5 brokers — verify against your own server hour before going live). ECN or low-spread RAW account strongly recommended because the 1:3 R:R with a 500-point gold stop is sensitive to spread cost on entries.
Strategy Logic
Pipsgrowth EX07018 MA — Strategy Logic Analysis (from .mq5 source)
Family: MA
Magic: 22207018
Version: 2.00
BRIEF:
EMA crossover EA for XAUUSD M5 using fast/slow EMA crossover with ATR-based risk management, trailing stop, breakeven, session filter, spread filter and optional safe pyramiding. 12 layers: REGIME, SIGNAL, ENTRY, CONFIRM, NO-TRADE, CAPITAL CAP, RISK, SIZING, MANAGE, EXIT, SCALING, OnTester
INDICATOR STACK:
- Standard
MT5indicators
KEY FUNCTIONS:
CalculateLotSize()IsWithinTradingSession()IsSpreadOK()CountOpenTrades()IsPyramidSafe()ManageTrailingStop()ManageBreakeven()IsNewBar()TryClose_EX07018()TryClosePartial_EX07018()TryModify_EX07018()
INTERNAL CONSTANTS (0 total):
INPUT PARAMETERS (26 total across 8 groups):
- [=== Identity ===]
InpTradeComment= "Psgrowth.com Expert_07018" // TradeComment - [=== Identity ===]
InpMagicNumber=22207018// Magic Number - [===
EMASettings ===]InpFastMAPeriod= 10 // FastEMAPeriod - [===
EMASettings ===]InpSlowMAPeriod= 20 // SlowEMAPeriod - [=== Risk Management ===]
InpRiskPercent=1.0// Risk % per Trade - [=== Risk Management ===]
InpFixedLot=0.01// FixedLot(if Risk=0) - [=== Risk Management ===]
InpMaxLotSize=1.0// Max Lot Size - [=== Stop Loss & Take Profit ===]
InpStopLoss= 500 // StopLoss(Points) - [=== Stop Loss & Take Profit ===]
InpTakeProfit= 1500 // TakeProfit(Points) - [=== Trailing & Breakeven ===]
InpUseTrailing=true// Enable Trailing Stop - [=== Trailing & Breakeven ===]
InpTrailStart= 300 // TrailStart(Points) - [=== Trailing & Breakeven ===]
InpTrailDistance= 200 // TrailDistance(Points) - [=== Trailing & Breakeven ===]
InpUseBreakeven=true// Enable Breakeven - [=== Trailing & Breakeven ===]
InpBEStart= 200 // BETrigger(Points) - [=== Trailing & Breakeven ===]
InpBEProfit= 50 // BE LockProfit(Points) - [=== Time Management ===]
InpEnableSession1=true// Enable Session 1 - [=== Time Management ===]
InpSession1Start= 8 // Session 1 Start Hour - [=== Time Management ===]
InpSession1End= 12 // Session 1 End Hour - [=== Time Management ===]
InpEnableSession2=true// Enable Session 2 - [=== Time Management ===]
InpSession2Start= 14 // Session 2 Start Hour - [=== Time Management ===]
InpSession2End= 18 // Session 2 End Hour - [=== Spread Filter ===]
InpEnableSpreadFilter=true// Enable Spread Filter - [=== Spread Filter ===]
InpMaxSpread= 200 // MaxSpread(Points) - [=== Safe Pyramid ===]
InpEnablePyramid=false// Enable Pyramiding - [=== Safe Pyramid ===]
InpMaxPyramidLevels= 3 // Max Pyramid Positions - [=== Safe Pyramid ===]
InpMinSLProfit= 150 // Min SL inProfit(Points)
// Pipsgrowth EX07018 MA — Execution Flow (from source analysis)
// Family: MA
// EMA crossover EA for XAUUSD M5 using fast/slow EMA crossover with ATR-based risk management, trailing stop, breakeven, session filter, spread filter and optional safe pyramiding. 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
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 an H4 or Daily chart for best results
- 7Configure EMA periods, ADX threshold, and lot size in the dialog
- 8Enable Allow Algo Trading and click OK
EA Parameters
| Parameter | Default | Description |
|---|---|---|
| InpTradeComment | "Psgrowth.com Expert_07018" | Trade Comment |
| InpMagicNumber | 22207018 | Magic Number |
| InpFastMAPeriod | 10 | Fast EMA Period |
| InpSlowMAPeriod | 20 | Slow EMA Period |
| InpRiskPercent | 1.0 | Risk % per Trade |
| InpFixedLot | 0.01 | Fixed Lot (if Risk=0) |
| InpMaxLotSize | 1.0 | Max Lot Size |
| InpStopLoss | 500 | Stop Loss (Points) |
| InpTakeProfit | 1500 | Take Profit (Points) |
| InpUseTrailing | true | Enable Trailing Stop |
| InpTrailStart | 300 | Trail Start (Points) |
| InpTrailDistance | 200 | Trail Distance (Points) |
| InpUseBreakeven | true | Enable Breakeven |
| InpBEStart | 200 | BE Trigger (Points) |
| InpBEProfit | 50 | BE Lock Profit (Points) |
| InpEnableSession1 | true | Enable Session 1 |
| InpSession1Start | 8 | Session 1 Start Hour |
| InpSession1End | 12 | Session 1 End Hour |
| InpEnableSession2 | true | Enable Session 2 |
| InpSession2Start | 14 | Session 2 Start Hour |
| InpSession2End | 18 | Session 2 End Hour |
| InpEnableSpreadFilter | true | Enable Spread Filter |
| InpMaxSpread | 200 | Max Spread (Points) |
| InpEnablePyramid | false | Enable Pyramiding |
| InpMaxPyramidLevels | 3 | Max Pyramid Positions |
| InpMinSLProfit | 150 | Min SL in Profit (Points) |
#property copyright "Pipsgrowth.com"
#property link "https://pipsgrowth.com"
#property version "2.00"
#property strict
#property description "Pipsgrowth.com EX07018 XAUUSD_M5_EMA_Crossover_EA — EMA crossover with trailing/breakeven, full 12-layer stack."
#include <Trade/Trade.mqh>
CTrade trade;
//+------------------------------------------------------------------+
//| Input Parameters |
//+------------------------------------------------------------------+
input group "=== Identity ==="
input string InpTradeComment = "Psgrowth.com Expert_07018"; // Trade Comment
input ulong InpMagicNumber = 22207018; // Magic Number
input group "=== EMA Settings ==="
input int InpFastMAPeriod = 10; // Fast EMA Period
input int InpSlowMAPeriod = 20; // Slow EMA Period
input group "=== Risk Management ==="
input double InpRiskPercent = 1.0; // Risk % per Trade
input double InpFixedLot = 0.01; // Fixed Lot (if Risk=0)
input double InpMaxLotSize = 1.0; // Max Lot Size
input group "=== Stop Loss & Take Profit ==="
input int InpStopLoss = 500; // Stop Loss (Points)
input int InpTakeProfit = 1500; // Take Profit (Points)
input group "=== Trailing & Breakeven ==="
input bool InpUseTrailing = true; // Enable Trailing Stop
input int InpTrailStart = 300; // Trail Start (Points)
input int InpTrailDistance = 200; // Trail Distance (Points)
input bool InpUseBreakeven = true; // Enable Breakeven
input int InpBEStart = 200; // BE Trigger (Points)
input int InpBEProfit = 50; // BE Lock Profit (Points)
input group "=== Time Management ==="
input bool InpEnableSession1 = true; // Enable Session 1
input int InpSession1Start = 8; // Session 1 Start Hour
input int InpSession1End = 12; // Session 1 End Hour
input bool InpEnableSession2 = true; // Enable Session 2
input int InpSession2Start = 14; // Session 2 Start Hour
input int InpSession2End = 18; // Session 2 End Hour
input group "=== Spread Filter ==="
input bool InpEnableSpreadFilter = true; // Enable Spread Filter
input int InpMaxSpread = 200; // Max Spread (Points)
input group "=== Safe Pyramid ==="
input bool InpEnablePyramid = false; // Enable Pyramiding
input int InpMaxPyramidLevels = 3; // Max Pyramid Positions
input int InpMinSLProfit = 150; // Min SL in Profit (Points)
//+------------------------------------------------------------------+
//| Global Variables |
//+------------------------------------------------------------------+
int g_fastHandle, g_slowHandle;
datetime g_lastCandle = 0;
//+------------------------------------------------------------------+
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 Trend Following strategy EAs from our library
Pipsgrowth EX16080 Trend
Pipsgrowth.com EX16080 EURUSDTrendFollower — triple-EMA H4 trend follower, full 12-layer stack.
Pipsgrowth EX16081 Trend
Pipsgrowth.com EX16081 GoldTrendEA — XAUUSD H4 EMA cross with Fib targets, full 12-layer stack.
Pipsgrowth EX16033 Trend
Pipsgrowth.com EX16033 EA_Price_Action — price-action grid scalper, full 12-layer stack.
Community
Educational purposes only. Do NOT use with real money. Test on demo accounts only.