Strategy · Pine Script v6 · On the chart

Seykota Alt 2: EMA Crossover

by trustdan· code credited to danieltuckerrust

This strategy enters long or short when a fast exponential moving average crosses a slow one, then sizes each unit from a percentage of equity and an ATR-based initial stop.

View on GitHub

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

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

19_PF-1.043_SPY_seykota_alt2_ema_crossover.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 2: Classic EMA Crossover
// THEORY: Weighted moving averages filter noise better than absolute high/low breakouts.
// Ed Seykota's original approach used EMA systems. A fast EMA crossing a slow EMA
// signals trend direction more smoothly than Donchian breakouts.
// Trade-off: Smoother signals, less noise, but delayed entries compared to breakouts.

//@version=6
strategy("Seykota Alt 2: EMA Crossover 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: EMA parameters instead of Donchian
fastLen     = input.int(50,     "Fast EMA length",                    minval=2)
slowLen     = input.int(200,    "Slow EMA length",                    minval=5)
trailLen    = input.int(22,     "Chandelier trail lookback",          minval=5)

nLen        = input.int(20,     "N = ATR length",                     minval=5)
stopN       = input.float(2.5,  "Initial stop (in N)",                minval=0.5, step=0.25)
trailN      = input.float(3.0,  "Chandelier trail (in N)",            minval=0.25, 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?")
plotMAs     = input.bool(true,  "Plot EMAs?")

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

// CHANGED: EMAs instead of Donchian
fast = ta.ema(close, fastLen)
slow = ta.ema(close, slowLen)

// 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 (crossover logic)
longCross  = allowLong  and liqOK and longRegOK  and ta.crossover(fast, slow)
shortCross = allowShort and liqOK and shortRegOK and ta.crossunder(fast, slow)

//================ 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 inRange and not inPos and longCross
    N_entry := N
    float sh = sharesForUnit(strategy.equity, N_entry)
    strategy.entry("L", strategy.long, qty=sh)
    units       := 1
    lastAddLong := close

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

//================ Chandelier trailing stops
trailL = ta.highest(high, trailLen) - trailN * N_entry
trailS = ta.lowest(low,  trailLen) + trailN * N_entry

//================ Add-ons (pyramid into strength)
// Add when price extends favorably by addStepN * N
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 (Chandelier trail + initial stop)
var float stopL = na
var float stopS = na

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

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

//================ Plots
plot(plotMAs ? fast : na, "Fast EMA", color=color.new(color.blue, 0), linewidth=2)
plot(plotMAs ? slow : na, "Slow EMA", color=color.new(color.red, 0), linewidth=2)

// Highlight crossover zones
bgcolor(longCross ? color.new(color.green, 90) : na, title="Long Cross")
bgcolor(shortCross ? color.new(color.red, 90) : na, title="Short Cross")

plotshape(showSignals and longCross,  title="Long Cross",  style=shape.triangleup,   location=location.belowbar, size=size.small, color=color.new(color.green, 0), text="EMA↑")
plotshape(showSignals and shortCross, title="Short Cross", style=shape.triangledown, location=location.abovebar, size=size.small, color=color.new(color.red,   0), text="EMA↓")

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)

Overview

Seykota Alt 2: EMA Crossover can add positions as price moves by a multiple of ATR, up to a set unit limit, and trails risk with a chandelier stop. Optional filters require a chosen market to sit above or below its moving average and a minimum average volume. It draws the averages, signals, and stops on the price chart and limits trading to a date range.

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, Moving averages, Volatility & bands

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
Fast EMA lengthint50fastLen
Slow EMA lengthint200slowLen
Chandelier trail lookbackint22trailLen
N = ATR lengthint20nLen
Initial stop (in N)float2.5stopN
Chandelier trail (in N)float3.0trailN
Add every X * Nfloat0.5addStepN
Max units (incl. initial)int4maxUnits
Risk % of equity PER UNITfloat1.0riskPct
Use market regime filter?boolfalseuseMarket
Show all 21 settings
SettingTypeDefaultVariable
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 EMAs?booltrueplotMAs
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

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 overlay strategy targets one-minute ES futures and plots volume-weighted moving-average bands from the open, scaled by a standard-deviation multiple, plus a slower band from ten-minute opens. A higher-timeframe exponential moving average can filter trades

Strategy v6 Moving averagesVolatility & bands
Updated 6 weeks ago · None stated GitHub repository of ES - Futures 1M No Repaint

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

Bollinger Bands Strategy

by cklose2000
105 stars

This strategy generates buy and sell signals based on Bollinger Band crossovers combined with a simple moving average trend filter. It enters a long position when price crosses above the lower band while trading above the SMA filter line, and enters a short po

Strategy v5 Volatility & bandsMoving averages
Updated 1 year ago · None stated GitHub repository of Bollinger Bands Strategy
104 stars

This overlay strategy combines a Chandelier Exit with a zero-lag least squares moving average. Although the header mentions Heikin Ashi candles, the calculations use ordinary closes. An ATR trailing stop sets long and short levels, and direction flips when pri

Strategy v5 TrendMoving averages
Updated 3 years ago · MIT GitHub repository of Chandelier Exit & ZLSMA 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