Indicator · Pine Script v6 · On the chart

Median Cascade Trend

by vedkanani123· code credited to BackQuant

A price-chart indicator by BackQuant that smooths a chosen source through up to three causal median filters, then a two-pole Super Smoother, to draw a trend line coloured by direction.

View on GitHub

GitHub stars1on the repository
Pine versionv6current
Lines of code125
Settings26inputs
LicenceNone statedfile: MPL-2.0
Last update2 months ago23 Aug 2026

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 indicator, select all of the template text and paste. Press Save and give it a name.
  4. 4Add it to the chartPress Add to chart, then adjust the settings with the gear icon next to its name.

Source Code

125 lines of Pine Script v6 from indicator/olg_7_6_26/ALL_2/codex/indicator/6/EMA Crossover Buy/Median Cascade Trend [BackQuant]_29.txt, published under MPL-2.0 (file header). Keep the author's credit and licence lines when you reuse it.

Median Cascade Trend [BackQuant]_29.txt
// This Pine Script® code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © BackQuant

//@version=6
indicator("Median Cascade Trend [BackQuant]", "Median Cascade [BackQuant]", overlay = true)

// Inputs
const string g1 = "Median Cascade"
const string g2 = "Low-Pass Filter"
const string g3 = "Chop Filter"
const string g4 = "UI Settings"

float src = input.source(close, "Source", group = g1)
int stages = input.int(3, "Cascade Stages", minval = 1, maxval = 3, group = g1, tooltip = "Number of causal median filters applied before the low-pass stage.")
int medianLen1 = input.int(3, "Median Stage 1", minval = 2, maxval = 50, group = g1, tooltip = "Removes isolated one-bar spikes.")
int medianLen2 = input.int(5, "Median Stage 2", minval = 2, maxval = 50, group = g1, tooltip = "Removes remaining short-duration noise.")
int medianLen3 = input.int(7, "Median Stage 3", minval = 2, maxval = 50, group = g1, tooltip = "Final median stage before low-pass smoothing.")

int smoothLen = input.int(10, "Low-Pass Length", minval = 2, maxval = 100, group = g2, tooltip = "Two-pole Super Smoother applied after the median cascade.")
int directionLen = input.int(2, "Direction Lookback", minval = 1, maxval = 20, group = g2, tooltip = "Bars used to determine the direction of the final trend line.")

bool useGate = input.bool(true, "Chop Filter", group = g3, tooltip = "Blocks trend changes when movement lacks directional efficiency or sufficient slope.")
string gateMode = input.string("Both", "Gate Mode", options = ["Efficiency Ratio", "ATR-Normalized Slope", "Both", "Either"], group = g3, tooltip = "Both requires efficiency and slope to pass. Either allows a trend when one condition passes.")
int efficiencyLen = input.int(20, "Efficiency Length", minval = 5, maxval = 100, group = g3)
float efficiencyMin = input.float(0.25, "Minimum Efficiency", minval = 0.0, maxval = 1.0, step = 0.05, group = g3)
int slopeLen = input.int(2, "Slope Length", minval = 1, maxval = 20, group = g3)
int slopeAtrLen = input.int(14, "Slope ATR Length", minval = 1, maxval = 100, group = g3)
float slopeMin = input.float(0.08, "Minimum ATR-Normalized Slope", minval = 0.0, maxval = 5.0, step = 0.01, group = g3)

bool showLine = input.bool(true, "Show Trend Line", group = g4)
bool showFill = input.bool(true, "Gradient Fill", group = g4)
bool showGlow = input.bool(true, "Trend Glow", group = g4)
bool showSig = input.bool(true, "Show Signals", group = g4)
bool showBlocked = input.bool(false, "Show Blocked Flips", group = g4)
bool showGate = input.bool(true, "Show Gate Status", group = g4)
string gateDisplay = input.string("Dim", "Closed Gate Display", options = ["Dim", "Neutral", "Hide"], group = g4)
bool paintBar = input.bool(true, "Color Candles", group = g4)
int lineW = input.int(3, "Line Width", minval = 1, maxval = 6, group = g4)
color longCol = input.color(#00ff00, "Bullish", inline = "c", group = g4)
color shortCol = input.color(#ff0000, "Bearish", inline = "c", group = g4)
color gateCol = input.color(#555555, "Gated", inline = "c", group = g4)

// Two-Pole Super Smoother
superSmoother(float source, simple int length) =>
    float a1 = math.exp(-1.414 * math.pi / length)
    float b1 = 2.0 * a1 * math.cos(1.414 * math.pi / length)
    float c2 = b1
    float c3 = -a1 * a1
    float c1 = 1.0 - c2 - c3
    float filt = na
    filt := c1 * (source + nz(source[1], source)) * 0.5 + c2 * nz(filt[1], source) + c3 * nz(filt[2], source)
    filt

// Median Cascade
float median1 = ta.median(src, medianLen1)
float median2 = ta.median(median1, medianLen2)
float median3 = ta.median(median2, medianLen3)
float medianOut = stages == 1 ? median1 : stages == 2 ? median2 : median3

// Low-Pass Stage
float trendLine = superSmoother(medianOut, smoothLen)

// Chop Filter
float netMovement = math.abs(trendLine - trendLine[efficiencyLen])
float totalMovement = math.sum(math.abs(ta.change(trendLine)), efficiencyLen)
float efficiency = totalMovement > 0.0 ? netMovement / totalMovement : 0.0

float slopeAtr = ta.atr(slopeAtrLen)
float normalizedSlope = slopeAtr > 0.0 ? math.abs(trendLine - trendLine[slopeLen]) / slopeAtr : 0.0

bool efficiencyPass = efficiency >= efficiencyMin
bool slopePass = normalizedSlope >= slopeMin
bool gatePass = gateMode == "Efficiency Ratio" ? efficiencyPass : gateMode == "ATR-Normalized Slope" ? slopePass : gateMode == "Either" ? efficiencyPass or slopePass : efficiencyPass and slopePass
bool gateOpen = not useGate or gatePass

// Trend
int rawTrend = trendLine > trendLine[directionLen] ? 1 : trendLine < trendLine[directionLen] ? -1 : 0

var int trend = 0
if gateOpen and rawTrend != 0 and rawTrend != trend
    trend := rawTrend

bool bullFlip = trend == 1 and trend[1] == -1
bool bearFlip = trend == -1 and trend[1] == 1
bool blocked = not gateOpen and rawTrend != 0 and rawTrend != trend and rawTrend != rawTrend[1]

// Plot Colors
color baseTrendCol = trend == 1 ? longCol : trend == -1 ? shortCol : color.gray
color trendCol = not gateOpen and showGate and gateDisplay == "Neutral" ? gateCol : baseTrendCol
int lineAlpha = not gateOpen and showGate and gateDisplay == "Dim" ? 65 : 0
float plottedTrend = not gateOpen and showGate and gateDisplay == "Hide" ? na : trendLine

color candleCol = baseTrendCol
if not gateOpen and showGate
    candleCol := gateDisplay == "Neutral" ? gateCol : gateDisplay == "Hide" ? na : color.new(baseTrendCol, 65)
else
    candleCol := color.new(baseTrendCol, 10)

// Plots
pLine = plot(showLine ? plottedTrend : na, "Median Cascade Trend", color = color.new(trendCol, lineAlpha), linewidth = lineW)
pPrice = plot(close, "Price Ref", display = display.none, editable = false)

// Gradient Fill
fill(pPrice, pLine, close > trendLine ? close : trendLine, close > trendLine ? trendLine : close, showFill and close > trendLine and not na(plottedTrend) ? color.new(trendCol, 20 + lineAlpha) : na, showFill and close > trendLine and not na(plottedTrend) ? color.new(trendCol, 92) : na, title = "Bull Fill")
fill(pPrice, pLine, close < trendLine ? trendLine : close, close < trendLine ? close : trendLine, showFill and close < trendLine and not na(plottedTrend) ? color.new(trendCol, 20 + lineAlpha) : na, showFill and close < trendLine and not na(plottedTrend) ? color.new(trendCol, 92) : na, title = "Bear Fill")

// Trend Glow
float glow = ta.atr(14) * 0.06
pGlowLower = plot(not na(plottedTrend) ? trendLine - glow : na, "Glow Lower Ref", display = display.none, editable = false)
pGlowUpper = plot(not na(plottedTrend) ? trendLine + glow : na, "Glow Upper Ref", display = display.none, editable = false)
fill(pLine, pGlowLower, showGlow and not na(plottedTrend) ? color.new(trendCol, 55 + int(lineAlpha * 0.5)) : na, title = "Glow Lower")
fill(pLine, pGlowUpper, showGlow and not na(plottedTrend) ? color.new(trendCol, 55 + int(lineAlpha * 0.5)) : na, title = "Glow Upper")

// Candles
barcolor(paintBar ? candleCol : na, title = "Trend Candles")

// Signals
plotshape(showSig and bullFlip ? trendLine : na, "Bull Flip", shape.labelup, location.absolute, longCol, text = "▲", textcolor = chart.bg_color, size = size.small)
plotshape(showSig and bearFlip ? trendLine : na, "Bear Flip", shape.labeldown, location.absolute, shortCol, text = "▼", textcolor = chart.bg_color, size = size.small)
plotshape(showBlocked and blocked ? trendLine : na, "Blocked Flip", shape.xcross, location.absolute, gateCol, size = size.tiny)

// Alerts
alertcondition(bullFlip, "Median Cascade Bullish", "Median Cascade Trend turned bullish on {{ticker}}")
alertcondition(bearFlip, "Median Cascade Bearish", "Median Cascade Trend turned bearish on {{ticker}}")
alertcondition(blocked, "Median Cascade Flip Blocked", "Median Cascade trend change blocked by the chop filter on {{ticker}}")

Overview

A chop filter can block trend changes when directional efficiency or ATR-normalised slope is too low, using either, both or one of the two tests. It can show signals, blocked flips, gate status, gradient fill, glow and coloured candles. Median lengths, smoothing length and thresholds are adjustable.

Details

Published by

vedkanani123 on GitHub

Code credit

BackQuant, as written in the script's header

Type

Indicator, Pine Script v6

Draws

On the price chart

Category

Trend, Volatility & bands

Markets

Any symbol

Timeframes

Any timeframe

Risk Notes

No repainting, lookahead or stacked entries were found in its code or README. That says nothing about how well it works: test it first.

Settings

The inputs you can change from the gear icon on the chart. Defaults are the author's.

SettingTypeDefaultVariable
Sourcesourceclosesrc
Cascade Stagesint3stages
Median Stage 1int3medianLen1
Median Stage 2int5medianLen2
Median Stage 3int7medianLen3
Low-Pass Lengthint10smoothLen
Direction Lookbackint2directionLen
Chop FilterbooltrueuseGate
Gate ModestringBothgateMode
Efficiency Lengthint20efficiencyLen
Minimum Efficiencyfloat0.25efficiencyMin
Slope Lengthint2slopeLen
Show all 26 settings
SettingTypeDefaultVariable
Slope ATR Lengthint14slopeAtrLen
Minimum ATR-Normalized Slopefloat0.08slopeMin
Show Trend LinebooltrueshowLine
Gradient FillbooltrueshowFill
Trend GlowbooltrueshowGlow
Show SignalsbooltrueshowSig
Show Blocked FlipsboolfalseshowBlocked
Show Gate StatusbooltrueshowGate
Closed Gate DisplaystringDimgateDisplay
Color CandlesbooltruepaintBar
Line Widthint3lineW
Bullishcolor#00ff00longCol
Bearishcolor#ff0000shortCol
Gatedcolor#555555gateCol
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

Chandelier Exit

by everget
948 stars

This indicator plots an ATR-based Chandelier Exit trailing stop on the price chart. It tracks a long stop under recent highs and a short stop above recent lows, then switches direction when price crosses the opposite stop. Buy and sell labels mark those flips.

Indicator v6 Volatility & bandsTrend Repaints
Updated 11 days ago · GPL-3.0 GitHub repository of Chandelier Exit

The Momentum Setup is a multi-indicator visual tool designed for trend and momentum analysis directly on the price chart. It combines Relative Strength Index (RSI), Money Flow Index (MFI), Commodity Channel Index (CCI), Supertrend, and a 250-bar percentage cha

Indicator v5 Oscillators & momentumTrend
Updated 1 year ago · MPL-2.0 GitHub repository of Momentum Setup - Ankush Bajaj Momentum Investing Setup
330 stars

Range Filter [Alorse] is a technical indicator overlay for TradingView designed to filter market volatility and identify price trends. It calculates a smoothed range based on historical volatility using a configurable sampling period and multiplier applied to

Indicator v5 TrendVolatility & bands
Updated 2 months ago · None stated GitHub repository of Range Filter [Alorse]
318 stars

This indicator calculates an ATR trailing stop line derived from the highest high minus an average true range multiple over a specified lookback period. It plots the trailing stop line directly on the price chart and colors price bars based on whether the clos

Indicator v5 TrendVolatility & bands
Updated 2 months ago · MIT GitHub repository of ATR Trailing Stoploss

NVDA Trend Ribbon

by longsurf-ai
277 stars

This indicator plots three exponential moving averages and ATR volatility envelopes on the price chart. It compares the fast and slow EMAs to shade a trend ribbon and marks confirmed upward and downward crossovers with triangle labels. Settings change the thre

Indicator v6 TrendMoving averages
Updated 2 days ago · MIT GitHub repository of NVDA Trend Ribbon

[RS]Donchian Fans

by ricardosantos79
261 stars

This indicator plots Donchian Channel boundary lines along with dynamic fan projections directly on the price chart. It calculates the highest high, lowest low, and median price over a customizable lookback period. Whenever price establishes a new channel high

Indicator v4 Support & resistanceTrend
Updated 4 years ago · None stated GitHub repository of [RS]Donchian Fans

More indicators

Trade Your Charts With a Regulated Broker

Compare brokers that connect to TradingView, with spreads, minimum deposits and leverage side by side.

Compare brokers