RSI Divergence Indicator For ThinkOrSwim

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

This indicator for ThinkorSwim will help you detect bullish and bearish RSI divergences on your chart.
The header of this script also detailed how to set up the scanner that looks for RSI divergences, which often signal possible reversals.
There are a couple of versions for you to check out. The first by Mobius, the other by @cos251
I gave up on RSI divergence, it has so many false positives.

Yes, divergence indicators are problematic.
That is why our group went back to CCI and EM!

@marlonjalonzo This is true of most indicators designed to plot divergences. Divergences are best hand-drawn.
Your trend is still your best friend!
 
While it seems this indicator does not plot RSI divergences correctly, it is firing off pivot points that are relevant and often powerful.
I actually went ahead and bought an RSI divergence indicator, at first because I wanted a scanner that would work, but using that new indicator I realized how this one is off with divergences, at least how they are traditionally understood. But again many of the points here are meaningful. If anyone understands more about how this indicator is identifying pivot points it would be helpful.
 
I am looking for code snippets that plot divergence lines between price and the RSI. I mean if the price has higher highs while RSI has a lower high (or vice versa). Instead of visually verifying the divergence, I want to be able to plot it.

Here is the code that I want to use to add these lines. @tomsk helped me and I made few tweaks.
Code:
# Divergence Updown Points
# tomsk  (modfied further by [USER=2184]@venus360[/USER])
# 1.17.2020

# Plots the ratio of Up/Down points relative to the prior candle

input period = 14;
declare lower;

def upPoints   = fold i = 0 to period
                 with p
                 do p + GetValue(if close > close[1] then close - close[1] else 0, i);
def downPoints = fold j = 0 to period
                 with r
                 do r + GetValue(if close < close[1] then close - close[1] else 0, j);

def au = upPoints / period;
def ad = AbsValue(downPoints) / period;

def ratio = au / ad;

def step0 = 1 + ratio;
def step1 = 100 / step0;
plot final = 100 - step1;

# End UpDown Points Divergence

0uufIZ1.png


I manually added the lines, I want to explore if the divergence lines can be plotted using code.
Do you have scan for this? i'm looking for scan the divergence on daily time frame. Thanks
 
thanks for the penetrating reply! now, let's see: i've appended the complete code below. i believe i got it here and it does reference a poster named signet.

1/ box3: yes, you're absolutely right, it's not premature as per the stated rules. i guess if i wanted to try a number higher than 30, i could just change the code, no biggie.
2/ you're right once again re box4. as per the rules, it would not fire true, so best to leave it out and go with /1 above, with box3 being the signal moment.
3/ again, yes: if it exceeds 50, abort and start over, looking for rule #1.

thanks a million for taking the time to catch these things!

any other questions, fire away.

Code:
#Hint: RSI Divergence Scan Developed by Signet. 01/23/2019. \n\n The relative strength index (RSI) is a momentum indicator that measures the magnitude of recent price changes to evaluate overbought or oversold conditions in the price of a stock or other asset. The indicator was originally developed by J. Welles Wilder and introduced in his seminal 1978 book, "New Concepts in Technical Trading Systems." \n\n Traditional interpretation and usage of the RSI is that values of 70 or above indicate that a security is becoming overbought or overvalued and may be primed for a trend reversal or corrective pullback in price. An RSI reading of 30 or below indicates an oversold or undervalued condition. The standard is to use 14 periods to calculate the initial RSI value. In a strong upward trending environment, the RSI rarely falls below 40, and will most always stick to the 50 – 80 range. When the RSI crosses the centreline it is a stronger signal that a trend change has happened than a simple extreme reading above or below the 70-30 lines. When the indicator crosses the centreline to the upside, it means that the average gains are exceeding the average losses over the period. The opposite is true for a downside cross.When a centreline cross happens, it can be a good time to think about trade entry on a fresh pullback in price.\n\n This is how the RSI is calculated: \n Pick the base number of periods on which to base the study. \n compare todays closing price with yesterdays. \n add all the upward movements in points between closing prices. \n add all the downwards movements between closing prices. \n calculate the EMA ( exponential moving average ) of the upward and downward price movements. \n calculate the relative strength: \n    <b>[ RS = EMA Upward Price Movements / EMA Downward Price Move ments ]</b> \n Calculate the Relative Strength Index (RSI): \n   <b> RSI = 1 / ( 1 + RS ) </b> \n\n There are a few indicators that pair well with the RSI and using them together can proved better trading signals. \n RSI, candlestick strategy, \n RSI, MACD strategy, \n RSI, MA Cross strategy, & \n RSI, Bollinger band strategy,

#Trade Lessons:
#Wait for conformation before considering a trade,
#The RSI can remain at extreme levels for long periods in a strong trend
#Dont jump right in when you see a reading of 90, first allow the RSI line to fall back below the overbought line to at least give a stoploss level to trade off .
#Watch the Centreline for trend confirmtion.
#If the RSI line reaches an extreme and then returns to the centreline it is a better indication of a turning point in the trend. Waiting for this to occur can cut out those nasty impulsive trades!
#It is common for technical traders to watch the centreline to show shifts in trend,
#If the RSI is above 50, then it is considered a bullish uptrend, and if its below 50, then a bearish downtrend is in play.

# RSI Failure Swing Trade:
#A ‘bearish failure swing’ happens when the RSI enters the overbought zone at 70 and then comes back down below the 70 mark again.
#In this case, a short position will be entered only after the RSI cuts down through the 70 line from the top.
#The ‘bullish failure swing’ occurs when the RSI enters the oversold zone at 30 and then rallies out again and rises above the 30 line again.
#The trader uses this rise above the 30 line as a trigger to go long.

declare lower;
#Hint showDivergentRSI: YES will plot a Divergent Signal on the RSI line, NO will remove the Divergent Signal from the RSI Line

#Hint showDivergentSignals: YES will plot a Divergent Signal on the OS / OB line, NO will remove the Divergent Signal from the OS / OB Line

#Hint showBreakoutSignals: Actual indication of RSI crossovers with the overbought/oversold levels can be enabled by setting the show breakout signals parameter value to YES.

#Hint averageType: By default, the Wilder's moving average is used in the calculation of RSI, however, you are free to select a different type of average.

#Hint over_Sold: On a scale from 0 to 100, default values of 30 are typically use for the oversold level

#Hint over_Bought: On a scale from 0 to 100, default values of 70 are typically use for the overbought level

#Hint Length: The standard is to use 14 periods to calculate the initial RSI value but I like using 10 Periods.

#Hint Sound_AudibleAlert_for_RSI_Cross : This turns off the audio alerts for the RSI Crossovers

# input parameters
input length = 10;
input over_Bought = 70;
input over_Sold = 30;
input price = close;
input averageType = AverageType.WILDERS;
input showDivergentRSI = yes;
input showBreakoutSignals = no;
input showDivergentSignals = yes;
input Sound_AudibleAlert_for_RSI_Cross = No;
def NetChgAvg = MovingAverage(averageType, price - price[1], length);
def TotChgAvg = MovingAverage(averageType, AbsValue(price - price[1]), length);
def ChgRatio = if TotChgAvg != 0 then NetChgAvg / TotChgAvg else 0;


plot RSI = 50 * (ChgRatio + 1);
RSI .SetLineWeight(2);
plot OverSold = over_Sold;
plot OverBought = over_Bought;
plot RSI_CrossUp = if RSI crosses above OverSold then OverSold else Double.NaN;
plot RSI_CrossDn = if RSI crosses below OverBought then OverBought else Double.NaN;

RSI_CrossUp .SetHiding(!showBreakoutSignals);
RSI_CrossDn .SetHiding(!showBreakoutSignals);

RSI.DefineColor("OverBought", GetColor(5));
RSI.DefineColor("Normal", GetColor(7));
RSI.DefineColor("OverSold", GetColor(5));
RSI.AssignValueColor(if RSI > over_Bought then RSI.Color("OverBought") else if RSI < over_Sold then RSI.Color("OverSold") else RSI.Color("Normal"));
OverSold.SetDefaultColor(GetColor(8));
OverBought.SetDefaultColor(GetColor(8));
RSI_CrossUp .SetDefaultColor(Color.UPTICK);
RSI_CrossUp .SetPaintingStrategy(PaintingStrategy.ARROW_UP);
RSI_CrossDn .SetDefaultColor(Color.DOWNTICK);
RSI_CrossDn .SetPaintingStrategy(PaintingStrategy.ARROW_DOWN);

def n = Double.NaN;
def Hclose = high;
def lclose = low;
def prSlope = (Hclose + lclose) / 2;

# Define the Volume Study
def volavg = Average(volume, length);
#Define Volume Slope for Divergence Measurement
def hvol = Highest(volume, length);
def lvol = Lowest(volume, length);
def volslope = (hvol + lvol) / 2;

# Define the Divergence
def isbulld = if (lvol < 0 and volavg >= 0) then 1 else 0;
def isbeard = if (hvol > 0 and volavg <= 0) then 1 else 0;

def myslope = reference LinearRegressionSlope(RSI, length);
def bullslope = reference LinearRegressionSlope(low, length);
def bearslope = reference LinearRegressionSlope(high, length);
def priceslope = (bullslope + bearslope) / 2;

plot Divergence = if (bullslope < 0 and myslope >= 0) or (bearslope > 0 and myslope <= 0) then  RSI else n;
Divergence .DefineColor("Bullish_Divergence", GetColor(6));
Divergence .DefineColor("Bearish_Divergence", GetColor(5));
Divergence .AssignValueColor(if (bullslope < 0 and myslope >= 0) then Divergence .Color("Bullish_Divergence") else if (bearslope > 0 and myslope <= 0) then Divergence .Color("Bearish_Divergence") else Color.GRAY);
Divergence .SetHiding(!showDivergentRSI);
Divergence .SetPaintingStrategy(PaintingStrategy.POINTS);
Divergence .SetLineWeight(5);


plot BullSignal = if (bullslope < 0 and myslope >= 0) then OverBought else Double.NaN;
plot BearSignal = if (bearslope > 0 and myslope <= 0) then OverSold else Double.NaN;

PLOT "0" = 50;
"0" .SetDefaultColor(GetColor(8));
"0" .hidebubble();
"0" .hidetitle();
plot "50" = 50;
"50" .SetDefaultColor(GetColor(8));
"50" .hidebubble();
"50" .hidetitle();
PLOT "100" = 50;
"100" .SetDefaultColor(GetColor(8));
"100" .hidebubble();
"100" .hidetitle();
#Positive divergence happens when the price of an asset is drifting lower yet the RSI is starting to trend higher.
#This could mean that the price is nearing a bottom and will probably turn up soon.
#Negative divergence happens the opposite way, the price is driving higher, but the RSI has stalled and is beginning to turn lower.
#When this occurs it is likely that the price will stop rising soon after. And then follow the RSI lower.
DefineGlobalColor("Bull_Label_Color", CreateColor(148, 214, 232));
DefineGlobalColor("Bear_Label_Color", CreateColor(255, 127, 0));

AddLabel (BullSignal, "Bullish Divergence", GlobalColor("Bull_Label_Color" ) );
AddLabel (BearSignal, "Bearish Divergence", GlobalColor("Bear_Label_Color" ) );

input Show_RSIcross_Labels = yes;
AddLabel (Show_RSIcross_Labels, if
    RSI_CrossUp then "RSI OverSold" else if
    RSI_CrossDn then "RSI OverBought" else "",  if
            RSI_CrossUp then
            Divergence .Color("Bullish_Divergence") else
            Divergence .Color("Bearish_Divergence"));
BullSignal .SetHiding(!showDivergentSignals);
BearSignal .SetHiding(!showDivergentSignals);
BullSignal .SetDefaultColor(Color.UPTICK);
BullSignal .SetPaintingStrategy(PaintingStrategy.TRIANGLES);
BearSignal .SetDefaultColor(Color.DOWNTICK);
BearSignal .SetPaintingStrategy(PaintingStrategy.TRIANGLES);

def MidlineCross = (RSI crosses above 50) or (RSI crosses below 50);
def ExtremeCross = (RSI crosses 70 ) or (RSI crosses below 30);

def Midline_signal = MidlineCross is true;
def Extreme_signal = ExtremeCross is true;

def TrendChange = if Sound_AudibleAlert_for_RSI_Cross == yes then rsi crosses 50 or rsi else no;

Alert(TrendChange, "RSI Trend Change", Alert.BAR, Sound.Ring);

def Extreme = if Sound_AudibleAlert_for_RSI_Cross == yes then rsi crosses 70 or rsi crosses 30 else no;

Alert(Extreme, "RSI @ Extreme", Alert.BAR, Sound.Ring);
Any way to add a watchlist column that displays the bullish or bearish Divergence label?
 
Any way to add a watchlist column that displays the bullish or bearish Divergence label?

The forum contains numerous complaints about divergence scanners and watchlists.
This issue arises because divergence indicators are complicated and do not update in real time.
Consequently, divergence scripts tend to be unreliable with watchlists and scanners.
 
Last edited:

Similar threads

Not the exact question you're looking for?

Start a new thread and receive assistance from our community.

87k+ Posts
263 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