Indicator · Pine Script v5 · On the chart

Fair Value Gap (FVG)

by heyphat· code credited to TigerX - Fair Value Gap Indicator

This indicator identifies and plots bullish and bearish Fair Value Gaps (FVG) directly on the price chart.

View on GitHub

GitHub stars26on the repository
Pine versionv5runs as is
Lines of code250
Settings13inputs
LicenceAGPL-3.0
Last update2 months ago21 Aug 2026

Add It to Your TradingView Chart

  1. 1Copy the scriptPress Copy script above, or the copy button on the code below.
  2. 2Open the Pine EditorOpen a TradingView chart and choose Pine Editor at the bottom of the screen.
  3. 3Paste over the templateCreate a new indicator, select all of the template text and paste. Press Save and give it a name.
  4. 4Add it to the chartPress Add to chart, then adjust the settings with the gear icon next to its name.

Source Code

250 lines of Pine Script v5 from test/pinescripts/lux-algo/fvg.pine, published under AGPL-3.0. Keep the author's credit and licence lines when you reuse it.

fvg.pine
// This Pine Script™ code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © TigerX - Fair Value Gap Indicator

//@version=5
indicator("Fair Value Gap (FVG)", overlay=true, max_boxes_count=500)

// ─────────────────────────────────────────────────────────────────────────────
// INPUTS
// ─────────────────────────────────────────────────────────────────────────────

showBullishFVG      = input.bool(true, "Show Bullish FVG", group="Detection")
showBearishFVG      = input.bool(true, "Show Bearish FVG", group="Detection")
filterByATR         = input.bool(true, "Filter by ATR", group="Detection")
atrMultiplier       = input.float(0.5, "Min ATR Multiplier", minval=0.0, step=0.1, group="Detection", tooltip="Minimum gap size as ATR multiple. Higher = fewer FVGs. Try 0.3-1.0")
maxBoxes            = input.int(50, "Max Boxes to Show", minval=1, maxval=500, group="Detection")

bullishColor        = input.color(color.new(#00ff00, 80), "Bullish FVG Color", group="Appearance")
bearishColor        = input.color(color.new(#ff0000, 80), "Bearish FVG Color", group="Appearance")
boxWidth            = input.int(5, "Box Width (candles)", minval=1, maxval=100, group="Appearance", tooltip="Number of candles the FVG box spans")
showMidline         = input.bool(false, "Show Midline", group="Appearance")
midlineStyle        = input.string("Dotted", "Midline Style", options=["Solid", "Dotted", "Dashed"], group="Appearance")

deleteMitigated     = input.bool(true, "Delete Mitigated FVG", group="Mitigation")
mitigationType      = input.string("Wick", "Mitigation Type", options=["Wick", "Close"], group="Mitigation")

// ─────────────────────────────────────────────────────────────────────────────
// CALCULATIONS
// ─────────────────────────────────────────────────────────────────────────────

atr = ta.atr(14)

// Get midline style
getMidlineStyle() =>
    switch midlineStyle
        "Solid" => line.style_solid
        "Dotted" => line.style_dotted
        "Dashed" => line.style_dashed

// ─────────────────────────────────────────────────────────────────────────────
// FVG DETECTION
// ─────────────────────────────────────────────────────────────────────────────

// Bullish FVG: Gap between candle 1's high and candle 3's low
// Candle 1 = bar_index[2], Candle 2 = bar_index[1], Candle 3 = bar_index (current)
bullishFVGCondition = low > high[2]
bullishTop = low
bullishBottom = high[2]
bullishGapSize = bullishTop - bullishBottom

// Bearish FVG: Gap between candle 1's low and candle 3's high  
// Candle 1 = bar_index[2], Candle 2 = bar_index[1], Candle 3 = bar_index (current)
bearishFVGCondition = high < low[2]
bearishTop = low[2]
bearishBottom = high
bearishGapSize = bearishTop - bearishBottom

// Apply ATR filter if enabled
bullishValid = bullishFVGCondition and (not filterByATR or bullishGapSize > atr * atrMultiplier)
bearishValid = bearishFVGCondition and (not filterByATR or bearishGapSize > atr * atrMultiplier)

// ─────────────────────────────────────────────────────────────────────────────
// FVG STORAGE
// ─────────────────────────────────────────────────────────────────────────────

var box[] bullBoxes = array.new_box()
var line[] bullMidlines = array.new_line()
var float[] bullTops = array.new_float()
var float[] bullBottoms = array.new_float()
var int[] bullBars = array.new_int()

var box[] bearBoxes = array.new_box()
var line[] bearMidlines = array.new_line()
var float[] bearTops = array.new_float()
var float[] bearBottoms = array.new_float()
var int[] bearBars = array.new_int()

// ─────────────────────────────────────────────────────────────────────────────
// CREATE FVG BOXES
// ─────────────────────────────────────────────────────────────────────────────

// Create Bullish FVG
if bullishValid and showBullishFVG
    // Create box
    newBox = box.new(
         left=bar_index - 2,
         top=bullishTop,
         right=bar_index - 2 + boxWidth,
         bottom=bullishBottom,
         bgcolor=bullishColor,
         border_color=color.new(color.green, 100),
         border_width=1
         )
    
    array.push(bullBoxes, newBox)
    array.push(bullTops, bullishTop)
    array.push(bullBottoms, bullishBottom)
    array.push(bullBars, bar_index)
    
    // Create midline if enabled
    if showMidline
        midPrice = (bullishTop + bullishBottom) / 2
        newLine = line.new(
             x1=bar_index - 2,
             y1=midPrice,
             x2=bar_index - 2 + boxWidth,
             y2=midPrice,
             color=color.new(color.green, 50),
             style=getMidlineStyle()
             )
        array.push(bullMidlines, newLine)
    else
        array.push(bullMidlines, line(na))
    
    // Limit number of boxes
    if array.size(bullBoxes) > maxBoxes
        box.delete(array.shift(bullBoxes))
        line.delete(array.shift(bullMidlines))
        array.shift(bullTops)
        array.shift(bullBottoms)
        array.shift(bullBars)

// Create Bearish FVG
if bearishValid and showBearishFVG
    // Create box
    newBox = box.new(
         left=bar_index - 2,
         top=bearishTop,
         right=bar_index - 2 + boxWidth,
         bottom=bearishBottom,
         bgcolor=bearishColor,
         border_color=color.new(color.red, 100),
         border_width=1
         )
    
    array.push(bearBoxes, newBox)
    array.push(bearTops, bearishTop)
    array.push(bearBottoms, bearishBottom)
    array.push(bearBars, bar_index)
    
    // Create midline if enabled
    if showMidline
        midPrice = (bearishTop + bearishBottom) / 2
        newLine = line.new(
             x1=bar_index - 2,
             y1=midPrice,
             x2=bar_index - 2 + boxWidth,
             y2=midPrice,
             color=color.new(color.red, 50),
             style=getMidlineStyle()
             )
        array.push(bearMidlines, newLine)
    else
        array.push(bearMidlines, line(na))
    
    // Limit number of boxes
    if array.size(bearBoxes) > maxBoxes
        box.delete(array.shift(bearBoxes))
        line.delete(array.shift(bearMidlines))
        array.shift(bearTops)
        array.shift(bearBottoms)
        array.shift(bearBars)

// ─────────────────────────────────────────────────────────────────────────────
// MITIGATION CHECK
// ─────────────────────────────────────────────────────────────────────────────

// Check Bullish FVG mitigation (price comes down to fill the gap)
if deleteMitigated and array.size(bullBoxes) > 0
    for i = array.size(bullBoxes) - 1 to 0
        fvgTop = array.get(bullTops, i)
        fvgBottom = array.get(bullBottoms, i)
        fvgBar = array.get(bullBars, i)
        
        // Skip mitigation check on the bar when FVG was created
        if bar_index <= fvgBar
            continue
        
        bool isMitigated = false
        
        if mitigationType == "Close"
            // Full mitigation: price closes inside or below the FVG
            isMitigated := close <= fvgTop
        else
            // Wick mitigation: price wick enters the FVG zone
            isMitigated := low <= fvgTop
        
        if isMitigated
            box.delete(array.get(bullBoxes, i))
            line.delete(array.get(bullMidlines, i))
            array.remove(bullBoxes, i)
            array.remove(bullMidlines, i)
            array.remove(bullTops, i)
            array.remove(bullBottoms, i)
            array.remove(bullBars, i)

// Check Bearish FVG mitigation (price comes up to fill the gap)
if deleteMitigated and array.size(bearBoxes) > 0
    for i = array.size(bearBoxes) - 1 to 0
        fvgTop = array.get(bearTops, i)
        fvgBottom = array.get(bearBottoms, i)
        fvgBar = array.get(bearBars, i)
        
        // Skip mitigation check on the bar when FVG was created
        if bar_index <= fvgBar
            continue
        
        bool isMitigated = false
        
        if mitigationType == "Close"
            // Full mitigation: price closes inside or above the FVG
            isMitigated := close >= fvgBottom
        else
            // Wick mitigation: price wick enters the FVG zone
            isMitigated := high >= fvgBottom
        
        if isMitigated
            box.delete(array.get(bearBoxes, i))
            line.delete(array.get(bearMidlines, i))
            array.remove(bearBoxes, i)
            array.remove(bearMidlines, i)
            array.remove(bearTops, i)
            array.remove(bearBottoms, i)
            array.remove(bearBars, i)



// ─────────────────────────────────────────────────────────────────────────────
// ALERTS
// ─────────────────────────────────────────────────────────────────────────────

alertcondition(bullishValid, title="Bullish FVG", message="Bullish Fair Value Gap detected!")
alertcondition(bearishValid, title="Bearish FVG", message="Bearish Fair Value Gap detected!")

// ─────────────────────────────────────────────────────────────────────────────
// INFO TABLE
// ─────────────────────────────────────────────────────────────────────────────

showTable = input.bool(true, "Show Info Table", group="Table")

if showTable and barstate.islast
    var table infoTable = table.new(position.top_right, 2, 3, bgcolor=color.new(color.gray, 85))
    
    table.cell(infoTable, 0, 0, "FVG Type", text_color=color.white, text_size=size.small)
    table.cell(infoTable, 1, 0, "Count", text_color=color.white, text_size=size.small)
    
    table.cell(infoTable, 0, 1, "🟢 Bullish", text_color=color.green, text_size=size.small)
    table.cell(infoTable, 1, 1, str.tostring(array.size(bullBoxes)), text_color=color.green, text_size=size.small)
    
    table.cell(infoTable, 0, 2, "🔴 Bearish", text_color=color.red, text_size=size.small)
    table.cell(infoTable, 1, 2, str.tostring(array.size(bearBoxes)), text_color=color.red, text_size=size.small)

Overview

Fair Value Gap (FVG) detects three-bar imbalances where gaps occur between the high of the first candle and the low of the third candle, or vice versa. The tool includes an ATR multiplier filter to isolate significant gaps, options to show midlines, and configurable mitigation settings based on price wicks or bar closes. Mitigated gaps can be deleted or updated automatically.

Details

Published by

heyphat on GitHub

Code credit

TigerX - Fair Value Gap Indicator, as written in the script's header

Type

Indicator, Pine Script v5

Draws

On the price chart

Category

SMC / ICT / price action, Support & resistance

Markets

Any symbol

Timeframes

Any timeframe

Risk Notes

No repainting, lookahead or stacked entries were found in its code or README. That says nothing about how well it works: test it first.

Topics

backtestingindicatorspine-scriptpinescripttechnical-analysistradingtradingviewtypescript

Settings

The inputs you can change from the gear icon on the chart. Defaults are the author's.

SettingTypeDefaultVariable
Show Bullish FVGbooltrueshowBullishFVG
Show Bearish FVGbooltrueshowBearishFVG
Filter by ATRbooltruefilterByATR
Min ATR Multiplierfloat0.5atrMultiplier
Max Boxes to Showint50maxBoxes
Bullish FVG Colorcolorcolor.new(#00ff00, 80)bullishColor
Bearish FVG Colorcolorcolor.new(#ff0000, 80)bearishColor
Box Width (candles)int5boxWidth
Show MidlineboolfalseshowMidline
Midline StylestringDottedmidlineStyle
Delete Mitigated FVGbooltruedeleteMitigated
Mitigation TypestringWickmitigationType
Show all 13 settings
SettingTypeDefaultVariable
Show Info TablebooltrueshowTable
Third-party code. ForexR did not write, test or endorse this script, and the summary above was generated automatically from its code and README. Indicators describe the past, and a strategy's backtest can look better than live trading, especially when a script repaints. Check it in the Strategy Tester and on a demo account before you rely on it.

Similar Pine Scripts

ICT Equal Highs and Lows

by ArunKBhaskar
575 stars

This overlay indicator finds pivot highs and lows on the price chart and compares the last two highs and the last two lows. When the percentage difference between a pair is below the Equal HL threshold, it treats them as equal levels and draws a box. Left and

Indicator v5 SMC / ICT / price actionSupport & resistance
Updated 1 year ago · MPL-2.0 GitHub repository of ICT Equal Highs and Lows

DE-tracker

by Allen1212
303 stars

This indicator plots labels on the TradingView price chart to mark ARK Invest's buy and sell trades for the DE stock. Buy transactions appear in green with X1 or X2 multipliers showing the number of ARK ETFs involved on the same day; sells appear in red. The m

Indicator v4 Support & resistanceSMC / ICT / price action
Updated 2 years ago · None stated GitHub repository of DE-tracker

This Pine Script indicator plots a ZigZag on the price chart. It identifies reversal points when price moves more than a set percentage from the last pivot. The script calculates forecasts using zigzag data and labels detected geometric patterns including harm

Indicator v4 TrendSupport & resistance

Golden Bullet Strategy

by TradersPost
218 stars

The Golden Bullet Strategy is an overlay signal indicator based on Smart Money Concepts and time-based liquidity models. It identifies liquidity sweeps of a designated reference session range during a specified hunt window. It then confirms Market Structure Sh

Indicator v6 SMC / ICT / price actionSessions & time
Updated 3 months ago · None stated GitHub repository of Golden Bullet Strategy

Open Source Fractal

by cantolab
183 stars

This indicator implements the Fractal Model concept to plot market structure shifts, liquidity sweeps, and Change in State of Delivery (CISD) levels. It overlays custom higher-timeframe candle previews, open prices, and time markers directly on the price chart

Indicator v6 SMC / ICT / price actionSupport & resistance
Updated 2 months ago · MIT GitHub repository of Open Source Fractal

Swing Failure Signals

by Ganador1
154 stars

This indicator calculates pivot highs and pivot lows to detect liquidity sweeps and Swing Failure Patterns. It identifies when price breaks past recent key swing highs or lows within a configurable historical window, then looks for a quick reversal or change i

Indicator v6 SMC / ICT / price actionSupport & resistance
Updated 2 months ago · Apache-2.0 GitHub repository of Swing Failure Signals

More indicators

Trade Your Charts With a Regulated Broker

Compare brokers that connect to TradingView, with spreads, minimum deposits and leverage side by side.

Compare brokers