Strategy · Pine Script v5 · On the chart

Donchian Breakout + ATR Risk

by JustACoder279

A trend-following strategy that goes long when the close breaks above the previous Donchian channel high and short when it breaks below the previous low.

View on GitHub

Repaints

GitHub stars1on the repository
Pine versionv5runs as is
Lines of code81
Settings11inputs
LicenceMIT
Last update9 months ago5 Jan 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

81 lines of Pine Script v5 from donchian_breakout.pine, published under MIT. Keep the author's credit and licence lines when you reuse it.

donchian_breakout.pine
//@version=5
strategy("Donchian Breakout + ATR Risk (Robust Trend) [v5]", overlay=true,
     initial_capital=10000, pyramiding=0, calc_on_every_tick=true,
     commission_type=strategy.commission.percent, commission_value=0.02)


// Inputs

dcLen        = input.int(55, "Donchian Length", minval=5)
emaLen       = input.int(200, "EMA Filter Length", minval=1)
useEMAFilter = input.bool(true, "Use EMA Trend Filter")

atrLen       = input.int(14, "ATR Length", minval=1)
atrBaseLen   = input.int(50, "ATR Baseline Length", minval=5)
atrMult      = input.float(1.0, "ATR Regime Filter (>=)", step=0.05)

riskATR      = input.float(2.0, "Stop (ATR)", step=0.1)
trailATR     = input.float(2.5, "Trailing (ATR)", step=0.1)
useTrail     = input.bool(true, "Use Trailing Stop")

takeMode     = input.string("TrailOnly", "Take Profit Mode", options=["TrailOnly","RR_Target"])
rr           = input.float(2.0, "RR Target (if RR_Target)", step=0.1)

// Indicators

upper = ta.highest(high, dcLen)
lower = ta.lowest(low, dcLen)
mid   = (upper + lower) / 2.0

ema   = ta.ema(close, emaLen)

atr = ta.atr(atrLen)
atrBase = ta.sma(atr, atrBaseLen)
regimeOk = atr >= atrBase * atrMult

trendUp   = close > ema
trendDown = close < ema

// Breakout signals (use previous channel to avoid repaint-like behavior)
longBreak  = close > upper[1]
shortBreak = close < lower[1]

longAllowed  = regimeOk and (not useEMAFilter or trendUp)
shortAllowed = regimeOk and (not useEMAFilter or trendDown)

//Entries

if longBreak and longAllowed and strategy.position_size <= 0
    strategy.entry("LONG", strategy.long)

if shortBreak and shortAllowed and strategy.position_size >= 0
    strategy.entry("SHORT", strategy.short)

// Exits

if strategy.position_size > 0
    ep = strategy.position_avg_price
    stopL = ep - atr * riskATR
    if useTrail
        strategy.exit("L-EXIT", "LONG", stop=stopL, trail_points=atr * trailATR)
    else if takeMode == "RR_Target"
        takeL = ep + (ep - stopL) * rr
        strategy.exit("L-EXIT", "LONG", stop=stopL, limit=takeL)
    else
        strategy.exit("L-EXIT", "LONG", stop=stopL)

if strategy.position_size < 0
    ep = strategy.position_avg_price
    stopS = ep + atr * riskATR
    if useTrail
        strategy.exit("S-EXIT", "SHORT", stop=stopS, trail_points=atr * trailATR)
    else if takeMode == "RR_Target"
        takeS = ep - (stopS - ep) * rr
        strategy.exit("S-EXIT", "SHORT", stop=stopS, limit=takeS)
    else
        strategy.exit("S-EXIT", "SHORT", stop=stopS)

plot(upper, "Donchian Upper")
plot(lower, "Donchian Lower")
plot(mid,   "Donchian Mid")
plot(ema,   "EMA Filter")

Overview

An optional 200 EMA filter limits direction, and an ATR regime filter skips quiet markets. Each trade has an ATR-multiple stop, with an optional ATR trailing stop or a fixed reward-to-risk target. The channel lines and EMA are drawn on the price chart. Orders recalculate on every tick, so intrabar signals can differ from bar-close results. Commission is set to a small percentage.

Details

Published by

JustACoder279 on GitHub

Type

Strategy, Pine Script v5

Draws

On the price chart

Category

Breakout, Trend, Volatility & bands

Markets

Any symbol

Timeframes

H4 and above

Risk Notes

  • Signals can change on the live bar or after it closes (repainting)

Settings

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

SettingTypeDefaultVariable
Donchian Lengthint55dcLen
EMA Filter Lengthint200emaLen
Use EMA Trend FilterbooltrueuseEMAFilter
ATR Lengthint14atrLen
ATR Baseline Lengthint50atrBaseLen
ATR Regime Filter (>=)float1.0atrMult
Stop (ATR)float2.0riskATR
Trailing (ATR)float2.5trailATR
Use Trailing StopbooltrueuseTrail
Take Profit ModestringTrailOnlytakeMode
RR Target (if RR_Target)float2.0rr
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

257 stars

This strategy plots VWMA-based Bollinger bands on the 1-minute ES futures price chart for volatility analysis and potential breakout identification. It calculates dynamic long and short stop loss and take profit levels using percentage inputs relative to entry

Strategy v6 Volatility & bandsSupport & resistance
Updated 6 weeks ago · None stated GitHub repository of V1.6 ES - Futures 1M No Repaint
106 stars

This strategy runs on the price chart and enters long when a fast simple moving average crosses above a slow one, and short on the opposite cross, while closing the other side. Entries also need ATR above a filter, a pullback check, a minimum candle-body chang

Strategy v5 TrendMoving averages
Updated 2 years ago · GPL-3.0 GitHub repository of 9:22 5 MIN 15 MIN BANKNIFTY

均线突破交易系统

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 5 months ago · None stated GitHub repository of 均线突破交易系统
16 stars

This trend-following strategy adapts classic Donchian breakout channels according to market volatility regimes. It calculates an ATR percentile rank across a rolling lookback period, shifting dynamically between tighter breakout channels with smaller stops dur

Strategy v6 TrendBreakout
Updated 12 months ago · None stated GitHub repository of Seykota Alt 1: Adaptive Volatility

This strategy executes breakout trades using two Donchian Channels alongside an optional 200-period EMA trend filter. Entries trigger when the price sets a new highest high or lowest low over the primary Donchian Channel period. Exits are managed via a shorter

Strategy v5 BreakoutTrend
Updated 1 year ago · None stated GitHub repository of Ruckard Walcrypto DoubleDonchian B002

Breakout Strategy

by JoelPasapera
11 stars

This strategy implements a channel breakout system directly on the main price chart. It calculates highest highs and lowest lows over configurable entry and exit periods using historical candles. A long entry triggers when the close breaks above the entry chan

Strategy v6 BreakoutTrend
Updated 5 months ago · Apache-2.0 GitHub repository of Breakout 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