Indicator · Pine Script v5 · On the chart

3 Bar Gap

by kevinhhl· code credited to DojiEmoji

The 3 Bar Gap indicator identifies fair value gaps and price imbalances across a three-bar pattern directly on the price chart.

View on GitHub

GitHub stars4on the repository
Pine versionv5runs as is
Lines of code72
Settings5inputs
LicenceNone statedfile: MPL-2.0
Last update3 years ago6 Oct 2023

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

72 lines of Pine Script v5 from Scripts/3 Bar Gap.pine, published under MPL-2.0 (file header). Keep the author's credit and licence lines when you reuse it.

3 Bar Gap.pine
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © DojiEmoji

// This script is tailored towards experienced traders who prefer to view raw price charts during live execution. 
// It searches for a three-bar pattern of what is colloquially called "fair value gap", or "imbalance" and uses 
// a single line to plot the results. The goal is to display price in a way that is as simple as possible so that 
// chart readers who don't prefer to add indicators on their screen will still find this indicator as an 
// acceptable option to consider for.

//@version=5
indicator("3 Bar Gap [DojiEmoji]", overlay=true)

//---------------------
// Settings - Adjustable:
var int atr_filter_len = input.int(20, minval=2, inline="ln1", title="Threshold: ATR")
var float atr_filter_multi = input.float(0.5, minval=0.1, maxval=1, step=0.1, inline="ln1", title="x",
 tooltip="The minimum distance that candles [over 3 bars] must 'gap' by in order for move to be"+
 "considered significant.\n\n-Higher Multi. => Less lines \n-Lower Multi. => More lines (might be noisy)"
 )
var color col_up    = input.color(color.new(color.blue,0), title="Colors for Up move / Down move:", inline="ln2", group="Plots")
var color col_dn    = input.color(color.new(color.red,0), title="/", inline="ln2", group="Plots")
var int linewidth   = input.int(2, minval=1, maxval=9,title="Width of the line", group="Plots")
//---------------------
// Data structure for gaps. Will remember their characteristics. Will also store them according to order of occurrence. 
// {
type gap                                                        // Attributes to describe gap 
    float pivot_upper   = na
    float pivot_lower   = na
    float pivot_mid     = na
    color linecolor     = na
    int barindex        = na

var gap[] _history = array.new<gap>()                           // Array of gaps, to keep track of them.
if barstate.isfirst
    array.push(_history, gap.new())                             // to prevent none type errors at the beginning when size==0

// @function insert_gap(price[2], price[0]) returns void
insert_gap(gap g, float price_t_minustwo, float price_t_zero) =>
    g.pivot_upper := math.max(price_t_minustwo, price_t_zero)
    g.pivot_lower := math.min(price_t_minustwo, price_t_zero)
    g.pivot_mid := (g.pivot_upper+g.pivot_lower)/2
    g.linecolor := price_t_minustwo < price_t_zero ? col_up : price_t_minustwo > price_t_zero ? col_dn : na
    g.barindex := bar_index
    array.unshift(_history, g)

// @function get_recent_gap() returns an instance of gap obj.
get_recent_gap() =>
    if array.size(_history) == 0
        runtime.error(message="Array of gaps is empty")      
    array.get(_history,0)
//}

//---------------------
// Tests for FVGs:
// Requirement 1: Displacement test;                            upward FVG must > 0, and downward FVG must < 0
// Requirement 2: Threshold test;                               distance of FVG must > ATR200 x 0.5

float displacement_up = low[0] - high[2]                        // Test for FVG-up
float displacement_dn = high[0] - low[2]                        // Test for FVG-down

// FVG is valid iff both requirements (1 & 2) are met:
float _threshold = ta.atr(atr_filter_len) * atr_filter_multi
if math.abs(displacement_up) > _threshold and displacement_up > 0
    insert_gap(gap.new(), high[2], low[0])
if math.abs(displacement_dn) > _threshold and displacement_dn < 0
    insert_gap(gap.new(), low[2], high[0])

//---------------------
// Plotting:
var float main_pivot = na
main_pivot := get_recent_gap().pivot_mid[0] == get_recent_gap().pivot_mid[1] ? get_recent_gap().pivot_mid[0] : na
plot(main_pivot, color=get_recent_gap().linecolor, linewidth=linewidth, title="Pivot", offset=-1, editable=false, style=plot.style_linebr)

Overview

3 Bar Gap calculates displacement between the price boundaries of two bars ago and the current bar. To filter out market noise during quiet periods, gaps must exceed an Average True Range threshold. Valid bullish and bearish gaps are tracked in an internal array structure and drawn with customizable line styles. Traders can fine-tune the ATR period and multiplier sensitivity.

Details

Published by

kevinhhl on GitHub

Code credit

DojiEmoji, as written in the script's header

Draws

On the price chart

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.

Settings

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

SettingTypeDefaultVariable
Threshold: ATRint20atr_filter_len
xfloat0.5atr_filter_multi
Colors for Up move / Down move:colorcolor.new(color.blue,0)col_up
/colorcolor.new(color.red,0)col_dn
Width of the lineint2linewidth
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 Liquidity Void Fill

by ArunKBhaskar
575 stars

This overlay indicator marks ICT liquidity void fills on the price chart and can show long and short signals. It places a Fibonacci level inside a displacement candle, defaulting to the midpoint, and draws lines in a chosen style. Optional filters limit the fi

Indicator v6 SMC / ICT / price actionSupport & resistance
Updated 1 year ago · MPL-2.0 GitHub repository of ICT Liquidity Void Fill
228 stars

This indicator maps market structure and supply and demand zones on the price chart. It marks validated and optional unvalidated swing highs and lows using a pivot length and extra confirmation bars. Consolidation and impulse moves are measured against ATR to

Indicator v6 SMC / ICT / price actionSupport & resistance Repaints
Updated 3 months ago · None stated GitHub repository of Market Structure + Supply/Demand
55 stars

This Pine Script indicator overlays institutional liquidity levels on the price chart. It identifies order block levels using pivot highs and lows, then draws mean reversion lines from the 20 and 50 period simple moving averages, a volatility range midpoint pr

Indicator v6 Support & resistanceSMC / ICT / price action Repaints
Updated 6 months ago · Apache-2.0 GitHub repository of AAPL Institutional Liquidity Grid

This indicator combines six trading tools into a single chart overlay to optimize indicator limits. It calculates Bollinger Bands, projects weekend price boundaries, plots market structure elements like order blocks, breaker blocks, and MSB lines, marks New Yo

Indicator v6 Support & resistanceSMC / ICT / price action Repaints

More SMC / ICT scripts

Related on ForexR

Trade Your Charts With a Regulated Broker

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

Compare brokers