Fair Value Gap MT4 indicator mapping bullish and bearish price imbalance boxes.
The ICT Fair Value Gap (FVG) MT4 Indicator is an open-source technical tool written in MQL4. It automatically detects 3-candle market imbalances (BISI and SIBI), highlights unfilled liquidity voids, plots 50% Consequent Encroachment levels, and provides instant mitigation alerts.
ICT Fair Value Gap (FVG) MT4 Indicator Overview
What Is a Fair Value Gap (FVG) in ICT & Smart Money Trading?
In Inner Circle Trader (ICT) and Smart Money Concepts (SMC) methodology, a Fair Value Gap (FVG) is a specific 3-candlestick price pattern that marks an area of market inefficiency or liquidity void. It is created when aggressive institutional market orders cause an explosive displacement candle (Candle 2), leaving a price void between the wick extreme of Candle 1 and the wick extreme of Candle 3.
In efficient auction market theory, price naturally seeks balance (fair value delivery). Because one side of the order book was overwhelmed during the displacement move, institutional algorithms frequently re-deliver price back into these inefficient voids to balance orders before continuing in the intended trend direction. As a result, FVGs serve as magnetic retracement targets and high-probability entry confluence levels.
Bullish (BISI) vs Bearish (SIBI) Imbalances
FVG patterns are divided into two primary structural forms depending on market direction and liquidity delivery:
Bullish FVG (BISI)
Buyside Imbalance Sellside Inefficiency: Created when Candle 2 surges upward. The gap between the High of Candle 1 and the Low of Candle 3 forms a bullish imbalance box where only buying occurred. When price pulls back into this gap, it acts as high-probability support.
Bearish FVG (SIBI)
Sellside Imbalance Buyside Inefficiency: Created when Candle 2 plunges downward. The gap between the Low of Candle 1 and the High of Candle 3 forms a bearish imbalance box where only selling occurred. When price retraces up into this gap, it acts as high-probability resistance.
Advanced FVG Types: Inversion FVGs (IFVG) & Balanced Price Ranges (BPR)
Professional institutional traders do not view Fair Value Gaps in isolation. When market conditions shift rapidly, two advanced variations frequently emerge:
Inversion Fair Value Gap (IFVG)
When a bullish or bearish FVG fails to support price and is aggressively violated with a closed candle, it flips polarity. A failed bullish FVG becomes a potent bearish resistance zone on subsequent retests.
Balanced Price Range (BPR)
Formed when an aggressive upward displacement BISI is immediately followed by an equal downward displacement SIBI. The overlapping zone creates a high-sensitivity institutional equilibrium pivot.
Consequent Encroachment (C.E.) & Mitigation Mechanics
The 50% midpoint of any Fair Value Gap is referred to as Consequent Encroachment (C.E.). ICT algorithms monitor this equilibrium level with extreme precision. The lifecycle of a Fair Value Gap follows three distinct states:
| FVG State | Price Condition | Visual Indicator Behavior | Trading Action |
|---|---|---|---|
| Open (Unmitigated) | Price has not yet touched the gap | Full color semi-transparent rectangle extending to live price | Primary target for pending orders and limit entries. |
| Partially Filled (C.E. Touch) | Price retraced into 50% midpoint | Displays dashed C.E. line with real-time audio alert | Ideal lower-timeframe execution trigger. |
| Fully Mitigated (Filled) | Price closed through entire gap | Automatically grayed out or removed from chart | Imbalance balanced; no further entries taken. |
How the FVG MT4 Indicator Calculates Imbalances
The MQL4 algorithm calculates Fair Value Gaps using strict closed-candle logic:
- Iterates across historical bar sequences evaluating 3 consecutive candle triplets (i, i+1, i+2).
- For Bullish FVG: Verifies if
Low[i] > High[i+2] + MinGapPoints. - For Bearish FVG: Verifies if
High[i] < Low[i+2] - MinGapPoints. - Draws an MT4 graphical rectangle (OBJ_RECTANGLE) spanning from the start time of Candle 1 forward.
- Calculates and renders the exact 50% Consequent Encroachment (C.E.) horizontal line.
- Monitors real-time price ticks to trigger audio, popup, and push notification alerts when the gap is touched.
Pro Trader Rules & 5 Common FVG Mistakes to Avoid
- Do Not Trade Every Single FVG: Low-timeframe charts generate dozens of small gaps. Only take FVGs that align with higher timeframe (H4/D1) market structure direction.
- Look for Confluence with Order Blocks: The highest probability FVGs reside directly at the origin of an unmitigated Order Block.
- Watch the Candle Closes at C.E.: If candle bodies close past the 50% Consequent Encroachment level, the probability of an inversion breakout increases significantly.
- Account for Economic News Releases: Avoid entering on FVGs created during high-impact news releases (NFP, CPI, FOMC) until initial volatility settles into structured order flow.
- Never Place Stop Losses Inside the Gap: Place your invalidation stop beyond the outer extreme of Candle 1 or beyond the structural swing pivot.
Supported MT4 Timeframes for FVG Analysis
| Timeframe | Trading Style | Application |
|---|---|---|
| M1 / M5 | Scalping | Precision lower-timeframe entry confluence inside HTF zones. |
| M15 / M30 | Day Trading | Mapping London and New York session displacement voids. |
| H1 / H4 | Swing Trading | Primary liquidity void targets and multi-day trend continuation setups. |
| D1 / W1 | Macro / Position | Institutional macro rebalancing zones for long-term swing positions. |
Fair Value Gap vs Order Block vs Volume Profile
| Metric | Fair Value Gap (FVG) | Order Block (OB) | Volume Profile (VP) |
|---|---|---|---|
| Definition | 3-candle price imbalance void | Origin base candle before displacement | Volume traded per price level |
| Trading Role | Retracement target & entry confluence | Primary supply/demand pivot | Value Area (VA) & POC level identification |
| Optimal Confluence | Overlapping inside an unmitigated Order Block | Order Block containing a fresh FVG | FVG aligning with Low Volume Nodes (LVN) |
Key Features & Capabilities
Input Parameters & Settings Guide
Configure the indicator inputs inside MetaTrader MT4 via the Inputs tab upon attaching to your chart:
| Parameter | Default Value | Description | Recommended |
|---|---|---|---|
| InpBullishFVGColor | clrMediumSeaGreen | Color for bullish imbalance boxes | SeaGreen / Emerald |
| InpBearishFVGColor | clrIndianRed | Color for bearish imbalance boxes | IndianRed / Crimson |
| InpMinGapPoints | 10 | Minimum gap size in points to filter noise | 10-20 points |
| InpExtendUnmitigated | true | Extend box forward until price touches it | True |
| InpAlertOnMitigation | true | Audio & popup alert upon gap fill | True |
| InpShowMidpointCE | true | Plot 50% Consequent Encroachment line | True |
Trading Strategy & Entry Rules
Step 1: Determine Macro Trend Direction
Identify whether the higher timeframe (H1/H4) is in an established bullish or bearish market structure with consecutive BOS breaks.
Step 2: Identify High-Momentum Displacement
Look for strong expansion candles that leave clean, wide Fair Value Gaps overlapping with key Order Blocks.
Step 3: Wait for Retracement into the FVG
Patiently allow price to retrace into the 50% Consequent Encroachment (C.E.) of the highlighted imbalance zone without chasing price.
Step 4: Lower Timeframe Entry Trigger
On the M5 or M1 chart, enter upon observing a Change of Character (CHoCH) or a rejection pin bar inside the FVG box.
Step 5: Target Opposing Liquidity
Place your stop loss safely beyond the outer invalidation candle and target the next swing high or low liquidity pool for a 1:3+ risk-to-reward ratio.
MQL4 Source Code
//+------------------------------------------------------------------+
//| FairValueGap_FVG_MT4.mq4 |
//| Copyright 2026, TraderSentiments Quant Team |
//| https://tradersentiments.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2026, TraderSentiments"
#property link "https://tradersentiments.com/indicators/mt4/smart-money/fair-value-gap-indicator"
#property version "2.10"
#property strict
#property indicator_chart_window
input color InpBullishFVGColor = clrMediumSeaGreen; // Bullish Imbalance Box Color
input color InpBearishFVGColor = clrIndianRed; // Bearish Imbalance Box Color
input bool InpExtendUnmitigated= true; // Extend Lines Until Price Mitigates
input int InpMinGapPoints = 10; // Minimum Gap Size (Points)
input bool InpAlertOnMitigation= true; // Alert When FVG Is Filled
int OnInit() {
IndicatorShortName("ICT Fair Value Gap (FVG) MT4");
return(INIT_SUCCEEDED);
}How to Install & Compile in MetaTrader MT4
Follow this complete step-by-step technical guide to install, compile, and configure the custom MQL4 indicator on your desktop trading terminal:
Download Source File
Download the raw .mq4 source file to your computer using the direct download button below.
Open MT4 Data Folder
Open your MetaTrader terminal, navigate to the top menu bar, click File → Open Data Folder, and open the MQL4 → Indicators subfolder.
Copy & Compile in MetaEditor
Paste the downloaded file into the Indicators directory. Press F4 on your keyboard to launch MetaEditor, open the file, and press Compile (F7). Ensure the compiler reports 0 errors and 0 warnings.
Attach to Chart & Configure
Return to your terminal, refresh the Navigator (Ctrl+N) panel, drag the indicator onto your active chart, check Allow DLL imports (if applicable), and customize input parameters.
Integrating with Expert Advisors (EA) via iCustom()
Algorithmic traders and quant developers can seamlessly integrate this indicator into custom automated Expert Advisors (EAs). Because the indicator calculates values into standardized plot buffers on closed bars, you can query buffer values using native MQL4 functions without recompilation:
// MT4 MQL4 iCustom Calling Syntax Example
double signalBuy = iCustom(Symbol(), Period(), "FairValueGap_FVG_MT4", 0, 1);
double signalSell = iCustom(Symbol(), Period(), "FairValueGap_FVG_MT4", 1, 1);
if (signalBuy != 0.0 && signalBuy != EMPTY_VALUE) {
// Bullish signal confirmed on closed bar [1] -> Execute Buy Order
}
if (signalSell != 0.0 && signalSell != EMPTY_VALUE) {
// Bearish signal confirmed on closed bar [1] -> Execute Sell Order
}How to Set Up Mobile Push Notifications on iOS & Android
To receive real-time push alerts on your smartphone whenever an institutional signal triggers:
- Install the official MetaTrader MT4 app on your iPhone or Android smartphone.
- Open the mobile app, go to Settings → Messages, and copy your unique 8-character MetaQuotes ID.
- In your desktop MetaTrader terminal, click Tools → Options (Ctrl+O) → Notifications tab.
- Check Enable Push Notifications and paste your MetaQuotes ID into the box.
- Click Test to verify phone delivery, then enable push alerts in the indicator inputs.
Institutional Risk Management & Capital Preservation Protocol
Professional proprietary trading desks operate under strict risk control parameters to ensure longevity:
- Maximum 1% - 2% Risk Rule: Never risk more than 1% to 2% of total account equity on any individual trade setup.
- Minimum 1:2.5 Risk-to-Reward Ratio (RRR): Only execute setups where the potential profit target is at least 2.5 times greater than the stop-loss invalidation distance.
- Multi-Timeframe Confluence Required: Never take an intraday trade against the primary Daily or 4-Hour trend direction.
- High-Impact Economic News Awareness: Avoid entering new positions 15 minutes before and after major macroeconomic data releases (such as US Non-Farm Payrolls, CPI Inflation, and central bank FOMC/ECB interest rate announcements).
Strategy Backtesting & Historical Modeling Protocol
Before deploying any indicator or automated strategy in a live trading environment, professional quants conduct rigorous multi-year backtesting across varying market conditions:
- 99.9% Tick Data Modeling: Use high-precision tick history from reputable data providers (such as Dukascopy or TrueFX) to eliminate spread anomalies and slippage distortion.
- Spread & Commission Inclusion: Always test with realistic variable spreads and broker commission structures to simulate true real-world execution friction.
- Out-of-Sample Walk-Forward Optimization: Avoid curve-fitting by validating parameters on 70% in-sample data and testing robustness on 30% out-of-sample data.
- Monte Carlo Drawdown Analysis: Run randomized trade sequence simulations to calculate the maximum potential drawdown under adverse market volatility regimes.
Virtual Private Server (VPS) & Execution Latency Optimization
For active day traders, scalpers, and automated Expert Advisors, execution speed is paramount:
- Low-Latency Proximity Hosting: Deploy your MetaTrader MT4 terminal on a dedicated Windows VPS located in the same financial data center (e.g. Equinix LD4 in London or NY4 in New York) as your broker server to achieve sub-millisecond execution times.
- Terminal Memory Optimization: Go to Tools → Options → Charts and decrease Max bars in chart to 5,000 to conserve CPU and RAM resources.
- Audio & News Feed Disabling: Turn off unneeded terminal audio event chimes and background news feeds to ensure 100% of CPU cycles are dedicated to indicator calculations.
Common MetaTrader Error Codes & Resolution Matrix
| Error Code | Description | Exact Resolution Action |
|---|---|---|
| ERR_INVALID_STOPS (130) | Stop Loss or Take Profit is too close to current price. | Verify broker freeze/stops level in symbol specification and increase SL distance. |
| ERR_OFF_QUOTES (136) | Broker server has no available liquidity quotes. | Market may be closed or experiencing extreme liquidity disruption during major news. |
| ERR_REQUOTE (138) | Price moved before order reached broker liquidity pool. | Increase slippage tolerance deviation parameter in your order execution settings. |
| ERR_TRADE_TIMEOUT (128) | Order request timed out waiting for server acknowledgment. | Check internet connection latency or migrate terminal to a dedicated trading VPS. |
Institutional Quantitative Trading Lexicon
Broker Execution Models & Raw Spread Compatibility
To achieve optimal performance when using custom technical indicators:
- ECN / Raw Spread Accounts: Use True ECN accounts with 0.0 pip spreads and transparent commissions to ensure precision stop loss and take profit execution.
- No Dealing Desk (NDD) Routing: Direct market access ensures orders are routed straight to tier-1 liquidity providers without dealer intervention or artificial requotes.
- Leverage & Margin Safety: Maintain sufficient free margin (minimum 500% margin level) to avoid margin calls during sudden macroeconomic volatility spikes.
FairValueGap_FVG_MT4.mq4
Version: v2.10File Size: 15.2 KBTotal Downloads: 15,000+License: Free Open SourcePlatform: MetaTrader MT4
Frequently Asked Questions

Quantitative algorithmic trading research desk specializing in MetaTrader MQL4/MQL5 automated systems, institutional order book mechanics, and risk management tools.
