Trend
Donchian Channel
The highest high and the lowest low of the last N bars drawn as a shaded channel with its midline, which is the simplest honest picture of the range price has actually traded in.
indicator
//@version=6
indicator("Donchian Channel", "Donchian", overlay = true)
length = input.int(20, "Lookback", minval = 1, group = "Settings")
bull = input.color(#26A69A, "Upper band", group = "Style")
bear = input.color(#EF5350, "Lower band", group = "Style")
neutral = input.color(#787B86, "Midline", group = "Style")
upper = ta.highest(high, length)
lower = ta.lowest(low, length)
mid = math.avg(upper, lower)
pUpper = plot(upper, "Upper", color = bull, linewidth = 2)
pLower = plot(lower, "Lower", color = bear, linewidth = 2)
plot(mid, "Midline", color = color.new(neutral, 30))
fill(pUpper, pLower, color = color.new(neutral, 92), title = "Channel")
brokeUp = close > upper[1]
brokeDown = close < lower[1]
plotshape(brokeUp, "Closed above", location = location.belowbar, style = shape.triangleup, color = bull, size = size.tiny)
plotshape(brokeDown, "Closed below", location = location.abovebar, style = shape.triangledown, color = bear, size = size.tiny)
alertcondition(brokeUp, "Closed above the channel", "Price closed above the previous Donchian upper band")
alertcondition(brokeDown, "Closed below the channel", "Price closed below the previous Donchian lower band")
This runs in TradingView, not here
Pine Script only executes inside TradingView. Paste the source into the Pine Editor and add it to a chart to see it plotted.
What it will not do
- The bands step rather than slide. One extreme bar sets a level that stays put until it falls out of the lookback window.
- Price cannot close outside a band that already includes the current bar, so the breakout test uses the previous bar's band.
- A single volatile bar widens the channel for the whole lookback, which makes the calm bars after it look tamer than they are.
Written from this description
Draw the highest high and the lowest low over a lookback window as an upper and a lower band, shade between them, add a midline, and mark the bars that close beyond the previous bar's band.
Educational only, not financial advice. The maths is simple arithmetic on the numbers you enter; it knows nothing about your broker, fees, slippage or the market. Something wrong with it? Say so in Site Feedback.