OPEN-SOURCE SCRIPT

Smart Trend Filter Confirmation [MarkitTick]

4 214
💡 A confirmed-bar trend-following system that fuses a volatility-adaptive trailing band with a six-condition consensus filter, designed to suppress the false flips that plague standard trend-following tools when markets stall, chop, or thin out. Rather than reacting to every band cross, the script cross-examines each potential signal against stall detection, slope strength, volume participation, range compression, basis-point movement, and trend strength (ADX) before allowing a flip to display — while retaining a breakout override so genuinely explosive moves are never suppressed by the very filters designed to catch noise.

✨ Originality and Utility

Trailing-band trend systems (Chandelier-style or SuperTrend-style constructs) are common on TradingView, but nearly all of them share the same weakness: the trailing line flips direction on every price crossover, regardless of whether that crossover reflects a genuine change in market character or simply noise generated during a stalled, illiquid, or compressing market. This script's originality lies in the "Regime Consensus" layer built on top of the adaptive trailing band. Six independent, mathematically distinct filters — measuring band stall, linear-regression slope, relative volume, historical range percentile, basis-point velocity, and ADX-based trend strength — are computed every bar. If any single filter flags a "flat" regime, the display direction is held at its last confirmed state instead of flipping, which materially reduces whipsaw signals in ranging conditions. A dedicated breakout override simultaneously monitors for abnormally large single-bar moves (measured in ATR multiples) and forces the flip through regardless of filter status, ensuring the system does not become sluggish during genuine volatility expansion. This combination — adaptive smoothing of the source price, a volatility- and momentum-weighted dynamic band, a multi-factor flat-market veto, and a breakout bypass — is not a simple mashup of stock indicators but an integrated decision layer where each component directly informs whether the others are permitted to act. The trend line, filters, override, and dashboard are not separable add-ons; they operate as a single signal-gating pipeline.

🔬 Methodology and Concepts

● Adaptive Source Smoothing
Before any band math is applied, the script conditions the underlying HL2-style source price using one of two selectable adaptive filters:
  • Kalman Filter — a recursive estimator that maintains an internal "belief" about the true price and a corresponding uncertainty (error covariance). Each new bar, the filter computes a gain factor from the ratio of predicted uncertainty to total uncertainty (predicted plus measurement noise, set by the Kalman R input) and blends the new price observation into its estimate proportionally. A higher Kalman Q input allows the estimate to adapt faster to new prices; a higher Kalman R input makes the filter trust new observations less, producing a smoother but slower-reacting line.
  • LLAMA (an adaptive-length moving average inspired by Kaufman's Efficiency Ratio concept) — measures how efficiently price has moved over the lookback window by comparing net directional change to the sum of all bar-to-bar movement (an efficiency ratio between 0 and 1). This ratio is squared into a smoothing constant that continuously shifts the moving average's responsiveness between a fast EMA-like constant and a slow EMA-like constant, so the average tightens to price during clean directional runs and widens during choppy conditions.


• Dynamic Volatility Band
The core trailing band's half-width is not a fixed ATR multiple. It is calculated from three weighted components: a base multiplier, an ATR-based term scaled by the ATR Weight input, and a normalized recent-price-movement term (capped at its own 95th percentile to prevent single outlier bars from distorting the band) scaled by the Move Weight input. This composite value is then multiplied by the current ATR and smoothed with an exponential moving average (controlled by the Smooth Len input) to prevent the band width itself from jumping erratically bar to bar.

• Trailing Trend Line Construction
The trend line follows classic chandelier-style trailing logic: while price remains above the trend line, the line can only ratchet upward (never retreating below its prior value even if the lower band momentarily dips beneath it); while price remains below the trend line, the line can only ratchet downward. A flip only occurs when confirmed prior-bar closing price crosses to the opposite side of the line.

• Six-Factor Regime Consensus Filter
Before a directional flip is permitted to display, up to six independent conditions are checked. If any active filter flags the market as "flat," the displayed direction holds at its previous confirmed state rather than flipping:
  • Stall Filter — flags when the trend line's bar-to-bar movement is smaller than a fraction (Flatness input) of current ATR, indicating the line itself has gone quiet.
  • Slope Filter — runs a short linear regression across recent trend-line values, measures the resulting slope, normalizes it against ATR, and flags when that normalized slope falls below the Slope Thr input.
  • Volume Filter — flags when confirmed volume falls at or below its own moving average, treating below-average participation as unreliable for a fresh directional call.
  • Range Filter — flags when the current bar's high-low range falls within the lower percentile band (Range Pct input) of its historical distribution over the Pctile Len lookback, identifying range compression.
  • BPS Filter — converts the trend line's bar-to-bar movement into basis points relative to price and flags when that figure falls under the Min BPS input, catching moves too small to be economically meaningful.
  • ADX Filter — computes a standard Directional Movement Index reading and flags when it sits below the ADX Thr input, indicating weak underlying trend strength.


• Breakout Override
Running in parallel to the consensus filters, this component measures the absolute prior-bar price change against a multiple of ATR (Ovr ATR Mult input). If that threshold is exceeded, the override forces the flip through immediately, bypassing every flat-market filter above. This prevents the filter layer from muting the system's response to genuine volatility expansion or breakout conditions.

🎨 Visual Guide

  • Trend Line — a stepped line plotted along the confirmed trailing band value. It renders in the Bull color when the confirmed direction is up and the Bear color when down; both colors are fully customizable in the Colors group.
  • Gradient Candles / Bar Coloring — when enabled, chart candles and bars are recolored on a gradient between the Neutral color and the active directional color, with gradient intensity scaled by how far confirmed price has extended from the trend line relative to ATR (capped at 3x ATR for full saturation). A muted candle indicates price sitting close to the trend line; a fully saturated candle indicates an extended move.
  • Cloud Fill — a semi-transparent fill (opacity set by Cloud Transp) rendered between the trend line and a short moving average of HLC3 (length set by Cloud MA Len), tinted in the active directional color to visually reinforce which side of the trend the market currently occupies.
  • Bull / Bear Signal Labels — a "Bull" label appears below price the bar a confirmed flip to the up-regime occurs, and a "Bear" label above price on a confirmed flip to the down-regime, provided the Regime Consensus Filter did not veto the flip and Lock Signal is not engaged.
  • Trade Level Lines and Labels (optional, enabled via Show Trade Levels) — on each new confirmed signal, five lines are drawn forward from the signal bar: an Entry line (at prior confirmed close), a Stop Loss line, and three Take Profit lines (TP1, TP2, TP3), each offset from entry by ATR multiples set in the Trade Tools group. A shaded risk zone connects Entry to Stop Loss, and a shaded reward zone connects Entry to the furthest take-profit line. Each line carries a right-aligned label showing its exact price.
  • Live Dashboard (optional, position configurable via Dash X / Dash Y) — a compact table summarizing current symbol/timeframe, signal lock state, active direction, current signal status, regime classification (Flat/Trending), breakout override status, active adaptive filter type, current trend-line and ATR values, a visual progress bar for trend strength, and individual on/off/flat status readouts for each of the six regime filters.
  • Non-Standard Chart Warning — a red-bordered table automatically appears in the top-left corner if the script detects it is being run on a Heikin Ashi, Renko, Line Break, Kagi, or Point & Figure chart, warning that signal reliability is compromised on synthetic chart types.


📖 How to Use

  • A "Bull" label with the trend line switching to the Bull color signals a confirmed transition to an up-regime that has passed all active consensus filters (or was pushed through by the breakout override).
  • A "Bear" label with the trend line switching to the Bear color signals the equivalent confirmed down-regime transition.
  • Because flips are gated by the consensus filter, the absence of a new signal during a period of price consolidation is intentional — the script is treating the move as noise rather than a lack of function. Check the dashboard's individual filter rows to see exactly which condition(s) are currently classifying the market as flat.
  • The dashboard's "Override" row shows "Engaged" when the Breakout Override has just bypassed the filters — useful for distinguishing a filter-confirmed signal from a volatility-forced one.
  • When Show Trade Levels is active, treat the Entry/SL/TP lines as a reference risk framework tied to current ATR, not a guaranteed execution plan; always verify levels make sense for the instrument and timeframe before acting on them.
  • Enable Lock Signal to freeze the current signal state on the most recent bar, useful when reviewing historical signal behavior without new signals interrupting the current view.
  • If the Non-Standard Chart warning appears, switch to a standard candlestick chart type before relying on any signal from this script.


⚙️ Inputs and Settings

  • ATR Len — lookback period for the underlying ATR calculation that drives band width and multiple filter thresholds. Shorter values make the band more reactive to recent volatility; longer values smooth it out.
  • Band Mult, ATR Weight, Move Weight — the three components that combine into the dynamic band multiplier. Band Mult sets a base width, ATR Weight scales the contribution of current ATR relative to price, and Move Weight scales the contribution of recent capped price movement.
  • Smooth Len — the EMA length applied to the calculated band half-width, controlling how quickly the band itself can widen or narrow.
  • Adaptive Filter / Filter Type — toggles and selects between Kalman and LLAMA smoothing of the source price feeding the trend line.
  • Kalman Q / Kalman R — process noise and measurement noise inputs for the Kalman filter; higher Q increases responsiveness, higher R increases smoothing.
  • LLAMA Len — lookback window for the efficiency-ratio calculation driving the LLAMA adaptive average.
  • Stall Filter / Flatness — enables the stall check and sets the ATR-relative threshold below which trend-line movement is considered stalled.
  • Slope Filter / Reg Len / Slope Thr — enables the regression-slope check, sets its lookback window, and sets the normalized slope threshold below which the market is considered flat.
  • Volume Filter / Vol MA Len — enables the volume check and sets the moving-average length volume is compared against.
  • Range Filter / Pctile Len / Range Pct — enables the range-compression check and sets the historical lookback and percentile threshold used to classify current range as compressed.
  • BPS Filter / Min BPS — enables the basis-point movement check and sets the minimum basis-point threshold for a trend-line move to be considered meaningful.
  • ADX Filter / ADX Len / ADX Thr — enables the ADX-based trend-strength check and sets its calculation length and minimum threshold.
  • Breakout Ovr / Ovr ATR Mult — enables the override and sets the ATR multiple of single-bar price change required to force a flip through the filters.
  • Show Trade Levels / SL, TP1, TP2, TP3 ATR Mult — enables the trade-level drawing tool and sets each level's distance from entry as a multiple of ATR.
  • Bar Coloring, Bull/Bear Marks, Cloud Fill, Cloud MA Len, Cloud Transp — visual toggles and parameters controlling gradient candles, signal labels, and the cloud fill between trend line and reference average.
  • Show Dash, Dash X, Dash Y — toggles the dashboard and sets its screen position.
  • Long/Short/Close Action inputs — customizable text strings inserted into the "action" field of each alert's JSON payload, for direct use with automated webhook execution systems.
  • Colors group — full color customization for bull/bear/neutral states, label text, warning banner, dashboard theme, gradient candle tiers, and trade-level line colors.


🔍 Deconstruction of the Underlying Scientific and Academic Framework

The trailing-band mechanism draws on the same volatility-normalized stop methodology popularized by Chandelier Exit-style systems, which themselves extend J. Welles Wilder's Average True Range concept into an adaptive trailing stop: rather than a fixed price distance, the stop distance breathes with recently realized volatility, tightening in calm markets and widening in turbulent ones.

The Kalman filter option applies a classical state-space estimation technique originally developed for aerospace tracking problems (Rudolf Kálmán, 1960). It treats the "true" price trend as an unobserved state to be estimated from noisy observations, recursively updating a prediction and its uncertainty at each time step and weighting new information by a gain term derived from the relative magnitude of prediction versus measurement uncertainty. Applied to price series, it produces a smoothed estimate that adapts its own responsiveness based on the ongoing balance of signal versus noise.

The LLAMA adaptive average is built on an efficiency-ratio concept in the lineage of Perry Kaufman's Adaptive Moving Average research: the ratio of net directional displacement to total path length over a window quantifies how "efficiently" price has trended, and this ratio is used to interpolate the smoothing constant between fast and slow exponential-average bounds. Markets that trend efficiently receive a fast, responsive average; markets that chop inefficiently receive a slow, heavily smoothed one.

The Slope Filter applies ordinary least squares (OLS) linear regression across a short trend-line window to extract a first-derivative estimate (slope) of the trend line's trajectory, normalizing it by ATR so the threshold behaves consistently across instruments and volatility regimes of different scale.

The ADX Filter is grounded in Wilder's Directional Movement System, which decomposes price movement into positive and negative directional components and derives a smoothed trend-strength oscillator independent of direction — a standard framework for distinguishing trending from ranging conditions.

The Range Filter's use of percentile-rank classification reflects a basic non-parametric statistical approach: rather than assuming a normal distribution of high-low ranges, it empirically ranks the current range against its own recent historical distribution, which is more robust to the fat-tailed, non-normal behavior typically observed in financial return and range series.

Collectively, the six-factor consensus mechanism reflects a general principle from ensemble/multi-condition filtering: requiring independent, structurally uncorrelated confirmations to agree (or, here, requiring none to actively veto) before acting on a signal tends to reduce the false-positive rate relative to any single condition acting alone, at the cost of some responsiveness — a classic precision/recall tradeoff which the Breakout Override is specifically designed to mitigate during high-volatility regimes.

⚠️ Disclaimer
All provided scripts and indicators are strictly for educational exploration and must not be interpreted as financial advice or a recommendation to execute trades. We expressly disclaim all liability for any financial losses or damages that may result, directly or indirectly, from the reliance on or application of these tools. Market participation carries inherent risk where past performance never guarantees future returns, leaving all investment decisions and due diligence solely at your own discretion.

Declinazione di responsabilità

Le informazioni e le pubblicazioni non sono intese come, e non costituiscono, consulenza o raccomandazioni finanziarie, di investimento, di trading o di altro tipo fornite o approvate da TradingView. Per ulteriori informazioni, consultare i Termini di utilizzo.