Indicator · Pine Script v5 · On the chart

Polarity Divergences

by ivansoft· code credited to TradingView

An indicator on the price chart that compares the direction of each chart bar with the net direction of the smaller intrabars inside it, fetched from a lower timeframe chosen by the chart timeframe.

View on GitHub

GitHub stars1on the repository
Pine versionv5runs as is
Lines of code48
Settings9inputs
LicenceNone statedfile: MPL-2.0
Last update1 year ago1 Mar 2025

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

48 lines of Pine Script v5 from edu_std/polarity_divergence.pine, published under MPL-2.0 (file header). Keep the author's credit and licence lines when you reuse it.

polarity_divergence.pine
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © TradingView

//@version=5
indicator("Polarity Divergences", overlay = true)

// Polarity Divergences
// v2, 2022.07.30

// This code was written using the recommendations from the Pine Script™ User Manual's Style Guide:
//   https://www.tradingview.com/pine-script-docs/en/v5/writing/Style_guide.html

bool    showCharUpInput  = input.bool(false,            "Show character on divergences for up bars")
string  charUpInput      = input.string("↗",            "  Character",  inline = "01")
color   charUpColorInput = input.color(color.lime,      "",             inline = "01")
bool    charUpBelowInput = input.bool(true,             "Below bar",    inline = "01")

bool    showCharDnInput  = input.bool(false,            "Show character on divergences for down bars")
string  charDnInput      = input.string("↘",            "  Character",  inline = "02")
color   charDnColorInput = input.color(color.fuchsia,   "",             inline = "02")
bool    charDnAboveInput = input.bool(true,             "Above bar",    inline = "02")

bool    fillBodiesInput  = input.bool(true,             "Fill candle bodies on divergences")


// @function    Selects a LTF from the chart's TF.
// @returns     (simple string) A timeframe string.
ltfStep() =>
    int MS_IN_DAY = 1000 * 60 * 60 * 24
    int tfInMs    = timeframe.in_seconds() * 1000
    string result =
      switch
        tfInMs < MS_IN_DAY      => "1"
        tfInMs < MS_IN_DAY * 7  => "30"
        => "D"


// Calculate the polarity of the chart bar. 
float chartBarPolarity = math.sign(close - open)
// Fetch an array containing the +1/0/-1 polarity of each intrabar.
float[] polaritiesArray = request.security_lower_tf(syminfo.tickerid, ltfStep(), chartBarPolarity)
// Calculate the average polarity of intrabars.
float intrabarPolarity = math.sign(array.sum(polaritiesArray))
// Color the chart bar orange when the majority of intrabar polarities does not match that of the chart bar.
barcolor(fillBodiesInput and intrabarPolarity != chartBarPolarity ? color.orange : na)
// Plot characters showing divergence direction, if enabled. 
plotchar(showCharUpInput ? intrabarPolarity < chartBarPolarity : na, "Div. on up bar",   charUpInput, charUpBelowInput ? location.belowbar : location.abovebar, charUpColorInput, size = size.tiny)
plotchar(showCharDnInput ? intrabarPolarity > chartBarPolarity : na, "Div. on down bar", charDnInput, charDnAboveInput ? location.abovebar : location.belowbar, charDnColorInput, size = size.tiny)

Overview

When the two disagree, the candle is coloured orange. Optional characters can mark divergences on up bars and down bars, with a choice of symbol, colour and placement above or below the bar. It depends on lower timeframe data being available for the symbol.

Details

Published by

ivansoft on GitHub

Code credit

TradingView, as written in the script's header

Draws

On the price chart

Category

Divergence

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

pinescripttradingvew

Settings

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

SettingTypeDefaultVariable
Show character on divergences for up barsboolfalseshowCharUpInput
  Characterstring↗charUpInput
charUpColorInputcolorcolor.limecharUpColorInput
Below barbooltruecharUpBelowInput
Show character on divergences for down barsboolfalseshowCharDnInput
  Characterstring↘charDnInput
charDnColorInputcolorcolor.fuchsiacharDnColorInput
Above barbooltruecharDnAboveInput
Fill candle bodies on divergencesbooltruefillBodiesInput
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

257 stars

This overlay indicator looks for regular price divergences against a set of oscillators, using pivot highs and lows. It compares those pivots with RSI, MACD and its histogram, stochastic, CCI, momentum, OBV, a directional oscillator, volume-weighted MACD, Chai

Indicator v5 DivergenceOscillators & momentum Repaints
Updated 6 weeks ago · None stated GitHub repository of Snag - Best Futures V3

RSI Divergence Scanner

by TradersPost
228 stars

The RSI Divergence Scanner calculates the Relative Strength Index and identifies regular and hidden bullish or bearish divergences against price using pivot high and low points. It plots divergence lines and customizable labels directly on the price chart. Inp

Indicator v6 Oscillators & momentumDivergence
Updated 3 months ago · None stated GitHub repository of RSI Divergence Scanner

Price Divergence

by capissimo
114 stars

This indicator detects regular and hidden divergences across multiple technical factors plotted directly on the price chart. It evaluates price highs and lows against peaks and troughs identified by a five-bar fractal mechanism on RSI, RSI Stochastic, MACD, re

Indicator v4 DivergenceOscillators & momentum
Updated 1 year ago · None stated GitHub repository of Price Divergence

RSI Div at dVWAP StDev

by cryptorife
75 stars

This indicator marks RSI divergences only when price trades beyond daily VWAP standard-deviation bands. It compares recent RSI extremes with price highs and lows over a lookback window, and it treats a divergence as valid only while RSI stays beyond overbought

Indicator v4 DivergenceOscillators & momentum Repaints
Updated 3 years ago · GPL-3.0 GitHub repository of RSI Div at dVWAP StDev

This indicator builds a momentum score from the rate of change of close, using a lookback that expands or contracts with ATR relative to its standard deviation. It divides that rate of change by price standard deviation, scales the result, and weights it by vo

Indicator v5 Oscillators & momentumVolatility & bands Repaints
Updated 7 weeks ago · None stated GitHub repository of Adaptive Volatility-Adjusted Momentum Score

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