Strategy · Pine Script v6 · On the chart

Seykota Alt 32: Momentum + Time

by trustdan· code credited to danieltuckerrust

This strategy enters long or short on Donchian channel breakouts and can add units when price moves in the trade direction and RSI confirms momentum.

View on GitHub

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

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

11_PF-1.275_SPY_seykota_alt32_momentum_time.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 32: Momentum-Gated + Time-Based Tightening
// THEORY: Combine Alt 30 (momentum-gated adds) + Alt 25 (time-based tightening)
// - Only add when RSI confirms strength (Alt 30: +23.6%)
// - Tighten stop from 3N to 1.5N after 30 bars (Alt 25: +23.5%)
// INSIGHT: Quality adds + protecting mature positions should compound benefits.
// Trade-off: Fewer adds (RSI filter) but better protection on old positions.
//
// BACKTEST RESULTS (SPY 2022-2025): +24.41% | Profit Factor: 1.275 | Win Rate: 49.29% | Max DD: 16.05%

//@version=6
strategy("Seykota Alt 32: Momentum + Time 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)
rsiLen      = input.int(14,     "RSI length",                         minval=2)
rsiLongAdd  = input.float(60.0, "RSI threshold for LONG adds",        minval=50, maxval=80, step=1)
rsiShortAdd = input.float(40.0, "RSI threshold for SHORT adds",       minval=20, maxval=50, step=1)
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,  "Initial trail distance (in N)",      minval=0.5, step=0.25)
tightTrailN = input.float(1.5,  "TIGHT trail after X days (in N)",    minval=0.25, step=0.25)
tightenAfter= input.int(30,     "Tighten stop after X bars",          minval=5)
addStepN    = input.float(0.5,  "Add every X * N",                    minval=0.25, step=0.25)
maxUnits    = input.int(4,      "Max units",                          minval=1, maxval=10)
riskPct     = input.float(1.0,  "Risk % per unit",                    minval=0.1, maxval=5, step=0.1)

useTargets   = input.bool(true,  "Use profit targets?")
target1N     = input.float(3.0,  "Target 1 (in N)",                   minval=1, step=0.5)
target2N     = input.float(6.0,  "Target 2 (in N)",                   minval=1, step=0.5)
target3N     = input.float(9.0,  "Target 3 (in N)",                   minval=1, step=0.5)

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

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

fromDate = input.time(defval=timestamp("2022-01-01T00:00:00"), title="Backtest FROM", confirm=true)
toDate   = input.time(defval=timestamp("2099-12-31T23:59:59"), title="Backtest TO", 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

// RSI for momentum gating
rsi = ta.rsi(close, rsiLen)
longMomentum = rsi >= rsiLongAdd
shortMomentum = rsi <= rsiShortAdd

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

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

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 int   barsInPos     = 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 inPos
    barsInPos += 1
else
    barsInPos    := 0
    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 (MOMENTUM-GATED)
canAddLong  = inRange and inLong  and units < maxUnits and high >= nz(lastAddLong)  + addStepN * N_entry and longMomentum
canAddShort = inRange and inShort and units < maxUnits and low  <= nz(lastAddShort) - addStepN * N_entry and shortMomentum

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

//================ Exits with TIME-BASED TIGHTENING
var float stopL = na
var float stopS = na

if inRange and inLong
    initStopL = entryPrice - stopN * N_entry

    // TIME-BASED TIGHTENING
    effectiveTrailN = barsInPos >= tightenAfter ? tightTrailN : trailN
    chandelierL = trailHighest - effectiveTrailN * 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

    effectiveTrailN = barsInPos >= tightenAfter ? tightTrailN : trailN
    chandelierS = trailLowest + effectiveTrailN * 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",  style=shape.triangleup,   location=location.belowbar, size=size.tiny, color=color.new(color.green, 0), text="Long")
plotshape(showSignals and shortBreak, title="Short", style=shape.triangledown, location=location.abovebar, size=size.tiny, color=color.new(color.red, 0), text="Short")

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

var table infoTable = table.new(position.top_right, 2, 5, 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, "Mom + Time", text_color=color.white, bgcolor=color.purple)

    table.cell(infoTable, 0, 1, "RSI:", text_color=color.white, bgcolor=color.gray)
    table.cell(infoTable, 1, 1, str.tostring(math.round(rsi, 1)), text_color=color.white, bgcolor=color.gray)

    table.cell(infoTable, 0, 2, "Bars in Pos:", text_color=color.white, bgcolor=color.gray)
    table.cell(infoTable, 1, 2, str.tostring(barsInPos), text_color=color.white, bgcolor=color.gray)

    table.cell(infoTable, 0, 3, "Stop Tight?", text_color=color.white, bgcolor=color.gray)
    tightStatus = barsInPos >= tightenAfter ? "YES" : "No"
    tightColor = barsInPos >= tightenAfter ? color.orange : color.gray
    table.cell(infoTable, 1, 3, tightStatus, text_color=color.white, bgcolor=tightColor)

    table.cell(infoTable, 0, 4, "Combo:", text_color=color.white, bgcolor=color.gray)
    table.cell(infoTable, 1, 4, "Alt30 + Alt25", text_color=color.white, bgcolor=color.orange)

Overview

Seykota Alt 32: Momentum + Time sizes each unit from a risk percent of equity and exits with an ATR initial stop, a chandelier trail that tightens after a set number of bars, and optional staged profit targets. Settings control lookbacks, add spacing, maximum units, and an optional higher-timeframe moving-average regime filter. It draws signals, stops, and Donchian bands on the 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, Oscillators & momentum, Volatility & bands, Breakout

Markets

Stocks, Indices

Timeframes

Any timeframe

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
RSI lengthint14rsiLen
RSI threshold for LONG addsfloat60.0rsiLongAdd
RSI threshold for SHORT addsfloat40.0rsiShortAdd
N = ATR lengthint20nLen
Initial stop (in N)float2.0stopN
Chandelier trail lookbackint22trailLen
Initial trail distance (in N)float3.0trailN
TIGHT trail after X days (in N)float1.5tightTrailN
Tighten stop after X barsint30tightenAfter
Show all 29 settings
SettingTypeDefaultVariable
Add every X * Nfloat0.5addStepN
Max unitsint4maxUnits
Risk % per unitfloat1.0riskPct
Use profit targets?booltrueuseTargets
Target 1 (in N)float3.0target1N
Target 2 (in N)float6.0target2N
Target 3 (in N)float9.0target3N
Use market regime filter?boolfalseuseMarket
Market symbolsymbolSPYmarketSym
Regime timeframetimeframeDmarketTF
Market MA lengthint200marketLen
Min 20-bar avg volumeint0minVol
Plot signals & stops?booltrueshowSignals
Plot Donchian bands?booltrueplotDon
Backtest FROMtimetimestamp("2022-01-01T00:00:00")fromDate
Backtest TOtimetimestamp("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
106 stars

This trading strategy combines three Exponential Moving Averages (8, 14, and 50 periods by default) with Stochastic RSI and Average True Range (ATR). It enters a long position when EMA 1 is above EMA 2, EMA 2 is above EMA 3, and the Stochastic RSI %K line cros

Strategy v4 TrendOscillators & momentum
Updated 2 years ago · GPL-3.0 GitHub repository of 3 x EMA + Stochastic RSI + ATR

均线突破交易系统

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

Momentum Rider DAILY FINAL

by greenpeas007
58 stars

This strategy combines exponential moving averages (EMA 9, 21, 50), RSI, MACD, and Supertrend indicators to enter long positions. It triggers trades using six dynamic setups based on momentum breakouts, EMA crossovers, and pullbacks. Position sizing is compute

Strategy v6 TrendOscillators & momentum Repaints
Updated 4 months ago · Custom licence GitHub repository of Momentum Rider DAILY FINAL
57 stars

This strategy identifies trend reversals through market structure changes (CHoCH) filtered by MACD momentum. It initiates long positions on bullish structure breaks when MACD is positive and above its signal line, and short positions on bearish breaks when MAC

Strategy v6 SMC / ICT / price actionOscillators & momentum Repaints
Updated 1 year ago · Apache-2.0 GitHub repository of Market Structure MACD 4H + Trailing

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