Indicator TutorialPine Script v5

How to Create Donchian Channel in TradingView

Master Breakout Trading with the Donchian Channel: From Manual Coding to Visual Creation

The Donchian Channel is a classic breakout indicator that plots the highest high and lowest low over a specified period. Made famous by the legendary Turtle Traders, it remains one of the most effective tools for identifying trend breakouts and managing risk. This comprehensive guide walks you through everything from the mathematical foundations to building your own custom Donchian Channel in TradingView using both Pine Script and the Pineify visual editor.

What is the Donchian Channel?

The Donchian Channel is a trend-following indicator developed by Richard Donchian, widely regarded as the "father of trend following." The indicator creates a channel by plotting three lines: the highest high over a given period (upper band), the lowest low over the same period (lower band), and the midline (average of upper and lower).

The Donchian Channel gained legendary status through the Turtle Trading experiment of the 1980s, where Richard Dennis and William Eckhardt trained a group of novice traders to use a systematic breakout strategy based primarily on the 20-day and 55-day Donchian Channels. The Turtles went on to earn over $175 million, proving that trend following with simple rules could be extraordinarily profitable.

Unlike Bollinger Bands, which use standard deviation to measure volatility, the Donchian Channel uses pure price extremes. This makes it particularly effective for breakout trading, as a new high or low by definition breaks the channel boundary.

Why Traders Use This Indicator

  • Breakout Identification: A close above the upper band signals a potential bullish breakout; below the lower band signals bearish.
  • Trend Following: The channel direction and width reveal the prevailing trend and its strength.
  • Dynamic Support and Resistance: The upper and lower bands act as natural support and resistance levels.
  • Risk Management: The channel width provides a volatility-based framework for setting stop losses.
  • Simplicity: The indicator uses only price extremes with no complex calculations, making signals unambiguous.
ParameterDefaultDescription
Length20The number of bars used to calculate the highest high and lowest low. The Turtle Traders used 20 for entries and 10 for exits.
Source HighHighThe price data used for the upper band calculation (typically the bar high).
Source LowLowThe price data used for the lower band calculation (typically the bar low).
Offset0Shifts the channel forward or backward on the chart for visual alignment.

How the Donchian Channel Works: The Formula

The Donchian Channel is one of the simplest indicators to calculate, relying on just two basic operations:

  1. Upper Band = Highest High over the last n periods
  2. Lower Band = Lowest Low over the last n periods
  3. Middle Band = (Upper Band + Lower Band) / 2

In Pine Script, these correspond to ta.highest(high, length) and ta.lowest(low, length). The middle band is simply the arithmetic mean of the two extremes.

The beauty of the Donchian Channel lies in its simplicity: when price makes a new high for the period, the upper band moves up. When it makes a new low, the lower band moves down. The channel only expands or contracts based on actual price extremes.

Signal Interpretation

  • Bullish Breakout: Price closes above the upper band, indicating a new high for the period and potential trend initiation.
  • Bearish Breakout: Price closes below the lower band, indicating a new low and potential downtrend.
  • Channel Squeeze: When the channel narrows significantly, it indicates low volatility and often precedes a major breakout.
  • Midline Crossover: Price crossing above the midline suggests bullish momentum; crossing below suggests bearish momentum.
  • Channel Walk: In strong trends, price will "walk" along the upper or lower band, with the opposite band trailing behind.

Combining with Other Indicators

  • ATR (Average True Range): Use ATR to set stop-loss distances relative to the channel breakout point.
  • ADX (Average Directional Index): Filter breakout signals by requiring ADX above 25 to confirm trend strength.
  • Volume: Confirm breakouts with above-average volume to reduce false signals.
  • Moving Averages: Use a 200-period MA as a trend filter—only take long breakouts above the MA and short breakouts below.

The Hard Way: Writing Pine Script Manually

Challenges of Manual Coding

Implementing dual-length channels (entry and exit) requires managing multiple lookback periods and separate plot logic.

Adding features like channel width percentage, squeeze detection, and breakout alerts significantly increases code complexity.

Multi-timeframe Donchian Channels require request.security() calls with proper lookahead handling to avoid repainting.

Color-coding the channel based on trend direction (expanding vs. contracting) requires state tracking across bars.

Pine Script v5
// This Pine Script™ code is subject to the terms of the Mozilla Public License 2.0
// © Pineify

//@version=5
indicator("Advanced Donchian Channel", overlay=true)

// --- Inputs ---
entryLength  = input.int(20, "Entry Channel Length", minval=1, group="Channel Settings")
exitLength   = input.int(10, "Exit Channel Length", minval=1, group="Channel Settings")
showExit     = input.bool(true, "Show Exit Channel?", group="Channel Settings")
showMidline  = input.bool(true, "Show Midline?", group="Channel Settings")
showFill     = input.bool(true, "Show Channel Fill?", group="Visuals")
showSqueeze  = input.bool(true, "Highlight Squeeze?", group="Visuals")
squeezePct   = input.float(2.0, "Squeeze Threshold (%)", minval=0.1, step=0.1, group="Visuals")

// --- Entry Channel Calculation ---
upperEntry = ta.highest(high, entryLength)
lowerEntry = ta.lowest(low, entryLength)
midEntry   = (upperEntry + lowerEntry) / 2

// --- Exit Channel Calculation ---
upperExit = ta.highest(high, exitLength)
lowerExit = ta.lowest(low, exitLength)

// --- Channel Width Analysis ---
channelWidth    = upperEntry - lowerEntry
channelWidthPct = (channelWidth / midEntry) * 100
isSqueeze       = channelWidthPct < squeezePct

// --- Breakout Detection ---
bullBreakout = ta.crossover(close, upperEntry[1])
bearBreakout = ta.crossunder(close, lowerEntry[1])

// --- Trend Direction ---
isUptrend   = close > midEntry
isDowntrend = close < midEntry

// --- Colors ---
upColor   = color.new(color.teal, 0)
downColor = color.new(color.red, 0)
midColor  = color.new(color.gray, 30)
exitColor = color.new(color.orange, 50)

// --- Plotting Entry Channel ---
pUpper = plot(upperEntry, "Upper Band", color=upColor, linewidth=2)
pLower = plot(lowerEntry, "Lower Band", color=downColor, linewidth=2)
pMid   = plot(showMidline ? midEntry : na, "Midline", color=midColor, style=plot.style_circles, linewidth=1)

// --- Plotting Exit Channel ---
plot(showExit ? upperExit : na, "Exit Upper", color=exitColor, linewidth=1, style=plot.style_stepline)
plot(showExit ? lowerExit : na, "Exit Lower", color=exitColor, linewidth=1, style=plot.style_stepline)

// --- Channel Fill ---
fillColor = showFill ? (isUptrend ? color.new(color.teal, 90) : color.new(color.red, 90)) : na
fill(pUpper, pLower, color=fillColor, title="Channel Fill")

// --- Squeeze Background ---
bgcolor(showSqueeze and isSqueeze ? color.new(color.yellow, 85) : na, title="Squeeze Highlight")

// --- Breakout Signals ---
plotshape(bullBreakout, "Bullish Breakout", shape.triangleup, location.belowbar, color.green, size=size.small)
plotshape(bearBreakout, "Bearish Breakout", shape.triangledown, location.abovebar, color.red, size=size.small)

// --- Alerts ---
alertcondition(bullBreakout, title="Bullish Breakout", message="Price broke above the Donchian Channel upper band on {{ticker}}")
alertcondition(bearBreakout, title="Bearish Breakout", message="Price broke below the Donchian Channel lower band on {{ticker}}")
alertcondition(isSqueeze and not isSqueeze[1], title="Squeeze Detected", message="Donchian Channel squeeze detected on {{ticker}}")

Maintenance Note: This script implements dual-length channels (entry and exit) following the Turtle Trading methodology. Adding features like position sizing based on ATR or multi-timeframe confirmation would require significant additional code and careful handling of request.security() to avoid repainting issues.

The Easy Way: Build with Pineify Visual Editor

What if you could create the same indicator without writing a single line of code? Pineify is a visual editor designed for TradingView users who want professional-grade indicators through an intuitive interface.

FeatureManual Pine ScriptPineify Visual Editor
Learning CurveModerate (requires understanding of ta.highest/ta.lowest)None (visual interface)
Development Time30-60 minutesUnder 5 minutes
Error RateMedium (off-by-one errors in lookback periods)Zero (pre-tested modules)
Dual Channel SupportComplex (separate calculations and plots)One-click toggle
Squeeze DetectionManual implementation requiredBuilt-in visual module

No programming required — build professional Donchian Channels with visual controls.

Instantly switch between entry and exit channel lengths without touching code.

Built-in squeeze detection and breakout alerts with one-click activation.

AI-powered assistance to combine Donchian Channels with ATR, ADX, or volume filters.

Clean, optimized Pine Script v5 code generated automatically.

Real-time preview shows exactly how your channel looks on the chart.

Step-by-Step Tutorial

1

Open Pineify

Navigate to https://pineify.app and open the visual editor.

2

Add Donchian Channel

Click "Add Indicator" and search for "Donchian Channel" in the indicator library.

3

Configure Entry Channel

Set the entry channel length (default 20) using the visual slider. This defines the breakout detection period.

4

Add Exit Channel (Optional)

Enable the exit channel with a shorter length (e.g., 10) for the Turtle Trading exit methodology.

5

Customize Visuals

Choose colors for upper/lower bands, enable midline display, and configure channel fill opacity.

6

Enable Breakout Alerts

Toggle breakout alerts for upper and lower band penetrations. Optionally add squeeze detection alerts.

7

Generate and Install

Click "Generate Pine Script," copy the code, and paste it into TradingView's Pine Editor. Click "Add to Chart."

Trading Strategies & Pro Tips

The Turtle Trading Breakout

Enter long when price closes above the 20-period upper band; enter short when price closes below the 20-period lower band. Exit using the 10-period channel in the opposite direction. This is the classic Turtle Trading System 1.

Pro Tip: The original Turtles also used a 55-period channel for System 2, which caught larger trends but had fewer signals.

Donchian Channel + ATR Trailing Stop

Use the Donchian breakout for entry signals, but instead of the exit channel, trail your stop loss using 2x ATR from the entry point. This allows you to ride strong trends longer while protecting profits.

Pro Tip: Combine with position sizing based on ATR (risk 1% of equity per ATR unit) for professional-grade risk management.

Squeeze Breakout Strategy

Monitor the channel width percentage. When it drops below a threshold (e.g., 2%), prepare for a breakout. Enter on the first candle that breaks above the upper or below the lower band after the squeeze.

Pro Tip: Squeezes on higher timeframes (Daily, 4H) produce more reliable breakouts than on lower timeframes.

Midline Bounce (Mean Reversion)

In a trending market, use pullbacks to the Donchian midline as entry opportunities. Buy when price bounces off the midline in an uptrend; sell when it rejects the midline in a downtrend.

Common Mistakes to Avoid

  • Trading breakouts in sideways markets — the Donchian Channel produces many false breakouts during consolidation. Use ADX to filter for trending conditions.
  • Using the same length for both entry and exit — the Turtle system specifically used a shorter exit channel (10) than the entry channel (20) to lock in profits faster.
  • Ignoring the channel width — a very wide channel means high volatility and larger risk per trade. Adjust position size accordingly.
  • Not accounting for gaps — overnight or weekend gaps can trigger false breakout signals. Consider using the close price instead of high/low for the channel calculation.

Frequently Asked Questions

Build Your Donchian Channel Without Writing Code

  • Create professional Donchian Channels with dual entry/exit lengths in minutes.
  • No coding required — focus on your breakout strategy, not syntax.
  • Generate clean, error-free Pine Script v5 code automatically.

Disclaimer: Trading involves significant risk. The indicators, code, and strategies provided are for educational purposes only and do not constitute financial advice. Past performance is not indicative of future results.