Strategy · Pine Script v6 · On the chart

Seykota Alt 3: Anti-Chop Filter

by trustdan· code credited to danieltuckerrust

This strategy trades Donchian breakouts on the price chart and tries to avoid choppy conditions.

View on GitHub

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

220 lines of Pine Script v6 from archive/old-iterations/Claude/seykota_alt3_anti_chop.pine, published under MPL-2.0 (file header). Keep the author's credit and licence lines when you reuse it.

seykota_alt3_anti_chop.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 3: Mean Reversion Protection System
// THEORY: Trend following systems suffer in choppy, ranging markets. Use ADX, efficiency ratio,
// and directional movement to only trade when a genuine trend exists. Seykota: "The elements of 
// good trading are: (1) cutting losses, (2) cutting losses, and (3) cutting losses. If you can 
// follow these three rules, you may have a chance." - This version focuses on avoiding bad trades.

//@version=6
strategy("Seykota Alt 3: Anti-Chop Filter v1.0",
     overlay=true,
     initial_capital=100000,
     commission_type=strategy.commission.percent, commission_value=0.005,
     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)
exitLen     = input.int(10,     "Donchian EXIT lookback",     minval=5)

// Trend strength filters
useAdx      = input.bool(true,  "Use ADX filter?")
adxLen      = input.int(14,     "ADX length",                 minval=5)
adxThresh   = input.float(25,   "Min ADX threshold",          minval=10, maxval=50, step=5)

useER       = input.bool(true,  "Use Efficiency Ratio filter?")
erLen       = input.int(20,     "ER length",                  minval=5)
erThresh    = input.float(0.3,  "Min ER threshold",           minval=0, maxval=1, step=0.05)

useTrendStr = input.bool(true,  "Use Trend Strength filter?")
trendLen    = input.int(20,     "Trend strength length",      minval=5)
trendThresh = input.float(60,   "Min trend strength %",       minval=0, maxval=100, step=5)

nLen        = input.int(20,     "N = ATR length",             minval=5)
stopN       = input.float(2.0,  "Initial stop (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(4,      "Max units",                  minval=1, maxval=10)
riskPct     = input.float(1.0,  "Risk % per unit",            minval=0.1, maxval=5, step=0.1)

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")
toDate   = input.time(defval=timestamp("2099-12-31T23:59:59"), title="Backtest TO")

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

//================ Core calcs
N        = ta.atr(nLen)
volMA    = ta.sma(volume, 20)
liqOK    = volMA >= minVol

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

exitHiPrev = ta.highest(high, exitLen)[1]
exitLoPrev = ta.lowest(low,  exitLen)[1]

// Market regime
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)

//================ ADX Calculation (Directional Movement Index)
[diPlus, diMinus, adx] = ta.dmi(adxLen, adxLen)
adxOK = not useAdx or (adx > adxThresh)

//================ Efficiency Ratio (Kaufman)
// ER = net movement / total movement
priceChange = math.abs(close - close[erLen])
volatility = 0.0
for i = 0 to erLen - 1
    volatility := volatility + math.abs(close[i] - close[i + 1])

efficiencyRatio = volatility > 0 ? priceChange / volatility : 0
erOK = not useER or (efficiencyRatio > erThresh)

//================ Trend Strength (% of bars closing higher/lower)
upBars = 0
for i = 1 to trendLen
    if close[i] > close[i + 1]
        upBars := upBars + 1

trendStrength = (upBars / trendLen) * 100
trendingUp = trendStrength > (50 + trendThresh/2)
trendingDown = trendStrength < (50 - trendThresh/2)
trendStrOK = not useTrendStr or trendingUp or trendingDown

// Combined trend quality filter
trendQualityOK = adxOK and erOK and trendStrOK

//================ Signals
longBreak  = allowLong  and liqOK and longRegOK  and trendQualityOK and (close > donHiPrev)
shortBreak = allowShort and liqOK and shortRegOK and trendQualityOK and (close < donLoPrev)

//================ 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 longBreak
    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 shortBreak
    N_entry := N
    float sh = sharesForUnit(strategy.equity, N_entry)
    strategy.entry("S", strategy.short, qty=sh)
    units        := 1
    lastAddShort := close

//================ Add-ons (only in trending conditions)
canAddLong  = inRange and inLong  and units < maxUnits and trendQualityOK and close >= nz(lastAddLong)  + addStepN * N_entry
canAddShort = inRange and inShort and units < maxUnits and trendQualityOK and close <= 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
var float stopL = na
var float stopS = na

if inRange and inLong
    initStopL = strategy.position_avg_price - stopN * N_entry
    stopL     := math.max(initStopL, exitLoPrev)
    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.min(initStopS, exitHiPrev)
    strategy.exit("S-EXIT", from_entry="S", stop=stopS)
else
    stopS := na

//================ Plots
// Background color for trend quality
trendBgColor = trendQualityOK ? color.new(color.green, 95) : color.new(color.red, 95)
bgcolor(trendBgColor, title="Trend Quality")

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.green)
plotshape(showSignals and shortBreak, title="Short", style=shape.triangledown, location=location.abovebar, size=size.tiny, color=color.red)

plot(showSignals and inLong  ? stopL : na, "Long Stop",  color=color.red, style=plot.style_linebr)
plot(showSignals and inShort ? stopS : na, "Short Stop", color=color.red, style=plot.style_linebr)

// Trend quality indicators panel
var table infoTable = table.new(position.top_right, 2, 5, border_width=1)
if barstate.islast and showSignals
    table.cell(infoTable, 0, 0, "Trend Quality:", text_color=color.white, bgcolor=color.gray)
    table.cell(infoTable, 1, 0, trendQualityOK ? "GOOD" : "POOR", text_color=color.white, bgcolor=trendQualityOK ? color.green : color.red)
    
    table.cell(infoTable, 0, 1, "ADX:", text_color=color.white, bgcolor=color.gray)
    adxColor = adxOK ? color.green : color.red
    table.cell(infoTable, 1, 1, str.tostring(adx, "#.#"), text_color=color.white, bgcolor=adxColor)
    
    table.cell(infoTable, 0, 2, "Efficiency:", text_color=color.white, bgcolor=color.gray)
    erColor = erOK ? color.green : color.red
    table.cell(infoTable, 1, 2, str.tostring(efficiencyRatio, "#.##"), text_color=color.white, bgcolor=erColor)
    
    table.cell(infoTable, 0, 3, "Trend %:", text_color=color.white, bgcolor=color.gray)
    trendColor = trendStrOK ? color.green : color.red
    table.cell(infoTable, 1, 3, str.tostring(trendStrength, "#.#") + "%", text_color=color.white, bgcolor=trendColor)
    
    table.cell(infoTable, 0, 4, "Units:", text_color=color.white, bgcolor=color.gray)
    table.cell(infoTable, 1, 4, str.tostring(units), text_color=color.white, bgcolor=color.gray)

Overview

Seykota Alt 3: Anti-Chop Filter can enter long or short when price breaks the entry channel and optional ADX, efficiency-ratio, and trend-strength filters pass. It exits on the shorter Donchian channel, places an initial ATR stop, and may add units as price advances by a fraction of ATR, sizing each unit by a risk percentage. Settings change lookbacks, filter thresholds, maximum units, an optional market moving-average regime, minimum volume, and the backtest 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, Breakout, Volatility & bands, Oscillators & momentum

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
Donchian ENTRY lookbackint55entryLen
Donchian EXIT lookbackint10exitLen
Use ADX filter?booltrueuseAdx
ADX lengthint14adxLen
Min ADX thresholdfloat25adxThresh
Use Efficiency Ratio filter?booltrueuseER
ER lengthint20erLen
Min ER thresholdfloat0.3erThresh
Use Trend Strength filter?booltrueuseTrendStr
Trend strength lengthint20trendLen
Show all 28 settings
SettingTypeDefaultVariable
Min trend strength %float60trendThresh
N = ATR lengthint20nLen
Initial stop (in N)float2.0stopN
Add every X * Nfloat0.5addStepN
Max unitsint4maxUnits
Risk % per unitfloat1.0riskPct
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