Donchian Channel with Breakout Age Counter
The Donchian channel plots the highest high and lowest low over a lookback period, framing a volatility band. The breakout age counter extends this by tracking how many candles have elapsed since price closed beyond that band, resetting if price re-enters it. Practitioners using breakout strategies or studying mean reversion use this to measure how far price has committed to a directional move outside its recent trading range.
//@version=6
indicator("Donchian Channel with Breakout Age Counter", overlay=true)
// Inputs
length = input.int(20, title="Donchian Length", minval=1)
showChannel = input.bool(true, title="Show Channel")
showCounter = input.bool(true, title="Show Breakout Age Counter")
highlightBars = input.bool(true, title="Highlight Breakout Bars")
// Calculate Donchian Channel
highest = ta.highest(high, length)
lowest = ta.lowest(low, length)
mid = (highest + lowest) / 2
// Breakout detection: price closes beyond yesterday's channel extremes
breakoutHigh = close > highest[1]
breakoutLow = close < lowest[1]
// State tracking with var: persists across candles
var int ageCounter = 0
var bool isBreakout = false
var string direction = na
// Update state each candle
if (breakoutHigh or breakoutLow) and not isBreakout
isBreakout := true
direction := breakoutHigh ? "UP" : "DOWN"
ageCounter := 0
else if isBreakout
ageCounter := ageCounter + 1
// Reset if price re-enters the channel (close within bounds)
if close <= highest and close >= lowest
isBreakout := false
direction := na
ageCounter := 0
// Plot Donchian bands
plot(highest, title="Donchian High", color=color.new(color.green, 20), linewidth=1)
plot(lowest, title="Donchian Low", color=color.new(color.red, 20), linewidth=1)
plot(showChannel ? mid : na, title="Donchian Mid", color=color.new(color.gray, 50),
linewidth=1, style=plot.style_dashed)
// Bar coloring during active breakout
barColor = isBreakout and highlightBars ?
(direction == "UP" ? color.new(color.green, 80) : color.new(color.red, 80)) :
na
barcolor(barColor)
// Plot the age counter as a label on active breakout
if showCounter and isBreakout
labelColor = direction == "UP" ? color.new(color.green, 0) : color.new(color.red, 0)
textColor = color.white
yPos = direction == "UP" ? highest : lowest
offset = direction == "UP" ? atr(5) * 0.5 : atr(5) * -0.5
label.new(bar_index, yPos + offset, str.tostring(ageCounter),
color=labelColor, textcolor=textColor,
style=label.style_label_center, size=size.small)
How the code works
The script first computes the highest high and lowest low over the specified lookback period (default 20 candles) using ta.highest() and ta.lowest(), forming the Donchian bands. A midline is calculated as their average.
Breakout detection compares the current close to the previous bar's channel extremes, stored via the [1](#ref-1) history reference. This prevents lookahead bias: the decision is made using only the data available at the close of the current candle. When price closes above highest[1](#ref-1), breakoutHigh triggers; when it closes below lowest[1](#ref-1), breakoutLow triggers.
State is maintained using var declarations: ageCounter accumulates candles since a breakout begins; isBreakout flags whether an active breakout is in progress; direction stores "UP" or "DOWN". On the first candle of a breakout, the counter resets to zero and the direction is recorded. On each subsequent candle, the counter increments by one. If price then re-enters the Donchian band (close falls between highest and lowest), all state resets, and the age counter stops until a new breakout occurs.
Bar coloring is applied only during an active breakout, shading green for upside and red for downside breakouts. A label displaying the current age is positioned near the relevant band and updated each candle.
Reading it on a chart
Traders watch for the age counter to identify how many candles price has held above or below the Donchian band. An age of 1 or 2 candles suggests a fresh breakout; larger ages indicate sustained directional commitment. The counter resets to zero if price re-enters the band, signalling a false breakout or a retracement back to the mean.
The Donchian bands themselves show the outer bounds of recent volatility. Breakouts that accelerate away from the midline and show a rising age counter may signal entry points for trend-following strategies. Conversely, a breakout that quickly reverses and resets the counter may indicate a whipsaw or mean-reversion opportunity.
Bar highlighting during breakout periods visually isolates the bars in which the directional move is active, aiding rapid chart scan. The label age counter is placed just outside the relevant band so it does not obscure price action.
Limitations
The indicator relies on overnight and intraday gaps being absent or small. A large gap at the open can trigger a breakout that the close-of-candle state update fails to capture cleanly, and the age counter may not reflect the true age of the move if multiple gap-opens compound.
The counter resets as soon as price touches the channel. In choppy, whipsaw markets with frequent re-entries, the age counter resets repeatedly, making it difficult to distinguish genuine breakouts from noise. Practitioners may need to increase the Donchian length or use additional filters to avoid false signals.
The indicator does not adapt to volatility regime changes. A 20-period Donchian channel tuned for calm markets may produce overly sensitive breakouts during volatile periods, or miss breakouts during low-volatility phases when the bands compress.
Label density can become overwhelming on shorter timeframes or when breakouts occur in clusters. The script places labels for every active breakout, which may overlap or obscure price in crowded markets.
State is maintained in memory via var declarations. If the chart is scrolled back and forward, or if the script is reloaded, the state resets. The age counter reflects only the current session, not historical breakout ages from previous sessions.
The indicator is not a trading signal. Breakout age alone does not predict continuation or reversal; it is merely a timing tool to measure how far a move has progressed outside its range envelope.
Key definitions
Donchian Channel: A volatility band marking the highest high and lowest low over a lookback period, typically used to frame support and resistance levels.
Breakout: A close outside the upper or lower boundary of the Donchian channel, indicating price has moved beyond the recent range.
Age Counter: The number of consecutive candles price has remained outside the Donchian channel since the initial breakout close.
Mean Reversion: The tendency of price to return to an average or midpoint after a directional move away from it.
Bar State Memory: Persistence of variables across candles using the var keyword, enabling the counter to accumulate without resetting each bar.
Lookahead Bias: Using future data to calculate a signal that would not be available at the time of the trade decision; avoided here by referencing [1](#ref-1) historical bars only.
References
- Investopedia, "Donchian Channel", investopedia.com. Accessed 2026-09-06.
- TradingView Pine Script Documentation, "ta.highest() / ta.lowest()", docs.tradingview.com. Accessed 2026-09-06.
- Wilder, J. Welles, New Concepts in Technical Trading Systems (1978). McLeansville, NC: Trend Research Ltd.
Educational research on historical data only. Not investment advice, not a signal, and never a performance promise. Past results do not predict future performance. Every reference is link-verified before publication and every paper is re-audited weekly against the library's editorial standard.
Last reviewed by the PropLedger research pipeline: 2026-09-06. Educational research on historical data, not financial advice.
Keep reading
Bollinger Band Squeeze Meter
Free open-source Pine Script indicator: Bollinger band squeeze meter (bandwidth percentile). Full code and a plain-English walkthrough.
Multi-Timeframe Moving Average Alignment Panel
Free open-source Pine Script indicator: multi-timeframe moving average alignment panel. Full code and a plain-English walkthrough.
Premium and Discount Zones
Free open-source Pine Script indicator: premium and discount zones from a rolling range midpoint. Full code and a plain-English walkthrough.