Indicator · Pine Script v6 · Own pane

Divergence Screener [Trendoscope®]

by theonetrade· code credited to Trendoscope

Divergence Screener [Trendoscope®] is a Pine Script v6 indicator that detects regular and hidden bullish or bearish divergences in a separate pane below the price chart.

View on GitHub

Repaints

GitHub stars34on the repository
Pine versionv6current
Lines of code260
Settings14inputs
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

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

divergence_screener_trendoscope_zewvHAvQ.pine
// This work is licensed under Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License (CC BY-NC-SA 4.0) https://creativecommons.org/licenses/by-nc-sa/4.0/
// © Trendoscope
//                                       ░▒             
//                                  ▒▒▒   ▒▒      
//                              ▒▒▒▒▒     ▒▒      
//                      ▒▒▒▒▒▒▒░     ▒     ▒▒          
//                  ▒▒▒▒▒▒           ▒     ▒▒          
//             ▓▒▒▒       ▒        ▒▒▒▒▒▒▒▒▒▒▒  
//   ▒▒▒▒▒▒▒▒▒▒▒ ▒        ▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒         
//   ▒  ▒       ░▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒░        
//   ▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒░▒▒▒▒▒▒▒▒         
//   ▓▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒ ▒▒                       
//    ▒▒▒▒▒         ▒▒▒▒▒▒▒                            
//                 ▒▒▒▒▒▒▒▒▒                           
//                ▒▒▒▒▒ ▒▒▒▒▒                          
//               ░▒▒▒▒   ▒▒▒▒▓      ████████╗██████╗ ███████╗███╗   ██╗██████╗  ██████╗ ███████╗ ██████╗ ██████╗ ██████╗ ███████╗
//              ▓▒▒▒▒     ▒▒▒▒      ╚══██╔══╝██╔══██╗██╔════╝████╗  ██║██╔══██╗██╔═══██╗██╔════╝██╔════╝██╔═══██╗██╔══██╗██╔════╝
//              ▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒        ██║   ██████╔╝█████╗  ██╔██╗ ██║██║  ██║██║   ██║███████╗██║     ██║   ██║██████╔╝█████╗ 
//             ▒▒▒▒▒       ▒▒▒▒▒       ██║   ██╔══██╗██╔══╝  ██║╚██╗██║██║  ██║██║   ██║╚════██║██║     ██║   ██║██╔═══╝ ██╔══╝  
//            ▒▒▒▒▒         ▒▒▒▒▒      ██║   ██║  ██║███████╗██║ ╚████║██████╔╝╚██████╔╝███████║╚██████╗╚██████╔╝██║     ███████╗
//             ▒▒             ▒                        
//@version=6
import Trendoscope/Drawing/3 as dr
import Trendoscope/Zigzag/11 as zg
import Trendoscope/oota/1 as eta
indicator('Divergence Screener [Trendoscope®]', 'DS1.1[Trendoscope®]', overlay = false, max_lines_count = 500, max_labels_count = 500, max_polylines_count = 100, calc_bars_count = 500)

oscillator(simple string type = 'rsi', simple int length = 14, float source = close, float highSource = high, float lowSource = low) =>
    oscillator = switch type
        'cci' => ta.cci(source, length)
        'cmo' => ta.cmo(source, length)
        'cog' => ta.cog(source, length)
        'mfi' => ta.mfi(source, length)
        'roc' => ta.roc(source, length)
        'rsi' => ta.rsi(source, length)
        'stoch' => ta.stoch(source, highSource, lowSource, length)
        'wpr' => ta.wpr(length)
        => ta.rsi(source, length)
    oscillator

oscillatorType = input.string('rsi', 'Oscillator', ['rsi', 'cci', 'cmo', 'cog', 'mfi', 'roc', 'stoch', 'wpr'], inline = 'osc', group = 'Oscillator', display = display.none)
length = input.int(14, '', group = 'Oscillator', inline = 'osc', tooltip = 'Built in Oscillator Type and Length', display = display.none)
useExternalOscillator = input.bool(false, 'Use External Oscillator', inline = 'eosc', group = 'Oscillator', display = display.none)
externalOscillator = input.source(close, '', 'Use external oscillator instead of the built ins', inline = 'eosc', group = 'Oscillator', display = display.none)

rsiColor = color.blue

trendTypeTooltip = 'Method to identify trend. \n' + '\tZigzag - HH, HL on the starting pivot of divergence line is considered as uptrend and LL, LH on the starting pivot of divergence line is considered as downtrend\n' + '\tMA Difference - Difference between moving average of divergence line pivot will define the trend\n' + '\tExternal - Use External Oscillator Input'
trendMethod = input.string('Zigzag', 'Trend Detection Method', ['Zigzag', 'MA Difference', 'External'], group = 'Trend', display = display.none, tooltip = trendTypeTooltip)
maType = input.enum(eta.CustomSeries.SMA, 'MA Filter', inline = 'ma', group = 'Trend', display = display.none)
maLength = input.int(200, '', minval = 5, step = 50, inline = 'ma', group = 'Trend', display = display.none, tooltip = 'Moving Average to identify trend. Direction of moving average between the divergence pivots identify trend')
externalTrendSignal = input.source(close, 'External Trend Signal', 'Use External trend signal instead of the built in. The external indicator should return positive value for uptrend and negative value for downtrend', group = 'Trend', display = display.none)

zigzagLength = input.int(13, 'Length', group = 'Zigzag', tooltip = 'Zigzag Length', display = display.none)

repaint = input.bool(true, 'Repaint', 'If selected, divergence lines repaint as per the latest info. ' + 'If repaint is disabled, then the divergence is calculated based on confirmed pivots only. ' + 'Hence, the signals will be delayed till the pivot is confirmed.', group = 'Miscellaneous', display = display.none)

bullishDivergenceAlert = input.bool(true, 'Bullish Divergence', 'Alert on bullish divergence', group = 'Alerts', display = display.none)
bullishHiddenDivergenceAlert = input.bool(true, 'Bullish Hidden Divergence', 'Alert on bullish hidden divergence', group = 'Alerts', display = display.none)
bearishDivergenceAlert = input.bool(true, 'Bearish Divergence', 'Alert on bearish divergence', group = 'Alerts', display = display.none)
bearishHiddenDivergenceAlert = input.bool(true, 'Bearish Hidden Divergence', 'Alert on bearish hidden divergence', group = 'Alerts', display = display.none)

textColor = chart.bg_color

trendMethodInt = trendMethod == 'Zigzag' ? 1 : trendMethod == 'External' ? 3 : 2
var map<int, float> priceMap = map.new<int, float>()
var map<int, float> oscillatorMap = map.new<int, float>()
priceMap.put(bar_index, close)

enum DivergenceType
    BullishDivergence = "Bullish Divergence"
    BearishDivergence = "Bearish Divergence"
    BullishHiddenDivergence = "Bullish Hidden Divergence"
    BearishHiddenDivergence = "Bearish Hidden Divergence"
    None = "None"

type DivergenceObject
    dr.Line priceLine
    dr.Line oscillatorLine
    dr.Label priceLabel
    dr.Label oscillatorLabel
    chart.point pricePoint
    DivergenceType divergenceType
    bool broken = false

method delete(DivergenceObject this)=>
    this.priceLine.delete()
    this.oscillatorLine.delete()
    this.priceLabel.delete()
    this.oscillatorLabel.delete()
    this

method draw(DivergenceObject this)=>
    this.delete()
    this.priceLine.draw()
    this.oscillatorLine.draw()
    this.priceLabel.draw()
    this.oscillatorLabel.draw()
    this

type ZigzagProperties
    color textColor = color.black
    int trendMethod = 1
    bool repaint = false

enum PivotDirection
    HH = "Higher High"
    LH = "Lower High"
    HL = "Higher Low"
    LL = "Lower Low"

getDivergenceType(direction, divergence)=>
    direction > 0?
         (divergence > 0 ? DivergenceType.BearishDivergence : DivergenceType.BearishHiddenDivergence):
         (divergence > 0 ? DivergenceType.BullishDivergence : DivergenceType.BullishHiddenDivergence)

getPivotDirection(dir, ratio) =>
    dir > 0 ? (ratio > 1 ? PivotDirection.HH : PivotDirection.LH) : ratio > 1 ? PivotDirection.LL : PivotDirection.HL

getLinePropertiesMap(bool force_overlay=false)=>
    linePropertiesMap = map.new<DivergenceType, dr.LineProperties>()
    linePropertiesMap.put(DivergenceType.BullishDivergence, dr.LineProperties.new(xloc.bar_time, extend.none, color.green, line.style_solid, 1, force_overlay))
    linePropertiesMap.put(DivergenceType.BearishDivergence, dr.LineProperties.new(xloc.bar_time, extend.none, color.red, line.style_solid, 1, force_overlay))
    linePropertiesMap.put(DivergenceType.BullishHiddenDivergence, dr.LineProperties.new(xloc.bar_time, extend.none, color.lime, line.style_solid, 1, force_overlay))
    linePropertiesMap.put(DivergenceType.BearishHiddenDivergence, dr.LineProperties.new(xloc.bar_time, extend.none, color.orange, line.style_solid, 1, force_overlay))
    linePropertiesMap

getLabelPropertiesMap(bool force_overlay=false)=>
    labelPropertiesMap = map.new<DivergenceType, dr.LabelProperties>()
    labelPropertiesMap.put(DivergenceType.BullishDivergence, dr.LabelProperties.new(xloc.bar_time, yloc.price, color.green, label.style_label_up, chart.bg_color, size.small, force_overlay = force_overlay))
    labelPropertiesMap.put(DivergenceType.BearishDivergence, dr.LabelProperties.new(xloc.bar_time, yloc.price, color.red, label.style_label_down, chart.bg_color, size.small, force_overlay = force_overlay))
    labelPropertiesMap.put(DivergenceType.BullishHiddenDivergence, dr.LabelProperties.new(xloc.bar_time, yloc.price, color.lime, label.style_label_up, chart.bg_color, size.small, force_overlay = force_overlay))
    labelPropertiesMap.put(DivergenceType.BearishHiddenDivergence, dr.LabelProperties.new(xloc.bar_time, yloc.price, color.orange, label.style_label_down, chart.bg_color, size.small, force_overlay = force_overlay))
    labelPropertiesMap

getAllowedDivergenceTypes()=>
    allowedDivergenceTypes = map.new<DivergenceType, bool>()
    allowedDivergenceTypes.put(DivergenceType.BullishDivergence, bullishDivergenceAlert)
    allowedDivergenceTypes.put(DivergenceType.BullishHiddenDivergence, bullishHiddenDivergenceAlert)
    allowedDivergenceTypes.put(DivergenceType.BearishDivergence, bearishDivergenceAlert)
    allowedDivergenceTypes.put(DivergenceType.BearishHiddenDivergence, bearishHiddenDivergenceAlert)
    allowedDivergenceTypes

const map<DivergenceType, bool> allowedDivergenceTypes = getAllowedDivergenceTypes()

const map<DivergenceType, dr.LineProperties> priceLinePropertiesMap = getLinePropertiesMap(true)
const map<DivergenceType, dr.LineProperties> oscillatorLinePropertiesMap = getLinePropertiesMap()

const map<DivergenceType, dr.LabelProperties> priceLabelPropertiesMap = getLabelPropertiesMap(true)
const map<DivergenceType, dr.LabelProperties> oscillatorLabelPropertiesMap = getLabelPropertiesMap()

method divergence(zg.Zigzag this, array<DivergenceObject> divergenceObjects, ZigzagProperties properties) =>
    startIndex = properties.repaint ? 0 : 1
    DivergenceType divergenceType = DivergenceType.None
    if this.zigzagPivots.size() > 2 + startIndex
        lastPivot = this.zigzagPivots.get(startIndex)
        llastPivot = this.zigzagPivots.get(startIndex + 2)
        skip = false
        if this.flags.updateLastPivot
            if divergenceObjects.size() > 0
                lastDivergence = divergenceObjects.last()
                divergenceStartBar = lastDivergence.priceLine.start.index
                llastPivotBar = llastPivot.point.index

                divergenceEndBar = lastDivergence.priceLine.end.index
                lastPivotBar = lastPivot.point.index
                if llastPivotBar == divergenceStartBar and lastPivotBar > divergenceEndBar
                    divergenceObjects.pop().delete()
                skip := llastPivotBar == divergenceStartBar and lastPivotBar == divergenceEndBar
                skip

        if this.flags.newPivot and not skip
            dir = math.sign(lastPivot.dir)
            lastOsc = lastPivot.point.price
            lastPrice = lastPivot.indicatorValues.get(0)
            oscRatio = lastPivot.ratio
            priceRatio = lastPivot.indicatorRatios.get(0)

            priceDirection = getPivotDirection(lastPivot.dir, priceRatio)
            oscillatorDirection = getPivotDirection(lastPivot.dir, oscRatio)

            lastTrend = lastPivot.indicatorValues.get(2)
            lastMa = lastPivot.indicatorValues.get(1)

            pricePoint = chart.point.new(lastPivot.point.time, lastPivot.point.index, lastPrice)
            oscillatorPoint = chart.point.new(lastPivot.point.time, lastPivot.point.index, lastPivot.point.price)

            if priceDirection != oscillatorDirection and llastPivot.indicatorRatios.size() > 0
                llastPrice = llastPivot.indicatorValues.get(0)
                llastRatio = llastPivot.indicatorRatios.get(0)
                llastMa = llastPivot.indicatorValues.get(1)
                lastPricePoint = chart.point.new(llastPivot.point.time, llastPivot.point.index, llastPrice)
                llastOscillatorPoint = chart.point.new(llastPivot.point.time, llastPivot.point.index, llastPivot.point.price)

                sentiment = math.sign(oscRatio - priceRatio)
                trend = properties.trendMethod == 3 ? math.sign(lastTrend) : properties.trendMethod == 1 ? math.sign(dir * (llastRatio - 1)) : math.sign(llastMa - lastMa)
                divergence = trend == dir and sentiment < 0 ? 1 : trend != dir and sentiment > 0 ? -1 : 0
                if divergence != 0
                    divergenceType := getDivergenceType(dir, divergence)
                    priceDivergenceLine = dr.Line.new(lastPricePoint, pricePoint, priceLinePropertiesMap.get(divergenceType))
                    oscillatorDivergenceLine = dr.Line.new(llastOscillatorPoint, oscillatorPoint, oscillatorLinePropertiesMap.get(divergenceType))

                    validDivergence = true
                    for bar = lastPricePoint.index + 1 to pricePoint.index - 1 by 1
                        priceAtBar = priceMap.get(bar)
                        oscillatorAtBar = oscillatorMap.get(bar)
                        if priceAtBar * dir > priceDivergenceLine.get_price(bar) * dir or oscillatorAtBar * dir > oscillatorDivergenceLine.get_price(bar) * dir
                            validDivergence := false
                            break

                    if validDivergence
                        priceLabelText = divergenceType == DivergenceType.BullishDivergence or divergenceType == DivergenceType.BearishDivergence ? 'D' : 'H'
                        priceTooltipText = str.tostring(divergenceType) + '\nPrice : ' + str.tostring(lastPrice) + ' ( ' + str.tostring(priceRatio) + ' ) - ' +
                                         str.tostring(priceDirection) + '\n' + 'Oscillator :' + str.tostring(lastMa) + ' ( ' + str.tostring(oscRatio) + ' ) - ' + str.tostring(oscillatorDirection)
                        priceDivergenceLabel = dr.Label.new(pricePoint, priceLabelText, priceTooltipText, priceLabelPropertiesMap.get(divergenceType))
                        oscillatorDivergenceLabel = dr.Label.new(oscillatorPoint, priceLabelText, priceTooltipText, oscillatorLabelPropertiesMap.get(divergenceType))
                        if allowedDivergenceTypes.get(divergenceType)
                            alert('Alert : ' + priceTooltipText, alert.freq_once_per_bar_close)
                        divergenceObject = DivergenceObject.new(priceDivergenceLine, oscillatorDivergenceLine,priceDivergenceLabel, oscillatorDivergenceLabel, pricePoint, divergenceType)
                        divergenceObject.delete()
                        divergenceObjects.push(divergenceObject.draw())
                        true
                    else
                        priceDivergenceLine.delete()
                        false
    divergenceType
ma = maType.ma(maLength)
oscillator = useExternalOscillator ? externalOscillator : oscillator(oscillatorType, length)
plot(oscillator, 'Oscillator')

oscillatorMap.put(bar_index, oscillator)
indicators = matrix.new<float>()
indicatorNames = array.from('Price', str.tostring(maType) +'-' +str.tostring(maLength), 'External Trend')

indicators.add_row(0, array.from(close, close, close))
indicators.add_row(1, array.from(ma, ma, ma))
indicators.add_row(2, array.from(externalTrendSignal, externalTrendSignal, externalTrendSignal))

var zg.Zigzag zigzag = zg.Zigzag.new(zigzagLength, 300, 0)
var ZigzagProperties properties = ZigzagProperties.new(textColor, trendMethodInt, repaint)
var divergenceObjects = array.new<DivergenceObject>()
zigzag.calculate(array.from(oscillator), indicators, indicatorNames)
currentDivergence = zigzag.divergence(divergenceObjects, properties)

for divergence in divergenceObjects
    direction = divergence.divergenceType == DivergenceType.BullishDivergence or divergence.divergenceType == DivergenceType.BullishHiddenDivergence ? 1 : -1
    if(not divergence.broken and divergence.pricePoint.price*direction > close*direction)
        divergence.broken := true

lastDivergence = divergenceObjects.size()==0 or divergenceObjects.last().broken? DivergenceType.None : divergenceObjects.last().divergenceType

plot(currentDivergence==DivergenceType.BullishDivergence?1:0, 'Bullish Divergence (Current)', color.green, display = display.data_window)
plot(currentDivergence==DivergenceType.BearishDivergence?1:0, 'Bearish Divergence (Current)', color.red, display = display.data_window)
plot(currentDivergence==DivergenceType.BullishHiddenDivergence?1:0, 'Bullish Hidden Divergence (Current)', color.lime, display = display.data_window)
plot(currentDivergence==DivergenceType.BearishHiddenDivergence?1:0, 'Bearish Hidden Divergence (Current)', color.red, display = display.data_window)

plot(lastDivergence==DivergenceType.BullishDivergence?1:0, 'Bullish Divergence (Last)', color.green, display = display.data_window)
plot(lastDivergence==DivergenceType.BearishDivergence?1:0, 'Bearish Divergence (Last)', color.red, display = display.data_window)
plot(lastDivergence==DivergenceType.BullishHiddenDivergence?1:0, 'Bullish Hidden Divergence (Last)', color.lime, display = display.data_window)
plot(lastDivergence==DivergenceType.BearishHiddenDivergence?1:0, 'Bearish Hidden Divergence (Last)', color.red, display = display.data_window)

Overview

Divergence Screener [Trendoscope®] calculates values using built-in oscillators such as RSI, CCI, CMO, and COG, or an external oscillator source, and filters signals using Zigzag pivots, a moving average filter, or an external trend signal. Users can configure the oscillator type and length, trend detection method, zigzag length, and individual divergence alerts. By default, the repaint setting is enabled, meaning divergence signals can change on the live bar.

Details

Published by

theonetrade on GitHub

Code credit

Trendoscope, as written in the script's header

Draws

Separate pane below the chart

Markets

Any symbol

Timeframes

Any timeframe

Risk Notes

  • Signals can change on the live bar or after it closes (repainting)

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
OscillatorstringrsioscillatorType
lengthint14length
Use External OscillatorboolfalseuseExternalOscillator
externalOscillatorsourcecloseexternalOscillator
Trend Detection MethodstringZigzagtrendMethod
MA Filterenumeta.CustomSeries.SMAmaType
maLengthint200maLength
External Trend SignalsourcecloseexternalTrendSignal
Lengthint13zigzagLength
Repaintbooltruerepaint
Bullish DivergencebooltruebullishDivergenceAlert
Bullish Hidden DivergencebooltruebullishHiddenDivergenceAlert
Show all 14 settings
SettingTypeDefaultVariable
Bearish DivergencebooltruebearishDivergenceAlert
Bearish Hidden DivergencebooltruebearishHiddenDivergenceAlert
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

The indicator scores whether a counter-move against the dominant structure is maturing and whether price has started turning back. It plots a composite score in a separate pane from weighted context, correction maturity, and exhaustion, scaled by trigger and a

Indicator v6 TrendOscillators & momentum
Updated 4 weeks ago · MIT GitHub repository of Directional Probability Engine v2 [WavesUnchained]

MTF MA bands + RSI

by InNoobWeTrust
4 stars

This indicator plots multi-timeframe moving average bands alongside a Relative Strength Index in a separate pane. It calculates up to four configurable moving averages across different timeframes, offering selectable types such as SMA, EMA, and WMA with colore

Indicator v6 Oscillators & momentumMoving averages
Updated 3 weeks ago · None stated GitHub repository of MTF MA bands + RSI
2 stars

This indicator plots the Vortex Indicator and the Relative Strength Index together in a separate pane. It calculates VI+ and VI- from absolute high-low ranges over a shared length, then draws RSI from a chosen source with a selectable SMA or EMA of the RSI. Ho

Indicator v5 Oscillators & momentumTrend
Updated 2 years ago · MIT GitHub repository of Combined Indicator RSI, Vortex

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 11 months ago · MPL-2.0 GitHub repository of QQE + AK Trend + EFI
1 stars

ADX Trend Filter Pro is a separate-pane indicator built on the directional movement system. It plots ADX with DI plus and DI minus, classifies trend strength as weak, moderate, strong or very strong from adjustable thresholds, and overlays a fast and slow EMA

Indicator v6 TrendOscillators & momentum
Updated 5 months ago · MPL-2.0 GitHub repository of ADX Trend Filter Pro

Kernal Cipher 2

by kdricha0602
1 stars

Kernal Cipher 2 is a lower-pane signal panel. It scores trend with fast, slow, and long EMAs, slope, Supertrend, and ADX, then blends WaveTrend, StochRSI, pivot divergence, volume, relative strength versus equity benchmarks, and beta. Green and red diamonds ma

Indicator v6 TrendOscillators & momentum
Updated 2 months ago · MIT GitHub repository of Kernal Cipher 2

More Divergence 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