Strategy · Pine Script v5 · On the chart

Donchian Channel - Turtle Trading

by Basant1Saini· code credited to TradingTools

This strategy implements the classic Turtle Trading System using Donchian channels.

View on GitHub

GitHub stars1on the repository
Pine versionv5runs as is
Lines of code90
Settings7inputs
LicenceNone statedfile: MPL-2.0
Last update7 months ago4 Mar 2026

Add It to Your TradingView Chart

  1. 1Copy the scriptPress Copy script above, or the copy button on the code below.
  2. 2Open the Pine EditorOpen a TradingView chart and choose Pine Editor at the bottom of the screen.
  3. 3Paste over the templateCreate a new strategy, select all of the template text and paste. Press Save and give it a name.
  4. 4Add it to the chartPress Add to chart. The trades and results appear in the Strategy Tester tab; adjust the settings with the gear icon.

Source Code

90 lines of Pine Script v5 from 13_Donchian_Channel/13_Donchian_Channel.pine, published under MPL-2.0 (file header). Keep the author's credit and licence lines when you reuse it.

13_Donchian_Channel.pine
// This Pine Script™ code is subject to the terms of the Mozilla Public License 2.0
// © TradingTools

//@version=5
strategy("Donchian Channel - Turtle Trading", overlay=true, default_qty_type=strategy.percent_of_equity, default_qty_value=100)

// ─── Inputs ───
entryLength     = input.int(20, "Entry Channel Length", group="Donchian")
exitLength      = input.int(10, "Exit Channel Length", group="Donchian")
useFilter       = input.bool(true, "Skip Entry if Previous Trade Won", group="Filters")
atrLength       = input.int(20, "ATR Length (Position Sizing)", group="Risk Management")
atrMult         = input.float(2.0, "ATR Multiplier for SL", step=0.1, group="Risk Management")
trailByExit     = input.bool(true, "Use Exit Channel as Trailing Stop", group="Risk Management")
pyramidMax      = input.int(3, "Max Pyramid Entries", minval=1, maxval=5, group="Risk Management")

// ─── Donchian Channel ───
// Entry channel (20-period)
entryHigh = ta.highest(high, entryLength)[1]
entryLow  = ta.lowest(low, entryLength)[1]

// Exit channel (10-period)
exitHigh  = ta.highest(high, exitLength)[1]
exitLow   = ta.lowest(low, exitLength)[1]

// Mid line
entryMid  = (entryHigh + entryLow) / 2

// ─── ATR ───
atrVal = ta.atr(atrLength)

// ─── Track Previous Trade Result ───
var bool lastTradeWon = false
var float lastEntryPrice = na

if strategy.closedtrades > 0
    lastPnL = strategy.closedtrades.profit(strategy.closedtrades - 1)
    lastTradeWon := lastPnL > 0

// Skip filter (Turtle System 1 rule)
skipOK = useFilter ? not lastTradeWon : true

// ─── Entry Conditions ───
longCondition  = high >= entryHigh and skipOK
shortCondition = low <= entryLow and skipOK

// ─── Execute Trades ───
if longCondition and strategy.position_size <= 0
    sl = trailByExit ? exitLow : close - atrVal * atrMult
    strategy.entry("Turtle Long", strategy.long)
    strategy.exit("Turtle Long Exit", "Turtle Long", stop=sl)
    lastEntryPrice := close

if shortCondition and strategy.position_size >= 0
    sl = trailByExit ? exitHigh : close + atrVal * atrMult
    strategy.entry("Turtle Short", strategy.short)
    strategy.exit("Turtle Short Exit", "Turtle Short", stop=sl)
    lastEntryPrice := close

// ─── Pyramid (add every 0.5 ATR move in favor) ───
if strategy.position_size > 0 and strategy.opentrades < pyramidMax
    if close >= lastEntryPrice + atrVal * 0.5
        strategy.entry("Turtle Long Add", strategy.long)
        lastEntryPrice := close

if strategy.position_size < 0 and strategy.opentrades < pyramidMax
    if close <= lastEntryPrice - atrVal * 0.5
        strategy.entry("Turtle Short Add", strategy.short)
        lastEntryPrice := close

// ─── Exit on Opposite Channel ───
if strategy.position_size > 0 and low <= exitLow
    strategy.close_all(comment="Exit Channel")
if strategy.position_size < 0 and high >= exitHigh
    strategy.close_all(comment="Exit Channel")

// ─── Plotting ───
pEntryH = plot(entryHigh, "Entry High (20)", color=color.new(color.blue, 0), linewidth=2)
pEntryL = plot(entryLow, "Entry Low (20)", color=color.new(color.blue, 0), linewidth=2)
plot(entryMid, "Mid", color=color.new(color.gray, 50), linewidth=1)
fill(pEntryH, pEntryL, color=color.new(color.blue, 92), title="Entry Channel")

plot(exitHigh, "Exit High (10)", color=color.new(color.orange, 30), linewidth=1, style=plot.style_linebr)
plot(exitLow, "Exit Low (10)", color=color.new(color.orange, 30), linewidth=1, style=plot.style_linebr)

plotshape(longCondition and strategy.position_size[1] <= 0, title="Long Breakout", location=location.belowbar, style=shape.arrowup, color=color.green, size=size.small, text="TURTLE")
plotshape(shortCondition and strategy.position_size[1] >= 0, title="Short Breakout", location=location.abovebar, style=shape.arrowdown, color=color.red, size=size.small, text="TURTLE")

// ─── Alerts ───
alertcondition(longCondition, title="Turtle Long", message="Donchian: 20-period high breakout — Long entry")
alertcondition(shortCondition, title="Turtle Short", message="Donchian: 20-period low breakout — Short entry")

Overview

Donchian Channel - Turtle Trading enters long when the price breaks above the upper entry channel and short when it breaks below the lower channel, with an optional filter that skips signals following a winning trade. Position sizing allows pyramiding up to a set limit every 0.5 ATR in profit. Positions exit either when hitting an ATR-based stop or upon breaking the shorter exit channel. It plots both entry and exit channels directly on the price chart.

Details

Published by

Basant1Saini on GitHub

Code credit

TradingTools, as written in the script's header

Type

Strategy, Pine Script v5

Draws

On the price chart

Category

Breakout, Trend

Markets

Stocks

Timeframes

H4 and above

Risk Notes

  • The strategy can add several entries in the same direction

Settings

The inputs you can change from the gear icon on the chart. Defaults are the author's.

SettingTypeDefaultVariable
Entry Channel Lengthint20entryLength
Exit Channel Lengthint10exitLength
Skip Entry if Previous Trade WonbooltrueuseFilter
ATR Length (Position Sizing)int20atrLength
ATR Multiplier for SLfloat2.0atrMult
Use Exit Channel as Trailing StopbooltruetrailByExit
Max Pyramid Entriesint3pyramidMax
Third-party code. ForexR did not write, test or endorse this script, and the summary above was generated automatically from its code and README. Indicators describe the past, and a strategy's backtest can look better than live trading, especially when a script repaints. Check it in the Strategy Tester and on a demo account before you rely on it.

Similar Pine Scripts

This trend-following strategy executes a classic Donchian channel breakout system designed to cross-validate backtest results against external framework benchmarks. It triggers a long entry when the closing price breaks above the highest high of the prior entr

Strategy v6 BreakoutTrend
Updated today · AGPL-3.0 GitHub repository of Forven S01509 - Simple Donchian 20/10 Breakout
257 stars

This strategy plots running pivot highs as red R circles and pivot lows as blue S circles directly on the price chart. It computes an EMA 3 and a Cto trend line from close prices, then generates long signals on upward EMA-Cto crossovers combined with price pos

Strategy v6 TrendMoving averages Repaints
Updated 6 weeks ago · None stated GitHub repository of Best Chart 1m Strategy Candle Bar

12/26-IT Strategy

by hasnocool
106 stars

This strategy executes trades based on crossovers between a 12-period and a 26-period exponential moving average (EMA). Long positions can be filtered by pivot resistance breakouts and RSI boundary ranges. For trade management, it provides two configurable par

Strategy v5 TrendMoving averages
Updated 2 years ago · GPL-3.0 GitHub repository of 12/26-IT Strategy

均线突破交易系统

by tangly1024
76 stars

This strategy trades long breakouts of a fast and a slow moving average on the price chart. It opens a long position when price crosses above either average, using a percentage of equity as size. It reduces the position by a set share when the high reaches the

Strategy v5 TrendMoving averages
Updated 4 months ago · None stated GitHub repository of 均线突破交易系统
53 stars

This strategy enters long or short on the price chart when price is on the correct side of a 200-period EMA, MACD agrees, RSI is not at the opposing extreme, ADX exceeds a threshold, volume beats a 20-bar average, and close breaks the recent high or low. A tim

Strategy v6 TrendOscillators & momentum
Updated 2 months ago · MPL-2.0 GitHub repository of BTCUSD 5M Optimized Strategy

More strategys

Trade Your Charts With a Regulated Broker

Compare brokers that connect to TradingView, with spreads, minimum deposits and leverage side by side.

Compare brokers