Logo
OFFLINEPIXEL
/ pinescript-strategies / pine-script-donchian-channels

$ Pinescript Donchian Channels

Master these fundamental trend-following channels in TradingView's Pinescript for identifying breakouts, defining trend direction, and implementing robust trading systems.

500+ Clients Helped
100% Satisfaction
Live Trading Ready
⚠️
Trading financial markets carries risk. All content (PineScript code, indicators, strategies) on this website is for educational purposes only. Past performance is not indicative of future results. By using any code or information from this site, you agree that you are solely responsible for your trading decisions. The author disclaims all liability for any losses incurred. To gain from experts experiences, You can always try our Invite Only Scripts
01

What are Donchian Channels?

Donchian Channels are a classic trend-following indicator developed by Richard Donchian. They consist of three lines that define a price channel:

  1. An Upper Band: The highest price over a specified number of past periods.
  2. A Lower Band: The lowest price over the same specified number of past periods.
  3. A Middle Band: The average of the Upper and Lower Bands.
02

Components and Calculation

The calculation of Donchian Channels is quite straightforward:

  1. Upper Band: The highest high over the specified `length` periods.
    `Upper Band = ta.highest(high, length)`
  2. Lower Band: The lowest low over the specified `length` periods.
    `Lower Band = ta.lowest(low, length)`
  3. Middle Band: The simple average of the Upper and Lower Bands.
    `Middle Band = (Upper Band + Lower Band) / 2`
03

Basic Donchian Channels Implementation in Pinescript

pine-script@terminal
//@version=5
indicator("My Donchian Channels", overlay=true) // overlay=true to plot directly on the price chart

// Input for Donchian Channel length
length = input.int(20, title="Channel Length", minval=1)

// Calculate Donchian Channels using the built-in function
// ta.donchian returns the Upper, Middle, and Lower bands
[upperBand, middleBand, lowerBand] = ta.donchian(length)

// Plot the Upper, Middle, and Lower Bands
plot(upperBand, title="Upper Band", color=color.blue, linewidth=1)
plot(middleBand, title="Middle Band", color=color.gray, linewidth=1)
plot(lowerBand, title="Lower Band", color=color.blue, linewidth=1)

// Fill the area between the upper and lower bands for visual appeal
fill(upperBand, lowerBand, color.new(color.blue, 90), title="Channel Background")
$ ✓ Compiled successfully
04

Trend-Following Focus

Trend-Following Focus

Donchian Channels are inherently a trend-following tool. Their primary strength lies in identifying when price is breaking into new territory, suggesting the start or continuation of a significant trend.

05

Practical Donchian Channels Trading Strategies

06

1. Trend Following (Breakout Strategy)

pine-script@terminal
//@version=5
strategy("Donchian Channel Breakout Strategy", overlay=true)

// Input for Donchian Channel length
length = input.int(20, title="Channel Length", minval=1)

// Calculate Donchian Channels
[upperBand, middleBand, lowerBand] = ta.donchian(length)

plot(upperBand, "Upper Band", color.blue)
plot(middleBand, "Middle Band", color.gray)
plot(lowerBand, "Lower Band", color.blue)
fill(upperBand, lowerBand, color.new(color.blue, 90))

// Long entry condition: Price closes above the upper band
longCondition = close > upperBand[1] and close[1] <= upperBand[1] // Current close above, previous below or equal

// Short entry condition: Price closes below the lower band
shortCondition = close < lowerBand[1] and close[1] >= lowerBand[1] // Current close below, previous above or equal

if (longCondition)
    strategy.entry("Long Breakout", strategy.long)

if (shortCondition)
    strategy.entry("Short Breakout", strategy.short)

// Exit strategy: Close if price crosses the middle band in opposite direction or touches opposite channel.
strategy.exit("Long Exit", from_entry="Long Breakout", stop=lowerBand, limit=upperBand + (upperBand - middleBand)) // Example: Stop at lower band, target 2x range
strategy.exit("Short Exit", from_entry="Short Breakout", stop=upperBand, limit=lowerBand - (middleBand - lowerBand)) // Example: Stop at upper band, target 2x range

// Alternatively, exit on touch of opposite channel or middle band crossover for simpler exits:
// strategy.close("Long Breakout", when=close < middleBand)
// strategy.close("Short Breakout", when=close > middleBand)
$ ✓ Compiled successfully
07

2. Trend Confirmation and Pullback Entries

pine-script@terminal
//@version=5
strategy("Donchian Trend & Pullback Strategy", overlay=true)

length = input.int(20, title="Channel Length", minval=1)

[upperBand, middleBand, lowerBand] = ta.donchian(length)

plot(upperBand, "Upper Band", color.blue)
plot(middleBand, "Middle Band", color.gray)
plot(lowerBand, "Lower Band", color.blue)
fill(upperBand, lowerBand, color.new(color.blue, 90))

// Define trend direction using the middle band slope
isUptrend = middleBand > middleBand[1] and middleBand[1] > middleBand[2]
isDowntrend = middleBand < middleBand[1] and middleBand[1] < middleBand[2]

// Long entry: In uptrend, price pulls back to middle band and bounces
longPullbackCondition = isUptrend and close > middleBand and close[1] <= middleBand[1]

// Short entry: In downtrend, price rallies to middle band and reverses
shortPullbackCondition = isDowntrend and close < middleBand and close[1] >= middleBand[1]

if (longPullbackCondition)
    strategy.entry("Long Pullback", strategy.long)

if (shortPullbackCondition)
    strategy.entry("Short Pullback", strategy.short)

// Exit strategy for pullbacks (e.g., break of opposite channel or strong counter-move)
strategy.close("Long Pullback", when=close < middleBand)
strategy.close("Short Pullback", when=close > middleBand)
$ ✓ Compiled successfully
08

3. Volatility and Range Breakouts

pine-script@terminal
//@version=5
indicator("Donchian Volatility & Breakout", overlay=true)

length = input.int(20, title="Channel Length", minval=1)
consolidationRatio = input.float(0.05, title="Consolidation Ratio (e.g., 0.05)", minval=0.01, step=0.01)

[upperBand, middleBand, lowerBand] = ta.donchian(length)

plot(upperBand, "Upper Band", color.blue)
plot(middleBand, "Middle Band", color.gray)
plot(lowerBand, "Lower Band", color.blue)
fill(upperBand, lowerBand, color.new(color.blue, 90))

// Calculate channel width relative to price or middle band
channelWidth = upperBand - lowerBand
relativeWidth = channelWidth / middleBand * 100 // Percentage width relative to price level

// Detect consolidation: width is narrow (e.g., below 5% of middle band)
isConsolidating = relativeWidth < consolidationRatio * 100

// Detect breakout from consolidation:
// Price breaks out of channel AFTER a period of consolidation
// For a robust signal, consider requiring a certain number of consolidating bars
breakoutUp = close > upperBand[1] and close[1] <= upperBand[1] and isConsolidating[1]
breakoutDown = close < lowerBand[1] and close[1] >= lowerBand[1] and isConsolidating[1]

bgcolor(isConsolidating ? color.new(color.yellow, 90) : na, title="Consolidation Zone")
plotshape(breakoutUp, title="Bullish Breakout", location=location.belowbar, color=color.new(color.green, 0), style=shape.triangleup, size=size.small)
plotshape(breakoutDown, title="Bearish Breakout", location=location.abovebar, color=color.new(color.red, 0), style=shape.triangledown, size=size.small)

alertcondition(breakoutUp, "Donchian Bullish Breakout", "Price broke above Donchian Channels after consolidation.")
alertcondition(breakoutDown, "Donchian Bearish Breakout", "Price broke below Donchian Channels after consolidation.")
$ ✓ Compiled successfully
09

Optimizing Donchian Channels Performance

To get the most from Donchian Channels in Pinescript:

  • Parameter Tuning: The `length` parameter is crucial.
    • Shorter Lengths (e.g., 10 or 20 periods): More reactive, suitable for shorter-term trend-following or identifying quick breakouts.
    • Longer Lengths (e.g., 55 periods): Smoother, less frequent signals, but potentially more reliable for capturing long-term trends and reducing whipsaws (as used by the Turtle Traders).
    Experiment to find the optimal length for your asset and timeframe.
  • Combine with Trend Filters: Donchian Channels are best used in conjunction with other indicators that confirm the strength and direction of the trend. For instance, a long entry signal (price breaking above the upper band) is stronger if confirmed by a rising long-term moving average or positive ADX.
  • Volume Confirmation: A breakout signal is more robust if accompanied by a significant increase in volume. This indicates strong conviction behind the move.
  • Volatility Filters: While channel width can show volatility, combining Donchian Channels with a dedicated volatility indicator like ATR can help filter out false breakouts during periods of low volatility.
  • Risk Management: Due to their trend-following nature, Donchian Channel strategies often involve larger stop losses (e.g., below the lower band for longs) but aim for larger profits. Implement strict risk management rules, including position sizing.
10

Turtle Trading Connection

Turtle Trading Connection

Donchian Channels were a core component of the legendary Turtle Trading system, where traders were taught to enter when price broke above the 20-day high and exit when price broke below the 10-day low. This highlights their effectiveness in systematic trend following.

11

Common Donchian Channels Pitfalls

  • Whipsaws in Sideways Markets: Donchian Channels are inherently trend-following. In prolonged choppy or range-bound markets, price can frequently cross the bands back and forth, leading to numerous false signals and whipsaws. This is their biggest weakness.
  • Lag: As they rely on historical highs and lows, Donchian Channels are lagging indicators. Entries will often occur after a significant portion of the move has already happened.
  • Limited for Mean Reversion: While a Middle Band crossover can be used for exits, they are not designed for mean-reversion strategies in the way Bollinger Bands or Keltner Channels might be.
  • No Fixed Overbought/Oversold Levels: They do not directly indicate overbought or oversold conditions in the same way oscillators like RSI do.
  • Not a Standalone Indicator: Relying solely on Donchian Channel signals without confirmation from other tools and a complete trading plan is not recommended.
12

Conclusion

Conclusion

Donchian Channels are a fundamental and highly effective trend-following indicator available in Pinescript for TradingView. By providing clear visual boundaries of recent price action, they offer traders a straightforward method for identifying potential breakouts, confirming trend direction, and managing risk. While they excel in trending markets and form the basis of robust breakout strategies like those used by the Turtle Traders, it's crucial to understand their limitations, particularly in choppy environments. By thoughtfully tuning their parameters, combining them with appropriate trend filters and volume analysis, and implementing sound risk management, you can leverage Donchian Channels to enhance your trading decisions and capitalize on significant market movements.

Enhance Your Trading

Get a high-performance Pinescript analysis tool for actionable market insights, designed for traders on the move.

This strategy runs in live mode on TradingView, helping you identify potential opportunities.

Get Pinescript Strategy