Strategy · Pine Script v6 · On the chart

Seykota Alt 4: Weekly Donchian

by trustdan· code credited to danieltuckerrust

This strategy trades Donchian breakouts measured on weekly bars while orders execute on the chart timeframe.

View on GitHub

GitHub stars16on the repository
Pine versionv6current
Lines of code167
Settings19inputs
LicenceNone statedfile: MPL-2.0
Last update11 months ago3 Nov 2025

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

167 lines of Pine Script v6 from pine-scripts/29_PF-0.788_SPY_seykota_alt4_weekly_donchian.pine, published under MPL-2.0 (file header). Keep the author's credit and licence lines when you reuse it.

29_PF-0.788_SPY_seykota_alt4_weekly_donchian.pine
// This Pine Script® code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © danieltuckerrust
// ALTERNATIVE 4: Weekly Timeframe Donchian
// THEORY: Higher timeframe lookbacks capture major trends and avoid daily noise.
// By anchoring breakout logic on weekly bars (26-week entry, 13-week exit), we catch only
// the most significant trends. Execution still happens on the chart timeframe (e.g., daily).
// Trade-off: Fewer, higher-quality trades with less chop; may miss medium-term trends.

//@version=6
strategy("Seykota Alt 4: Weekly Donchian v1.0",
     overlay=true,
     initial_capital=100000,
     commission_type=strategy.commission.percent, commission_value=0.005,
     slippage=2,
     default_qty_type=strategy.fixed, default_qty_value=0,
     pyramiding=10,
     max_bars_back=5000)

//================ Inputs
allowLong   = input.bool(true,  "Allow LONGs?")
allowShort  = input.bool(true,  "Allow SHORTs?")

// CHANGED: Weekly Donchian parameters
wEntryLen   = input.int(26,     "Weekly ENTRY lookback (weeks)",      minval=8)
wExitLen    = input.int(13,     "Weekly EXIT lookback (weeks)",       minval=5)
nLen        = input.int(20,     "N = ATR length (chart TF)",          minval=5)
stopN       = input.float(2.0,  "Initial stop (in N)",                minval=0.5, step=0.25)
addStepN    = input.float(0.5,  "Add every X * N",                    minval=0.25, step=0.25)
maxUnits    = input.int(4,      "Max units (incl. initial)",          minval=1, maxval=10)
riskPct     = input.float(1.0,  "Risk % of equity PER UNIT",          minval=0.1, maxval=5, step=0.1)

useMarket   = input.bool(false, "Use market regime filter?")
marketSym   = input.symbol("SPY", "Market symbol for regime (if used)")
marketTF    = input.timeframe("D", "Regime timeframe (if used)")
marketLen   = input.int(200,    "Market MA length (if used)",         minval=50)

minVol      = input.int(0,      "Min 20-bar avg volume (chart TF)",   minval=0)
showSignals = input.bool(true,  "Plot signals & stops?")
plotDon     = input.bool(true,  "Plot weekly Donchian bands?")

// Date-range filter
fromDate = input.time(defval=timestamp("2022-01-01T00:00:00"), title="Backtest FROM (yyyy-mm-dd)", confirm=true)
toDate   = input.time(defval=timestamp("2099-12-31T23:59:59"), title="Backtest TO (yyyy-mm-dd)",   confirm=true)
flatAtFrom = input.bool(true, "Force FLAT at range start?")
isRangeStart = (time[1] < fromDate) and (time >= fromDate)
if flatAtFrom and isRangeStart and strategy.position_size != 0
    strategy.close_all(comment="Flat at FROM")

//================ Helpers
sharesForUnit(_equity, _Nentry) =>
    riskDollars   = _equity * (riskPct/100.0)
    perShareRisk  = math.max(stopN * _Nentry, syminfo.mintick)
    math.max(1, math.floor(riskDollars / perShareRisk))

inRange = (time >= fromDate) and (time <= toDate)

//================ Core calcs (chart timeframe)
N     = ta.atr(nLen)
volMA = ta.sma(volume, 20)
liqOK = volMA >= minVol

// CHANGED: Weekly Donchian levels using request.security
// Use [1] offset to avoid lookahead bias
wHiPrev = request.security(syminfo.tickerid, "W", ta.highest(high, wEntryLen)[1], lookahead=barmerge.lookahead_off)
wLoPrev = request.security(syminfo.tickerid, "W", ta.lowest(low,  wEntryLen)[1], lookahead=barmerge.lookahead_off)

wExitHiPrev = request.security(syminfo.tickerid, "W", ta.highest(high, wExitLen)[1], lookahead=barmerge.lookahead_off)
wExitLoPrev = request.security(syminfo.tickerid, "W", ta.lowest(low,  wExitLen)[1], lookahead=barmerge.lookahead_off)

// Market regime (optional)
mClose = request.security(marketSym, marketTF, close)
mMA    = request.security(marketSym, marketTF, ta.sma(close, marketLen))
longRegOK  = not useMarket or (mClose > mMA)
shortRegOK = not useMarket or (mClose < mMA)

//================ Signals (weekly breakout executed on chart TF)
longBreak  = allowLong  and liqOK and longRegOK  and inRange and (close > wHiPrev)
shortBreak = allowShort and liqOK and shortRegOK and inRange and (close < wLoPrev)

//================ Position state
var float N_entry       = na
var float lastAddLong   = na
var float lastAddShort  = na
var int   units         = 0

inPos     = strategy.position_size != 0
inLong    = strategy.position_size > 0
inShort   = strategy.position_size < 0

if not inPos
    units        := 0
    lastAddLong  := na
    lastAddShort := na
    N_entry      := na

//================ Entries
if not inPos and longBreak
    N_entry := N
    float sh = sharesForUnit(strategy.equity, N_entry)
    strategy.entry("L", strategy.long, qty=sh)
    units       := 1
    lastAddLong := close

if not inPos and shortBreak
    N_entry := N
    float sh = sharesForUnit(strategy.equity, N_entry)
    strategy.entry("S", strategy.short, qty=sh)
    units        := 1
    lastAddShort := close

//================ Add-ons (on chart timeframe, every 0.5N)
canAddLong  = inRange and inLong  and units < maxUnits and high >= nz(lastAddLong)  + addStepN * N_entry
canAddShort = inRange and inShort and units < maxUnits and low  <= nz(lastAddShort) - addStepN * N_entry

if canAddLong
    float sh = sharesForUnit(strategy.equity, N_entry)
    strategy.entry("L", strategy.long, qty=sh)
    units       += 1
    lastAddLong := close

if canAddShort
    float sh = sharesForUnit(strategy.equity, N_entry)
    strategy.entry("S", strategy.short, qty=sh)
    units        += 1
    lastAddShort := close

//================ Exits (weekly Donchian + ATR stop)
var float stopL = na
var float stopS = na

if inRange and inLong
    initStopL = strategy.position_avg_price - stopN * N_entry
    // Use weekly exit level OR initial stop, whichever is tighter
    exitL     = math.round_to_mintick(math.max(initStopL, wExitLoPrev))
    stopL     := exitL
    strategy.exit("L-EXIT", from_entry="L", stop=stopL)
else
    stopL := na

if inRange and inShort
    initStopS = strategy.position_avg_price + stopN * N_entry
    // Use weekly exit level OR initial stop, whichever is tighter
    exitS     = math.round_to_mintick(math.min(initStopS, wExitHiPrev))
    stopS     := exitS
    strategy.exit("S-EXIT", from_entry="S", stop=stopS)
else
    stopS := na

//================ Plots
plot(plotDon ? wHiPrev : na, "Weekly High", color=color.new(color.blue, 30), linewidth=2, style=plot.style_stepline)
plot(plotDon ? wLoPrev : na, "Weekly Low",  color=color.new(color.blue, 30), linewidth=2, style=plot.style_stepline)

plot(plotDon ? wExitHiPrev : na, "Weekly Exit High", color=color.new(color.red, 50), linewidth=1, style=plot.style_circles)
plot(plotDon ? wExitLoPrev : na, "Weekly Exit Low",  color=color.new(color.red, 50), linewidth=1, style=plot.style_circles)

plotshape(showSignals and longBreak,  title="Long Breakout",  style=shape.triangleup,   location=location.belowbar, size=size.small, color=color.new(color.green, 0), text="W↑")
plotshape(showSignals and shortBreak, title="Short Breakout", style=shape.triangledown, location=location.abovebar, size=size.small, color=color.new(color.red,   0), text="W↓")

plot(showSignals and inLong  ? stopL : na, "Long Stop",  color=color.new(color.red, 0), style=plot.style_linebr, linewidth=2)
plot(showSignals and inShort ? stopS : na, "Short Stop", color=color.new(color.red, 0), style=plot.style_linebr, linewidth=2)

// Info label
var label infoLabel = na
if barstate.islast and showSignals
    labelText = "Weekly Donchian\nEntry: " + str.tostring(wEntryLen) + "W\nExit: " + str.tostring(wExitLen) + "W"
    label.delete(infoLabel)
    infoLabel := label.new(bar_index, high, labelText, style=label.style_label_down, color=color.new(color.blue, 80), textcolor=color.white, size=size.small)

Overview

Seykota Alt 4: Weekly Donchian allows long and short entries when price breaks the prior weekly channel and exits against the shorter weekly channel. Position size risks a set percent of equity per unit, with an ATR-based initial stop and optional adds at ATR intervals up to a unit cap. Optional filters include a higher-timeframe moving-average regime, minimum volume, and a backtest date window. It plots signals, stops, and weekly bands on the price chart. The script enables pyramiding.

Details

Published by

trustdan on GitHub

Code credit

danieltuckerrust, as written in the script's header

Type

Strategy, Pine Script v6

Draws

On the price chart

Category

Trend, Breakout, Volatility & bands, Support & resistance

Markets

Stocks, Indices

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
Allow LONGs?booltrueallowLong
Allow SHORTs?booltrueallowShort
Weekly ENTRY lookback (weeks)int26wEntryLen
Weekly EXIT lookback (weeks)int13wExitLen
N = ATR length (chart TF)int20nLen
Initial stop (in N)float2.0stopN
Add every X * Nfloat0.5addStepN
Max units (incl. initial)int4maxUnits
Risk % of equity PER UNITfloat1.0riskPct
Use market regime filter?boolfalseuseMarket
Market symbol for regime (if used)symbolSPYmarketSym
Regime timeframe (if used)timeframeDmarketTF
Show all 19 settings
SettingTypeDefaultVariable
Market MA length (if used)int200marketLen
Min 20-bar avg volume (chart TF)int0minVol
Plot signals & stops?booltrueshowSignals
Plot weekly Donchian bands?booltrueplotDon
Backtest FROM (yyyy-mm-dd)timetimestamp("2022-01-01T00:00:00")fromDate
Backtest TO (yyyy-mm-dd)timetimestamp("2099-12-31T23:59:59")toDate
Force FLAT at range start?booltrueflatAtFrom
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
11 stars

Calculates upper and lower Donchian Channel bands over a customizable lookback length and plots them on the main price chart. At a specified exchange hour, the strategy places a long buy stop order at the upper Donchian Channel level. Unfilled pending orders a

Strategy v6 BreakoutSupport & resistance
Updated 5 months ago · Apache-2.0 GitHub repository of Estrategia Donchian Breakout

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
106 stars

This overlay strategy plots a two-timeframe Ichimoku setup on the price chart, with Tenkan, Kijun, Chikou, and Kumo from a base higher timeframe and an optional highest-timeframe cloud. It allows two entries in the same direction and uses ATR-based trailing st

Strategy v4 TrendVolatility & bands
Updated 2 years ago · GPL-3.0 GitHub repository of 2Tier Ichimoku Pyramiding [Takazudo]

均线突破交易系统

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 均线突破交易系统

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