Indicator · Pine Script v6 · Own pane

MAD Adaptive Trend Score [BackQuant]

by theonetrade· code credited to BackQuant

MAD Adaptive Trend Score calculates a robust trend persistence oscillator in a separate chart pane using a Median Absolute Deviation (MAD) adaptive filter.

View on GitHub

GitHub stars34on the repository
Pine versionv6current
Lines of code138
Settings15inputs
LicenceMIT
Last update2 weeks ago8 Nov 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

138 lines of Pine Script v6 from assets/indicator/bit-exact/mad_adaptive_trend_score_backquant_PlQjuEoQ.pine, published under MIT. Keep the author's credit and licence lines when you reuse it.

mad_adaptive_trend_score_backquant_PlQjuEoQ.pine
// 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("MAD Adaptive Trend Score [BackQuant]", shorttitle = "MAD Trend Score [BackQuant]", overlay=false)

// Constants
const string calc  = "Core Calculation Settings"
const string thres = "Signal Settings"
const string ui    = "Plotting and Coloring"
const color GREEN  = #00ff00
const color RED    = #ff0000

// Inputs
float src = input.source(close, "Source", group=calc)
int madLen = input.int(15, "MAD Length", minval=3, group=calc, tooltip="Length used for the rolling median and Median Absolute Deviation.")
float madMult = input.float(5.2, "MAD Multiplier", minval=0.1, step=0.1, group=calc, tooltip="Controls how far price may move away from the rolling median. Lower values suppress more noise. Higher values follow price more closely.")
int scoreStart = input.int(1, "Score Lookback Start", inline="SL", group=calc)
int scoreEnd = input.int(45, "End", maxval=50, inline="SL", group=calc, tooltip="Range of bars used for the directional persistence score.")

bool showRefs = input.bool(true, "Show Reference Lines", group=thres)
bool showSignals = input.bool(true, "Show Signals on Chart?", group=thres)
int longThres = input.int(40, "Long Threshold", group=thres, inline="TH")
int shortThres = input.int(-6, "Short Threshold", group=thres, inline="TH")

color longCol = input.color(GREEN, "Long Color", group=ui, inline="col")
color shortCol = input.color(RED, "Short Color", group=ui, inline="col")
int lineW = input.int(5, "Line Width", group=ui)
bool showSmooth = input.bool(false, "Show MAD Filter on Chart?", group=ui)
bool paintCandles = input.bool(true, "Paint Candles to Trend?", group=ui)
bool bgCol = input.bool(false, "Background Color?", group=ui)

// Helpers
method transp(color x, int t) =>
    color.new(x, t)

/////////////////////////////////////////////////////////////// © BackQuant ///////////////////////////////////////////////////////////////

// Exact Rolling Median + MAD
madStats(float source, simple int length) =>
    array<float> values = array.new_float()

    for i = 0 to length - 1
        if not na(source[i])
            array.push(values, source[i])

    float median = array.size(values) > 0 ? array.median(values) : na
    array<float> deviations = array.new_float()

    if not na(median)
        for i = 0 to array.size(values) - 1
            array.push(deviations, math.abs(array.get(values, i) - median))

    float mad = array.size(deviations) > 0 ? array.median(deviations) : na
    [median, mad]

/////////////////////////////////////////////////////////////// © BackQuant ///////////////////////////////////////////////////////////////

// MAD Calculation
[medianValue, rawMad] = madStats(src, madLen)

// Scale MAD to a standard-deviation-like measure
float scaledMad = math.max(rawMad * 1.4826, syminfo.mintick)

// Allow price to move around the median only within the MAD envelope
float deviation = src - medianValue
float maxDeviation = scaledMad * madMult
float clippedDeviation = math.max(-maxDeviation, math.min(maxDeviation, deviation))

// MAD Adaptive Filter
float madFilt = medianValue + clippedDeviation

/////////////////////////////////////////////////////////////// © BackQuant ///////////////////////////////////////////////////////////////

// Score the MAD filter's directional persistence
float scoreS = 0.0

for i = scoreStart to scoreEnd
    scoreS += madFilt > madFilt[i] ? 1.0 : -1.0

// Signal State
var int signal = 0

float prevScore = nz(scoreS[1], scoreS)
bool longCond = scoreS > longThres
bool shortCond = prevScore >= shortThres and scoreS < shortThres

if longCond and not shortCond
    signal := 1
else if shortCond
    signal := -1

// Color State
color col = signal == 1 ? longCol : shortCol

/////////////////////////////////////////////////////////////// © BackQuant ///////////////////////////////////////////////////////////////
// Plotting

// Score line in pane
plot(scoreS, "Trend Score", col, lineW)

// Reference lines
if barstate.islast and showRefs
    line.new(last_bar_index, longThres, bar_index - 1, longThres, color=chart.fg_color.transp(50), style=line.style_dashed, extend=extend.right)
    line.new(last_bar_index, shortThres, bar_index - 1, shortThres, color=chart.fg_color.transp(50), style=line.style_dashed, extend=extend.right)

// MAD Filter on chart
plot(madFilt, "MAD Adaptive Filter", col, 2, plot.style_line, force_overlay=true,
     display=showSmooth ? display.all : display.none)

// Candle painting
plotcandle(open, high, low, close, "Trend Candles",
     col, col, true,
     bordercolor=col,
     display=paintCandles ? display.all : display.none, force_overlay=true)

// Background
bgcolor(bgCol ? col.transp(80) : na, force_overlay=true)

// Signals
plotshape(signal == 1 and signal[1] == -1, "Long Signal", shape.triangleup, location.belowbar, longCol, 0, "𝕃", longCol, true, size.small,
     display=showSignals ? display.all : display.none, force_overlay=true)

plotshape(signal == -1 and signal[1] == 1, "Short Signal", shape.triangledown, location.abovebar, shortCol, 0, "𝕊", shortCol, true, size.small,
     display=showSignals ? display.all : display.none, force_overlay=true)

/////////////////////////////////////////////////////////////// © BackQuant ///////////////////////////////////////////////////////////////
// Data Window

plot(medianValue, "Rolling Median", display=display.data_window)
plot(rawMad, "Raw MAD", display=display.data_window)
plot(scaledMad, "Scaled MAD", display=display.data_window)

/////////////////////////////////////////////////////////////// © BackQuant ///////////////////////////////////////////////////////////////
// Alerts

alertcondition(signal == 1 and signal[1] == -1, title="MAD Trend Score Long", message="MAD Adaptive Trend Score Long {{exchange}}:{{ticker}}")
alertcondition(signal == -1 and signal[1] == 1, title="MAD Trend Score Short", message="MAD Adaptive Trend Score Short {{exchange}}:{{ticker}}")

Overview

MAD Adaptive Trend Score [BackQuant] computes a rolling median and scaled MAD envelope to constrain price noise, then evaluates the filter's directional persistence over a specified lookback range. The resulting score is compared against customizable long and short thresholds to identify trend shifts and signals. Key settings adjust MAD length, MAD multiplier, lookback bounds, signal thresholds, and bar or background coloring.

Details

Published by

theonetrade on GitHub

Code credit

BackQuant, as written in the script's header

Draws

Separate pane below the chart

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.

Topics

algorithmic-tradingbacktestingbitcoinccxtcrypto-tradingllm-agentoffline-backtestingopen-source-tradingpine-scriptpine-to-pythonpinescriptpynecorepythonquantquantitative-financestrategy-backtestingtechnical-analysistrading-indicatorstrading-strategiestradingview

Settings

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

SettingTypeDefaultVariable
Sourcesourceclosesrc
MAD Lengthint15madLen
MAD Multiplierfloat5.2madMult
Score Lookback Startint1scoreStart
Endint45scoreEnd
Show Reference LinesbooltrueshowRefs
Show Signals on Chart?booltrueshowSignals
Long Thresholdint40longThres
Short Thresholdint-6shortThres
Long ColorcolorGREENlongCol
Short ColorcolorREDshortCol
Line Widthint5lineW
Show all 15 settings
SettingTypeDefaultVariable
Show MAD Filter on Chart?boolfalseshowSmooth
Paint Candles to Trend?booltruepaintCandles
Background Color?boolfalsebgCol
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

Schaff Trend Cycle

by everget
947 stars

This indicator plots the Schaff Trend Cycle in a separate pane. It subtracts a slow exponential moving average from a fast one, applies a stochastic cycle twice, and smooths each result to form a 0–100 oscillator. Line color follows the slope, or the upper and

Indicator v4 Oscillators & momentumTrend
Updated 5 weeks ago · GPL-3.0 GitHub repository of Schaff Trend Cycle

Beep Boop

by magic8bot
408 stars

This indicator calculates a modified MACD oscillator and signal line alongside a trend EMA filter, plotting the output as a stylized column histogram in a separate pane. Instead of plotting true MACD distance, it quantifies positive and negative histogram mome

Indicator v4 Oscillators & momentumTrend
Updated 3 years ago · MIT GitHub repository of Beep Boop

[RS]Standardized Trend Map

by ricardosantos79
261 stars

Standardized Trend Map calculates series momentum relative to active price range across 40 distinct lookback periods ranging from 2 to 80 bars on an exponential moving average source. Each standardized calculation rounds to an integer values of -1, 0, or 1 to

Indicator v4 TrendOscillators & momentum
Updated 5 years ago · None stated GitHub repository of [RS]Standardized Trend Map
228 stars

Multi-Timeframe Analysis Suite calculates trend direction and momentum conditions across five user-selected timeframes using moving averages, RSI, and Stochastic oscillators. It evaluates moving average slope and oscillator levels to compute trend alignment, m

Indicator v6 Screeners & dashboardsTrend
Updated 4 months ago · None stated GitHub repository of Multi-Timeframe Analysis Suite

ADX Histogram

by harryguiacorn
220 stars

This indicator calculates and displays the Average Directional Index (ADX) as a column histogram in a separate pane. It evaluates market trend strength by calculating directional movement metrics based on specified smoothing and DI length inputs. When the ADX

Indicator v5 TrendOscillators & momentum
Updated 1 year ago · None stated GitHub repository of ADX Histogram

More Trend scripts

Related on ForexR

Trade Your Charts With a Regulated Broker

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

Compare brokers