OPEN-SOURCE SCRIPT

Median Cascade Trend [BackQuant]

1 652
Median Cascade Trend [BackQuant]

Overview
Median Cascade Trend is a noise-resistant trend-following indicator that combines multiple causal median filters, an Ehlers-style two-pole Super Smoother, and a configurable chop-gating system.

Its purpose is to identify meaningful directional structure while rejecting the types of price movement that frequently cause conventional moving averages to whipsaw:
  • Single-bar spikes
  • Short-lived price shocks
  • Irregular wicks
  • Low-efficiency sideways movement
  • Weak slopes that do not represent genuine directional progress


The indicator processes price in three distinct stages:
  • A median-filter cascade removes impulsive and short-duration noise.
  • A two-pole low-pass filter smooths the remaining structural signal.
  • A chop gate decides whether a change in direction is strong enough to update the active trend state.


This creates a trend line that is intentionally more selective than a standard moving average. The line itself can continue evolving, but trend-state changes are only accepted when the underlying movement passes the chosen quality tests.

The result is a system that separates:
  • The estimated trend line
  • The raw direction of that line
  • The confirmed trend regime


That distinction is important. The indicator does not assume that every small turn in a smoothed line represents a valid trend reversal.

Core idea
Most trend filters are built around linear averaging. They combine historical prices using fixed or exponentially decaying weights.

Examples include:
  • SMA
  • EMA
  • WMA
  • HMA
  • DEMA


These filters are effective for general smoothing, but they have a weakness: a single extreme observation can influence the output immediately.

If one bar produces a large wick or temporary price shock, a moving average will usually be pulled toward that value because it includes the magnitude of every observation.

A median filter behaves differently.

Instead of averaging the values inside a window, it sorts them and selects the middle observation. This makes it highly resistant to isolated extremes.

Median Cascade Trend uses this property repeatedly before applying traditional low-pass smoothing.

The central idea is:
  • Remove impulsive noise first.
  • Smooth the cleaned signal second.
  • Confirm direction only when the movement is efficient or sufficiently steep.


This ordering is deliberate. Smoothing a noisy series and filtering noise before smoothing are not the same thing.

Where median filtering comes from
Median filters are widely used in digital signal processing, image processing, and engineering.

One of their best-known applications is the removal of impulse noise, sometimes called salt-and-pepper noise in image processing.

Impulse noise consists of isolated extreme observations that are not representative of the surrounding signal.

In market data, comparable events include:
  • Temporary liquidity gaps
  • Single-bar stop runs
  • Erroneous prints
  • Sharp wick reversals
  • News spikes that immediately retrace


A linear smoother such as an SMA or EMA cannot distinguish between an important sustained move and an isolated outlier. Both are included according to their numerical magnitude.

A median filter is nonlinear. It selects the central-ranked value rather than calculating an arithmetic mean.

For example, consider five observations:

  • 100
  • 101
  • 102
  • 103
  • 140


The average is:

  • 109.2


The median is:

  • 102


The isolated value at 140 significantly distorts the average but has almost no effect on the median.

This is why median filtering is especially useful when the objective is to preserve structural turns while rejecting isolated noise.

What makes a median filter nonlinear
A normal moving average can be represented as a weighted sum of its inputs.

A median filter cannot.

Its output depends on the ordering of observations, not their arithmetic combination. This makes it a nonlinear filter.

That has several important consequences:
  • Outliers have limited influence.
  • Edges and structural shifts can be preserved more cleanly.
  • The response is not equivalent to ordinary low-pass averaging.
  • The filter may hold a value until enough observations confirm a change.


In trading terms, the median filter often behaves more like a structural selector than a conventional average.

What “causal” means
The median stages in this indicator are causal.

A causal filter uses:
  • The current bar
  • Past bars


It does not use future observations.

This matters because many visually smooth filtering methods can only produce their best result by centering the calculation around the current point, which requires future data.

This script does not do that.

Every value is calculated from information available at that bar, making the filter suitable for live use.

Why use a cascade of median filters
A single median filter can remove isolated spikes, but noise does not always occur as one extreme bar.

It can appear as:
  • Two-bar shocks
  • Short bursts of alternating movement
  • Small clusters of irregular candles
  • Residual distortion left after the first filtering pass


A cascade applies multiple median stages sequentially:
  • Stage 1 processes the original source.
  • Stage 2 processes the output of Stage 1.
  • Stage 3 processes the output of Stage 2.


Each stage removes a different layer of short-duration instability.

The process is similar to progressively cleaning a signal:
  • The first stage removes obvious impulse noise.
  • The second stage removes remaining short-term irregularity.
  • The third stage produces a more stable structural series before low-pass smoothing.


Median Stage 1
The first median stage is intended to reject isolated one-bar disturbances.

With a short setting such as 3:
  • The filter remains responsive.
  • Single-bar spikes are strongly suppressed.
  • Most genuine multi-bar movement remains visible.


This is the most tactical stage.

Median Stage 2
The second stage receives an already-cleaned input.

Its role is to remove:
  • Short-duration residual noise
  • Small alternating movements
  • Irregularity that survived the first stage


A slightly longer setting such as 5 creates stronger structural consistency.

Median Stage 3
The third stage provides the final nonlinear cleaning pass.

With a longer setting such as 7:
  • The output becomes more stable.
  • Short-lived reversals are reduced.
  • Only more persistent changes are passed into the low-pass stage.


This is the most conservative median stage.

Cascade Stages input
The user can select how many median stages are active:
  • 1 stage: fastest and most responsive
  • 2 stages: balanced noise rejection
  • 3 stages: strongest impulse-noise suppression


The unused stages are still calculated internally, but the selected stage determines which output is sent into the Super Smoother.

Why cascade instead of one very long median
Applying several shorter filters is not always equivalent to applying one very long median filter.

A long median window can:
  • Delay structural changes heavily
  • Flatten shorter trend legs
  • Become insensitive to local turns


A cascade allows the filtering process to be distributed across stages.

This provides greater control over:
  • How aggressively isolated noise is removed
  • How much short-duration movement survives
  • How smooth the final structural input becomes


It also lets users build a progression such as 3, 5, and 7 rather than applying one blunt window.

The low-pass stage
After the median cascade, the signal is passed into a two-pole Super Smoother.

The median cascade removes nonlinear impulse noise, but its output can still contain:
  • Small step changes
  • Residual high-frequency movement
  • Sharp transitions caused by median replacement


The Super Smoother converts that cleaned but potentially stepped series into a smoother trend line.

This creates a hybrid filtering system:
  • Nonlinear median filtering for outlier rejection
  • Recursive low-pass filtering for smooth trend extraction


These components solve different problems.

Where the Super Smoother comes from
The Super Smoother is associated with John F. Ehlers’ application of digital signal processing techniques to financial markets.

It is based on the behavior of a two-pole low-pass filter and is designed to suppress high-frequency components more effectively than many conventional moving averages.

Traditional moving averages are simple smoothers, but they are not necessarily optimized as frequency-selective filters.

The Super Smoother uses recursively calculated coefficients derived from:
  • Exponential decay
  • Trigonometric terms
  • A selected cutoff period


The objective is to reduce high-frequency market noise while retaining lower-frequency directional structure.

What a low-pass filter does
A low-pass filter allows slow-moving components of a signal to pass while reducing fast-moving components.

In market terms:
  • Slow components represent broader trend structure.
  • Fast components represent short-term noise, rapid oscillation, and microstructure disturbance.


The Low-Pass Length determines the separation.

Lower values:
  • Allow more short-term movement through.
  • React faster.
  • Produce more turns.


Higher values:
  • Reject more high-frequency movement.
  • Produce a smoother trend line.
  • Respond later to structural changes.


Why use a two-pole filter
The number of poles broadly describes the order and steepness of a filter.

A two-pole filter generally provides:
  • Stronger attenuation of high-frequency noise than a one-pole filter.
  • A smoother output.
  • A more defined frequency response.


It also uses prior filter outputs recursively, allowing substantial smoothing without requiring an extremely long direct averaging window.

The full signal-processing chain
The calculation can be understood as:

  • Raw price source
  • Median Stage 1
  • Optional Median Stage 2
  • Optional Median Stage 3
  • Two-pole Super Smoother
  • Direction measurement
  • Chop-quality validation
  • Persistent trend state


Each layer has a distinct purpose.

Median cascade
  • Rejects isolated and short-lived noise.


Super Smoother
  • Reduces the remaining high-frequency variation.


Direction logic
  • Determines whether the final line is rising or falling.


Chop gate
  • Determines whether that directional change is trustworthy enough to update the confirmed trend.


Trend direction calculation
The raw direction is determined by comparing the current trend line with its value several bars ago:

  • Bullish if trendLine > trendLine[directionLen]
  • Bearish if trendLine < trendLine[directionLen]
  • Neutral if equal


The Direction Lookback controls how much movement is required before the line is classified as rising or falling.

A one-bar comparison is extremely responsive but can detect tiny slope changes.

A longer comparison:
  • Measures movement across a wider interval.
  • Reduces sensitivity to one-bar flattening.
  • Produces more stable raw direction.


Raw trend versus confirmed trend
One of the most important design choices is that the script separates:
  • Raw trend
  • Confirmed trend


The raw trend reflects the current direction of the filtered line.

The confirmed trend is persistent and changes only when:
  • The raw trend points in a new direction.
  • The chop gate is open.


If the line turns but the gate is closed:
  • The active trend state remains unchanged.
  • The attempted flip can optionally be displayed as blocked.


This prevents every small line turn from immediately becoming a regime reversal.

Why a chop filter is needed
Even an advanced smoother can turn repeatedly during sideways markets.

Smoothing reduces noise, but it does not determine whether movement is:
  • Directional
  • Efficient
  • Large enough relative to volatility


A line can move upward and downward in a range while making almost no net progress.

The chop gate addresses this by evaluating two separate properties:
  • Directional efficiency
  • ATR-normalized slope


Efficiency Ratio
The first gate component measures how efficiently the trend line has moved over a selected window.

The calculation compares:
  • Net movement
  • Total movement


Net movement is:

  • |trendLine - trendLine[efficiencyLen]|


Total movement is:

  • Sum of |bar-to-bar changes in trendLine|


The Efficiency Ratio is:

  • Efficiency = Net Movement / Total Movement


The result ranges approximately from 0 to 1.

Efficiency near 1
The line has moved mostly in one direction.

Example:
  • It advanced 10 units.
  • Its total path was approximately 11 units.


This indicates a clean directional move.

Efficiency near 0
The line has moved back and forth without achieving much net progress.

Example:
  • It travelled 20 units in total.
  • But ended only 1 unit from where it started.


This indicates chop.

Where the Efficiency Ratio comes from
The Efficiency Ratio is commonly associated with Perry Kaufman’s work on adaptive market analysis and the Kaufman Adaptive Moving Average.

Its purpose is to distinguish directional movement from noisy movement.

It does not measure the size of a move alone.

It measures the quality of the path.

This makes it highly suitable as a trend gate.

A market can be volatile but inefficient. It can move aggressively in both directions and still make little progress.

The Efficiency Ratio helps identify that distinction.

Minimum Efficiency
The Minimum Efficiency input determines the directional quality required for the efficiency condition to pass.

Lower values:
  • Allow more irregular movement.
  • Open the gate more frequently.
  • Produce earlier but noisier trend changes.


Higher values:
  • Require cleaner directional travel.
  • Block more sideways flips.
  • Produce fewer but more selective regime changes.


ATR-Normalized Slope
The second gate component measures how large the trend-line movement is relative to current market volatility.

It calculates:

  • |trendLine - trendLine[slopeLen]| / ATR


This converts the line’s movement into ATR units.

Without normalization, a slope of 10 points could be:
  • Large for one instrument
  • Negligible for another
  • Large in a quiet regime
  • Small during extreme volatility


ATR normalization makes the slope more comparable across assets and regimes.

What normalized slope measures
The Efficiency Ratio asks:
  • Was the movement directionally clean?


ATR-normalized slope asks:
  • Was the movement large enough to matter?


These are different questions.

A move can be highly efficient but extremely small.

For example:
  • A perfectly smooth drift of only 0.02 ATR may not justify a new trend regime.


A move can also be large but inefficient:
  • A violent range may travel several ATRs while repeatedly reversing.


Using both filters gives a more complete view of trend quality.

Minimum ATR-Normalized Slope
The Minimum ATR-Normalized Slope defines the movement threshold.

Lower values:
  • Accept weaker slopes.
  • React sooner.
  • Allow more low-energy flips.


Higher values:
  • Require stronger displacement.
  • Reduce weak trend transitions.
  • Delay signals until movement becomes more meaningful.


Gate modes
The indicator provides four chop-gate modes.

Efficiency Ratio
Only directional efficiency is required.

Best suited for users who care primarily about whether movement is clean, regardless of its exact magnitude.

ATR-Normalized Slope
Only slope strength is required.

Best suited for users who want movement to exceed a volatility-adjusted threshold, even if the path is not perfectly efficient.

Both
Both conditions must pass:
  • Efficiency must be high enough.
  • Slope must be strong enough.


This is the strictest mode and generally provides the strongest chop rejection.

Either
Only one condition must pass.

This is more permissive:
  • A very clean slow trend may pass through efficiency.
  • A powerful but less orderly move may pass through slope.


It provides a balance between responsiveness and filtering.

Gate behavior
When the gate is open:
  • A new raw direction can update the trend state.
  • Bullish and bearish flips can be confirmed.


When the gate is closed:
  • The previous confirmed trend persists.
  • Attempted changes are blocked.
  • The display can dim, turn neutral, or hide.


This means the indicator behaves like a regime-holding system during chop.

It does not constantly reset to neutral. It retains the last confirmed direction until sufficient evidence supports a new one.

Blocked flips
A blocked flip occurs when:
  • The filtered line attempts to change direction.
  • The attempted direction differs from the confirmed trend.
  • The chop gate is closed.
  • The raw direction has just changed.


These can optionally be displayed as small X markers.

Blocked flips are useful because they show:
  • Where a basic slope indicator would have reversed.
  • Where the chop filter rejected that reversal.
  • How much signal noise the gate is removing.


They are not trade signals. They are diagnostic information.

Trend persistence
The trend variable is persistent.

Once bullish:
  • It remains bullish until a valid bearish change passes the gate.


Once bearish:
  • It remains bearish until a valid bullish change passes the gate.


This persistence is central to the design.

The indicator is not merely coloring every local slope. It is maintaining a confirmed market regime.

Display modes when the gate is closed
The indicator offers three ways to display gated conditions.

Dim
The current trend color remains visible but becomes transparent.

This communicates:
  • The last confirmed trend is still active.
  • Current conditions are not strong enough to confirm a new direction.


This is useful when you want regime continuity without overstating conviction.

Neutral
The trend line and candles switch to the selected gate color.

This communicates:
  • The directional regime is being withheld.
  • Current conditions are considered non-trending or uncertain.


Hide
The trend line disappears while the gate is closed.

This is the strictest visual mode.

It communicates:
  • No actionable trend state should be displayed during the gated condition.


Trend line coloring
The base color is determined by the confirmed trend:
  • Bullish trend uses the long color.
  • Bearish trend uses the short color.
  • Uninitialized state uses gray.


The gate display can then modify the final presentation.

This allows the chart to show:
  • Direction
  • Confirmation status
  • Chop-filter activity


without needing a separate panel.

Gradient fill
The indicator fills the area between price and the trend line.

When price is above the trend line:
  • A bullish gradient is displayed.


When price is below the trend line:
  • A bearish gradient is displayed.


The fill is stronger near the trend line and fades toward price.

This emphasizes the trend line as the structural reference.

The fill color follows the gate display state:
  • Full trend color when active
  • Dimmed during a closed gate in Dim mode
  • Neutral when configured
  • Hidden when the trend line is hidden


Trend glow
A soft glow is created around the filtered line using a small ATR-scaled distance.

The glow width is:

  • ATR(14) × 0.06


Using ATR ensures the glow remains visually proportional across assets and price scales.

The glow does not affect the calculation. It improves readability and reinforces the line as the central structural output.

Candle coloring
Candles can be colored using the confirmed trend state.

When the gate is open:
  • Bull trend produces bullish candles.
  • Bear trend produces bearish candles.


When the gate is closed:
  • Dim mode fades the existing trend color.
  • Neutral mode uses the gate color.
  • Hide mode removes the candle override.


This gives an immediate full-chart view of both trend and gate status.

Signal logic
Signals only occur when the confirmed trend changes.

Bullish flip
A bullish signal requires:
  • The active trend becomes bullish.
  • The previous trend was bearish.
  • The gate accepted the change.


Bearish flip
A bearish signal requires:
  • The active trend becomes bearish.
  • The previous trend was bullish.
  • The gate accepted the change.


This is more selective than simply detecting a change in line slope.

How to interpret the indicator

Bullish confirmed regime
A bullish regime means:
  • The median-filtered and low-pass-smoothed trend line is rising.
  • The move satisfied the selected chop-filter conditions when the regime changed.
  • The last accepted direction remains bullish.


Bearish confirmed regime
A bearish regime means:
  • The final trend line is falling.
  • The bearish change passed the selected quality gate.
  • The last accepted direction remains bearish.


Gate closed in an existing trend
This means:
  • The market is no longer moving with sufficient efficiency or slope.
  • A new reversal cannot currently be confirmed.
  • The previous regime remains stored.


This often occurs during:
  • Consolidation
  • Pullbacks
  • Low-volatility drift
  • Transition phases


Repeated blocked flips
Repeated blocked changes suggest:
  • The filtered line is oscillating.
  • Directional quality is weak.
  • A normal trend-following system would likely be whipsawing.


This is exactly the environment the gate is designed to avoid.

How to use it in practice

1. Directional regime filter
Use the confirmed trend to filter other setups:
  • Favor long trades during bullish regimes.
  • Favor short trades during bearish regimes.
  • Reduce activity when the gate is closed.


2. Trend-following entries
Bullish and bearish flips can be used as directional entry triggers, especially when confirmed by:
  • Price structure
  • Breakouts
  • Volume expansion
  • Higher-timeframe alignment


3. Pullback framework
During an established trend:
  • Price returning toward the trend line may represent a pullback.
  • If the gate remains closed but the trend does not flip, the move may be consolidation rather than reversal.
  • If the opposite direction eventually passes the gate, the regime has changed more meaningfully.


4. Chop avoidance
The most direct use is avoiding repeated entries during low-quality conditions.

When the display is dim, neutral, or hidden:
  • Reduce confidence in new trend signals.
  • Wait for efficiency or slope to recover.


5. Diagnostic comparison
Enable blocked flips to see how often the raw trend attempts to reverse without confirmation.

This helps tune:
  • Efficiency threshold
  • Slope threshold
  • Gate mode


Input guide

Source
Selects the price series used by the median cascade.

Close is the standard choice.

Alternatives such as hl2 or hlc3 may produce a slightly smoother structural input.

Cascade Stages
Controls how many median filters are used.

  • 1: responsive
  • 2: balanced
  • 3: strongest noise rejection


Median Stage Lengths
Control the window used at each stage.

Shorter values:
  • Preserve responsiveness.
  • Remove only very short-duration noise.


Longer values:
  • Produce stronger structural filtering.
  • Delay shorter turns.


Low-Pass Length
Controls the two-pole Super Smoother.

Lower:
  • Faster
  • More reactive


Higher:
  • Smoother
  • More conservative


Direction Lookback
Controls how far back the current line is compared when determining raw direction.

Lower:
  • Faster slope changes


Higher:
  • More stable directional measurement


Efficiency Length
Controls the window used to measure net movement versus total path movement.

Shorter:
  • More responsive efficiency reading
  • More sensitive to recent chop


Longer:
  • More stable directional-quality assessment


Minimum Efficiency
Controls how clean the directional path must be.

Higher values make the gate stricter.

Slope Length
Controls the interval across which trend-line movement is measured.

Slope ATR Length
Controls the ATR baseline used to normalize slope.

Minimum ATR-Normalized Slope
Controls the minimum volatility-adjusted displacement required.

Higher values require stronger movement.

Tuning examples

Faster trend configuration
  • 1 or 2 median stages
  • Short median windows
  • Lower Super Smoother length
  • Direction Lookback of 1 or 2
  • Either gate mode
  • Lower efficiency and slope thresholds


Balanced configuration
  • 2 or 3 median stages
  • Progressive windows such as 3, 5, 7
  • Moderate Super Smoother length
  • Both gate mode
  • Moderate thresholds


Conservative configuration
  • 3 stages
  • Longer median windows
  • Higher Super Smoother length
  • Longer Direction Lookback
  • Both gate mode
  • Higher minimum efficiency and slope


How this differs from a normal moving average
A standard moving average:
  • Uses linear averaging.
  • Responds directly to outlier magnitude.
  • Changes direction whenever its slope changes.


Median Cascade Trend:
  • Uses nonlinear outlier-resistant preprocessing.
  • Applies a proper recursive low-pass stage.
  • Separates raw direction from confirmed regime.
  • Blocks changes during inefficient or weak movement.


How this differs from a normal median filter
A basic median filter only removes impulse noise.

This indicator extends the idea by adding:
  • Multiple median stages
  • Low-pass smoothing
  • Direction measurement
  • Efficiency gating
  • Volatility-normalized slope gating
  • Persistent trend states
  • Signals and alerts


It is not simply a median-smoothed line. It is a complete trend-regime system built on median preprocessing.

How this differs from a Supertrend
A Supertrend uses ATR bands around price and changes state when price crosses the trailing boundary.

Median Cascade Trend does not use a volatility band to define direction.

Instead:
  • Direction comes from the slope of the filtered trend line.
  • ATR is used only to normalize slope and scale visuals.
  • Trend changes are controlled by movement quality rather than price crossing a stop band.


Strengths
  • Strong rejection of isolated price spikes
  • Preserves broader structural movement
  • Combines nonlinear and linear filtering
  • Separates raw turns from confirmed trend changes
  • Configurable chop rejection
  • Volatility-normalized slope testing
  • Persistent directional regimes
  • Blocked-flip diagnostics
  • Fully causal calculation


Limitations
  • Strong filtering can delay genuine reversals.
  • Long median windows may suppress shorter trend legs.
  • Strict gate settings can hold the previous regime too long.
  • Loose gate settings reduce the benefit of chop filtering.
  • Median filters can produce stepped transitions before low-pass smoothing.
  • The indicator remains reactive rather than predictive.


Best use cases
Median Cascade Trend is particularly suited for:
  • Trend filtering in noisy markets
  • Reducing false reversals caused by wicks
  • Swing-trading regime identification
  • Filtering entries from faster systems
  • Dynamic trend-structure visualization
  • Avoiding sideways-market whipsaws


It can be applied across:
  • Equities
  • Indices
  • Futures
  • Forex
  • Cryptocurrency
  • Commodities


Alerts
The indicator provides alerts for:
  • Confirmed bullish trend changes
  • Confirmed bearish trend changes
  • Trend changes blocked by the chop filter


The blocked-flip alert is especially useful for monitoring when the line attempts to reverse but market quality remains insufficient.

Summary
Median Cascade Trend is a multi-stage trend extraction system designed to reject impulsive market noise before determining direction. It first applies up to three causal median filters, progressively removing isolated spikes and short-duration disturbances. The cleaned series is then passed through a two-pole Super Smoother to extract a stable low-frequency trend line.

Rather than accepting every change in slope, the indicator evaluates the quality of the movement using directional efficiency and ATR-normalized slope. Depending on the selected gate mode, trend changes can require clean directional travel, sufficient volatility-adjusted displacement, or both.

This produces a persistent trend state that changes only when the filtered line turns and the surrounding movement is strong enough to justify the reversal. The final result is a robust trend-following framework that combines outlier rejection, low-pass smoothing, directional-quality measurement, and chop suppression into a single overlay.

إخلاء المسؤولية

لا يُقصد بالمعلومات والمنشورات أن تكون، أو تشكل، أي نصيحة مالية أو استثمارية أو تجارية أو أنواع أخرى من النصائح أو التوصيات المقدمة أو المعتمدة من TradingView. اقرأ المزيد في شروط الاستخدام.