Tutorial

Pine Script Gap Detection: Mark Gaps and Track If They Fill

Detect gap up and gap down bars in Pine Script v6, filter them by size, draw each gap as a box, and track whether and when it fills.

•12 min read

You add a gap indicator to your chart, and it either shows nothing or shows two hundred rectangles, half of which never close. Gaps look like the easiest thing to code, since a gap is just a bar that opens away from where the last one ended. The trouble starts when you try to answer the next two questions: how big does a gap have to be to count, and when exactly is it filled?

This guide builds a gap detector in Pine Script v6 from the definition up. You will detect gap up and gap down bars, filter out noise with a size threshold, draw each gap as a box, track whether it has been filled, and print simple statistics on how many filled and how long they took. Along the way you will see why the tracking code should run on confirmed bars only, and how to keep the box count under TradingView's limit.

What a gap is in code

A gap up happens when a bar opens above the previous bar's high. A gap down happens when a bar opens below the previous bar's low. In both cases there is a stretch of price where no trade happened on that chart's bars, and that empty stretch is the gap.

Notice what the definition leaves out. Many traders say "gap" when they mean "the open is higher than yesterday's close". That is a weaker idea. If the open is above the previous close but still inside the previous bar's range, nothing is empty: price traded through that area during the previous bar. Pine Script gives you the two versions as two different comparisons, and you should pick one on purpose.

pine
//@version=6
indicator("Gap Detection Basics", overlay = true)

gapUp   = open > high[1]
gapDown = open < low[1]

plotshape(gapUp,   title = "Gap up",   style = shape.triangleup,   location = location.belowbar, color = color.teal, size = size.tiny)
plotshape(gapDown, title = "Gap down", style = shape.triangledown, location = location.abovebar, color = color.maroon, size = size.tiny)

This is the strict version. The gap region for a gap up runs from the previous high up to the current open. For a gap down it runs from the current open up to the previous low. Everything below uses those two edges, because they define what "filled" means later on.

On the first bar of a chart, high[1] is na, and a comparison with na is false, so the script needs no special first-bar guard. If you want to know why that works and where it stops working, the post on how Pine Script handles na covers it.

Which markets actually gap

Whether you see gaps depends on the market more than on your code. Stocks trade in sessions, so the open after a night, a weekend, or an earnings release often lands away from the last close. Crypto spot markets trade around the clock. On a liquid pair, one bar's open sits very close to the previous bar's close, so the strict test above rarely fires, and when it does the gap is small.

That has a practical effect on testing. PineScripter's chart runs your script on 308 crypto spot markets, with up to 5,000 bars per run, and draws the plots, shapes, and labels your script produces. It is a good place to check that the drawing and fill logic behaves, but expect few gaps there and loosen the threshold if you want to see the boxes at work. For stocks, paste the finished script into TradingView and load a stock symbol, where gaps are common.

Gaps on 24/7 markets can still happen, for example after a thin bar on a quiet pair or a very low timeframe where one trade moves the book. A minimum size filter, covered next, is what keeps those from flooding the chart.

Filtering gaps by size

A gap of one tick is technically a gap. It is also not worth drawing. A size threshold turns the raw test into something you can read, and the cleanest way to express it is as a percentage of the previous close, so the same setting works on a cheap coin and an expensive stock.

pine
//@version=6
indicator("Gap Size Filter", overlay = true)

minGapPct = input.float(0.3, "Minimum gap size (%)", minval = 0.0, step = 0.05)

gapUpPct   = (open - high[1]) / close[1] * 100
gapDownPct = (low[1] - open) / close[1] * 100

gapUp   = gapUpPct   >= minGapPct and gapUpPct   > 0
gapDown = gapDownPct >= minGapPct and gapDownPct > 0

plotshape(gapUp,   title = "Gap up",   style = shape.triangleup,   location = location.belowbar, color = color.teal, size = size.tiny)
plotshape(gapDown, title = "Gap down", style = shape.triangledown, location = location.abovebar, color = color.maroon, size = size.tiny)

The > 0 guard matters when someone sets the minimum to zero. Without it, a bar that opens inside the previous range would still pass a >= 0 test, and the strict definition would quietly turn into the loose one.

Some people prefer to measure gaps in ATR instead of percent, so that the threshold adapts to current volatility. That is a fair design choice. The trade-off is that the same gap can pass in a quiet period and fail in a volatile one, which makes results harder to compare across a chart. Percent is easier to reason about, and you can swap in ta.atr(14) later without touching the rest of the script.

Day-open gaps on intraday charts

On a 15 minute chart, most bars open right where the last one closed, so the strict test fires only at the start of a session. If you care about the gap between yesterday's close and today's open, and you want it on intraday charts, compare the first bar of the new day to the last bar of the previous one.

pine
//@version=6
indicator("Day Open Gap", overlay = true)

newDay = timeframe.change("D")

var float prevDayClose = na
if newDay
    prevDayClose := close[1]

dayGapPct = newDay ? (open - prevDayClose) / prevDayClose * 100 : na

plot(newDay ? open : na, title = "Day open", style = plot.style_circles, color = color.orange, linewidth = 3)

if newDay and not na(dayGapPct)
    label.new(bar_index, high, str.tostring(dayGapPct, "#.00") + "%", style = label.style_label_down, color = color.new(color.gray, 70), textcolor = color.white, size = size.small)

This version measures open against the previous close, so it is the looser definition: it reports a number even when the open lands inside the previous day's range. That is useful as a context number. It should be a separate setting from the strict gap that you track for fills. For more on detecting a new day, week, or session without off-by-one mistakes, see ta.change and new day detection.

Tracking whether a gap gets filled

Drawing a gap is the easy half. The harder half is deciding what filled means, and the answer changes your statistics a lot.

There are two reasonable definitions. A gap is partially filled once price trades back into the empty region. It is fully filled once price trades all the way back to the far edge, which for a gap up is the previous high. Most gap traders talk about the full fill, because partial fills happen constantly and tell you little. The script below tracks the full fill and records the bar where it happened.

The detector keeps each open gap as an object in an array. Every confirmed bar it checks every open gap against the new bar's low or high, closes the ones that were filled, and opens a new box if the bar itself gapped.

pine
//@version=6
indicator("Gap Tracker", overlay = true, max_boxes_count = 200)

minGapPct = input.float(0.3, "Minimum gap size (%)", minval = 0.05, step = 0.05)
maxOpen   = input.int(20, "Max open gaps tracked", minval = 1, maxval = 100)

type Gap
    float top
    float bottom
    bool  isUp
    int   startBar
    box   zone

var array<Gap> openGaps = array.new<Gap>()
var int foundCount  = 0
var int filledCount = 0
var int barsToFill  = 0

upColor   = color.new(color.teal, 80)
downColor = color.new(color.maroon, 80)
doneColor = color.new(color.gray, 90)

if barstate.isconfirmed
    gapUpPct   = (open - high[1]) / close[1] * 100
    gapDownPct = (low[1] - open) / close[1] * 100

    if gapUpPct >= minGapPct
        zone = box.new(bar_index - 1, open, bar_index, high[1], border_color = color.teal, bgcolor = upColor)
        openGaps.push(Gap.new(open, high[1], true, bar_index, zone))
        foundCount += 1
    else if gapDownPct >= minGapPct
        zone = box.new(bar_index - 1, low[1], bar_index, open, border_color = color.maroon, bgcolor = downColor)
        openGaps.push(Gap.new(low[1], open, false, bar_index, zone))
        foundCount += 1

    if openGaps.size() > 0
        for i = openGaps.size() - 1 to 0 by -1
            g = openGaps.get(i)
            filled = g.isUp ? low <= g.bottom : high >= g.top
            g.zone.set_right(bar_index)
            if filled
                g.zone.set_bgcolor(doneColor)
                g.zone.set_border_color(color.gray)
                filledCount += 1
                barsToFill += bar_index - g.startBar
                openGaps.remove(i)

    while openGaps.size() > maxOpen
        openGaps.shift()

var table stats = table.new(position.top_right, 2, 3, border_width = 1)
if barstate.islast
    stats.cell(0, 0, "Gaps found", text_color = color.white, bgcolor = color.new(color.gray, 40))
    stats.cell(1, 0, str.tostring(foundCount), text_color = color.white, bgcolor = color.new(color.gray, 40))
    stats.cell(0, 1, "Filled", text_color = color.white, bgcolor = color.new(color.gray, 40))
    stats.cell(1, 1, str.tostring(filledCount), text_color = color.white, bgcolor = color.new(color.gray, 40))
    stats.cell(0, 2, "Avg bars to fill", text_color = color.white, bgcolor = color.new(color.gray, 40))
    stats.cell(1, 2, filledCount > 0 ? str.tostring(barsToFill / filledCount, "#.0") : "n/a", text_color = color.white, bgcolor = color.new(color.gray, 40))

A few details in that script are worth slowing down for.

The loop runs backward. Removing an element from an array while you walk it forward shifts every later index by one, so you skip the item after each removal. Walking from the end to zero avoids that, and the size() > 0 guard keeps the loop from running on an empty array.

A gap that forms on a bar can also fill on that same bar. If a bar opens above the previous high and then trades back down through it, its low is at or below the gap's bottom edge. Because the new gap is pushed before the fill loop runs, that case is caught on the spot and the box closes immediately with a width of one bar. Whether you want to count those as gaps is a judgment call, and you can skip them by running the fill loop before the creation block.

The maxOpen cap protects you from an unfilled gap that sits for thousands of bars. TradingView limits how many boxes a script can have, set through max_boxes_count up to 500, and old boxes are dropped when the limit is hit. Capping what you track keeps the oldest gaps from silently disappearing mid-calculation. The article on Pine Script label and line limits goes into how those caps behave, and drawing objects that do not hit the limit shows patterns for staying well under them.

Why the tracking code runs on confirmed bars

The whole block sits under barstate.isconfirmed. That is deliberate. On a live bar, the script re-runs on every tick, and arrays are not rolled back between ticks the way ordinary variables are. If the creation code ran on each tick of the gap bar, it could push the same gap into the array several times. Running only when the bar closes means each bar is processed exactly once, on the same values it will have in history, so the chart you see live matches the chart you see after reloading.

The cost is a one bar delay: the box appears when the gap bar closes, not the instant it opens. For a drawing tool that is a good trade. If you need the alert at the open itself, that is a separate question with its own pitfalls, and the post on barstate.isconfirmed explains what you gain and lose either way. For a wider view of how scripts redraw, see repainting explained.

Reading the statistics without fooling yourself

The table gives you three numbers: how many gaps were found, how many filled, and the average number of bars the filled ones took. These are descriptive counts of what happened on the bars loaded on your chart. They are not a forecast, and they are easy to misread in three ways.

First, the average bars to fill only includes gaps that did fill. Gaps still open are missing from it, so the true average is longer than the number shown. The gap between "found" and "filled" is the more honest figure, and it grows or shrinks as you load more history.

Second, the numbers depend completely on your threshold. A 0.1 percent minimum and a 1 percent minimum describe different things, and comparing them is comparing apples to oranges. Pick the threshold first, then read the counts, and do not tune the threshold until the counts look good.

Third, the sample is whatever your chart loaded. A handful of gaps tells you almost nothing, and gap behavior differs by symbol, timeframe, and period. Treat the table as a way to see what your script is doing, and as a basis for questions to check, not conclusions.

Checking it bar by bar

Gap code is easy to get subtly wrong at the edges: a fill that triggers one bar early, a box that never closes, a size that looks right on one symbol and wrong on another. The quickest check is to walk the script through the bars around a gap and watch what it does.

PineScripter's replay steps a chart run one bar at a time, so you can stop on a gap bar, see the box appear when the bar closes, then step forward until the low or high crosses the far edge and watch the box turn gray. You can also ask the AI about any bar to see why a box did or did not close. If a fill looks wrong, describe the bar in plain English and the editor changes only the lines that need it. The post on checking a script before and after it goes live shows that workflow in more detail.

If you would rather start from the idea than the code, you can describe what you want, for example "mark gaps over 0.5 percent on the chart and turn the box gray when price trades back to the previous high", and get a Pine Script v6 script that compiles, which you then read through with the explanations above. The code is yours to copy into TradingView and keep. You can try it at PineScripter.

Turning gaps into alerts

Once the boxes behave, the natural next step is an alert when a new gap forms or when one fills. Pine Script has two ways to do that, alertcondition() and alert(), and they behave differently on live bars. Because the tracker above works on confirmed bars, either one will fire once per closed bar, which is the safer pattern. The comparison of alertcondition and alert() lays out which fits which job. If you also want gaps to sit next to levels you already track, the guide to support and resistance zones from swing points uses the same box approach.

Common mistakes

Most broken gap scripts fail in one of five ways. They compare open to the previous close and call it a gap, which flags bars where nothing is empty. They use a fixed price threshold that is too big for one symbol and too small for another. They count a gap as filled on the bar it formed without deciding whether that counts. They draw a new box on every tick of the live bar. Or they track every gap forever and run into the box limit with no warning. Each of those has a fix in the script above, and each is worth deciding on purpose rather than inheriting from a copied example.

Wrapping up

A gap detector comes down to four decisions: the definition (strict, against the previous range, or loose, against the previous close), the size threshold, what counts as filled, and when the code is allowed to run. Make each one explicit and the rest is bookkeeping. The tracker in this guide gives you a starting point you can read line by line, change one setting at a time, and step through on a chart until its behavior is no surprise.

PineScripter is a coding tool, not a financial advisor. Nothing here is financial advice, and counts of past gaps do not predict future price moves.

Frequently asked questions

What is the difference between a gap and an open above the previous close?

A gap means the bar opened outside the previous bar's whole high to low range, so there is an empty stretch with no trades. An open above the previous close can still sit inside that range, so nothing is empty. The strict test compares open to the previous high or low.

Do crypto charts have gaps?

Rarely. Crypto spot markets trade around the clock, so a bar usually opens near the previous close. Stocks gap far more often because they trade in sessions. On crypto, a size threshold keeps tiny gaps from cluttering the chart.

What counts as a filled gap in Pine Script?

A full fill for a gap up is a bar whose low reaches the previous high. For a gap down it is a bar whose high reaches the previous low. A partial fill only needs price to trade back into the empty region.

Why does the gap script only run on confirmed bars?

Arrays are not rolled back between live ticks, so code that pushes a gap on every tick could store the same gap several times. Using barstate.isconfirmed processes each bar once, so live and historical results match.

How many gap boxes can a script draw?

The max_boxes_count setting in indicator() goes up to 500. When the limit is reached, the oldest boxes are removed, so tracking only a capped number of open gaps keeps the logic stable.

Run your script on real market data and see what it plots →


Disclaimer: PineScripter is a coding tool for Pine Script development. It does not provide financial advice and does not guarantee trading profits. Always backtest strategies thoroughly and understand the risks before live trading.