P
PipsGrowth
GridOpen Source – Free

Pipsgrowth EX03014 Grid

MT5 Expert Advisor (Open Source) · XAUUSD · M1, M15

Pipsgrowth.com EX03014 MT5_BuildYourGridEA — configurable grid system, full 12-layer stack.

Overview

Pipsgrowth EX03014 Grid is a price-only MT5 grid engine. It contains zero indicator handles — the strategy is driven entirely by open-position bookkeeping, configurable pips thresholds, and a single .mq5 file of pure order-management logic. The EA opens its first orders at the market, then layers additional entries whenever price moves a configured step against the latest position on that side. There is no regime filter, no trend read, no volatility gate; what you get is a deterministic geometric grid you can tune from the inputs panel.

The grid is parameterized along four orthogonal axes, each driven by its own input. TypeOrdersPlace (Open_Buy_And_Sell by default) controls whether the basket starts with both sides, only buys, or only sells. TypeOfNextOrders (Grid_Contrary_Trend) decides whether the next entry is added on the side that is already winning — pyramid with the trend — or on the side that is losing, which is the classic mean-reversion martingale posture. PipsForNextOrder (50.0 default) sets the base distance. TypeOfStepProgress then reshapes that base distance for every additional layer: Statical_Step keeps a flat 50 pips between every order, Geometrical_Step multiplies the step by the count of orders already open on that side (so layer 3 sits 150 pips from the last buy, layer 4 sits 200 pips, and so on), and Exponetial_Step is declared but unreachable in the source because both branches in GetSignals test for TypeOfStepProgress==1 — the geometric branch matches first, which is a real source-code bug worth flagging if you intend to run exponential sizing.

Sizing is decoupled from step. TypeOfLotProgress picks one of three regimes. Statical_Lot reuses the size of the first order on each side for every subsequent layer — predictable and conservative. Geometrical_Lot doubles the lot on the second order, then from the third layer onward it adds the latest lot to the first lot, so the sequence is 0.01, 0.02, 0.03, 0.04, 0.05Exponetial_Lot (also flagged via the same enum value 2) doubles the previous lot indefinitely, producing the most aggressive martingale curve. The MaxMultiplierLot input acts as a hard cap: in Statical and Geometrical modes, the calculated lot is clamped to LotFirstBuy × MaxMultiplierLot (default 50.0) before normalization, so a single position can never exceed 50× the opening lot regardless of what the progression calls for. AutoLotSize is a separate path: when enabled, lot becomes (AccountBalance × RiskFactor) / 100000, with RiskFactor defaulting to 1.0, which on a $10,000 account yields 0.10 lots as the base unit.

Exits are basket-level, not per-order. GetSignals() runs first, and if there is at least one open position, it checks the combined P&L of the entire basket — BuyProfits+SellProfits in pips or in account currency, depending on TypeTargetClose — against the configured PipsCloseInProfit (10.0 default) or CurrCloseInProfit (10.0 default). The instant that threshold is reached, CloseOrdersInProfit flips to true, MainFunction routes through CloseOrders(), and the EA walks PositionsTotal() in reverse to close every position whose magic matches OrdersID. There is no scaling-out by order, no partial close, no scaling-in via a separate trigger — the basket closes whole or not at all. The same mechanism handles loss: PipsForCloseInLoss (100.0 pips) combined with ModeCloseInLoss (Close_All_Orders by default) wipes the basket if unrealized loss exceeds the threshold, with the alternative Close_First_Orders selectively closing only the oldest tickets.

Hedge mode is an optional layer that activates when PlaceHedgeOrder is true. The trigger is a balance-percent loss test: if |BuyProfits+SellProfits| / AccountBalance × 100 ≥ LevelLossForHedge (10.0% default) and the basket is net negative, the EA flags UnderHedgePair=true and OpenHedgeOrder=true. From that tick onward MainFunction only calls OpenOrders() on the side that has less aggregate volume, with the hedge lot size computed as |TotalLotsBuy - TotalLotsSell| × MuliplierHedgeLot, normalizing to volume step and bounded by the broker's SYMBOL_VOLUME_LIMIT. The UnderHedgePair flag stays set until the basket is fully closed, so the EA will not start a new basket while a hedge is open.

The safety stack is intentionally light. The OnInit() block validates RiskFactor (0.01-100), MaxSpread (≥ 0), and MaxOrders (≥ 0); everything else is permissive. MaxSpread defaults to 0.0, which means no spread filter at all — the EA will open a buy and a sell on any tick, even with a 50-pip quote spread. Slippage is 3 points by default, and the close path uses request.deviation=5, so closes tolerate twice the slippage of opens. There is no OnTradeTransaction hook, no daily loss counter, no equity-floor kill switch, no session filter, no news filter, and no OnTester fitness function. OrderCalcMargin calls are present in the source as commented-out blocks, so margin pre-checks do not run; a free-margin guard would have to be added by the user. Order retries go through TryOrderSend_EX03014, which loops up to three times at 200ms intervals on TRADE_RETCODE_REQUOTE, TIMEOUT, PRICE_OFF, or PRICE_CHANGED, and breaks out on any other retcode.

The chart-side behaviour is decorative. When ShowComments is enabled, the EA renders a 312×168 raised panel via DrawObjects, then stacks DisplayText labels for spread, money-management mode, current buy/sell exposure, and closed history results in the upper-left corner. SetChartRun is a convenience toggle: when true, the EA calls ChartSetSymbolPeriod to switch the active chart to SymbolPairRun (EURUSD default) and TimeFrameRun (1=M1) before OnInit returns, then calls MainFunction() once to seed any visual state. In the tester and visual modes, the same call runs every tick from OnTick(); on a live terminal, OnTick() short-circuits to MainFunction unless UseCompletedBar is true, in which case it gates on bar-open and re-reads TimeLastBar regardless of the bar timestamp.

Practical tuning on XAUUSD. The defaults are calibrated for a tight-spread major or XAUUSD on an ECN/Raw account, with the basket expected to close on a 10-pip move and a 100-pip loss limit as the worst-case stop. With MuliplierHedgeLot at 1.0 and MaxMultiplierLot at 50, the worst-case position size scales linearly with the size of the imbalance rather than doubling it. Most live grids on this template will want MaxSpread raised to a non-zero value, a session filter added, and either a manual RiskFactor reduction or a manual cap on order count — the source has MaxOrders=0 (unlimited) by default, so the only soft brake is the symbol's SYMBOL_VOLUME_LIMIT and the broker's free margin.

Strategy Deep Dive

EX03014 is a pure price-step grid with zero indicator handles and no regime or session filter. On every tick, MainFunction() calls CountCurrentOrders() to refresh the per-side lot, pip and price aggregates, then GetSignals() decides whether to (1) close the basket on the profit or loss threshold, (2) trigger a hedge fill, or (3) open the next layer. OpenOrders() is fed by CalcLots(), which picks Statical / Geometrical / Exponetial lot progression, caps the result at MaxMultiplierLot × first lot, and rounds to the symbol's volume step. The retry layer in TryOrderSend_EX03014() loops three times at 200ms on requote/timeout/price-change before giving up; opens use 3-point slippage, closes use request.deviation=5. There is no OnTester fitness formula and no margin pre-check — the broker's free margin is the only brake on stack depth once MaxMultiplierLot is reached.

Entry Signal

First layers open on the next tick after OnInit returns — one buy and one sell in the default Open_Buy_And_Sell mode — at the prevailing ask/bid. Once any side has one or more positions, the EA places an additional order whenever price moves PipsForNextOrder (50.0 default) past the latest fill on that side, with the distance scaling by BuyOrders or SellOrders in Geometrical_Step mode and staying fixed in Statical_Step. The GetSignals() function flips the OpenBuy/OpenSell flags, then MainFunction() routes through OpenOrders() which calculates the lot via CalcLots() and sends a market order via TryOrderSend_EX03014() with three retries on requote/timeout/price-change.

Exit Signal

There is no per-order exit. The basket closes as a whole when BuyProfits+SellProfits (in pips or in account currency) reaches the target threshold — PipsCloseInProfit (10.0 default) or CurrCloseInProfit (10.0 default) depending on TypeTargetClose. A loss-side exit triggers when the basket's net pips falls to -100.0 pips with ModeCloseInLoss set to Close_All_Orders, wiping the basket via CloseOrders() walking PositionsTotal() in reverse. Close_First_Orders is the alternative that closes only the oldest tickets on each side.

Stop Loss

Grid orders carry no per-trade stop-loss. The risk envelope is the basket-level PipsForCloseInLoss (100.0 pips default) plus the MaxMultiplierLot cap (50.0× the first lot) on each leg, and the optional hedge trigger at 10.0% balance loss. OrderCalcMargin pre-checks are commented out in the source, so a free-margin guard is not enforced — adequate account equity is required to absorb the worst-case stack depth.

Take Profit

Per-order take-profit is implicit: each grid layer targets one step in its favour. The basket-level TP is the 10.0-pip / 10.0-currency net threshold that closes every position in the basket simultaneously. In hedge mode the basket stays open beyond that threshold until the imbalance is neutralized; in normal mode the basket locks and exits at the first crossing of the target line.

Best For

Best for tight-spread XAUUSD on an ECN/Raw account, where basket exits at 10 pips are realistic and the geometric step progression (50 pips × layer count) keeps the loss window per cycle bounded. Minimum recommended balance: $1,000 per 0.01-lot first layer to absorb a 6-layer drawdown. Run M1 for fastest re-entry, M15 if the broker widens spreads intraday. Set MaxSpread to a non-zero value (e.g., 30 points) before live use — the default of 0.0 will let the EA open on any quote. Avoid during FOMC, NFP and ECB pressers; this build has no news filter and no session gate.

Strategy Logic

Pipsgrowth EX03014 Grid — Strategy Logic Analysis (from .mq5 source)

Family: Grid Magic: 22203014 Version: 2.00

BRIEF: Grid system with configurable order placement (buy/sell/ both), step progression (static/geometric/exponential), profit target in pips or currency, loss-close options, hedge mode and auto lot sizing. Designed for tight-spread pairs. 12 layers: REGIME, SIGNAL, ENTRY, CONFIRM, NO-TRADE, CAPITAL CAP, RISK, SIZING, MANAGE, EXIT, SCALING, OnTester

INDICATOR STACK:

  • Standard MT5 indicators

KEY FUNCTIONS:

  • MainFunction()
  • OpenOrders()
  • CloseOrders()
  • CountCurrentOrders()
  • CountHistoryOrders()
  • CalcLots()
  • DrawObjects()
  • DisplayText()
  • CommentScreen()
  • GetSignals()
  • TryOrderSend_EX03014()

INTERNAL CONSTANTS (1 total):

  • MagicSet = 101010 // ============================================================================================================================================================================================================================//

INPUT PARAMETERS (35 total across 8 groups):

  • [=== Open Orders Parameters ===] TypeOrdersPlace = Open_Buy_And_Sell // Type Of Orders Place
  • [=== Open Orders Parameters ===] TypeOfNextOrders = Grid_Contrary_Trend // Type Of Grid Build
  • [=== Open Orders Parameters ===] PipsForNextOrder = 50.0 // Step For Next Order (Pips)
  • [=== Open Orders Parameters ===] TypeOfStepProgress = Geometrical_Step // Type Step Progress
  • [=== Close At Profit Parameters ===] TypeTargetClose = Target_In_Pips // Type Of Target Close At Profit
  • [=== Close At Profit Parameters ===] PipsCloseInProfit = 10.0 // Target In Pips Close At Profit
  • [=== Close At Profit Parameters ===] CurrCloseInProfit = 10.0 // Target In Currency Close At Profit
  • [=== Close At Loss Parameters ===] ModeCloseInLoss = Close_All_Orders // Mode Close In Loss
  • [=== Close At Loss Parameters ===] PipsForCloseInLoss = 100.0 // Losses For Close (Pips)
  • [=== Hedge Mode Parameters ===] PlaceHedgeOrder = false // Place Hedge Order
  • [=== Hedge Mode Parameters ===] LevelLossForHedge = 10.0 // Level Loss For Hedge (% Of Balance)
  • [=== Hedge Mode Parameters ===] MuliplierHedgeLot = 1.0 // Multiplier Hedge Lot
  • [=== Money Management Parameters ===] AutoLotSize = false // Auto Money Management
  • [=== Money Management Parameters ===] RiskFactor = 1.0 // Risk Money Management (From 0.01 To 100)
  • [=== Money Management Parameters ===] ManualLotSize = 0.01 // Manual Lot Size
  • [=== Money Management Parameters ===] TypeOfLotProgress = Statical_Lot // Type Lot Progress
  • [=== Money Management Parameters ===] MaxMultiplierLot = 50.0 // Maximum Multiplier Lot (0=No Limit)
  • [=== Set Chart Parameters ===] SetChartRun = false // Set Automatically Chart To Run
  • [=== Set Chart Parameters ===] SymbolPairRun = "EURUSD" // Set Symbol Pair To Run
  • [=== Set Chart Parameters ===] TimeFrameRun = 1 // Timeframe (1=M1,2=M5,3=M15,4=M30,5=H1,6=H4,7=D1)//Set Time Frame To Run
  • [=== Information On Chart Parameters ===] ShowComments = false // Show Comments On Chart
  • [=== Information On Chart Parameters ===] ColorOffLines = clrGray // Color Off Lines
  • [=== Information On Chart Parameters ===] ColorExpertName = clrDodgerBlue // Color Expert Name
  • [=== Information On Chart Parameters ===] ColorSpreadInfo = clrChocolate // Color Spread Information
  • [=== Information On Chart Parameters ===] ColorMoneyManagement = clrOrange // Color Money Management
  • [=== Information On Chart Parameters ===] ColorCurrentOrders = clrNavajoWhite // Color Current Orders
  • [=== Information On Chart Parameters ===] ColorHistoryOrders = clrIvory // Color History Orders
  • [=== General Options Parameters ===] MagicNumber = 22203014 // Orders' ID (0=Generate Automatically)
  • [=== General Options Parameters ===] InpTradeComment = "Psgrowth.com Expert_03014" // Orders' Comment
  • [=== General Options Parameters ===] MaxSpread = 0.0 // Max Accepted Spread (0=No Limit)
  • [=== General Options Parameters ===] MaxOrders = 0 // Max Opened Orders (0=No Limit)
  • [=== General Options Parameters ===] Slippage = 3 // Accepted Slippage
  • [=== General Options Parameters ===] UseCompletedBar = false // Use Completed Bar
  • [=== General Options Parameters ===] SoundAlert = false // Play Sound Alerts
  • [=== General Options Parameters ===] PrintOperations = false // Print Information Log
Pseudocode
// Pipsgrowth EX03014 Grid — Execution Flow (from source analysis)
// Family: Grid
// Grid system with configurable order placement (buy/sell/ both), step progression (static/geometric/exponential), profit target in pips or currency, loss-close options, hedge mode and auto lot sizing. Designed for tight-spread pairs. 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:
M1M15

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 — H1 or H4 is recommended for grid EAs
  7. 7Set grid step (pips), maximum orders, and lot size in the EA dialog
  8. 8Enable Allow Algo Trading and click OK

EA Parameters

ParameterDefaultDescription
TypeOrdersPlaceOpen_Buy_And_SellType Of Orders Place
TypeOfNextOrdersGrid_Contrary_TrendType Of Grid Build
PipsForNextOrder50.0Step For Next Order (Pips)
TypeOfStepProgressGeometrical_StepType Step Progress
TypeTargetCloseTarget_In_PipsType Of Target Close At Profit
PipsCloseInProfit10.0Target In Pips Close At Profit
CurrCloseInProfit10.0Target In Currency Close At Profit
ModeCloseInLossClose_All_OrdersMode Close In Loss
PipsForCloseInLoss100.0Losses For Close (Pips)
PlaceHedgeOrderfalsePlace Hedge Order
LevelLossForHedge10.0Level Loss For Hedge (% Of Balance)
MuliplierHedgeLot1.0Multiplier Hedge Lot
AutoLotSizefalseAuto Money Management
RiskFactor1.0Risk Money Management (From 0.01 To 100)
ManualLotSize0.01Manual Lot Size
TypeOfLotProgressStatical_LotType Lot Progress
MaxMultiplierLot50.0Maximum Multiplier Lot (0=No Limit)
SetChartRunfalseSet Automatically Chart To Run
SymbolPairRun"EURUSD"Set Symbol Pair To Run
TimeFrameRun1Timeframe (1=M1,2=M5,3=M15,4=M30,5=H1,6=H4,7=D1)//Set Time Frame To Run
ShowCommentsfalseShow Comments On Chart
ColorOffLinesclrGrayColor Off Lines
ColorExpertNameclrDodgerBlueColor Expert Name
ColorSpreadInfoclrChocolateColor Spread Information
ColorMoneyManagementclrOrangeColor Money Management
ColorCurrentOrdersclrNavajoWhiteColor Current Orders
ColorHistoryOrdersclrIvoryColor History Orders
MagicNumber22203014Orders' ID (0=Generate Automatically)
InpTradeComment"Psgrowth.com Expert_03014"Orders' Comment
MaxSpread0.0Max Accepted Spread (0=No Limit)
MaxOrders0Max Opened Orders (0=No Limit)
Slippage3Accepted Slippage
UseCompletedBarfalseUse Completed Bar
SoundAlertfalsePlay Sound Alerts
PrintOperationsfalsePrint Information Log
Source Code (.mq5)Open Source
Pipsgrowth_com_EX03014.mq5
#property copyright "Pipsgrowth.com"
#property link      "https://pipsgrowth.com"
#property version   "2.00"
#property strict
#property description "Pipsgrowth.com EX03014 MT5_BuildYourGridEA — configurable grid system, full 12-layer stack."
//============================================================================================================================================================================================================================//
enum Type {Open_Buy_And_Sell, Open__Only_Buy, Open__Only_Sell};
enum Next {Grid_According_Trend, Grid_Contrary_Trend};
enum Step {Statical_Step, Geometrical_Step, Exponetial_Step};
enum Target {Target_In_Pips, Target_In_Currency};
enum Loss {Not_Close_In_Loss, Close_First_Orders, Close_All_Orders};
enum Lot  {Statical_Lot, Geometrical_Lot, Exponetial_Lot};
//============================================================================================================================================================================================================================//
#define MagicSet 101010
//============================================================================================================================================================================================================================//
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_TimeFrameRun = PERIOD_H1;
input group "=== Open Orders Parameters ==="
input Type   TypeOrdersPlace       = Open_Buy_And_Sell;//Type Of Orders Place
input Next   TypeOfNextOrders      = Grid_Contrary_Trend;//Type Of Grid Build
input double PipsForNextOrder      = 50.0;//Step For Next Order (Pips)
input Step   TypeOfStepProgress    = Geometrical_Step;//Type Step Progress
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_TimeFrameRun = PERIOD_H1;
input group "=== Close At Profit Parameters ==="
input Target TypeTargetClose       = Target_In_Pips;//Type Of Target Close At Profit
input double PipsCloseInProfit     = 10.0;//Target In Pips Close At Profit
input double CurrCloseInProfit     = 10.0;//Target In Currency Close At Profit
ENUM_TIMEFRAMES MapTimeframeInt(int tf)
{
   switch(tf)
   {
      case 1: return PERIOD_M1;
      case 2: return PERIOD_M5;

Full source code available on download

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

Tags:ex03014gridpipsgrowthfreemt5xauusd

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_EX03014.mq5
File Size56.8 KB
Versionv2.00
PlatformMetaTrader 5
File Type.mq5 Source
StrategyGrid
Risk LevelVery High Risk
Timeframes
M1M15
Currency Pairs
XAUUSD
Min. Deposit$100