Strategy · Pine Script v6 · On the chart

Seykota Alt 20: Asymmetric Long/Short

by trustdan· code credited to danieltuckerrust

This strategy executes trend-following breakout trades using asymmetric parameters for long and short directions.

View on GitHub

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

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

31_PF-0.729_SPY_seykota_alt20_asymmetric_long_short.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 20: Asymmetric Long/Short
// THEORY: Long and short trends behave differently; optimize parameters separately.
// The baseline uses identical parameters for both directions (55-bar entry, 2N stop, 0.5N adds).
// But market reality is asymmetric: long trends tend to be slower and steadier (bull markets climb
// a "wall of worry"), while short trends are faster and more volatile (bear markets fall quickly).
// This alternative uses different parameters for each direction to match their behavior patterns.
// Trade-off: Better match directional asymmetry, but introduces more parameters to optimize.

//@version=6
strategy("Seykota Alt 20: Asymmetric L/S 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: Separate parameters for LONG positions
longEntryLen  = input.int(55,    "LONG: Donchian ENTRY lookback",     minval=10)
longExitLen   = input.int(10,    "LONG: Donchian EXIT lookback",      minval=5)
longStopN     = input.float(2.0, "LONG: Initial stop (in N)",         minval=0.5, step=0.25)
longAddStepN  = input.float(0.5, "LONG: Add every X * N",             minval=0.25, step=0.125)
longMaxUnits  = input.int(4,     "LONG: Max units",                   minval=1, maxval=10)

// CHANGED: Separate parameters for SHORT positions
shortEntryLen = input.int(35,    "SHORT: Donchian ENTRY lookback",    minval=10)
shortExitLen  = input.int(10,    "SHORT: Donchian EXIT lookback",     minval=5)
shortStopN    = input.float(2.5, "SHORT: Initial stop (in N)",        minval=0.5, step=0.25)
shortAddStepN = input.float(0.75,"SHORT: Add every X * N",            minval=0.25, step=0.125)
shortMaxUnits = input.int(4,     "SHORT: Max units",                  minval=1, maxval=10)

// Common parameters
nLen        = input.int(20,     "N = ATR length (both)",              minval=5)
riskPct     = input.float(1.0,  "Risk % per unit (both)",             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)

timeExitMode= input.string("None","Time exit", options=["None","Close","Roll"])
timeExitBars= input.int(60,     "Time exit bars (if used)",           minval=5)

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, _stopN) =>
    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

// CHANGED: Separate Donchian levels for long and short
donHiLong    = ta.highest(high, longEntryLen)
donLoShort   = ta.lowest(low,  shortEntryLen)
donHiLongPrev  = donHiLong[1]
donLoShortPrev = donLoShort[1]

exitHiPrevLong  = ta.highest(high, longExitLen)[1]
exitLoPrevShort = ta.lowest(low,  shortExitLen)[1]

// 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 (asymmetric lookbacks)
longBreak  = allowLong  and liqOK and longRegOK  and (close > donHiLongPrev)
shortBreak = allowShort and liqOK and shortRegOK and (close < donLoShortPrev)

//================ Position state
var float N_entry       = na
var float lastAddLong   = na
var float lastAddShort  = na
var int   units         = 0
var int   barsInPos     = 0
var bool  wantReenterL  = false
var bool  wantReenterS  = 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
    wantReenterL := false
    wantReenterS := false

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

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

//================ Add-ons (asymmetric step sizes and max units)
canAddLong  = inRange and inLong  and units < longMaxUnits  and close >= nz(lastAddLong)  + longAddStepN  * N_entry
canAddShort = inRange and inShort and units < shortMaxUnits and close <= nz(lastAddShort) - shortAddStepN * N_entry

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

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

//================ Exits (asymmetric stops)
var float stopL = na
var float stopS = na

if inRange and inLong
    initStopL = strategy.position_avg_price - longStopN * N_entry
    stopL     := math.max(initStopL, exitHiPrevLong)
    strategy.exit("L-EXIT", from_entry="L", stop=stopL)
else
    stopL := na

if inRange and inShort
    initStopS = strategy.position_avg_price + shortStopN * N_entry
    stopS     := math.min(initStopS, exitLoPrevShort)
    strategy.exit("S-EXIT", from_entry="S", stop=stopS)
else
    stopS := na

//================ Optional time exit
timeExitTrig = inRange and inPos and (timeExitMode != "None") and (barsInPos >= timeExitBars)

if timeExitTrig
    if inLong
        if timeExitMode == "Close"
            strategy.close("L", comment="Time Exit")
        else if timeExitMode == "Roll"
            wantReenterL := true
            strategy.close("L", comment="Time Exit (Roll)")
    if inShort
        if timeExitMode == "Close"
            strategy.close("S", comment="Time Exit")
        else if timeExitMode == "Roll"
            wantReenterS := true
            strategy.close("S", comment="Time Exit (Roll)")

// Re-enter after Roll
if inRange and not inPos and wantReenterL and longRegOK and (close > donHiLongPrev)
    N_entry := N
    float sh = sharesForUnit(strategy.equity, N_entry, longStopN)
    strategy.entry("L", strategy.long, qty=sh)
    units       := 1
    lastAddLong := close
    wantReenterL := false

if inRange and not inPos and wantReenterS and shortRegOK and (close < donLoShortPrev)
    N_entry := N
    float sh = sharesForUnit(strategy.equity, N_entry, shortStopN)
    strategy.entry("S", strategy.short, qty=sh)
    units        := 1
    lastAddShort := close
    wantReenterS := false

//================ Plots
// Plot both long and short Donchian levels
plot(plotDon ? donHiLongPrev : na, "Long Entry Level", color=color.new(color.green, 40), linewidth=2)
plot(plotDon ? donLoShortPrev : na, "Short Entry Level", color=color.new(color.red, 40), linewidth=2)

// Background shading for which side is in position
positionBg = inLong ? color.new(color.green, 97) : (inShort ? color.new(color.red, 97) : na)
bgcolor(positionBg, title="Position Direction")

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

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)

// Comparison table showing asymmetric parameters
var table paramTable = table.new(position.top_right, 3, 6, border_width=1)
if barstate.islast and showSignals
    // Header
    table.cell(paramTable, 0, 0, "Parameter", text_color=color.white, bgcolor=color.gray)
    table.cell(paramTable, 1, 0, "LONG", text_color=color.white, bgcolor=color.green)
    table.cell(paramTable, 2, 0, "SHORT", text_color=color.white, bgcolor=color.red)

    // Entry lookback
    table.cell(paramTable, 0, 1, "Entry:", text_color=color.white, bgcolor=color.gray)
    table.cell(paramTable, 1, 1, str.tostring(longEntryLen) + " bars", text_color=color.white, bgcolor=color.green)
    table.cell(paramTable, 2, 1, str.tostring(shortEntryLen) + " bars", text_color=color.white, bgcolor=color.red)

    // Stop N
    table.cell(paramTable, 0, 2, "Stop:", text_color=color.white, bgcolor=color.gray)
    table.cell(paramTable, 1, 2, str.tostring(longStopN) + "N", text_color=color.white, bgcolor=color.green)
    table.cell(paramTable, 2, 2, str.tostring(shortStopN) + "N", text_color=color.white, bgcolor=color.red)

    // Add step
    table.cell(paramTable, 0, 3, "Add Step:", text_color=color.white, bgcolor=color.gray)
    table.cell(paramTable, 1, 3, str.tostring(longAddStepN) + "N", text_color=color.white, bgcolor=color.green)
    table.cell(paramTable, 2, 3, str.tostring(shortAddStepN) + "N", text_color=color.white, bgcolor=color.red)

    // Max units
    table.cell(paramTable, 0, 4, "Max Units:", text_color=color.white, bgcolor=color.gray)
    table.cell(paramTable, 1, 4, str.tostring(longMaxUnits), text_color=color.white, bgcolor=color.green)
    table.cell(paramTable, 2, 4, str.tostring(shortMaxUnits), text_color=color.white, bgcolor=color.red)

    // Current units
    table.cell(paramTable, 0, 5, "Current:", text_color=color.white, bgcolor=color.gray)
    currentColor = inLong ? color.green : (inShort ? color.red : color.gray)
    currentText = inPos ? str.tostring(units) + " units" : "Flat"
    table.cell(paramTable, 1, 5, currentText, text_color=color.white, bgcolor=currentColor)
    table.cell(paramTable, 2, 5, "", text_color=color.white, bgcolor=currentColor)

// Rationale label
var label rationaleLabel = na
if barstate.islast and showSignals
    rationaleText = "Asymmetric Parameters\n\n" + "LONG: Slower entry (" + str.tostring(longEntryLen) + "), tighter stop (" + str.tostring(longStopN) + "N)\n" + "Bull markets climb slow & steady\n\n" + "SHORT: Faster entry (" + str.tostring(shortEntryLen) + "), wider stop (" + str.tostring(shortStopN) + "N)\n" + "Bear markets fall fast & choppy"
    label.delete(rationaleLabel)
    rationaleLabel := label.new(bar_index - 70, high, rationaleText, style=label.style_label_down, color=color.new(color.purple, 80), textcolor=color.white, size=size.small)

Overview

Seykota Alt 20: Asymmetric Long/Short calculates Donchian channels and ATR (N) to adapt to directional market speeds. Long positions utilize a longer entry lookback and tighter ATR trailing stops, while shorts use shorter lookbacks and wider stops. Signals enter on channel breakouts with ATR-based position sizing and multi-unit pyramiding steps up to a set maximum. Exits trigger on opposite Donchian channel boundaries, ATR stops, or optional time-based exits. Everything plots directly on the main 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

Markets

Any symbol

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
LONG: Donchian ENTRY lookbackint55longEntryLen
LONG: Donchian EXIT lookbackint10longExitLen
LONG: Initial stop (in N)float2.0longStopN
LONG: Add every X * Nfloat0.5longAddStepN
LONG: Max unitsint4longMaxUnits
SHORT: Donchian ENTRY lookbackint35shortEntryLen
SHORT: Donchian EXIT lookbackint10shortExitLen
SHORT: Initial stop (in N)float2.5shortStopN
SHORT: Add every X * Nfloat0.75shortAddStepN
SHORT: Max unitsint4shortMaxUnits
Show all 26 settings
SettingTypeDefaultVariable
N = ATR length (both)int20nLen
Risk % per unit (both)float1.0riskPct
Use market regime filter?boolfalseuseMarket
Market symbol for regime (if used)symbolSPYmarketSym
Regime timeframe (if used)timeframeDmarketTF
Market MA length (if used)int200marketLen
Time exitstringNonetimeExitMode
Time exit bars (if used)int60timeExitBars
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
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 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