Strategy · Pine Script v6 · On the chart

Seykota Alt 22: Parabolic SAR

by trustdan· code credited to danieltuckerrust

Seykota Alt 22 is a trend-following strategy combining 55-bar Donchian channel breakouts for entries with a Parabolic SAR trailing stop for exits.

View on GitHub

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

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

28_PF-0.805_SPY_seykota_alt22_parabolic_sar.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 22: Parabolic SAR Hybrid
// THEORY: Use Donchian breakouts for entries but Parabolic SAR for exits.
// The Parabolic SAR is specifically designed as a trailing stop that accelerates
// as the trend extends, locking in more profit over time. Combined with profit targets.
// INSIGHT FROM BACKTESTS: Alt 7 (Chandelier trail) lost money, but combined with
// profit targets from Alt 10, this could work better. SAR accelerates better than Chandelier.
// Trade-off: SAR can reverse quickly on consolidation, but that's OK with profit targets.

//@version=6
strategy("Seykota Alt 22: Parabolic SAR 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)
sarStart    = input.float(0.02, "SAR start acceleration",             minval=0.001, maxval=0.2, step=0.001)
sarIncrement= input.float(0.02, "SAR acceleration increment",         minval=0.001, maxval=0.2, step=0.001)
sarMax      = input.float(0.2,  "SAR max acceleration",               minval=0.01, maxval=1.0, step=0.01)
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)

// Profit targets
useTargets   = input.bool(true,  "Use profit targets?")
target1N     = input.float(3.0,  "Target 1 (in N) - Close 1 unit",    minval=1, step=0.5)
target2N     = input.float(6.0,  "Target 2 (in N) - Close 1 unit",    minval=1, step=0.5)
target3N     = input.float(9.0,  "Target 3 (in N) - Close 1 unit",    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 (for entry only)
donHi    = ta.highest(high, entryLen)
donLo    = ta.lowest(low,  entryLen)
donHiPrev= donHi[1]
donLoPrev= donLo[1]

// Parabolic SAR (for trailing stop)
sar = ta.sar(sarStart, sarIncrement, sarMax)

// 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

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

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

//================ PROFIT TARGETS (scale out partial positions)
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

    if not target1Hit and high >= target1Price
        float closeQty = sharesForUnit(strategy.equity, N_entry)
        strategy.close("L", qty=closeQty, comment="Target 1 (+" + str.tostring(target1N) + "N)")
        target1Hit := true

    if target1Hit and not target2Hit and high >= target2Price
        float closeQty = sharesForUnit(strategy.equity, N_entry)
        strategy.close("L", qty=closeQty, comment="Target 2 (+" + str.tostring(target2N) + "N)")
        target2Hit := true

    if target2Hit and not target3Hit and high >= target3Price
        float closeQty = sharesForUnit(strategy.equity, N_entry)
        strategy.close("L", qty=closeQty, comment="Target 3 (+" + str.tostring(target3N) + "N)")
        target3Hit := 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

    if not target1Hit and low <= target1Price
        float closeQty = sharesForUnit(strategy.equity, N_entry)
        strategy.close("S", qty=closeQty, comment="Target 1 (+" + str.tostring(target1N) + "N)")
        target1Hit := true

    if target1Hit and not target2Hit and low <= target2Price
        float closeQty = sharesForUnit(strategy.equity, N_entry)
        strategy.close("S", qty=closeQty, comment="Target 2 (+" + str.tostring(target2N) + "N)")
        target2Hit := true

    if target2Hit and not target3Hit and low <= target3Price
        float closeQty = sharesForUnit(strategy.equity, N_entry)
        strategy.close("S", qty=closeQty, comment="Target 3 (+" + str.tostring(target3N) + "N)")
        target3Hit := true

//================ Exits using PARABOLIC SAR
var float stopL = na
var float stopS = na

if inRange and inLong
    initStopL = entryPrice - stopN * N_entry
    // Use SAR for trailing, but don't let it be worse than initial stop
    stopL := math.round_to_mintick(math.max(initStopL, sar))
    strategy.exit("L-EXIT", from_entry="L", stop=stopL)
else
    stopL := na

if inRange and inShort
    initStopS = entryPrice + stopN * N_entry
    // Use SAR for trailing, but don't let it be worse than initial stop
    stopS := math.round_to_mintick(math.min(initStopS, sar))
    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))

// Plot SAR
plot(showSignals ? sar : na, "Parabolic SAR", style=plot.style_cross, linewidth=2, color=color.new(color.orange, 0))

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, "SAR Stop",  color=color.new(color.red, 0), style=plot.style_linebr, linewidth=2)
plot(showSignals and inShort ? stopS : na, "SAR Stop", color=color.new(color.red, 0), style=plot.style_linebr, linewidth=2)

// Info table
var table infoTable = table.new(position.top_right, 2, 6, border_width=1)
if barstate.islast and showSignals
    table.cell(infoTable, 0, 0, "Exit Type:", text_color=color.white, bgcolor=color.gray)
    table.cell(infoTable, 1, 0, "Parabolic SAR", text_color=color.white, bgcolor=color.orange)

    table.cell(infoTable, 0, 1, "SAR Accel:", text_color=color.white, bgcolor=color.gray)
    table.cell(infoTable, 1, 1, str.tostring(sarStart) + " to " + str.tostring(sarMax), text_color=color.white, bgcolor=color.gray)

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

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

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

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

Overview

Position sizing and initial stop-loss levels are determined using Average True Range (ATR). The strategy supports pyramiding into winning positions at fixed ATR increments up to a defined unit limit, along with optional multi-step profit targets. A market regime filter can restrict trades based on a higher-timeframe moving average. All channels and stop levels are plotted on the main price chart.

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, Moving averages

Markets

Stocks, Indices

Timeframes

M15-H1, 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
Donchian ENTRY lookbackint55entryLen
N = ATR lengthint20nLen
Initial stop (in N)float2.0stopN
SAR start accelerationfloat0.02sarStart
SAR acceleration incrementfloat0.02sarIncrement
SAR max accelerationfloat0.2sarMax
Add every X * Nfloat0.5addStepN
Max units (incl. initial)int4maxUnits
Risk % of equity PER UNITfloat1.0riskPct
Use profit targets?booltrueuseTargets
Show all 25 settings
SettingTypeDefaultVariable
Target 1 (in N) - Close 1 unitfloat3.0target1N
Target 2 (in N) - Close 1 unitfloat6.0target2N
Target 3 (in N) - Close 1 unitfloat9.0target3N
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

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

This mean-reversion strategy plots Bollinger Bands and a long-term moving average directly on the price chart. It enters trades when price candles penetrate the outer Bollinger Bands beyond a user-defined body percentage, anticipating a price reversal. Entries

Strategy v5 Mean reversionVolatility & bands
Updated 2 months ago · None stated GitHub repository of Bollinger Bands Winner PRO [Alorse]
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

STRG-BBForce

by harryguiacorn
219 stars

STRG-BBForce is a Bollinger Bands trend-following strategy. It calculates standard Bollinger Bands and tracks directional alignment across the upper, lower, and basis lines. When all three lines slope upward, it opens a long position and closes short positions

Strategy v5 TrendVolatility & bands
Updated 1 year ago · None stated GitHub repository of STRG-BBForce

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