Tutorial

Pine Script ta.highest and ta.lowest: Rolling Extremes

How ta.highest, ta.lowest and ta.highestbars work in Pine Script v6, why the current bar is in the window, and how to build a lookback channel.

•12 min read

You have a breakout idea that sounds simple: mark the highest high of the last 20 bars, and react when price closes above it. You write ta.highest(high, 20), plot it, and the line looks right. Then you test the condition and nothing ever breaks out, because the line you plotted includes the very bar you are comparing it to. Or the line works on history and you cannot tell why it jumps on one bar and sits still for ten. Rolling extremes are one of the first things people build in Pine Script, and they hide a few details that decide whether the result means what you think it means.

This guide covers ta.highest and ta.lowest in Pine Script v6 from the signature up: what they return, which bars they look at, why the current bar matters, how ta.highestbars and ta.lowestbars tell you where the extreme happened, and how to put it together into a lookback channel you can trust. Along the way there is a section on marking the same levels on a chart with PineScripter's chart agent, so you can see the thing before you code it.

What ta.highest and ta.lowest actually return

ta.highest(source, length) returns the largest value of source over the last length bars. ta.lowest(source, length) returns the smallest. That is the whole contract. If you leave out the source and write ta.highest(20), Pine uses high for the highest and low for the lowest, which is a convenient default for price channels.

pine
//@version=6
indicator("Rolling Extremes", overlay = true)

length = input.int(20, "Length", minval = 2)

upper = ta.highest(high, length)
lower = ta.lowest(low, length)

plot(upper, "Highest high", color = color.teal)
plot(lower, "Lowest low", color = color.orange)

Run this and you get a channel that hugs price. The upper line steps up the moment a new high prints, and it steps down only when the old high ages out of the window. That asymmetry is the first thing worth understanding. A rolling maximum rises instantly but falls late, and it falls in jumps: it holds a high for exactly length bars after it occurred, then drops to the next highest value still in the window. If you have ever wondered why a Donchian-style line looks like a staircase going down and a ramp going up, this is why.

The window counts bars, not time. On a 4 hour chart, a length of 20 covers 80 hours. On a 1 day chart the same code covers 20 days. The function has no idea what the timeframe means; it counts bars back from the current one. This matters when you move the same script between timeframes, because "the last 20 bars" is a different slice of market history on each.

The current bar is inside the window

Here is the detail that breaks most first attempts. The window of ta.highest(high, 20) is the current bar plus the 19 bars before it. The current bar's own high is one of the 20 values being compared. So the current high can never be above ta.highest(high, 20), because if it were the highest, it would simply become the answer.

That means this condition can never be true:

pine
//@version=6
indicator("Self-Comparison Trap", overlay = true)

// Never true: high is part of the window it is compared to
breakout = high > ta.highest(high, 20)
plotshape(breakout, title = "Never fires", style = shape.xcross, location = location.abovebar)

The closest you can get is high == ta.highest(high, 20), which tells you the current bar made a new 20-bar high, but it does not tell you it broke out of a prior range. If you want to ask whether this bar exceeded the extreme of the bars before it, you need the value as it stood one bar ago. In Pine that is the history-referencing operator:

pine
//@version=6
indicator("Lookback Breakout Channel", overlay = true)

length = input.int(20, "Lookback", minval = 2)

// The extreme of the previous `length` bars, excluding the current one
upper = ta.highest(high, length)[1]
lower = ta.lowest(low, length)[1]

breakUp = barstate.isconfirmed and close > upper
breakDown = barstate.isconfirmed and close < lower

plot(upper, "Prior highest high", color = color.teal)
plot(lower, "Prior lowest low", color = color.orange)
plotshape(breakUp, title = "Close above", style = shape.triangleup, location = location.belowbar, color = color.teal, size = size.small)
plotshape(breakDown, title = "Close below", style = shape.triangledown, location = location.abovebar, color = color.orange, size = size.small)

The [1] shifts the result back one bar, so on each bar upper is the highest high of the length bars that ended one bar earlier. Now a close above it is a real event: price finished a bar above everything it did over the prior window. The barstate.isconfirmed guard keeps the marker from flickering on a live bar that has not closed yet, which is the same repainting concern covered in barstate.isconfirmed in Pine Script. If you are building a full strategy on this idea, the Donchian channel breakout strategy post takes it through entries, exits and the Strategy Tester.

Once the offset is involved, name your variables so the next reader does not have to guess. priorHigh is a better name than upper, because it says the current bar is excluded.

Choosing the source: high, close, or something else

Nothing forces you to use high and low. The source argument takes any series of floats, and the choice changes the meaning of the line.

Using high and low gives you the full range, wicks included. A single spike wick sets the extreme and holds it for the whole window. That is what most people mean by "the 20 bar high", and it is what charting platforms usually draw.

Using close gives you the highest and lowest closing price. Wicks stop mattering, so a one-bar spike that closed back inside the range no longer pins the line. A close-based channel is quieter and sits closer to where price actually settled. It also makes breakouts a stricter test, since you are comparing a close against prior closes instead of a close against prior wicks.

You can also feed in something that is not price at all. ta.highest(volume, 50) gives you the loudest volume bar in the last 50. ta.lowest(ta.rsi(close, 14), 30) gives you the lowest RSI reading in 30 bars, which is the building block of a lot of divergence logic. The function does not care what the series is. It cares only that it is a series, and that the first length - 1 bars do not yet have a full window.

What happens on the first bars

Before the chart has length bars of history, there is not enough data to fill the window, and both functions return na for those early bars. On a script with length = 20, the first 19 bars plot nothing. This is correct behavior, but it catches people who then combine the result with other values. Any arithmetic with na produces na, and a comparison against na is never true, so early bars quietly produce no signal. If you need a value on every bar, you can substitute explicitly with nz(), but think about whether a made-up number is better than an honest gap. For a channel, a gap is almost always the more truthful choice. The full story of how na spreads through a script is in How Pine Script Handles na.

There is a related limit to know about. Pine decides how much history a series needs by looking at how your code refers back to it. If you ever see a history buffer error after using a long length or a variable length, the fix is described in Pine Script max_bars_back errors. In normal use with a plain length input, you will not hit it.

ta.highestbars and ta.lowestbars: where was the extreme?

Knowing the value of the extreme is half the story. Often you also want to know how long ago it happened. ta.highestbars(source, length) returns the offset, in bars, from the current bar back to the highest value in the window. The result is zero when the current bar is the highest, and negative otherwise: minus 3 means the extreme was three bars ago. ta.lowestbars does the same for the minimum.

The negative sign is deliberate, because the number is designed to be used as an offset for the history operator and for drawing functions. Negate it if you want a plain count of bars since the extreme.

pine
//@version=6
indicator("Bars Since Extreme", overlay = false)

length = input.int(20, "Lookback", minval = 2)

barsSinceHigh = -ta.highestbars(high, length)
barsSinceLow = -ta.lowestbars(low, length)

plot(barsSinceHigh, "Bars since highest high", color = color.teal, style = plot.style_columns)
plot(barsSinceLow, "Bars since lowest low", color = color.orange, style = plot.style_columns)

This gives you two columns that count up as an extreme ages and snap back to zero when a new one prints. It is a useful diagnostic for the staircase behavior described earlier: you can see the exact bar where a high is about to leave the window and the upper line is about to drop. It also lets you reason about the age of a level. A 20-bar high that is 2 bars old and one that is 18 bars old are the same value but very different situations, since the second is about to expire.

If you want other values from the bar that set the extreme, use the offset as a history index: high[-ta.highestbars(high, length)] is valid, because the negated result is zero or positive. It returns the high of the bar that set the extreme, the same number ta.highest gives you, and the same pattern with volume, time or low gives you the other values from that bar.

Mark it on the chart with the agent

Before you code a channel, it often helps to look at one. PineScripter's chart agent works the chart for you from a plain English request. In the chat, you could type something like this:

"Mark the swing highs and lows on BTCUSDT 4h, then draw the highest high and the lowest low of the last 20 bars as horizontal lines."

The agent reads the chart, which includes the swing levels and the drawings already on it, and then draws with the toolbar's tools while you watch its cursor click the points. The whole batch it draws can be undone in one step, so you can ask for something, look at it, and take it back if it is not what you meant. It works on PineScripter's own chart, which covers crypto spot markets, and it never reads or touches a chart on your TradingView account.

What the agent produces is markup for you to inspect, not an answer. Check it the way you would check any level. Count the touches on the swing levels it marked and ask whether you agree with them. Switch the timeframe and see whether the same lines still make sense, since a 20-bar window on 4 hours is not the same slice of time as on 1 day. Then step through the chart in replay, one bar at a time, and watch the high age out of the window and the line step down on the exact bar your code would predict. If the agent's horizontal line and your ta.highest line disagree, that is useful information: one of you has a different idea of the window, and finding out which is the point of the exercise.

When the picture looks like what you want, the next step is to make it permanent. Describe it to PineScripter in plain terms, for example "turn this into an indicator that draws the prior 20 bar high and low on every chart and marks closes beyond them", and it writes the Pine Script v6, checks the code for compile errors, and fixes them itself. The result will look a lot like the lookback breakout channel above, and because the editor changes only the lines a follow-up affects, adding a volume filter later does not rewrite the rest. You can open it from the chart and indicator analysis page.

Turning the extremes into a position within the range

Once you have both lines, you can express where price sits between them as a single number from 0 to 1. This is the idea behind a stochastic-style readout, built from nothing but the two functions.

pine
//@version=6
indicator("Range Position", overlay = false)

length = input.int(20, "Lookback", minval = 2)

hh = ta.highest(high, length)
ll = ta.lowest(low, length)

// 0 at the lowest low, 1 at the highest high; na if the range has no height
rangePosition = hh > ll ? (close - ll) / (hh - ll) : na

plot(rangePosition, "Range position", color = color.teal)
hline(0.0, "Bottom", color = color.gray)
hline(0.5, "Middle", color = color.gray)
hline(1.0, "Top", color = color.gray)

The hh > ll check matters. On a market where nothing has moved for the whole window, the high and low are equal and the denominator is zero. The guard makes the intent visible and avoids dividing by zero. Here the current bar is included in the window on purpose, so the value stays between 0 and 1: a close at the window's top gives 1, and there is no way to exceed it. That is the case where including the current bar is exactly what you want, and it is a good example of why the same function is right in one script and wrong in another.

Common mistakes and how to avoid them

The first mistake is the self-comparison covered above: comparing a bar to a window that contains it. Whenever a breakout condition never fires, look at whether you used the offset. The second is forgetting that length counts bars and not time, which makes a script look different on every timeframe even though nothing in it changed. If you need a window of fixed clock time, you need a different approach, such as computing from time with a session or a request.security call to a higher timeframe. That route has its own repainting traps, which are covered in how request.security works in Pine Script.

The third is using a short length and reading too much into it. With a length of 3 or 4, nearly every bar is close to a 4-bar extreme, so crossings happen constantly and mean little. The length is a statement about what you consider significant, and it should come from the structure you care about rather than from whatever made the chart look tidy. The fourth is treating the lines as support and resistance that must hold. A rolling extreme is a statistic of the past window. It describes what price did, and it makes no claim about what price will do next. If your idea needs levels that come from swing structure rather than from a fixed window, the approach in support and resistance zones from swing points is a better fit, and ta.pivothigh and ta.pivotlow explains why swing detection always arrives late.

The fifth is not testing on closed bars. A breakout that fires on a live bar can vanish before the bar closes, so a script that looks good in replay can disagree with what an alert would have done. Stepping through a Pine Script before and after it goes live is the practical way to catch that.

Where to go from here

The functions themselves are small. The value is in knowing exactly which bars they look at, whether the current bar is in or out, and what a number like -3 from ta.highestbars means. With that, a lookback channel stops being a line that mysteriously "does not work" and becomes a precise statement you can reason about and verify.

If you would rather describe the idea than write it, you can do that on PineScripter. Ask the chart agent to mark the levels first, check them against the touches and the replay, and then ask for the indicator that draws them on every chart. The code is yours to copy and keep, and you can test it on TradingView by pasting it into the Pine Editor.

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.

Frequently asked questions

Does ta.highest include the current bar?

Yes. The window is the current bar plus the previous length minus 1 bars, so the current high can never be above ta.highest(high, length). To compare the current bar with the bars before it, use ta.highest(high, length)[1].

What does ta.highestbars return?

The offset from the current bar back to the highest value in the window. It is 0 when the current bar is the highest and negative otherwise, so -3 means the extreme was three bars ago. Negate it for a plain count of bars since the extreme.

Why does ta.highest return na at the start of the chart?

Until the chart has length bars of history the window is not full, so the function returns na for those early bars. Any arithmetic or comparison with na produces na or false, so those bars produce no markers.

Can I use ta.highest on something other than price?

Yes. The source can be any float series, such as close, volume or an RSI value. ta.highest(volume, 50) gives the largest volume in the last 50 bars.

Is a rolling high the same as resistance?

No. It is a statistic of the last length bars and describes what price did. It makes no claim about what price will do, and it changes as old bars leave the window.

Ask the agent to mark it on the chart, then turn it into Pine Script →


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.