Indicator · Pine Script v6 · Own pane

MAD Supertrend

by vedkanani123

A separate-pane indicator that builds a Supertrend-style trailing channel from median absolute deviation instead of ATR, scaled to standard-deviation units.

View on GitHub

GitHub stars1on the repository
Pine versionv6current
Lines of code139
Settings15inputs
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

139 lines of Pine Script v6 from indicator/olg_7_6_26/ALL_2/codex/indicator/MAD Supertrend ~ C H I P A_14.txt, published under MPL-2.0 (file header). Keep the author's credit and licence lines when you reuse it.

MAD Supertrend ~ C H I P A_14.txt
// This Pine Script™ code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
//@version=6
indicator("MAD Supertrend ~ C H I P A", overlay=false)

// > ——— Inputs ——— < \\
gg          = "!! MAD ST !!"
src         = input.source(close, "Source", group = gg)
madLen      = input.int(20, "MAD Length", minval=2, group = gg)
multUp      = input.float(1.8, "Upper MAD Multiplier", step=0.05, group = gg)
multDn      = input.float(0.7, "Lower MAD Multiplier", step=0.05, group = gg)
madMode     = input.string("Median", "MAD Estimator", options=["Median", "Mean"], tooltip = "Median = true MAD (most robust). Mean = average absolute deviation (slightly smoother).", group = gg)
smoothDev   = input.int(6, "MAD Smoothing", minval=0, tooltip = "Set to '0' to turn off", group = gg)

gc          = "!! CENTERLINE !!"
centerMode  = input.string("Double Median", "Centerline Mode", options=["Source", "Single Median", "Double Median"], group = gc)
medLen1     = input.int(45, "First Median Length", minval=1, group = gc)
medLen2     = input.int(1, "Second Median Length (Smoother)", minval=1, group = gc)

ga          = "!! EXIT ACCEL !!"
useAccel    = input.bool(true, "Accelerate exit trail with trend age", group = ga)
accelStep   = input.float(0.05, "Acceleration per new extreme", step=0.01, group = ga)
minMultFrac = input.float(0.45, "Minimum multiplier fraction", step=0.05, minval=0.1, maxval=1.0, tooltip = "Exit trail can tighten down to this fraction of its base multiplier", group = ga)

// > ——— Volatility core (MAD) ——— < \\
med       = ta.median(src, madLen)
absDev    = math.abs(src - med)
firstMed  = ta.median(src, medLen1)
dblMed    = ta.median(firstMed, medLen2)
rawMad    = madMode == "Median" ? ta.median(absDev, madLen) : ta.sma(absDev, madLen)
// 1.4826 ≈ consistency constant: scales MAD to stdev-equivalent units,
// so the multiplier behaves like the StdDev Supertrend's
madVol    = rawMad * 1.4826
vol       = smoothDev > 0 ? ta.ema(madVol, smoothDev) : madVol

// > ——— Basic bands around the selected centerline ——— < \\
basis      = centerMode == "Source" ? src : centerMode == "Single Median" ? firstMed : dblMed

// > ——— Exit trail acceleration (PSAR-style, keyed to new extremes) ——— < \\
var int   dir     = 1
var float accel   = 0.0
var float extreme = na

newExtreme = dir == 1 ? (na(extreme) or close > extreme) : (na(extreme) or close < extreme)
if newExtreme
    extreme := close
    accel   := math.min(accel + accelStep, 1.0 - minMultFrac)

tight = useAccel ? (1.0 - accel) : 1.0
effUp = dir == -1 ? multUp * tight : multUp   // exit trail when short
effDn = dir ==  1 ? multDn * tight : multDn   // exit trail when long

upperBasic = basis + effUp * vol
lowerBasic = basis - effDn * vol

// > ——— Supertrend-style trailing logic ——— < \\
var float upper = na
var float lower = na

upper := if na(upper)
    upperBasic
else
    (upperBasic < upper or close[1] > upper) ? upperBasic : upper

lower := if na(lower)
    lowerBasic
else
    (lowerBasic > lower or close[1] < lower) ? lowerBasic : lower

dir := dir == -1 and close > upper ? 1 :
       dir ==  1 and close < lower ? -1 : dir

if ta.change(dir) != 0
    accel   := 0.0
    extreme := close

trendLine = dir == 1 ? lower : upper

// > ——— Colors ——— < \\
upCol   = color.rgb(0, 180, 255)
dnCol   = color.rgb(255, 80, 60)
lineCol = dir == 1 ? upCol : dnCol
barCol  = dir == 1 ? color.new(upCol, 40) : color.new(dnCol, 60)

// > ——— Main Chart ——— < \\

// ——— Main chart: price ↔ trend fill (unique names) ———
useDir_mainFill   = input.bool(true,  "Directional color (main fill)")
atrLen_mainFill   = 80
strength_mainFill = 12

// plot handles (distinct)
pTrend_main = plot(trendLine, title="MAD Supertrend (main)", color=lineCol, linewidth=2, force_overlay = true)
pPrice_main = plot(close,     title="Price (fill ref, main)", color=color.new(color.gray, 100), force_overlay = true)  // invisible

// adaptive alpha (distinct vars)
gap_main   = math.abs(close - trendLine)
norm_main  = ta.atr(atrLen_mainFill) * strength_mainFill
ratio_main = norm_main > 0 ? math.min(1.0, gap_main / norm_main) : 0.0
alpha_main = 95 - math.round(25 * ratio_main)  // 95=faint → 70=stronger

fillColor_main = useDir_mainFill
     ? color.new(close >= trendLine ? color.new(upCol, 40) : color.new(dnCol, 60), alpha_main)
     : color.new(color.gray, alpha_main)

fill(pTrend_main, pPrice_main, fillColor_main, title="Price↔Trend fill (main)")

// > ——— Secondary Pane ——— < \\

mbu = plot(upper, title="Upper Trail", color=color.new(color.gray, 100), linewidth=1)
mbl = plot(lower, title="Lower Trail", color=color.new(color.gray, 100), linewidth=1)

atrLen   = 80
strength = 12

gap   = math.abs(upper - lower)
norm  = ta.atr(atrLen) * strength
ratio = norm > 0 ? math.min(1.0, gap / norm) : 0.0
alpha = 95 - math.round(25 * ratio)
fill(mbu, mbl, color.new(dir == 1 ? upCol : dnCol, alpha), title="Rails fade")

// ——— Robustness view: MAD vs StdDev volatility ratio ———
showVolRatio = input.bool(false, "Show MAD/StdDev ratio line", tooltip = "Below 1.0 = outliers inflating stdev; MAD is holding steady")
sdVol    = ta.stdev(src, madLen)
volRatio = sdVol > 0 ? madVol / sdVol : 1.0
plot(showVolRatio ? volRatio : na, title="MAD/StdDev Ratio", color=color.new(color.yellow, 30), linewidth=1, display=display.pane)

showPaneCandles = input.bool(true, "Draw candles in pane")
o1 = showPaneCandles ? open  : na
h1 = showPaneCandles ? high  : na
l1 = showPaneCandles ? low   : na
c1 = showPaneCandles ? close : na
plotcandle(o1, h1, l1, c1, color=barCol, bordercolor=barCol, wickcolor=barCol, title="Pane Candles", force_overlay = false)

// > ——— Alerts ——— < \\
longFlip  = barstate.isconfirmed and ta.change(dir) != 0 and dir == 1
shortFlip = barstate.isconfirmed and ta.change(dir) != 0 and dir == -1

alertcondition(longFlip,  "MAD ST flip → LONG",  "MAD Supertrend flipped to LONG")
alertcondition(shortFlip, "MAD ST flip → SHORT", "MAD Supertrend flipped to SHORT")

Overview

The centerline can be the source, a single median or a double median, and upper and lower multipliers are set separately. An optional exit-trail acceleration tightens the stop with trend age after each new extreme. It can draw candles in the pane and a MAD to standard deviation ratio line. Colours follow the active direction.

Details

Published by

vedkanani123 on GitHub

Type

Indicator, Pine Script v6

Draws

Separate pane below the 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
MAD Lengthint20madLen
Upper MAD Multiplierfloat1.8multUp
Lower MAD Multiplierfloat0.7multDn
MAD EstimatorstringMedianmadMode
MAD Smoothingint6smoothDev
Centerline ModestringDouble MediancenterMode
First Median Lengthint45medLen1
Second Median Length (Smoother)int1medLen2
Accelerate exit trail with trend agebooltrueuseAccel
Acceleration per new extremefloat0.05accelStep
Minimum multiplier fractionfloat0.45minMultFrac
Show all 15 settings
SettingTypeDefaultVariable
Directional color (main fill)booltrueuseDir_mainFill
Show MAD/StdDev ratio lineboolfalseshowVolRatio
Draw candles in panebooltrueshowPaneCandles
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

This indicator plots a Supertrend-based trend-following setup in a separate pane and skips conditions it treats as a sideways market. A volatility range is built from an ATR value, with RMA, SMA, EMA, or WMA smoothing, or from a fixed point distance. Optional

Indicator v5 TrendVolatility & bands
Updated 1 year ago · MPL-2.0 GitHub repository of Trend Following Setup - Sideways Market Skipper
147 stars

This indicator generates trade entry signals and target levels optimized for 1-hour timeframes, designed for external signal extraction. It calculates 7-period and 16-period EMAs alongside 10-period RSI and ATR filters. Long signals occur when the fast EMA cro

Indicator v5 TrendOscillators & momentum
Updated 6 weeks ago · MIT GitHub repository of Signal Strategy 100 Candles of 1H Timeframe

MultiIndicator

by capissimo
114 stars

MultiIndicator combines multiple technical indicators into a single separate pane to save chart space. It calculates and displays market regime detection based on ordinary least squares regression, a Holt exponential smoothing crossover, normalized RSI, ADX, a

Indicator v4 Oscillators & momentumTrend
Updated 1 year ago · None stated GitHub repository of MultiIndicator

This indicator plots an oscillator in a separate pane. It builds several SuperTrend series across a user-defined factor range and step, using ATR as the band width. On each bar it measures the distance between the close and each SuperTrend output, then groups

Indicator v5 TrendVolatility & bands
Updated 2 years ago · GPL-3.0 GitHub repository of AI SuperTrend Clustering Oscillator [LuxAlgo]

Choppiness Index

by mihakralj
99 stars

The script plots the Choppiness Index in a separate pane. It sums true range over a lookback and compares that sum with the highest-high to lowest-low range, then scales the result from 0 to 100. Lower readings indicate a trending market and higher readings in

Indicator v6 TrendVolatility & bands
Updated 4 weeks ago · Apache-2.0 GitHub repository of Choppiness Index

This indicator combines Chaikin Money Flow (CMF), a SuperTrend baseline, and an Average True Range (ATR) calculation inside a separate sub-pane. It calculates a standard 20-period CMF plotted as a line and colored histogram columns around a zero baseline, trac

Indicator v6 TrendVolume
Updated 6 months ago · Apache-2.0 GitHub repository of Institutional View: CMF & SuperTrend

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