P
PipsGrowth
Trend FollowingOpen Source – Free

Pipsgrowth EX07004 MA

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

Pipsgrowth.com EX07004 GoldScalper_MACrossover_AdaptivePyramid — EMA crossover with adaptive pyramiding, full 12-layer stack.

Overview

Pipsgrowth EX07004 is a lean M15 gold scalper. It is built around a single rule — when the 10-period EMA closes above the 20-period EMA, the EA buys; when the 10 closes below the 20, it sells — and the rest of the file is plumbing to keep that rule running safely on a noisy instrument. There is no regime classifier, no higher-timeframe bias, no news filter, no time filter, and no equity floor. What you get is a mechanical crossover with adaptive pyramiding, a risk-based lot, and a 1:2 minimum reward-to-risk.

The signal logic lives in GetMASignal() and is unambiguous. On every new M15 bar, RefreshIndicators() copies two points of iMA(_Symbol, PERIOD_M15, 10, 0, MODE_EMA, PRICE_CLOSE) and two points of the 20-period EMA into arrays, plus one point of iATR(_Symbol, PERIOD_M15, 14) for sizing and stop distance. The function compares the closed-bar values: if prevFastMA <= prevSlowMA and fastMA > slowMA, a long signal fires (the EA prints "LONG: MA Golden Cross"); if prevFastMA >= prevSlowMA and fastMA < slowMA, a short fires. Bars that don't contain a cross return 0 and the EA does nothing. The new-bar gate is hardcoded to PERIOD_M15 in IsNewBar(), so even when you attach the EA to an M5 or H1 chart the signal cadence stays M15 — this is intentional for XAUUSD where the lower-timeframe noise on gold makes a clean M15 crossover more reliable than a chart-period signal.

Entries are filtered by CanOpenPosition(), which loops backward through PositionsTotal(), ignores anything whose symbol is not the chart or whose magic is not 22207004, and counts what is left. The first hard rule is directionality: if there is already a buy position open, the EA will not open a sell (and vice versa). The second is the pyramid cushion — MathAbs(price - PositionGetDouble(POSITION_PRICE_OPEN)) must be at least PyramidDistPips * pipSize (15 pips) before another entry in the same direction is permitted. The third is the cap: if count >= MaxPositions (default 3), the EA refuses. Set UsePyramiding=false to keep only the first position. So the practical pyramid on gold is up to three buy orders spaced 15 pips apart, or three sell orders spaced 15 pips apart — never both sides simultaneously.

Position sizing is risk-based. When UseMoneyManagement=true (default), CalculatePositionSize() reads the account balance, multiplies it by RiskPercent (default 2.0%), divides by slPips * pipValuePerLot where pipValuePerLot = (tickValue/tickSize) * pipSize, then floors the result to the symbol's SYMBOL_VOLUME_STEP and clamps between SYMBOL_VOLUME_MIN and SYMBOL_VOLUME_MAX. With money management off, every order is FixedLotSize (0.01 lots). Note that RiskPercent is percent of balance, not percent of equity, so a floating drawdown does not shrink the next lot — this is the more aggressive of the two common conventions.

Stop and take are recomputed in OpenPosition() for every entry. The stop distance is slDist = MathMax(currentATR * 1.5, MathMax(StopLossPips * pipSize, minDist * 1.5)), where minDist is the broker's SYMBOL_TRADE_STOPS_LEVEL floored to 10 pips. In practice this means the stop is at least 15 pips (the StopLossPips default), but is widened to 1.5×ATR(14) whenever volatility demands it. The take is tpDist = MathMax(slDist * 2, minDist * 1.5) — at least 1:2 R:R, often closer to 1:3 in volatile regimes. The SL price and TP price are written into the order at entry; from that point on the position runs to its hard server-side stop or target. There is no trailing stop, no breakeven ratchet, no partial close, and no time stop in the source. Manage functions (SafePositionModify, TryClose_EX07004, TryClosePartial_EX07004, TryModify_EX07004) are present and the 3-retry logic on REQUOTE, TIMEOUT, PRICE_OFF, and PRICE_CHANGED is in place (200ms close retry, 100ms modify retry), but they are only called if you wire them in or if a future modification is needed.

The pre-trade gate is a single line. CheckFilters() reads the current spread, divides by GetPipSize() to express it in pips (handles 3/5-digit symbols via the standard _Point * 10 rule), and returns false if spread > MaxSpreadPips (default 25.0). Twenty-five pips is wide on most FX pairs but normal for XAUUSD during London and New York overlap, so this filter is a session-quality check, not a tight scalper gate. There is no time-of-day filter, no day-of-week filter, no news blackout, no margin check, no daily-loss guard, no equity-floor guard, and no consecutive-losses cooldown. Anyone running this EA on a live account is accepting that the EA will keep trading through news spikes, weekend gaps (if held), and personal drawdown limits unless the user wires those in externally.

Order routing uses the standard MQL5 CTrade wrapper. OnInit() calls trade.SetExpertMagicNumber(22207004), trade.SetDeviationInPoints(3), and trade.SetTypeFilling(GetAllowedFilling()), where GetAllowedFilling() probes SYMBOL_FILLING_MODE and returns FOK if supported, else IOC, else RETURN. This is the right order for most ECN and market-execution brokers, but it is not the auto-detect-by-symbol helper seen in newer PipsGrowth EAs — the filling mode is fixed at init time and never re-checked. Slippage tolerance is 3 points (not pips) — for XAUUSD with 2-decimal pricing that is 3 cents, which is tight.

Differentiating this EA from the other MAs in the family matters. EX07001 (XAUUSD M30, EMA 10/30) runs a 7-state regime classifier, H1 EMA(50) bias, chandelier trailing, 1R breakeven, 1.5R 50% partial, and a 3R final target, with DryRun=true shipped as the default. EX07003 (XAUUSD/EURUSD/GBPUSD/USDJPY M15, EMA 10/21) layers a 3-leg safe pyramid with a 250-point cushion, a hard 1:3 R:R, 3% daily and 10% equity drawdown guards, and a Friday 20:00 close on top of the cross. EX07004 is the simplest of the three — no regime filter, no partial close, no trailing, no daily guard, no time filter. The trade-off is transparency: every decision in the file is one of three lines in GetMASignal(), CanOpenPosition(), or OpenPosition(). A user who wants full control of pyramiding and stop distance and is willing to manage session and drawdown risk externally will find this EA predictable; a user who wants the safety stack out of the box should look at EX07001 or EX07003.

What to expect in backtest: on M15 XAUUSD with default inputs, the EA produces a steady stream of single-direction pyramids (typically 1 to 3 orders per signal leg) with 1:2+ R:R and a 15-pip floor on the stop. Around 2% of balance risked per entry, 3 concurrent positions at the apex. Expect equity curves that look like staircases on clean trends and sawteeth on chop — the lack of a regime filter means the EA will pyramid into ranging markets and take the chop on the chin. A user who wants to soften that should reduce MaxPositions to 1 and disable UsePyramiding in the inputs; that converts EX07004 into a single-shot crossover that is functionally similar to EX07003 minus the 21-period slow EMA, the daily-loss guard, and the panel.

Broker requirements: a low-spread XAUUSD feed is recommended but not required — the 25-pip filter will reject the worst moments but does not protect against a 5-pip-quoted broker that widens to 20 pips during news. The EA uses CTrade defaults for margin, so the recommended account size is the $100 minimum listed in the EA card, and you should keep total exposure (3 × 0.0X lots) under 30% of free margin to absorb a -15-pip adverse spike on all three pyramid legs without a margin call.

Strategy Deep Dive

Every new M15 bar, the EA copies two closed-bar points from the 10-period and 20-period EMAs (both MODE_EMA on PRICE_CLOSE, both pinned to PERIOD_M15 regardless of the chart timeframe) plus one point of ATR(14) on the same period. GetMASignal() compares prev/current pairs: prevFastMA ≤ prevSlowMA + fastMA > slowMA returns +1, the mirror returns -1, otherwise 0. CanOpenPosition() walks PositionsTotal() backward, ignoring foreign symbols and other magics, and enforces three rules — direction match (no sell while a buy pyramid is open), 15-pip price cushion from the last entry, and the 3-position cap. If a signal passes and CheckFilters() clears the spread test (≤ 25 pips), OpenPosition() computes slDist as max(1.5×ATR, 15 pips, 1.5×minDist), tpDist as max(slDist×2, 1.5×minDist), sizes the lot from RiskPercent=2% of balance floored to the volume step, and sends a market order via CTrade with a 3-point slippage cap. GetAllowedFilling() returns FOK > IOC > RETURN based on SYMBOL_FILLING_MODE; retry helpers retry 3 times on REQUOTE/TIMEOUT/PRICE_OFF/PRICE_CHANGED.

Entry Signal

Long entry on a closed M15 bar where the 10-period EMA crosses above the 20-period EMA (golden cross); short entry on the mirror death cross. Pyramiding permits up to 3 same-direction positions spaced at least 15 pips apart; the EA refuses to add a position within 15 pips of an existing one and refuses to open in the opposite direction while a pyramid is open. A spread filter rejects entries when current XAUUSD spread exceeds 25 pips.

Exit Signal

Positions are managed to their hard server-side stop and target set at entry (1:2+ R:R). There is no trailing stop, no breakeven ratchet, and no time stop in the source — once an order is on, it runs to either the SL or the TP. The 3-retry close and modify functions are wired but not called by an active manage loop in this build.

Stop Loss

Stop loss = max(1.5 × ATR(14), 15 pips, 1.5 × broker stop-level) per entry, written to the order at open and held to expiry. SafePositionModify() enforces the broker's minimum stop distance on any subsequent modification attempt.

Take Profit

Take profit = max(SL × 2, 1.5 × broker stop-level) per entry, a 1:2 minimum R:R that widens with ATR-based stops. The TP is server-side and untouched by the EA after entry.

Best For

Traders who want full manual control over a gold M15 crossover with no opinionated safety stack, on a $100 micro account with XAUUSD on a low-spread ECN or standard account. The pyramid of up to 3 same-direction positions with 15-pip cushion suits a swing-style gold trader comfortable sizing their own session and drawdown risk; the lack of trailing, breakeven, time filter, daily-loss guard, and equity floor means it should NOT be deployed unattended on a live account.

Strategy Logic

Pipsgrowth EX07004 MA — Strategy Logic Analysis (from .mq5 source)

Family: MA Magic: 22207004 Version: 2.00

BRIEF: Gold scalping EA using EMA crossover with adaptive pyramiding. Entry: Fast EMA crosses above Slow EMA = BUY (Golden Cross); below = SELL (Death Cross). ATR-based SL/TP, spread filter, and pyramid adding on distance. 12 layers: REGIME, SIGNAL, ENTRY, CONFIRM, NO-TRADE, CAPITAL CAP, RISK, SIZING, MANAGE, EXIT, SCALING, OnTester

INDICATOR STACK:

  • Standard MT5 indicators

KEY FUNCTIONS:

  • SafePositionModify()
  • RefreshIndicators()
  • GetMASignal()
  • CanOpenPosition()
  • OpenPosition()
  • CalculatePositionSize()
  • IsNewBar()
  • GetPipSize()
  • CheckFilters()
  • TryClose_EX07004()
  • TryClosePartial_EX07004()
  • TryModify_EX07004()

INTERNAL CONSTANTS (0 total):

INPUT PARAMETERS (2 total across 1 groups):

  • [=== Trade Settings ===] InpMagicNumber = 22207004 // Magic Number (222 + Expert ID)
  • [=== Trade Settings ===] InpTradeComment = "Psgrowth.com Expert_07004" // Trade Comment
Pseudocode
// Pipsgrowth EX07004 MA — Execution Flow (from source analysis)
// Family: MA
// Gold scalping EA using EMA crossover with adaptive pyramiding. Entry: Fast EMA crosses above Slow EMA = BUY (Golden Cross); below = SELL (Death Cross). ATR-based SL/TP, spread filter, and pyramid adding on distance. 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:
M15M5H1

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
InpMagicNumber22207004Magic Number (222 + Expert ID)
InpTradeComment"Psgrowth.com Expert_07004"Trade Comment
Source Code (.mq5)Open Source
Pipsgrowth_com_EX07004.mq5
#property copyright "Pipsgrowth.com"
#property link      "https://pipsgrowth.com"
#property version   "2.00"
#property strict
#property description "Pipsgrowth.com EX07004 GoldScalper_MACrossover_AdaptivePyramid — EMA crossover with adaptive pyramiding, full 12-layer stack."
#include <Trade\Trade.mqh>

input group "=== Risk Management ==="
input bool   UseMoneyManagement = true;
input double RiskPercent        = 2.0;
input double FixedLotSize       = 0.01;

input group "=== MA Settings ==="
input int    FastMA_Period      = 10;
input int    SlowMA_Period      = 20;
input ENUM_MA_METHOD MA_Method  = MODE_EMA;

input group "=== Trade Settings ==="
input int    StopLossPips       = 15;
input int    Slippage           = 3;
input int    InpMagicNumber     = 22207004;                      // Magic Number (222 + Expert ID)
input string InpTradeComment    = "Psgrowth.com Expert_07004"; // Trade Comment

input group "=== Pyramiding ==="
input bool   UsePyramiding      = true;
input int    MaxPositions       = 3;
input int    PyramidDistPips    = 15;

input group "=== Filters ==="
input bool   UseSpreadFilter    = true;
input double MaxSpreadPips      = 25.0;

CTrade trade;
int handleFastMA, handleSlowMA, handleATR;
datetime lastBarTime = 0;
double fastMA, slowMA, prevFastMA, prevSlowMA, currentATR;

ENUM_ORDER_TYPE_FILLING GetAllowedFilling()
{
   int filling_mode = (int)SymbolInfoInteger(_Symbol, SYMBOL_FILLING_MODE);
   if((filling_mode & SYMBOL_FILLING_FOK) == SYMBOL_FILLING_FOK) return ORDER_FILLING_FOK;
   else if((filling_mode & SYMBOL_FILLING_IOC) == SYMBOL_FILLING_IOC) return ORDER_FILLING_IOC;
   else return ORDER_FILLING_RETURN;
}


//+------------------------------------------------------------------+
//| Safe Position Modify - validates stops before modifying          |
//+------------------------------------------------------------------+
bool SafePositionModify(ulong ticket, double newSL, double newTP)
{
   // Select the position
   if(!PositionSelectByTicket(ticket))
   {
      return false; // Position doesn't exist, no error needed
   }
   
   // Get current price
   long type = PositionGetInteger(POSITION_TYPE);
   double price = (type == POSITION_TYPE_BUY) ? 

Full source code available on download

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

Tags:ex07004mapipsgrowthfreemt5xauusd

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_EX07004.mq5
File Size12.0 KB
Versionv2.00
PlatformMetaTrader 5
File Type.mq5 Source
StrategyTrend Following
Risk LevelMedium Risk
Timeframes
M15M5H1
Currency Pairs
XAUUSD
Min. Deposit$100