// 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.
SuperTrend with divergence-adjusted ATR multiplier
The inputs you can change from the gear icon on the chart. Defaults are the author's.
Setting
Type
Default
Variable
ATR Length
int
10
atrLen
Base ATR Multiplier
float
3.0
baseFactor
Pivot Length (Left/Right)
int
2
pivotLength
Divergence Sensitivity
float
0.3
divSensitivity
Color bars by trend
bool
true
colorBarsEnabled
Uptrend Color (Bullish)
color
color.rgb(6, 162, 47)
upColor
Downtrend Color (Bearish)
color
color.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.
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
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
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
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
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.
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