How to Automate Fair Value Gap (FVG) Detection for Smarter Trading
Tired of manually drawing FVG levels on your charts and answering the same questions in your trading group? Here's how to automate the entire process using Python, from data fetching to visualization and backtesting.
I saw a tweet from a trader last week that perfectly captures why I wrote this tutorial. He was complaining about being "too busy answering the same questions over and over." Questions like: Is this an indicator? Where do you get the data? How do I get it to draw levels? Do you draw them manually?
The irony is that this trader runs statistical analysis on Fair Value Gaps (FVG) for futures trading. He's clearly technical. Yet he's still manually identifying and drawing these gaps on charts. The same gaps that follow an algorithmic pattern. The same gaps that a script could detect in milliseconds.
If you're spending hours marking up charts, or worse, paying for indicators that do a mediocre job, this tutorial will change how you approach FVG trading. We're going to build a complete FVG detection system in Python. Not a toy example. A real system that fetches live data, identifies gaps, tracks their lifecycle, and visualizes everything cleanly.
By the end, you'll have code you can run against any market. More importantly, you'll understand the logic deeply enough to modify it for your specific trading style.
A Fair Value Gap forms when price moves so aggressively that it leaves an imbalance on the chart. In Smart Money Concepts terminology, this represents inefficient price action that the market often returns to "fill."
The mechanical definition is straightforward. For a bullish FVG, you need three consecutive candles where the low of the third candle is higher than the high of the first candle. The gap between them is the FVG. Bearish FVGs are the mirror image.
What makes FVGs tradeable isn't just their formation. It's what happens after. Price tends to revisit these zones. Sometimes it fills completely, sometimes partially. Tracking this behavior is where automation becomes invaluable.
Most tutorials stop at detection. We're going further. We'll track gap mitigation, calculate fill percentages, and build the foundation for backtesting FVG strategies.
You'll need a few libraries. Pandas for data manipulation, yfinance for free market data (or ccxt if you're trading crypto), and matplotlib plus mplfinance for visualization.
pip install pandas numpy yfinance mplfinance ccxt
The choice of data source matters. For stocks and futures, yfinance works well for prototyping. For crypto, ccxt gives you access to dozens of exchanges. For production systems, you'd want a proper data vendor, but free sources are fine for development.
import pandas as pdimport numpy as npimport yfinance as yfimport mplfinance as mpffrom datetime import datetime, timedelta
Here's where the magic happens. The detection logic scans through candles in groups of three, checking whether a gap exists between the first and third candle that the second candle doesn't fill.
The min_gap_pct parameter is crucial. Without it, you'll detect thousands of tiny gaps that have no trading significance. Start with 0.1% (0.001) and adjust based on the asset's volatility.
Detection is only half the story. The real value comes from tracking what happens to these gaps over time. Do they get filled? How quickly? These questions matter for strategy development.
def track_mitigation(df: pd.DataFrame, fvgs: List[FVG], lookforward: int = 50) -> List[FVG]: """ Track whether FVGs get mitigated (price returns to fill the gap). Args: df: Price data continuing after FVG formation fvgs: List of detected FVGs
The mitigation tracking reveals patterns that manual analysis would miss. When you run this on historical data, you start seeing things like "75% of bullish FVGs on this asset get at least partially filled within 20 candles." That's actionable intelligence.
A detection system isn't useful if you can't see what it found. Here's how to render FVGs on candlestick charts using mplfinance.
def plot_fvg_chart(df: pd.DataFrame, fvgs: List[FVG], title: str = "FVG Detection") -> None: """ Plot candlestick chart with FVG zones highlighted. """ # Create rectangles for FVG zones fvg_lines =
For a more sophisticated visualization with filled rectangles representing the gap zones, you'll need to use matplotlib's Rectangle patches directly. The mplfinance library has some limitations with custom shapes.
import matplotlib.pyplot as pltimport matplotlib.patches as patchesfrom mplfinance.original_flavor import candlestick_ohlcimport matplotlib.dates as mdatesdef plot_advanced_fvg_chart(df: pd.DataFrame, fvgs: List[
Here's a complete example that ties everything together. This script fetches data, detects FVGs, tracks mitigation, and outputs statistics.
def main(): # Fetch data - using SPY as example print("Fetching data...") df = fetch_ohlcv("SPY", interval="1h", days=60)
When you run this against SPY hourly data, you'll see output like:
Loaded 720 candlesDetecting Fair Value Gaps...Found 47 FVGsTracking mitigation...==================================================FVG STATISTICS==================================================Total FVGs detected: 47 - Bullish: 28 - Bearish: 19Mitigation rate: 72.3%Average fill when mitigated: 84.2%Average gap size: $0.43
Those numbers tell a story. A 72% mitigation rate means most gaps do eventually get filled. An 84% average fill suggests price often retraces deep into the gap zone. These are the kinds of insights that shape trading strategies.
Here's where most FVG systems fall short. They detect gaps but don't distinguish between high-probability and low-probability setups. Not all FVGs are equal.
Factors that affect FVG quality include the trend context (FVGs with trend are stronger), the gap size relative to recent volatility, time of day for futures, and volume during gap formation.
Building a scoring system for FVG quality is where you start developing real edge. This is also where tools like the EKX.AI scanner become valuable. While the code above handles detection, identifying which FVGs are worth trading requires analyzing broader market context. Smart money movements, unusual volume patterns, and liquidity conditions all factor in.
The scanner complements manual FVG analysis by surfacing the market conditions that make certain gaps more significant. When you see an FVG forming right as whale wallets start accumulating, that's a different signal than an FVG appearing during random noise.
Automated detection is step one. The real edge comes from combining technical patterns with on-chain data and volume analysis. Tools that aggregate multiple signal types help filter the noise from genuine opportunities.
After running FVG detection on dozens of assets, patterns emerge in what goes wrong.
Over-detection happens when your gap threshold is too small. You end up with hundreds of micro-gaps that have no statistical significance. Start with larger thresholds and work down.
Ignoring context leads to trading FVGs against the trend. A bullish FVG in a strong downtrend often just gets steamrolled. Add trend filters before taking signals.
Not tracking results means you never know if your FVG strategy actually works. Build in logging from day one. Track every gap detected, every fill, every outcome.
Curve fitting occurs when you optimize parameters on historical data until they look perfect. Then they fail on new data. Use out-of-sample testing, always.
You now have a complete FVG detection and tracking system. The code is modular enough to extend in several directions.
For a trading bot, add order execution logic and position sizing. For a scanner product, wrap it in a web API and build a frontend. For research, run it against years of data and publish your findings.
The traders who consistently profit from FVGs aren't the ones with the fanciest indicators. They're the ones who understand the underlying mechanics deeply, track their results meticulously, and continuously refine their approach based on data.
This tutorial gives you the foundation. What you build on top of it is where the real work begins.
Start with one asset. Run the detection for a month. Track what happens. Then expand. The best trading systems are built incrementally, with each layer tested before the next is added.
The code is yours to modify, extend, and deploy. Fair Value Gaps are just one piece of the Smart Money Concepts puzzle. But it's a piece that, when automated properly, can save hours of manual chart work every single week.
That time saved compounds. Use it to find edge elsewhere, or simply to trade with less stress. Either way, you're now equipped to do what most retail traders can't: let code do the tedious work while you focus on decisions that matter.