Strategy · Pine Script v6 · On the chart

Seykota Alt 29: Multi-Stage Scaling

by trustdan· code credited to danieltuckerrust

This strategy implements a multi-stage trend following system inspired by John W.

View on GitHub

GitHub stars16on the repository
Pine versionv6current
Lines of code280
Settings26inputs
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

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

16_PF-1.177_SPY_seykota_alt29_multi_stage_scaling.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 29: Multi-Stage Profit Scaling
// THEORY: Take profits at MANY levels (1.5N, 3N, 5N, 7N, 10N) instead of just 3.
// More granular scaling means we capture profit throughout the trend, not just at
// major milestones. Reduces risk of giving everything back on reversals.
// INSIGHT FROM BACKTESTS: Alt 10's 3-stage profit targets (+20%) worked brilliantly.
// This extends that concept: if 3 targets work, maybe 5-6 targets work even better.
// Trade-off: More execution complexity, but smoother equity curve and less drawdown.

//@version=6
strategy("Seykota Alt 29: Multi-Stage Scaling 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?")

entryLen    = input.int(55,     "Donchian ENTRY lookback",            minval=10)
nLen        = input.int(20,     "N = ATR length",                     minval=5)
stopN       = input.float(2.0,  "Initial stop (in N)",                minval=0.5, step=0.25)
trailLen    = input.int(22,     "Chandelier trail lookback",          minval=5)
trailN      = input.float(3.0,  "Chandelier trail (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(6,      "Max units (for 6-stage scaling)",    minval=4, maxval=10)
riskPct     = input.float(0.75, "Risk % per unit (smaller for more units)", minval=0.1, maxval=3, step=0.05)

// Multi-stage profit targets (6 levels)
useTargets   = input.bool(true,  "Use multi-stage targets?")
target1N     = input.float(1.5,  "Target 1 (in N) - Close unit 1",    minval=0.5, step=0.5)
target2N     = input.float(3.0,  "Target 2 (in N) - Close unit 2",    minval=1, step=0.5)
target3N     = input.float(5.0,  "Target 3 (in N) - Close unit 3",    minval=1, step=0.5)
target4N     = input.float(7.0,  "Target 4 (in N) - Close unit 4",    minval=1, step=0.5)
target5N     = input.float(10.0, "Target 5 (in N) - Close unit 5",    minval=1, step=0.5)

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 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
N        = ta.atr(nLen)
volMA    = ta.sma(volume, 20)
liqOK    = volMA >= minVol

// Donchian levels
donHi    = ta.highest(high, entryLen)
donLo    = ta.lowest(low,  entryLen)
donHiPrev= donHi[1]
donLoPrev= donLo[1]

// Chandelier levels
trailHighest = ta.highest(high, trailLen)
trailLowest  = ta.lowest(low,  trailLen)

// 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
longBreak  = allowLong  and liqOK and longRegOK  and (close > donHiPrev)
shortBreak = allowShort and liqOK and shortRegOK and (close < donLoPrev)

//================ Position state
var float N_entry       = na
var float entryPrice    = na
var float lastAddLong   = na
var float lastAddShort  = na
var int   units         = 0
var bool  target1Hit    = false
var bool  target2Hit    = false
var bool  target3Hit    = false
var bool  target4Hit    = false
var bool  target5Hit    = false

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
    entryPrice   := na
    target1Hit   := false
    target2Hit   := false
    target3Hit   := false
    target4Hit   := false
    target5Hit   := false

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

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

//================ Add-ons
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

//================ MULTI-STAGE PROFIT TARGETS (5 levels)
if useTargets and inLong and not na(entryPrice) and not na(N_entry)
    target1Price = entryPrice + target1N * N_entry
    target2Price = entryPrice + target2N * N_entry
    target3Price = entryPrice + target3N * N_entry
    target4Price = entryPrice + target4N * N_entry
    target5Price = entryPrice + target5N * N_entry

    if not target1Hit and high >= target1Price
        float closeQty = sharesForUnit(strategy.equity, N_entry)
        strategy.close("L", qty=closeQty, comment="T1")
        target1Hit := true

    if target1Hit and not target2Hit and high >= target2Price
        float closeQty = sharesForUnit(strategy.equity, N_entry)
        strategy.close("L", qty=closeQty, comment="T2")
        target2Hit := true

    if target2Hit and not target3Hit and high >= target3Price
        float closeQty = sharesForUnit(strategy.equity, N_entry)
        strategy.close("L", qty=closeQty, comment="T3")
        target3Hit := true

    if target3Hit and not target4Hit and high >= target4Price
        float closeQty = sharesForUnit(strategy.equity, N_entry)
        strategy.close("L", qty=closeQty, comment="T4")
        target4Hit := true

    if target4Hit and not target5Hit and high >= target5Price
        float closeQty = sharesForUnit(strategy.equity, N_entry)
        strategy.close("L", qty=closeQty, comment="T5")
        target5Hit := true

if useTargets and inShort and not na(entryPrice) and not na(N_entry)
    target1Price = entryPrice - target1N * N_entry
    target2Price = entryPrice - target2N * N_entry
    target3Price = entryPrice - target3N * N_entry
    target4Price = entryPrice - target4N * N_entry
    target5Price = entryPrice - target5N * N_entry

    if not target1Hit and low <= target1Price
        float closeQty = sharesForUnit(strategy.equity, N_entry)
        strategy.close("S", qty=closeQty, comment="T1")
        target1Hit := true

    if target1Hit and not target2Hit and low <= target2Price
        float closeQty = sharesForUnit(strategy.equity, N_entry)
        strategy.close("S", qty=closeQty, comment="T2")
        target2Hit := true

    if target2Hit and not target3Hit and low <= target3Price
        float closeQty = sharesForUnit(strategy.equity, N_entry)
        strategy.close("S", qty=closeQty, comment="T3")
        target3Hit := true

    if target3Hit and not target4Hit and low <= target4Price
        float closeQty = sharesForUnit(strategy.equity, N_entry)
        strategy.close("S", qty=closeQty, comment="T4")
        target4Hit := true

    if target4Hit and not target5Hit and low <= target5Price
        float closeQty = sharesForUnit(strategy.equity, N_entry)
        strategy.close("S", qty=closeQty, comment="T5")
        target5Hit := true

//================ Exits (Chandelier trail for remainder)
var float stopL = na
var float stopS = na

if inRange and inLong
    initStopL = entryPrice - stopN * N_entry
    chandelierL = trailHighest - trailN * N_entry
    stopL     := math.round_to_mintick(math.max(initStopL, chandelierL))
    strategy.exit("L-EXIT", from_entry="L", stop=stopL)
else
    stopL := na

if inRange and inShort
    initStopS = entryPrice + stopN * N_entry
    chandelierS = trailLowest + trailN * N_entry
    stopS     := math.round_to_mintick(math.min(initStopS, chandelierS))
    strategy.exit("S-EXIT", from_entry="S", stop=stopS)
else
    stopS := na

//================ Plots
float dHiPlot = plotDon ? donHi : na
float dLoPlot = plotDon ? donLo : na
plot(dHiPlot, "Donchian High", color=color.new(color.blue, 40))
plot(dLoPlot, "Donchian Low",  color=color.new(color.blue, 40))

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

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

// Info table
var table infoTable = table.new(position.top_right, 2, 8, border_width=1)
if barstate.islast and showSignals
    table.cell(infoTable, 0, 0, "Strategy:", text_color=color.white, bgcolor=color.gray)
    table.cell(infoTable, 1, 0, "Multi-Stage Scaling", text_color=color.white, bgcolor=color.purple)

    table.cell(infoTable, 0, 1, "Targets:", text_color=color.white, bgcolor=color.gray)
    table.cell(infoTable, 1, 1, "5 levels (1.5-10N)", text_color=color.white, bgcolor=color.gray)

    table.cell(infoTable, 0, 2, "T1 (" + str.tostring(target1N) + "N):", text_color=color.white, bgcolor=color.gray)
    t1Color = target1Hit ? color.green : color.gray
    table.cell(infoTable, 1, 2, target1Hit ? "✓" : "Pending", text_color=color.white, bgcolor=t1Color)

    table.cell(infoTable, 0, 3, "T2 (" + str.tostring(target2N) + "N):", text_color=color.white, bgcolor=color.gray)
    t2Color = target2Hit ? color.green : color.gray
    table.cell(infoTable, 1, 3, target2Hit ? "✓" : "Pending", text_color=color.white, bgcolor=t2Color)

    table.cell(infoTable, 0, 4, "T3 (" + str.tostring(target3N) + "N):", text_color=color.white, bgcolor=color.gray)
    t3Color = target3Hit ? color.green : color.gray
    table.cell(infoTable, 1, 4, target3Hit ? "✓" : "Pending", text_color=color.white, bgcolor=t3Color)

    table.cell(infoTable, 0, 5, "T4 (" + str.tostring(target4N) + "N):", text_color=color.white, bgcolor=color.gray)
    t4Color = target4Hit ? color.green : color.gray
    table.cell(infoTable, 1, 5, target4Hit ? "✓" : "Pending", text_color=color.white, bgcolor=t4Color)

    table.cell(infoTable, 0, 6, "T5 (" + str.tostring(target5N) + "N):", text_color=color.white, bgcolor=color.gray)
    t5Color = target5Hit ? color.green : color.gray
    table.cell(infoTable, 1, 6, target5Hit ? "✓" : "Pending", text_color=color.white, bgcolor=t5Color)

    table.cell(infoTable, 0, 7, "Units:", text_color=color.white, bgcolor=color.gray)
    table.cell(infoTable, 1, 7, str.tostring(units) + "/" + str.tostring(maxUnits), text_color=color.white, bgcolor=color.gray)

Overview

Seykota. It generates long and short entries when price breaks above or below Donchian channels of specified length. Each entry adds a unit sized to risk a fixed percentage of current equity using ATR-based stops. Profits are scaled out in stages at target distances of 1.5N, 3N, 5N, 7N and 10N. A Chandelier exit trail closes remaining positions. Optional market regime filter and volume minimum can be enabled. Plots buy/sell signals, stops and Donchian bands directly on the price chart. Settings control entry lookback, ATR length, stop and target multiples, maximum units, and pyramiding behavior. It draws exclusively on the price chart and supports both long and short sides.

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, Volatility & bands, Support & resistance

Markets

Stocks, Indices

Timeframes

H4 and above, M15-H1

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
Donchian ENTRY lookbackint55entryLen
N = ATR lengthint20nLen
Initial stop (in N)float2.0stopN
Chandelier trail lookbackint22trailLen
Chandelier trail (in N)float3.0trailN
Add every X * Nfloat0.5addStepN
Max units (for 6-stage scaling)int6maxUnits
Risk % per unit (smaller for more units)float0.75riskPct
Use multi-stage targets?booltrueuseTargets
Target 1 (in N) - Close unit 1float1.5target1N
Show all 26 settings
SettingTypeDefaultVariable
Target 2 (in N) - Close unit 2float3.0target2N
Target 3 (in N) - Close unit 3float5.0target3N
Target 4 (in N) - Close unit 4float7.0target4N
Target 5 (in N) - Close unit 5float10.0target5N
Use market regime filter?boolfalseuseMarket
Market symbol for regime (if used)symbolSPYmarketSym
Regime timeframe (if used)timeframeDmarketTF
Market MA length (if used)int200marketLen
Min 20-bar avg volume (chart TF)int0minVol
Plot signals & stops?booltrueshowSignals
Plot 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

Nasdaq Prop Firm Strategy

by TradersPost
218 stars

This strategy uses multiple VWAP anchors and a custom Lull indicator to generate buy and sell signals on the Nasdaq price chart. It plots the VWAP trend line and three VWAP anchors with customizable colors and mitigation methods. The Lull indicator produces si

Strategy v6 TrendSupport & resistance Repaints
Updated 3 months ago · None stated GitHub repository of Nasdaq Prop Firm Strategy
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]
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
8 stars

This strategy combines moving averages, ATR volatility bands and ADX trend strength on the price chart. It calculates ADX from price data and adjusts the ATR multiplier dynamically based on whether ADX is rising or falling. Long and short entries are controlle

Strategy v4 TrendMoving averages
Updated 4 years ago · None stated GitHub repository of MA+ATR+ADX+PP Strategy

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

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