Pipsgrowth EX15004 SMC-OrderBlock
MT5 Expert Advisor (Open Source) · XAUUSD · M5, M15
Pipsgrowth.com EX15004 Hybrid_Volatility_SMC_Scalper — OB+FVG + Larry Williams volatility, full 12-layer stack.
Overview
Pipsgrowth EX15004 reads SMC market structure the way a discretionary trader would, then filters every zone touch through a Larry Williams daily-range volatility test before pulling the trigger. The default mode, MODE_OB_AND_FVG, requires price to be inside an active Order Block AND a Fair Value Gap simultaneously — a stricter condition than either zone alone — and the operator can dial it down to OB-only or FVG-only via the InpEntryMode enum if one of the two zone types historically outperforms the other on the chosen symbol.
The market-structure engine is UpdateSwingStructure(). It scans a 10-bar pivot window on each closed bar (InpSwingLength = 10) for a strict high or low, then watches bar 1's close. A close above the prior swing high flips g_swingTrend to +1 and immediately calls CreateOrderBlock(+1), which walks back 10 bars and grabs the most recent bearish candle body — the open becomes the OB top, the close becomes the OB bottom, and the rectangle is drawn on the chart. A close below the prior swing low does the mirror operation with the most recent bullish candle body. So the OB is not a generic rectangle at the swing pivot; it is the body of the last counter-trend candle before the breakout, which is the textbook ICT definition.
Fair Value Gaps are created by DetectFVG() using the classic three-bar pattern: bar[3] high and bar[1] low are compared on every swing update, and a bullish FVG is born when bar[1].low exceeds bar[3].high by more than 0.5 ATR (FVG_MIN_ATR = 0.5). A bearish FVG is the inverse. Up to five of each zone type are kept in parallel (MAX_OB_COUNT = 5, MAX_FVG_COUNT = 5), and each one expires after MAX_ZONE_AGE_BARS = 100 bars. OBTouch() and FVGTouch() are the two functions the entry pipeline calls to confirm price is currently sitting inside one of those zones.
The Larry Williams volatility filter is where this EA diverges from a pure SMC implementation. IsVolatilityOK() pulls today's D1 high minus D1 low and divides it by yesterday's D1 range, then demands a ratio of at least 0.5 (InpRangeFactor). On gold that means if yesterday's range was $35, today has to print at least $17.5 before the engine is even allowed to scan. The idea is borrowed from Larry Williams's work on high-probability days: if today is a compressed, do-nothing day, no zone is worth touching. UpdateDailyRange() recomputes the prior-day range at the top of every new bar.
The regime classifier, ClassifyRegime(), runs on the same new-bar cadence and labels the market into seven buckets. It reads ADX(14), ATR(14) percentile versus the prior 100 bars, and Bollinger Bands(20,2.0) width percentile versus its own 100-bar lookback. ADX >= 25 plus ATR-percentile above 70 yields EXPAND; ADX >= 25 with calmer ATR is STRONG_TREND. ADX 20-25 with high ATR-percentile is BREAKOUT. Low ATR-percentile with low BB-width is COMPRESS. ATR-percentile below 30 without a trend signal is RANGE. Anything left over is CHOPPY — and CHOPPY is the only regime that fully blocks TryEntry(), so the EA explicitly chooses to sit on its hands when no edge is detectable.
The HTF trend filter is a single line: HTFConfirm(dir) reads an H1 EMA(50) and refuses the entry if the closed bar's close is on the wrong side. That is the only higher-timeframe dependency — there is no engulfing requirement, no surge detector, and no second-stage trigger. The signal has to be: (a) bar 1 just printed a candle in the direction of the swing trend, (b) price is currently inside an active OB or FVG of matching bias, and (c) the H1 EMA(50) agrees with the direction. R_MIN = 1.5 then verifies that the realised TP/SL ratio clears 1.5:1 — with the defaults of 2.0 ATR SL and 4.0 ATR TP the ratio is 2.0, so this gate only fires if a user slashes InpTPATR or stretches InpSLATR.
The risk stack is anchored to the EffectiveCapital() function, which returns min(InpCapitalCapAmount, equity). Setting InpCapitalCapAmount to anything above zero anchors the entire percentage-based risk architecture to that ceiling — a $5,000 account with a $500 cap trades as if the balance were $500, so InpRiskPercent = 0.5 risks 0.5% of $500 = $2.50 per trade. CalcLotSize() then converts that dollar risk into lots using the broker's tick value and tick size, with a hard ceiling at InpMaxLot = 10.0. The capital cap floor is $50 (InpCapitalCapFloor); below that floor, no entries are allowed and the comment block shows CAPITAL BELOW FLOOR.
In-trade management is a three-stage ladder that runs every tick through ManagePositions(). Stage one fires once profit reaches +1.0 ATR (InpBEActivateATR) and ratchets the stop to entry plus BE_BUFFER_POINTS = 10 points, locking in scratch-plus. Stage two fires at +2.0 ATR of unrealised profit (PARTIAL_TP_ATR) and closes 50% of the position (PARTIAL_TP_RATIO = 0.50) using TryClosePartial_EX15004, banking half the move while leaving half to run. Stage three is the ATR trail at InpTrailATR = 1.5 — every tick where the new stop is more than 10 points above the existing stop, ModifySLTP() ratchets it to bid minus 1.5 ATR for longs, ask plus 1.5 ATR for shorts. Three separate exits cut risk progressively rather than betting the whole position on a single target.
Three additional exit paths short-circuit the management ladder. If the regime classifier flips the market to CHOPPY while the trade is in profit, the position is closed with reason REGIME_CHOPPY. If the swing trend reverses against the position type (a long in a now-bearish swing, or a short in a now-bullish swing), the position is closed with reason OPP_SIGNAL. And if the trade has been open for more than 200 bars (MAX_BARS_IN_TRADE), it is force-closed with reason MAX_BARS — a time-stop that prevents zombie positions in sideways drift.
The defensive layer is heavier than it looks. IsWithinSession() blocks any server hour outside the 8-20 window when InpUseSessionFilter is on (the wrap-around logic supports midnight-spanning sessions, but the defaults do not use it). IsNewsBlackout() blocks ±30 minutes around server hours 8, 14, and 18 (NEWS_HOUR_1, NEWS_HOUR_2, NEWS_HOUR_3) — three news slots calibrated for the London open, the NY data dump, and the US afternoon. IsSpreadOK() kills entries when the live spread exceeds 30 points (InpMaxSpreadPoints). DailyLossExceeded() tallies today's realised PnL and stops the EA once losses reach 3% of the effective cap. The kill switch (InpKillSwitch) is a manual panic button that blocks all entries while still managing open positions.
The default InpDryRun = true is the most important setting to understand before going live. With dry-run enabled, the entire pipeline — regime classification, zone detection, signal direction, HTF confirm, lot sizing, margin check — runs as if the EA were trading, but TryEntry() short-circuits at the first line and no order is sent. This is the safe mode for the first week on a real account, and it lets the operator watch the comment block cycle through HIGH SPREAD, OUT OF SESSION, NEWS BLACKOUT, LOW VOLATILITY, CHOPPY REGIME, and SCANNING to verify the filters are working before flipping dry-run off. The OnTester custom criterion weights net profit, profit factor, and equity drawdown together as (net * pf) / (1 + maxDD), so the optimizer will favour smooth equity curves over raw return — set the optimization pass to at least 30 trades for a meaningful score.
In practice this EA is a session-aware SMC executor that prefers trending-volatility days, demands zone confluence at the close, and runs a tight three-stage management ladder on the survivors. It is not a grid and not a martingale; the only scaling behaviour is the swing-trend reversal exit, and the only capital overlay is the optional cap. Set InpEntryMode to match the symbol's character — MODE_OB_AND_FVG is the strictest and works on gold's 5-minute rhythm, while FX majors on M15 often respond better to MODE_OB_ONLY. Always dry-run a full trading week before going live, and keep InpMaxSpreadPoints tight on any pair where the spread is the edge.
Strategy Deep Dive
On every tick ManagePositions() runs first, ratcheting stops on survivors through the BE-partial-trail ladder. On a new bar, UpdateDailyRange() refreshes yesterday's D1 range for the volatility filter, ClassifyRegime() labels the market into one of seven buckets using ADX(14), ATR(14)-percentile vs 100 bars, and BB(20,2.0)-width-percentile vs 100 bars. UpdateSwingStructure() then scans a 10-bar pivot window, flips g_swingTrend on a close above/below the prior swing, and calls CreateOrderBlock to capture the last counter-trend candle body or DetectFVG to capture any 3-bar imbalance larger than 0.5 ATR. TryEntry() requires: bar 1 is directional in the swing direction, price is inside an active OB or FVG of matching bias (InpEntryMode selects which zones count), H1 EMA(50) agrees, R_MIN clears 1.5, capital is above the floor, today's PnL is above the -3% daily loss limit, and we are not inside the news blackout or out of session. The InpDryRun=true default short-circuits the actual order send, so the EA logs SCANNING/HIGH SPREAD/CHOPPY REGIME/etc. in the chart comment without placing trades.
Entries fire on a closed-bar trigger: when the swing trend is bullish (g_swingTrend=+1) or bearish (g_swingTrend=-1), the EA scans for price inside an active Order Block or Fair Value Gap of matching bias, the closed bar must be a directional candle in the same direction, and the H1 EMA(50) must agree with the trade side (HTFConfirm). R_MIN = 1.5 also blocks any setup whose realized TP/SL ratio falls below 1.5:1. The 8-20 server-hour session filter, the 30-point spread cap, the 3-hour news blackout windows, and the Larry Williams daily-range filter (today's D1 range >= 0.5x yesterday's) are all applied before the entry attempt. InpDryRun=true default prevents any order from being sent unless flipped to false.
Exits cascade through three layers. Stage one: when unrealised profit reaches +1.0 ATR (InpBEActivateATR), the stop ratchets to entry plus BE_BUFFER_POINTS (10 points) and locks in scratch-plus. Stage two: at +2.0 ATR (PARTIAL_TP_ATR) TryClosePartial_EX15004 fires once to bank 50% of the position. Stage three: every tick, the stop ratchets to bid-minus-1.5-ATR for longs and ask-plus-1.5-ATR for shorts, never moving against the position. Override exits close the trade entirely when the regime classifier flips to CHOPPY (with profit), when g_swingTrend reverses against the position type, or when the trade has been open for more than MAX_BARS_IN_TRADE=200 bars.
Hard stop is set at entry minus InpSLATR (default 2.0 ATR) for longs and entry plus 2.0 ATR for shorts, then normalized through RespectStops() which clamps it to the broker's stops-level plus freeze-level plus 5 points. Once profit reaches +1.0 ATR, the stop ratchets to entry plus 10 points (BE_BUFFER_POINTS) and then continues trailing at 1.5 ATR behind price. No fixed-pip safety net — the entire risk model is ATR-anchored and regime-conditional.
Hard take-profit is set at entry plus InpTPATR (default 4.0 ATR) for longs and entry minus 4.0 ATR for shorts, giving a clean 2:1 reward-to-risk ratio with the 2.0 ATR stop. The R_MIN = 1.5 gate refuses the order if the broker's stops-level would force a sub-1.5 realised ratio. Half of the position is also banked at +2.0 ATR via TryClosePartial_EX15004 before the full TP fires, so the EA realises some profit on most trades that survive the entry filters.
Recommended for XAUUSD M5 with InpMaxSpreadPoints set to 25-30 (broker-dependent — gold spread is the edge). Minimum deposit $100 with the default 0.5% risk per trade, but the practical floor is the $50 InpCapitalCapFloor — operators wanting to scale up should set InpCapitalCapAmount to 1-2% of their actual equity to anchor risk to a sub-account size. Use a low-spread ECN broker with sub-30ms execution — the ATR-anchored SL is tight and slippage matters. The 8-20 server-hour session filter assumes a GMT+2 or GMT+3 broker, which lines up with the London-NY overlap; GMT+0 brokers will trade through Asian hours and may want to disable InpUseSessionFilter and apply a manual hour window. Always run InpDryRun=true for a full trading week before flipping live.
Strategy Logic
Pipsgrowth EX15004 SMC-OrderBlock — Strategy Logic Analysis (from .mq5 source)
Family: SMC-OrderBlock
Magic: 22215004
Version: 2.00
BRIEF:
Hybrid Volatility + SMC scalper. Original thesis: SMC (Order Block + Fair Value Gap) on candle BODY, fused with Larry Williams daily-range volatility breakout. Wrapped in 12-layer
INDICATOR STACK:
ATRADXBBEMAEMA_LTF
KEY FUNCTIONS:
RegimeToString()Percentile()UpdateSwingStructure()CreateOrderBlock()CheckOBMitigation()DetectFVG()CreateFVG()CheckFVGMitigation()CheckZoneExpiration()OBTouch()FVGTouch()TryEntry()- ...and 26 more
INTERNAL CONSTANTS (24 total):
ATR_PERIOD= 14 //ATRperiod (bars)BB_PERIOD= 20 // Bollinger periodBB_DEVIATION=2.0// Bollinger std-devADX_PERIOD= 14 //ADXperiodADX_STRONG_TREND=25.0//ADX>= strong trendADX_WEAK_TREND=20.0//ADX>= weak trendATR_PCTILE_LOOKBACK= 100 // bars forATRpercentileBB_PCTILE_LOOKBACK= 100 // bars forBB-width percentileHTF_EMA_PERIOD= 50 //HTFtrend filterEMAMAX_OB_COUNT= 5 // order-block ring sizeMAX_FVG_COUNT= 5 //FVGring sizeMAX_ZONE_AGE_BARS= 100 // zone expiration (bars)FVG_MIN_ATR=0.5// minFVGsize asATRmultipleSESSION_START_HOUR= 8 // server hourSESSION_END_HOUR= 20 // server hour (exclusive)- ...and 9 more
INPUT PARAMETERS (21 total across 6 groups):
- [=== Identity ===]
InpMagic=22215004// Magic number - [=== Identity ===]
InpTradeComment= "Psgrowth.com Expert_15004" // Trade comment - [=== Identity ===]
InpDryRun=true// Dry-run (no live sends) - [=== Identity ===]
InpKillSwitch=false// Kill switch (block all) - [=== Risk & Sizing ===]
InpRiskPercent=0.5// Risk per trade (% effective cap) - [=== Risk & Sizing ===]
InpMaxLot=10.0// Max lot safeguard - [=== Risk & Sizing ===]
InpDailyLossLimitPct=3.0// Daily loss limit (% effective cap) - [=== Risk & Sizing ===]
InpMaxSpreadPoints= 30 // Max spread (points) - [=== Risk & Sizing ===]
InpMaxConcurrent= 1 // Max concurrent trades (symbol) - [=== Risk & Sizing ===]
InpCooldownMinutes= 5 // Cooldown between trades (min) - [=== Capital Allocation Cap ===]
InpCapitalCapAmount=0.0// Cap amount ($ equity, real money) - [=== Capital Allocation Cap ===]
InpCapitalCapFloor=50.0// Floor — block entries below - [===
Signal(SMC) ===]InpEntryMode=MODE_OB_AND_FVG// Entry mode - [===
Signal(SMC) ===]InpSwingLength= 10 // Swing pivot window (bars) - [=== Regime / Confirm ===]
InpUseVolatilityFilter=true// Larry Williams vol filter - [=== Regime / Confirm ===]
InpRangeFactor=0.5// Required daily range factor - [=== Regime / Confirm ===]
InpUseSessionFilter=true// Session filter - [=== Exit / Manage ===]
InpSLATR=2.0// Stop loss (xATR) - [=== Exit / Manage ===]
InpTPATR=4.0// Take profit (xATR) - [=== Exit / Manage ===]
InpBEActivateATR=1.0// Breakeven trigger (xATRprofit) - [=== Exit / Manage ===]
InpTrailATR=1.5// Trailing distance (xATR)
// Pipsgrowth EX15004 SMC-OrderBlock — Execution Flow (from source analysis)
// Family: SMC-OrderBlock
// Hybrid Volatility + SMC scalper. Original thesis: SMC (Order Block + Fair Value Gap) on candle BODY, fused with Larry Williams daily-range volatility breakout. Wrapped in 12-layer
ON_INIT:
Create indicator handles: ATR, ADX, BB, EMA, EMA_LTF
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 |
|---|---|---|
| InpMagic | 22215004 | Magic number |
| InpTradeComment | "Psgrowth.com Expert_15004" | Trade comment |
| InpDryRun | true | Dry-run (no live sends) |
| InpKillSwitch | false | Kill switch (block all) |
| InpRiskPercent | 0.5 | Risk per trade (% effective cap) |
| InpMaxLot | 10.0 | Max lot safeguard |
| InpDailyLossLimitPct | 3.0 | Daily loss limit (% effective cap) |
| InpMaxSpreadPoints | 30 | Max spread (points) |
| InpMaxConcurrent | 1 | Max concurrent trades (symbol) |
| InpCooldownMinutes | 5 | Cooldown between trades (min) |
| InpCapitalCapAmount | 0.0 | Cap amount ($ equity, real money) |
| InpCapitalCapFloor | 50.0 | Floor — block entries below |
| InpEntryMode | MODE_OB_AND_FVG | Entry mode |
| InpSwingLength | 10 | Swing pivot window (bars) |
| InpUseVolatilityFilter | true | Larry Williams vol filter |
| InpRangeFactor | 0.5 | Required daily range factor |
| InpUseSessionFilter | true | Session filter |
| InpSLATR | 2.0 | Stop loss (x ATR) |
| InpTPATR | 4.0 | Take profit (x ATR) |
| InpBEActivateATR | 1.0 | Breakeven trigger (x ATR profit) |
| InpTrailATR | 1.5 | Trailing distance (x ATR) |
#property copyright "Pipsgrowth.com"
#property link "https://pipsgrowth.com"
#property version "2.00"
#property strict
#property description "Pipsgrowth.com EX15004 Hybrid_Volatility_SMC_Scalper — OB+FVG + Larry Williams volatility, full 12-layer stack."
#include <Trade\Trade.mqh>
#include <Trade\PositionInfo.mqh>
#include <Trade\SymbolInfo.mqh>
#include <Trade\AccountInfo.mqh>
//+------------------------------------------------------------------+
//| TUNABLE CONSTANTS (NOT inputs — keeps input count <= 22) |
//+------------------------------------------------------------------+
#define ATR_PERIOD 14 // ATR period (bars)
#define BB_PERIOD 20 // Bollinger period
#define BB_DEVIATION 2.0 // Bollinger std-dev
#define ADX_PERIOD 14 // ADX period
#define ADX_STRONG_TREND 25.0 // ADX >= strong trend
#define ADX_WEAK_TREND 20.0 // ADX >= weak trend
#define ATR_PCTILE_LOOKBACK 100 // bars for ATR percentile
#define BB_PCTILE_LOOKBACK 100 // bars for BB-width percentile
#define HTF_TIMEFRAME PERIOD_H1
#define HTF_EMA_PERIOD 50 // HTF trend filter EMA
#define MAX_OB_COUNT 5 // order-block ring size
#define MAX_FVG_COUNT 5 // FVG ring size
#define MAX_ZONE_AGE_BARS 100 // zone expiration (bars)
#define FVG_MIN_ATR 0.5 // min FVG size as ATR multiple
#define SESSION_START_HOUR 8 // server hour
#define SESSION_END_HOUR 20 // server hour (exclusive)
#define NEWS_HOUR_1 8 // 0 disables slot
#define NEWS_HOUR_2 14
#define NEWS_HOUR_3 18
#define NEWS_BLACKOUT_MIN 30 // minutes each side of news
#define BE_BUFFER_POINTS 10 // breakeven lock-in buffer
#define PARTIAL_TP_RATIO 0.50 // close 50% at partial
#define PARTIAL_TP_ATR 2.0 // partial-TP trigger (x ATR)
#define MAX_BARS_IN_TRADE 200 // time-based exit
#define DEVIATION_POINTS 30 // slippage tolerance
#define R_MIN 1.5 // min reward:risk
#define DAILY_LOSS_RESET_HOUR 0 // server hour to reset daily PnL
//+------------------------------------------------------------------+
//| ENUMS |
//+------------------------------------------------------------------+
enum ENUM_REGIME
{
REGIME_STRONG_TREND,
REGIME_WEAK_TREND,
REGIME_RANGE,
REGIME_BREAKOUT,
REGIME_COMPRESS,
REGIME_EXPAND,
REGIME_CHOPPY
};
enum ENUM_ENTRY_MODE
{
MODE_OB_ONLY, // Order Block only
MODE_FVG_ONLY, // FVG onlyFull 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 EX12080 MultiIndicatorConfluence
Pipsgrowth.com EX12080 ic_gold — Multi-indicator confluence gold scalper, full 12-layer stack.
Pipsgrowth EX01003 Adaptive
Pipsgrowth.com EX01003 AdaptiveForexMaster FillingMode Fixed — multi-adaptive confirmation EA, full 12-layer stack, configurable timeframe, trailing/BE/profit-lock toggles, pyramid gate, spread filter, new-bar gate.
Pipsgrowth EX04002 HAEA
Pipsgrowth.com EX04002 HA_XAUUSD_5M — Heiken Ashi trend change scalping, full 12-layer stack.
Community
Educational purposes only. Do NOT use with real money. Test on demo accounts only.