Join useThinkScript to post your question to a community of 21,000+ developers and traders.
#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" = 0;
"0" .SetDefaultColor(GetColor(8));
"0" .hidebubble();
"0" .hidetitle();
plot "50" = 50;
"50" .SetDefaultColor(GetColor(8));
"50" .hidebubble();
"50" .hidetitle();
PLOT "100" = 100;
"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);
# RSI_With_Divergence
# Mobius
# V01.01.2013
# 4.15.2019
#hint:<b>RSI with Divergence</b>
# Note: Install this as a new study. Save this study using the name above (the first line of code RSI_With_Divergence).
# To use this study as a scan; DO NOT TRY TO LOAD IT DIRECTLY IN THE SCANNER, IT WILL THROW AN ERROR MESSAGE. Go to the scan tab. Delete any existing scan criteria. Click Add Study Filter. Click the window under Criteria. In that drop down menu click Custom. Delete the existing study. Click Add Condition. Click the down arrow in the Select A Condition window. Click Study. Scroll down the List till you find RSI_With_Divergence and click it. Click on the Plot window and you can choose Dhigh or Dlow in addition to the default plot RSI. If you choose either of the divergence siganls choose is True from the center column. Click on the aggregation period at the top left and set the aggregation period you want scaned. Then click Save and when the popup window shows the warning that this is a custom scan chose OK. Now put the list of stocks you wish to scan in the Scan In box and chose any list you want that to intersect with. If you wish to make this a Dynamic WatchList, save this scan with a name such as RSI_With_Div_WL then in your Gadgets box click the little gear icon, locate the name of the scan you just saved and click it. As equities match the scan criteria they will populate the list.
input n = 14; #hint nRSI: Periods or length for RSI
input Over_Bought = 70; #hint Over_Bought: Over Bought line
input Over_Sold = 30; #hint Over_Sold: Over Sold line
def o = open;
def h = high;
def l = low;
def c = close;
def x = BarNumber();
def MidLine = 50;
def NetChgAvg = ExpAverage(c - c[1], n);
def TotChgAvg = ExpAverage(AbsValue(c - c[1]), n);
def ChgRatio = if TotChgAvg != 0
then NetChgAvg / TotChgAvg
else 0;
def RSI = 50 * (ChgRatio + 1);
def OverSold = Over_Sold;
def OverBought = Over_Bought;
def bar = BarNumber();
def Currh = if RSI > OverBought
then fold i = 1 to Floor(n / 2)
with p = 1
while p
do RSI > getValue(RSI, -i)
else 0;
def CurrPivotH = if (bar > n and
RSI == highest(RSI, Floor(n/2)) and
Currh)
then RSI
else double.NaN;
def Currl = if RSI < OverSold
then fold j = 1 to Floor(n / 2)
with q = 1
while q
do RSI < getValue(RSI, -j)
else 0;
def CurrPivotL = if (bar > n and
RSI == lowest(RSI, Floor(n/2)) and
Currl)
then RSI
else double.NaN;
def CurrPHBar = if !isNaN(CurrPivotH)
then bar
else CurrPHBar[1];
def CurrPLBar = if !isNaN(CurrPivotL)
then bar
else CurrPLBar[1];
def PHpoint = if !isNaN(CurrPivotH)
then CurrPivotH
else PHpoint[1];
def priorPHBar = if PHpoint != PHpoint[1]
then CurrPHBar[1]
else priorPHBar[1];
def PLpoint = if !isNaN(CurrPivotL)
then CurrPivotL
else PLpoint[1];
def priorPLBar = if PLpoint != PLpoint[1]
then CurrPLBar[1]
else priorPLBar[1];
def HighPivots = bar >= highestAll(priorPHBar);
def LowPivots = bar >= highestAll(priorPLBar);
def pivotHigh = if HighPivots
then CurrPivotH
else double.NaN;
def PlotHline = pivotHigh;
def pivotLow = if LowPivots
then CurrPivotL
else double.NaN;
def PivotDot = if !isNaN(pivotHigh)
then pivotHigh
else if !isNaN(pivotLow)
then pivotLow
else double.NaN;
plot uparrow = pivotLow;
uparrow.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_UP);
plot downarrow = pivotHigh;
downarrow.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_DOWN);
# End Code RSI with Divergence
study(title="RSI Divergence", shorttitle="RSI Divergence")
src_fast = close, len_fast = input(5, minval=1, title="Length Fast RSI")
src_slow = close, len_slow = input(14,minval=1, title="Length Slow RSI")
up_fast = rma(max(change(src_fast), 0), len_fast)
down_fast = rma(-min(change(src_fast), 0), len_fast)
rsi_fast = down_fast == 0 ? 100 : up_fast == 0 ? 0 : 100 - (100 / (1 + up_fast / down_fast))
up_slow = rma(max(change(src_slow), 0), len_slow)
down_slow = rma(-min(change(src_slow), 0), len_slow)
rsi_slow = down_slow == 0 ? 100 : up_slow == 0 ? 0 : 100 - (100 / (1 + up_slow / down_slow))
//plotfast = plot(rsi_fast, color=blue)
//plotslow = plot(rsi_slow, color=orange)
divergence = rsi_fast - rsi_slow
plotdiv = plot(divergence, color = divergence > 0 ? lime:red, linewidth = 2)
//band1 = hline(70,color=green)
//band0 = hline(30,color=red)
band = hline(0)
//@version=4
study(title="{INDYAN} RSI + MACD", shorttitle="{INDYAN} RSI+MACD Divergence")
len = input(title="RSI Period", minval=1, defval=7)
src = input(title="RSI Source", defval=close)
lbR = input(title="Pivot Lookback Right", defval=5)
lbL = input(title="Pivot Lookback Left", defval=3)
rangeUpper = input(title="Max of Lookback Range", defval=60)
rangeLower = input(title="Min of Lookback Range", defval=5)
plotBull = input(title="Plot Bullish", defval=true)
plotHiddenBull = input(title="Plot Hidden Bullish", defval=true)
plotBear = input(title="Plot Bearish", defval=true)
plotHiddenBear = input(title="Plot Hidden Bearish", defval=false)
bearColor = color.purple
bullColor = color.green
hiddenBullColor = color.new(color.green, 80)
hiddenBearColor = color.new(color.red, 80)
textColor = color.white
noneColor = color.new(color.white, 100)
osc = rsi(src, len)
plot(osc, title="RSI", linewidth=2, color=#8D1699)
hline(50, title="Middle Line", linestyle=hline.style_dotted)
obLevel = hline(60, title="Overbought", linestyle=hline.style_dotted)
osLevel = hline(40, title="Oversold", linestyle=hline.style_dotted)
fill(obLevel, osLevel, title="Background", color=#9915FF, transp=90)
plFound = na(pivotlow(osc, lbL, lbR)) ? false : true
phFound = na(pivothigh(osc, lbL, lbR)) ? false : true
_inRange(cond) =>
bars = barssince(cond == true)
rangeLower <= bars and bars <= rangeUpper
//------------------------------------------------------------------------------
// Regular Bullish
// Osc: Higher Low
oscHL = osc[lbR] > valuewhen(plFound, osc[lbR], 1) and _inRange(plFound[1])
// Price: Lower Low
priceLL = low[lbR] < valuewhen(plFound, low[lbR], 1)
bullCond = plotBull and priceLL and oscHL and plFound
plot(
plFound ? osc[lbR] : na,
offset=-lbR,
title="Regular Bullish",
linewidth=2,
color=(bullCond ? bullColor : noneColor),
transp=0
)
plotshape(
bullCond ? osc[lbR] : na,
offset=-lbR,
title="Regular Bullish Label",
text=" Bull ",
style=shape.labelup,
location=location.absolute,
color=bullColor,
textcolor=textColor,
transp=0
)
//------------------------------------------------------------------------------
// Hidden Bullish
// Osc: Lower Low
oscLL = osc[lbR] < valuewhen(plFound, osc[lbR], 1) and _inRange(plFound[1])
// Price: Higher Low
priceHL = low[lbR] > valuewhen(plFound, low[lbR], 1)
hiddenBullCond = plotHiddenBull and priceHL and oscLL and plFound
plot(
plFound ? osc[lbR] : na,
offset=-lbR,
title="Hidden Bullish",
linewidth=2,
color=(hiddenBullCond ? hiddenBullColor : noneColor),
transp=0
)
plotshape(
hiddenBullCond ? osc[lbR] : na,
offset=-lbR,
title="Hidden Bullish Label",
text=" Hidden Bull ",
style=shape.labelup,
location=location.absolute,
color=bullColor,
textcolor=textColor,
transp=0
)
longCondition=bullCond or hiddenBullCond
//------------------------------------------------------------------------------
// Regular Bearish
// Osc: Lower High
oscLH = osc[lbR] < valuewhen(phFound, osc[lbR], 1) and _inRange(phFound[1])
// Price: Higher High
priceHH = high[lbR] > valuewhen(phFound, high[lbR], 1)
bearCond = plotBear and priceHH and oscLH and phFound
plot(
phFound ? osc[lbR] : na,
offset=-lbR,
title="Regular Bearish",
linewidth=2,
color=(bearCond ? bearColor : noneColor),
transp=0
)
plotshape(
bearCond ? osc[lbR] : na,
offset=-lbR,
title="Regular Bearish Label",
text=" Bear ",
style=shape.labeldown,
location=location.absolute,
color=bearColor,
textcolor=textColor,
transp=0
)
//------------------------------------------------------------------------------
// Hidden Bearish
// Osc: Higher High
oscHH = osc[lbR] > valuewhen(phFound, osc[lbR], 1) and _inRange(phFound[1])
// Price: Lower High
priceLH = high[lbR] < valuewhen(phFound, high[lbR], 1)
hiddenBearCond = plotHiddenBear and priceLH and oscHH and phFound
plot(
phFound ? osc[lbR] : na,
offset=-lbR,
title="Hidden Bearish",
linewidth=2,
color=(hiddenBearCond ? hiddenBearColor : noneColor),
transp=0
)
plotshape(
hiddenBearCond ? osc[lbR] : na,
offset=-lbR,
title="Hidden Bearish Label",
text=" Hidden Bear ",
style=shape.labeldown,
location=location.absolute,
color=bearColor,
textcolor=textColor,
transp=0
)
// Getting inputs
fast_length = input(title="Fast Length", type=input.integer, defval=5)
slow_length = input(title="Slow Length", type=input.integer, defval=8)
srcd = input(title="Source", type=input.source, defval=close)
signal_length = input(title="Signal Smoothing", type=input.integer, minval = 1, maxval = 50, defval = 3)
sma_source = input(title="Simple MA(Oscillator)", type=input.bool, defval=false)
sma_signal = input(title="Simple MA(Signal Line)", type=input.bool, defval=false)
// Plot colors
col_grow_above = #26A69A
col_grow_below = #FFC1D5
col_fall_above = #B2DFDB
col_fall_below = #EF5550
col_macd = #0094ff
col_signal = #ff6a00
// Calculating
fast_ma = sma_source ? sma(src, fast_length) : ema(src, fast_length)
slow_ma = sma_source ? sma(src, slow_length) : ema(src, slow_length)
macd = fast_ma - slow_ma
signal = sma_signal ? sma(macd, signal_length) : ema(macd, signal_length)
hist = macd - signal
plot(hist, title="Histogram", style=plot.style_columns, color=(hist>=0 ? (hist[1] < hist ? col_grow_above : col_fall_above) : (hist[1] < hist ? col_grow_below : col_fall_below) ), transp=0 )
plot(macd, title="MACD", color=col_macd, transp=0)
plot(signal, title="Signal", color=col_signal, transp=0)
Can you Please share the link to this chart? ThanksHi All, can I request to add arrows and alert for RSI Divergence that similar to Buy the dip.
I've no coding experience but I've tried add meter into the script.. Thanks in advance!
Awww ok, so just the one you listed up above. RSI with Divergence correct? Thanks@luiscervantes30 The code posted by @nightowl was for TradingView. Will not work in ToS.
How can I get these divergences in picture? This is on 3 min chart of /GC on Dec. 31. Thanks.
@chewie76 The one that you drew manually? Either by drawing it using the drawing toolkit, or you will have to code it. From what I know, divergences are best when identified manually
Thread starter | Similar threads | Forum | Replies | Date |
---|---|---|---|---|
Archived: TMO True Momentum Oscillator | Indicators | 346 | ||
Archived: Opening Range Breakout | Indicators | 340 | ||
Archived: Supertrend Indicator by Mobius for ThinkorSwim | Indicators | 312 | ||
Ultimate RSI [LuxAlgo] for ThinkOrSwim | Indicators | 12 | ||
Super 6x: RSI, MACD, Stoch, Loxxer, CCI, & Velocity [Loxx] for ThinkOrSwim | Indicators | 52 |
Start a new thread and receive assistance from our community.
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.
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.