Indicator · Pine Script v6 · On the chart

SuperTrend Weighted by Divergence

by anil-sn

A chart-overlay SuperTrend variant whose ATR multiplier shrinks for a limited number of bars after a divergence is found.

View on GitHub

GitHub stars1on the repository
Pine versionv6current
Lines of code271
Settings7inputs
LicenceNone statedfile: MPL-2.0
Last update9 months ago5 Jan 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

271 lines of Pine Script v6 from pinecode/Referance/SuperTrend Weighted by Divergence.pine, published under MPL-2.0 (file header). Keep the author's credit and licence lines when you reuse it.

SuperTrend Weighted by Divergence.pine
// This Pine Script® code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// █ OVERVIEW
// SuperTrend Weighted by Divergence is a trend-following indicator based on the classic SuperTrend, enhanced with dynamic ATR weighting driven by divergences. Its key feature is adaptive behavior: when a divergence appears, the indicator temporarily reduces the ATR multiplier, allowing the trend line to react faster to potential market reversals.
// The indicator remains clean, visually clear, and well suited for traders who want to combine trend-following with early detection of weakening momentum.
// 
// █ CONCEPT
// One of the biggest drawbacks of trend indicators is their lagging nature, caused by the characteristics of source data. Classic SuperTrends react only after the trend has already developed, which often leads to late entries or exits.
// 
// The idea behind SuperTrend Weighted by Divergence is to introduce dynamic adjustment of the trend line in response to the first signs of trend weakening.
// Instead of treating ATR as a constant volatility buffer, the indicator temporarily modifies its impact when the market sends warning signals in the form of price–oscillator divergences.
// 
// For divergence detection, a hidden auxiliary oscillator called “MPO4 Lines – Modal Engine” (default settings) is used. This oscillator is not displayed on the chart – only the points where divergences are detected are shown as markers on price bars.
// Divergences do not generate direct entry signals; they are used solely to temporarily adjust the behavior of the SuperTrend.
// 
// If, after detecting a divergence against the current trend, a divergence in line with the trend appears, the previous divergence is invalidated and the SuperTrend returns to its standard behavior (base ATR multiplier).
// 
// █ FEATURES
// Data sources:
// - ATR (Average True Range)
// - Reference point: HL2 (high/low average)
// - MPO4 Lines – Modal Engine oscillator (hidden, used only for divergence detection)
// 
// Divergence logic:
// - Bullish divergence: lower low in price + higher low in the oscillator
// - Bearish divergence: higher high in price + lower high in the oscillator
// - Divergences are detected using pivots (left/right)
// - Divergence detection is delayed by the pivot length, as confirmation requires a fixed number of bars on the right side
// 
// Divergence impact:
// - After a divergence is detected, the ATR multiplier is reduced
// - The reduction strength is controlled by Divergence Sensitivity
// - The effect is active only for a limited number of bars – 200 bars by default (divBars)
// - The effect is canceled on trend change or when a trend-aligned divergence appears
// 
// Trend change logic:
// - Trend changes only after a confirmed close beyond the trailing line
// - No repainting
// - Trend lines break at reversal points
// 
// Visual signals:
// - “Buy” and “Sell” labels only on confirmed trend changes
// - Optional bar coloring based on current trend (Color bars by trend)
// - Soft fill between price and the trend line
// - Divergence markers (dots above/below bars) shown at the point of divergence detection, not across the entire divergence structure
// 
// Alerts:
// - Buy Signal – trend change to bullish
// - Sell Signal – trend change to bearish
// - Bullish Divergence
// - Bearish Divergence
// 
// █ HOW TO USE
// Adding the indicator:
// Paste the code into Pine Editor or search for “SuperTrend Weighted by Divergence” on TradingView
// 
// Main settings:
// - ATR Length – ATR period
// - Base ATR Multiplier – base SuperTrend width
// - Pivot Length – divergence sensitivity and detection delay
// - Divergence Sensitivity – strength of divergence impact (0.0–1.0)
// - Color bars by trend – enable / disable bar coloring
// - Line and fill colors – fully customizable
// 
// Interpretation:
// - Green line and bars = uptrend
// - Red line and bars = downtrend
// - Divergence against the trend = possible weakening and faster SuperTrend reaction
// - Trend-aligned divergence = return to standard SuperTrend behavior
// - No divergence = classic, stable SuperTrend behavior
// 
// █ APPLICATIONS
// Ideal for:
// - Trend-following
// Entering positions only in the direction of the current trend, using the SuperTrend as a directional filter.
// - Early detection of trend weakness
// Repeated divergences against the trend may indicate decreasing momentum and a potential upcoming reversal.
// - Markets with variable dynamics (crypto, indices, forex)
// Entries based on trend changes, preferably confirmed by other tools such as Fibonacci levels, RSI, support/resistance, or market structure.
// - Scalping, day trading, and swing trading (with parameter adjustments)
// Increasing Divergence Sensitivity to around 0.4–0.5 produces many more signals on small, often short-lived moves.
// These settings work well for scalping and day trading, but are not ideal for swing trading, as they tend to generate more false signals and frequent trend changes.
// 
// █ NOTES
// - Works on all markets and timeframes
// - Divergences are used to adapt SuperTrend behavior, not as standalone entry signals
// - Higher Divergence Sensitivity = faster reaction and more signals
// - Lower Divergence Sensitivity = smoother trend and fewer changes
// - Best results are achieved by tuning parameters to the instrument and trading style
// 

//@version=6
indicator("SuperTrend Weighted by Divergence", overlay=true, max_lines_count=500, max_labels_count=500)

// INPUT SETTINGS
atrLen         = input.int(10, "ATR Length", minval=1)
baseFactor     = input.float(3.0, "Base ATR Multiplier", minval=0.1, step=0.1)
pivotLength    = input.int(2, "Pivot Length (Left/Right)", minval=1)
divSensitivity = input.float(
     0.3,
     "Divergence Sensitivity",
     minval=0.0,
     maxval=1.0,
     step=0.01,
     tooltip="0.0 = No divergence influence\n1.0 = Maximum ATR multiplier reduction (strongest effect)"
)

colorBarsEnabled = input.bool(true, "Color bars by trend", group="Color Settings")

// COLOR SETTINGS
upColor   = input.color(color.rgb(6, 162, 47), "Uptrend Color (Bullish)")
downColor = input.color(color.rgb(207, 23, 23), "Downtrend Color (Bearish)")

// FIXED PARAMETERS
confirmBars         = 1
len2                = 6
smoothLen2          = 7
calculateDivergence = true
showLine            = true
fillShade           = true
divBars             = 200

// MPO4 OSCILLATOR FUNCTION
calcCPO(_len, _smooth) =>
    body      = math.abs(close - open)
    avgBody   = ta.sma(body, _len)
    direction = close > open ? 1.0 : close < open ? -1.0 : 0.0
    weight    = avgBody != 0 ? body / avgBody : 1.0
    contrib   = direction * weight
    rolling   = 0.0
    for i = 0 to _len - 1
        rolling += contrib[i]
    norm = rolling / (_len * 2) * 100
    ta.ema(norm, _smooth)

osc = calcCPO(len2, smoothLen2)

// DIVERGENCE CALCULATION
lookbackRight = pivotLength
lookbackLeft  = pivotLength

pivotHighOsc = ta.pivothigh(osc, lookbackLeft, lookbackRight)
pivotLowOsc  = ta.pivotlow(osc, lookbackLeft, lookbackRight)

var bool bullCond = false
var bool bearCond = false

oscLbr = osc[lookbackRight]

if calculateDivergence
    plFound  = not na(pivotLowOsc)
    oscHL    = oscLbr > ta.valuewhen(plFound, oscLbr, 1)
    priceLL  = low[lookbackRight] < ta.valuewhen(plFound, low[lookbackRight], 1)
    bullCond := priceLL and oscHL and plFound

    phFound  = not na(pivotHighOsc)
    oscLH    = oscLbr < ta.valuewhen(phFound, oscLbr, 1)
    priceHH  = high[lookbackRight] > ta.valuewhen(phFound, high[lookbackRight], 1)
    bearCond := priceHH and oscLH and phFound

bullDiv = bullCond
bearDiv = bearCond

// ATR AND SUPERTREND BASE
atr = ta.atr(atrLen)
hl2 = (high + low) / 2

var float trailLong  = na
var float trailShort = na
var int   regime     = 0

trailLong  := na(trailLong)  ? hl2 : trailLong
trailShort := na(trailShort) ? hl2 : trailShort

var int bullCount = 0
var int bearCount = 0

bullCount := close > trailShort ? bullCount + 1 : 0
bearCount := close < trailLong  ? bearCount + 1 : 0

// TREND FLIP LOGIC
nextRegime = regime

if regime == 0
    if bullCount >= confirmBars
        nextRegime := 1
    else if bearCount >= confirmBars
        nextRegime := -1
else if regime == 1 and bearCount >= confirmBars
    nextRegime := -1
else if regime == -1 and bullCount >= confirmBars
    nextRegime := 1

flipHappens = nextRegime != regime

// DIVERGENCE IMPACT LOGIC
var int divAge  = 9999
var int divType = 0

if bullDiv
    divAge  := 0
    divType := 1
else if bearDiv
    divAge  := 0
    divType := -1
else if flipHappens
    divAge  := 9999
    divType := 0
else
    divAge += 1

divActive = divAge <= divBars and divType == -nextRegime

factorAdjusted = baseFactor
if divActive and not flipHappens
    factorAdjusted := baseFactor * (1 - divSensitivity)

// SUPERTREND BANDS AND TRAILS
bandTop = hl2 + factorAdjusted * atr
bandBot = hl2 - factorAdjusted * atr

if nextRegime == 1
    trailLong  := math.max(bandBot, nz(trailLong[1], bandBot))
    trailShort := bandTop
else if nextRegime == -1
    trailShort := math.min(bandTop, nz(trailShort[1], bandTop))
    trailLong  := bandBot
else
    trailLong  := bandBot
    trailShort := bandTop

regime := nextRegime

// VISUALIZATION
plotLine = flipHappens ? na : (regime == 1 ? trailLong : trailShort)

pLine   = plot(plotLine, color = showLine ? color.new(regime == 1 ? upColor : downColor, 40) : na, linewidth = 2, style = plot.style_linebr)
pCenter = plot(hl2, display = display.none)

fill(
    pLine,
    pCenter,
    plotLine,
    hl2,
    fillShade ? color.new(regime == 1 ? upColor : downColor, 75) : na,
    fillShade ? color.new(regime == 1 ? upColor : downColor, 95) : na
)

// BUY / SELL LABELS
if flipHappens
    label.new(
        bar_index,
        regime == 1 ? low - atr * 0.5 : high + atr * 0.5,
        regime == 1 ? "Buy" : "Sell",
        color = color.new(regime == 1 ? upColor : downColor, 40),
        style = regime == 1 ? label.style_label_up : label.style_label_down,
        textcolor = color.white,
        size = size.small
    )

// BAR COLORING – teraz zależne od nowego inputu
barcolor(colorBarsEnabled ? (regime == 1 ? upColor : downColor) : na)

// DIVERGENCE MARKERS
plotshape(bullDiv, title="Bullish Divergence", location=location.belowbar, color=upColor, style=shape.circle, size=size.tiny)
plotshape(bearDiv, title="Bearish Divergence", location=location.abovebar, color=downColor, style=shape.circle, size=size.tiny)

// ALERTS
alertcondition(flipHappens and regime == 1, title="Buy Signal",  message="SuperTrend Buy Signal")
alertcondition(flipHappens and regime == -1, title="Sell Signal", message="SuperTrend Sell Signal")
alertcondition(bullDiv, title="Bullish Divergence", message="Bullish Divergence Detected")
alertcondition(bearDiv, title="Bearish Divergence", message="Bearish Divergence Detected")

Overview

Divergences are detected with pivots between price and a hidden oscillator, and shown as small markers. If a divergence in the trend direction follows, the effect is cancelled. Buy and sell labels appear on confirmed closes beyond the trailing line, with optional bar colouring and a soft fill. Settings cover ATR length, base factor, pivot length and sensitivity. Divergences are confirmed after the pivot length.

Details

Published by

anil-sn on GitHub

Draws

On the price 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.

Settings

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

SettingTypeDefaultVariable
ATR Lengthint10atrLen
Base ATR Multiplierfloat3.0baseFactor
Pivot Length (Left/Right)int2pivotLength
Divergence Sensitivityfloat0.3divSensitivity
Color bars by trendbooltruecolorBarsEnabled
Uptrend Color (Bullish)colorcolor.rgb(6, 162, 47)upColor
Downtrend Color (Bearish)colorcolor.rgb(207, 23, 23)downColor
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

Adaptive Fair Value Cloud calculates a volatility-adaptive fair value channel around a selectable centerline, such as KAMA, EMA, linear regression, or VWMA. It blends ATR and mean deviation with volatility percentiles and trend sensors, including ADX, Efficien

Indicator v6 Volatility & bandsTrend
Updated 2 days ago · MIT GitHub repository of Adaptive Fair Value Cloud [WavesUnchained]
2 stars

The Refined Multi-TF Crypto Analyzer plots technical analysis signals on the main price chart by combining multi-timeframe moving averages, RSI, ADX, and volume spikes. It checks for trend alignment between the chart timeframe and a higher timeframe, identifie

Indicator v6 TrendOscillators & momentum Repaints
Updated 1 year ago · None stated GitHub repository of Refined Multi-TF Crypto Analyzer

QQE + AK Trend + EFI

by realanthonyc
2 stars

This indicator computes and plots a QQE histogram using RSI of the chosen source smoothed with Wilder's ATR method, alongside an AK Trend line derived from fast EMAs with dynamic scale factors adjusted by timeframe. It also calculates Elder Force Index with ad

Indicator v6 TrendOscillators & momentum
Updated 10 months ago · MPL-2.0 GitHub repository of QQE + AK Trend + EFI

This indicator calculates Kaufman's Efficiency Ratio normalized by an ATR ratio to create a dynamic volatility-adjusted threshold. It classifies market states into uptrend, downtrend, choppy, or consolidation regimes and colors price chart bars accordingly. It

Indicator v6 TrendVolatility & bands
Updated 6 months ago · None stated GitHub repository of Adaptive Regime Filter + Divergence (AER-VN) [KEYALGOS]

Chandelier Exit

by everget
947 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

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