RSI Divergence w/ Alerts For ThinkOrSwim

Join useThinkScript to post your question to a community of 21,000+ developers and traders.

@LLP
try it :)

CSS:
#// This source code is subject to the terms of the Mozilla Public License 2.0 at
#// © JayTradingCharts
#https://www.tradingview.com/script/AkWCX6pt-RSI-Divergence-Indicator-w-Alerts/
#study("RSI Divergence Indicator w/Alerts")
# Converted by Sam4Cok@Samer800 - 09/2022

declare lower;

input len = 14;           # "RSI Period"
input src = close;        # "RSI Source"
input overBought = 70;    # "Over Bought Limit"
input overSold = 30;      # "Over Sold Limit"
input alerts   = yes;
input sound    = {default "NoSound", "Ding", "Bell", "Chimes", "Ring"};
input lbR  = 5;           # "Pivot Lookback Right"
input lbL  = 5;           # "Pivot Lookback Left"
input MaxLookback = 60;   # "Max of Lookback Range"
input MinLookback = 5;    # "Min of Lookback Range"
input DivBull = yes;      # "Plot Bullish"
input DivHiddenBull = no; # "Plot Hidden Bullish"
input DivBear = yes;      # "Plot Bearish"
input DivHiddenBear = no; # "Plot Hidden Bearish"

def na = double.NaN;

def nRSI = RSI(Price = src, length= len);

plot osc = nRSI;
osc.SetDefaultColor(CreateColor(186,115,193));
osc.SetLineWeight(2);
plot midLine = 50;
midLine.SetDefaultColor(Color.DARK_GRAY);
plot obLevel = overBought;
obLevel.SetDefaultColor(Color.GRAY);
plot osLevel = overSold;
osLevel.SetDefaultColor(Color.GRAY);
#----Div-----------
def divSrc = nRSI;

def h = high;
def l = low;

script FindPivots {
    input dat = close; # default data or study being evaluated
    input HL  = 0;    # default high or low pivot designation, -1 low, +1 high
    input lbL  = 5;    # default Pivot Lookback Left
    input lbR  = 1;    # default Pivot Lookback Right
    ##############
    def _nan;    # used for non-number returns
    def _BN;     # the current barnumber
    def _VStop;  # confirms that the lookforward period continues the pivot trend
    def _V;      # the Value at the actual pivot point
    ##############
    _BN  = BarNumber();
    _nan = Double.NaN;
    _VStop = if !isNaN(dat) and lbr > 0 and lbl > 0 then
                fold a = 1 to lbR + 1 with b=1 while b do
                    if HL > 0 then dat > GetValue(dat,-a) else dat < GetValue(dat,-a) else _nan;
   if (HL > 0) {
        _V = if _BN > lbL and dat == Highest(dat, lbL+1) and _VStop
            then dat else _nan;
    } else {
        _V = if _BN > lbL and dat == Lowest(dat, lbL+1) and _VStop
            then dat else _nan;
    }
    plot result = if !IsNaN(_V) and _VStop then _V else _nan;
}
#valuewhen (Cond, source, lbr, occurrence)
script valuewhen {
  input cond = 0;
  input src = close;
  input lbr = 0;
  input occurrence = 0;
  def n = occurrence + 1;
  def offset = fold j = 0 to 200 with p=1 while p < n + 1
    do p + ( if p == n then j - n else if cond[j]==yes then 1 else 0 );
  plot price = GetValue(src[lbr], offset-1);
}
#_inRange(cond) =>
script _inRange {
    input cond = yes;
    input rangeUpper = 60;
    input rangeLower = 5;
        def bars = if cond then 0 else bars[1] + 1;
        def inrange =  (rangeLower <= bars) and (bars <= rangeUpper);
plot retrun = inRange;
}
def pl = findpivots(divSrc,-1, lbL, lbR);
def ph = findpivots(divSrc, 1, lbL, lbR);

def plFound = if !isNaN(pl) then 1 else 0;
def phFound = if !isNaN(ph) then 1 else 0;

def vlFound = valuewhen(plFound, divSrc, 0, 1);
def vhFound = valuewhen(phFound, divSrc, 0, 1);

def plPrice = valuewhen(plFound, l, 0, 1);
def phPrice = valuewhen(phFound, h, 0, 1);

#// Regular Bullish
def oscHL = divSrc > vlFound and  _inRange(plFound[1],MaxLookback,MinLookback);
def priceLL = l < plPrice;
def bullCond = DivBull and plFound and oscHL and priceLL;
#// Hidden Bullish
def oscLL = divSrc[lbr] < vlFound and  _inRange(plFound[1],MaxLookback,MinLookback);
def priceHL = l[lbr] > plPrice;
def hiddenBullCond = DivHiddenBull and plFound and oscLL and priceHL;

#// Regular Bearish
def oscLH   = divSrc < vhFound and  _inRange(phFound[1],MaxLookback,MinLookback);
def priceHH = h > phPrice;
def bearCond = DivBear and phFound and oscLH and priceHH;
#// Hidden Bearish
def oscHH = divSrc > vhFound and  _inRange(phFound[1],MaxLookback,MinLookback);
def priceLH = h < phPrice;
def hiddenBearCond = DivHiddenBear and phFound and oscHH and priceLH;

#---- Background
AddCloud(obLevel, osLevel, CreateColor(76,10,127));

#------ Bubbles
addchartbubble(bullCond, divSrc, "R", color.GREEN, no);
addchartbubble(bearCond, divSrc, "R", CreateColor(156,39,176), yes);
addchartbubble(hiddenBullCond, divSrc, "H", color.DARK_green, no);
addchartbubble(hiddenBearCond, divSrc, "H", color.DARK_red, yes);

#---- Alerts
Alert(alerts and bullCond, "Regular Bull Div", Alert.BAR, sound);
Alert(alerts and bearCond, "Regular Bear Div", Alert.BAR, sound);
Alert(alerts and hiddenBullCond, "Hidden Bull Div", Alert.BAR, sound);
Alert(alerts and hiddenBearCond, "Hidden Bear Div", Alert.BAR, sound);

#----End
 
Last edited by a moderator:
Love the indicator! Is there anyway to create a scan for Regular Bull & Bear Divergence (when bubble alerts) from this indicator? I don't see any way of doing it with the choices within the scan, using this study. Also, is there any way to move the arrows closer to the HA plots? They are so far to the top and bottom, its difficult to see them.
 
Last edited:
@samer800 Could you do the same for Fast Stochastic Divergence?
I loaded up the study above and works great for the RSI Divergence, Nice work!
 
Last edited:
1) Is it possible to make this a reliable scan? Especially on triple or quadruple divergence?

2) Is there a way to change the AddChartBubbles into Arrow Plots so it would be friendly with mobile?

Code:
plot Bullish = DivBull and plFound and oscHL and priceLL ;
                 Bullish.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_UP);

3) Is it possible to draw lines to show the divergence?

It doesnt look like it will work in a scan since it doesnt have the right plots? @SleepyZ
 
Last edited:
@LLP
try it :)

CSS:
#// This source code is subject to the terms of the Mozilla Public License 2.0 at
#// © JayTradingCharts
#https://www.tradingview.com/script/AkWCX6pt-RSI-Divergence-Indicator-w-Alerts/
#study("RSI Divergence Indicator w/Alerts")
# Converted by Sam4Cok@Samer800 - 09/2022

declare lower;

input len = 14;           # "RSI Period"
input src = close;        # "RSI Source"
input overBought = 70;    # "Over Bought Limit"
input overSold = 30;      # "Over Sold Limit"
input alerts   = yes;
input sound    = {default "NoSound", "Ding", "Bell", "Chimes", "Ring"};
input lbR  = 5;           # "Pivot Lookback Right"
input lbL  = 5;           # "Pivot Lookback Left"
input MaxLookback = 60;   # "Max of Lookback Range"
input MinLookback = 5;    # "Min of Lookback Range"
input DivBull = yes;      # "Plot Bullish"
input DivHiddenBull = no; # "Plot Hidden Bullish"
input DivBear = yes;      # "Plot Bearish"
input DivHiddenBear = no; # "Plot Hidden Bearish"

def na = double.NaN;

def nRSI = RSI(Price = src, length= len);

plot osc = nRSI;
osc.SetDefaultColor(CreateColor(186,115,193));
osc.SetLineWeight(2);
plot midLine = 50;
midLine.SetDefaultColor(Color.DARK_GRAY);
plot obLevel = overBought;
obLevel.SetDefaultColor(Color.GRAY);
plot osLevel = overSold;
osLevel.SetDefaultColor(Color.GRAY);
#----Div-----------
def divSrc = nRSI;

def h = high;
def l = low;

script FindPivots {
    input dat = close; # default data or study being evaluated
    input HL  = 0;    # default high or low pivot designation, -1 low, +1 high
    input lbL  = 5;    # default Pivot Lookback Left
    input lbR  = 1;    # default Pivot Lookback Right
    ##############
    def _nan;    # used for non-number returns
    def _BN;     # the current barnumber
    def _VStop;  # confirms that the lookforward period continues the pivot trend
    def _V;      # the Value at the actual pivot point
    ##############
    _BN  = BarNumber();
    _nan = Double.NaN;
    _VStop = if !isNaN(dat) and lbr > 0 and lbl > 0 then
                fold a = 1 to lbR + 1 with b=1 while b do
                    if HL > 0 then dat > GetValue(dat,-a) else dat < GetValue(dat,-a) else _nan;
   if (HL > 0) {
        _V = if _BN > lbL and dat == Highest(dat, lbL+1) and _VStop
            then dat else _nan;
    } else {
        _V = if _BN > lbL and dat == Lowest(dat, lbL+1) and _VStop
            then dat else _nan;
    }
    plot result = if !IsNaN(_V) and _VStop then _V else _nan;
}
#valuewhen (Cond, source, lbr, occurrence)
script valuewhen {
  input cond = 0;
  input src = close;
  input lbr = 0;
  input occurrence = 0;
  def n = occurrence + 1;
  def offset = fold j = 0 to 200 with p=1 while p < n + 1
    do p + ( if p == n then j - n else if cond[j]==yes then 1 else 0 );
  plot price = GetValue(src[lbr], offset-1);
}
#_inRange(cond) =>
script _inRange {
    input cond = yes;
    input rangeUpper = 60;
    input rangeLower = 5;
        def bars = if cond then 0 else bars[1] + 1;
        def inrange =  (rangeLower <= bars) and (bars <= rangeUpper);
plot retrun = inRange;
}
def pl = findpivots(divSrc,-1, lbL, lbR);
def ph = findpivots(divSrc, 1, lbL, lbR);

def plFound = if !isNaN(pl) then 1 else 0;
def phFound = if !isNaN(ph) then 1 else 0;

def vlFound = valuewhen(plFound, divSrc, 0, 1);
def vhFound = valuewhen(phFound, divSrc, 0, 1);

def plPrice = valuewhen(plFound, l, 0, 1);
def phPrice = valuewhen(phFound, h, 0, 1);

#// Regular Bullish
def oscHL = divSrc > vlFound and  _inRange(plFound[1],MaxLookback,MinLookback);
def priceLL = l < plPrice;
def bullCond = DivBull and plFound and oscHL and priceLL;
#// Hidden Bullish
def oscLL = divSrc[lbr] < vlFound and  _inRange(plFound[1],MaxLookback,MinLookback);
def priceHL = l[lbr] > plPrice;
def hiddenBullCond = DivHiddenBull and plFound and oscLL and priceHL;

#// Regular Bearish
def oscLH   = divSrc < vhFound and  _inRange(phFound[1],MaxLookback,MinLookback);
def priceHH = h > phPrice;
def bearCond = DivBear and phFound and oscLH and priceHH;
#// Hidden Bearish
def oscHH = divSrc > vhFound and  _inRange(phFound[1],MaxLookback,MinLookback);
def priceLH = h < phPrice;
def hiddenBearCond = DivHiddenBear and phFound and oscHH and priceLH;

#---- Background
AddCloud(obLevel, osLevel, CreateColor(76,10,127));

#------ Bubbles
addchartbubble(bullCond, divSrc, "R", color.GREEN, no);
addchartbubble(bearCond, divSrc, "R", CreateColor(156,39,176), yes);
addchartbubble(hiddenBullCond, divSrc, "H", color.DARK_green, no);
addchartbubble(hiddenBearCond, divSrc, "H", color.DARK_red, yes);

#---- Alerts
Alert(alerts and bullCond, "Regular Bull Div", Alert.BAR, sound);
Alert(alerts and bearCond, "Regular Bear Div", Alert.BAR, sound);
Alert(alerts and hiddenBullCond, "Hidden Bull Div", Alert.BAR, sound);
Alert(alerts and hiddenBearCond, "Hidden Bear Div", Alert.BAR, sound);

#----End
Hello sam, divergence indicator plots very beautifully in the chart, however, i am just so confused, why is the signal popping up after only few bars have been past, say there is a bullish divrgence on a hourly chart at 10 am on any stock but that bullish chart buble pops at about 3 pm on a 10 am chart, how do i get the instant bubble at 10 am if there is a divergence

what do i change in order to get the instant print when divergence occur, ibR, ibL, max lookback or min LookBack. your response will be greatly apprecaited. Thank you
 
Last edited by a moderator:
Hello sam, divergence indicator plots very beautifully in the chart, however, i am just so confused, why is the signal popping up after only few bars have been past, say there is a bullish divrgence on a hourly chart at 10 am on any stock but that bullish chart buble pops at about 3 pm on a 10 am chart, how do i get the instant bubble at 10 am if there is a divergence
divergence will print based on the Pivot Lookback period.

you need to give some time to confirm the divergence to avoid wrong print. You can go with minimum 3 but I believe not less than that. may be another members can advise.
 
Last edited by a moderator:
so what do i change in order to get the instant print when divergence occur, ibR, ibL, max lookback or min LookBack. your response will be greatly apprecaited. Thank you

@samer800 is right, the lag is required in order to identify the divergence.
If you go shorter; divergences will not identify correctly.
 

Similar threads

Not the exact question you're looking for?

Start a new thread and receive assistance from our community.

87k+ Posts
352 Online
Create Post

Similar threads

Similar threads

The Market Trading Game Changer

Join 2,500+ subscribers inside the useThinkScript VIP Membership Club
  • Exclusive indicators
  • Proven strategies & setups
  • Private Discord community
  • ‘Buy The Dip’ signal alerts
  • Exclusive members-only content
  • Add-ons and resources
  • 1 full year of unlimited support

Frequently Asked Questions

What is useThinkScript?

useThinkScript is the #1 community of stock market investors using indicators and other tools to power their trading strategies. Traders of all skill levels use our forums to learn about scripting and indicators, help each other, and discover new ways to gain an edge in the markets.

How do I get started?

We get it. Our forum can be intimidating, if not overwhelming. With thousands of topics, tens of thousands of posts, our community has created an incredibly deep knowledge base for stock traders. No one can ever exhaust every resource provided on our site.

If you are new, or just looking for guidance, here are some helpful links to get you started.

What are the benefits of VIP Membership?
VIP members get exclusive access to these proven and tested premium indicators: Buy the Dip, Advanced Market Moves 2.0, Take Profit, and Volatility Trading Range. In addition, VIP members get access to over 50 VIP-only custom indicators, add-ons, and strategies, private VIP-only forums, private Discord channel to discuss trades and strategies in real-time, customer support, trade alerts, and much more. Learn all about VIP membership here.
How can I access the premium indicators?
To access the premium indicators, which are plug and play ready, sign up for VIP membership here.
Back
Top