Cloud VPS from $1.98/mo · pay with Bitcoin, Ethereum, Monero, USDT or Solana · paid in crypto
Trading and crypto

Fair value gaps explained: the three-candle pattern in code

What a fair value gap is, how the three-candle rule defines bullish and bearish gaps, and how to detect them in Python without lookahead bias.

CloudSat teamNovember 18, 20266 min read
Abstract illustration of three tall candles with a glowing empty band between the first and the third, outlined like a missing puzzle piece
On this pageThe three-candle rule

A fair value gap (FVG) is a price range that one fast candle skipped over, leaving no overlap between the candles on either side. The term comes from the "smart money concepts" style of chart reading, where gaps are drawn as zones and watched for price to return into them. Whatever you think of that school, the pattern itself has a precise definition, which makes it easy to detect in code and to study on your own data. This guide covers the definition, the vocabulary, a detector without lookahead bias, and the limits of what the pattern tells you.

The three-candle rule

An FVG needs three consecutive candles. The middle one moves far enough that the wicks of the first and third candles do not overlap:

  • Bullish FVG: the low of candle 3 is above the high of candle 1. The gap runs from candle 1's high (bottom) to candle 3's low (top).
  • Bearish FVG: the high of candle 3 is below the low of candle 1. The gap runs from candle 3's high (bottom) to candle 1's low (top).

Candle 2's body and wicks fill the space between, but no trading happened in that range on either neighbor. On a chart, the gap is drawn as a box starting at candle 2 and extended to the right.

Bullish FVG Bearish FVG
Condition low[3] > high[1] high[3] < low[1]
Bottom of the zone high[1] high[3]
Top of the zone low[3] low[1]
Exists from Close of candle 3 Close of candle 3

The last row matters most for automation. Until candle 3 closes, its low or high can still change, so the gap is not confirmed. A detector that marks the gap at candle 2 is looking into the future.

How it differs from a price gap

A classic price gap is a jump between one candle's close and the next one's open, typical when an exchange reopens after a night or a weekend. A fair value gap can form in a market that never closes, such as crypto, or inside a single session, because it compares wicks across three candles rather than consecutive prices. A real price gap can create an FVG, but most FVGs involve no gap in the price feed at all.

The vocabulary around FVGs

Traders who use the pattern describe what happens next with a few recurring terms:

  • Mitigated or filled: price trades back into the zone. Some count any touch; others require a full fill to the far edge.
  • Partially filled: price enters the zone but does not cross it. Some charting tools then shrink the box to the unfilled part.
  • Midpoint: the 50% level of the zone, which some traders mark separately.
  • Inversion: price closes through the whole zone, after which some traders treat the old gap as a zone of the opposite type.

These are labels, not findings. Whether price returning into a gap means anything beyond the fact that prices move back and forth is a question for data.

Detecting FVGs in Python

The rule translates into a few lines of pandas. This function takes candles with open, high, low and close columns and returns one row per gap, stamped at candle 3, the moment it becomes known:

import pandas as pd

def find_fvgs(df: pd.DataFrame, min_size: float = 0.0) -> pd.DataFrame:
    """Return one row per fair value gap, indexed at the third candle."""
    h1, l1 = df["high"].shift(2), df["low"].shift(2)   # candle 1
    h3, l3 = df["high"], df["low"]                     # candle 3

    bull = l3 > h1 + min_size
    bear = h3 < l1 - min_size

    gaps = pd.concat([
        pd.DataFrame({"type": "bullish", "bottom": h1[bull], "top": l3[bull]}),
        pd.DataFrame({"type": "bearish", "bottom": h3[bear], "top": l1[bear]}),
    ]).sort_index()
    gaps["size"] = gaps["top"] - gaps["bottom"]
    return gaps

min_size filters out gaps too small to matter. A fixed price distance works for one instrument; across instruments, scale it to volatility, for example a fraction of the average true range.

To see whether and when each gap was touched afterward, scan the candles that follow it:

def first_touch(df: pd.DataFrame, gaps: pd.DataFrame) -> pd.DataFrame:
    touches = []
    for ts, g in gaps.iterrows():
        later = df.loc[df.index > ts]
        if g["type"] == "bullish":
            hit = later.index[later["low"] <= g["top"]]
        else:
            hit = later.index[later["high"] >= g["bottom"]]
        touches.append(hit[0] if len(hit) else pd.NaT)
    return gaps.assign(first_touch=touches)

The loop is slow on years of minute data but clear; vectorize it once the logic is settled. Everything here can run on a small Linux server next to the data it reads.

What changes the answer

FVG detection looks objective, but several choices change which gaps you find:

  • Timeframe. A gap on a 5-minute chart may vanish on the 15-minute chart, where the three candles merge. Every timeframe has its own set.
  • Price source. Forex brokers stream their own prices, usually bid prices, so two brokers' charts show slightly different wicks and different gaps. Crypto exchanges differ from each other in the same way.
  • Session boundaries. On instruments that close overnight, gaps across the close mix two effects. Decide whether to include them.
  • Size threshold. Without a minimum, quiet markets produce many tiny gaps that tell you nothing.
  • Overlapping gaps. A strong move can leave several gaps in a row that overlap. Decide whether to merge them into one zone or count each one, because the choice changes every statistic that follows.

Write these choices down. A study that does not state them cannot be repeated or checked.

What FVGs cannot tell you

An FVG records that price moved quickly through a range. It does not record why, who traded, or what happens next. Claims that gaps "must" be filled or that they mark where large institutions will buy are interpretations, not properties of the pattern.

If you want to test such a claim, compare against a baseline. Prices oscillate, so many zones get touched sooner or later just by chance. Draw zones of the same size at random times, run the same touch analysis, and see whether real gaps behave differently. Then add realistic spreads and fees, and keep some data aside that you only examine once at the end. Most impressive-looking pattern statistics shrink under those three steps, and an honest result either way is worth more than a chart with boxes drawn after the fact.

If you automate any rule built on gaps, the bot or expert advisor needs the same discipline: signals at candle 3's close, the same data source live as in testing, and a hosting setup that keeps it running. Gaps are often read alongside volume-based zones, covered in volume profile explained.

FAQ

Is an FVG the same as an imbalance?

In smart money concepts terminology, the two words are often used interchangeably for the same three-candle gap. Some educators draw finer distinctions, so check the definition behind any tool you use.

Which timeframe should FVGs be measured on?

There is no correct one. The pattern exists on every timeframe, and each produces different gaps. Pick the timeframe your analysis is about, state it, and keep it fixed while testing.

Can the same check run live in MetaTrader or a bot?

Yes. When a new bar opens, the last closed bar is candle 3 and the bar two before it is candle 1. In MQL5, compare iLow(_Symbol, PERIOD_CURRENT, 1) with iHigh(_Symbol, PERIOD_CURRENT, 3) for a bullish gap, and the reverse for a bearish one.

Why does my charting tool show gaps that my code does not?

Usually a different price source, a size filter, or a tool that draws the box from candle 2 before candle 3 has closed. Compare the rules, not the pictures.

Trading involves risk of loss. Nothing in this article is financial advice.

Run it on CloudSat. Cloud VPS on AMD EPYC and NVMe from $1.98/mo in 13 regions, delivered in under 5 minutes and paid in crypto. See plans or deploy a server.