Stochastic RSI with Divergences For ThinkOrSwim

MJFLOHIGH

New member
Plus
Author states:
Took my other Log RSI script and plugged in Stochastic RSI to see how divergences play on an oscillator with two lines. Turns out divergences are good at predicting changes in the oscillator but that doesn't mean that the oscillator will always mimic price action.

Log vs. no log is virtually the same.
ZkSzcHV.png


Here is the original Tradingview code:
https://www.tradingview.com/script/3ogyZpSE-Stochastic-RSI-with-Divergences/


For the new ThinkOrSwim code, you must scroll down to the next post
 
Last edited by a moderator:
Per a recommendation, I'm posting here a request to have the following TradingView indicator for a Stochastic RSI with Divergence converted into Thinkscript. I like using the Stochastic RSI vs. regular/fast/slow or full stochastics because it includes both a price and relative strength. The sorce code is below under the link to the source page. If there is anything else that I might need to provide, please let me know. Thanks in advance.
https://www.tradingview.com/script/3ogyZpSE-Stochastic-RSI-with-Divergences/

//@version=3
//Log RSI by @fskrypt
//Divergences by @RicardoSantos (@JustUncleL's edit)
//Edited by @NeoButane 8 Aug. 2018
study(title="Stochastic RSI with Divergences", shorttitle="Stoch RSI Divs", precision=0)
smoothK = input(3, minval=1)
smoothD = input(3, minval=1)
lengthRSI = input(14, minval=1)
lengthStoch = input(14, minval=1)
uselog = input(true, title="Log")
srcIn = input(close, type=source, title="Source")
showdivs = input(true, title="Show Divergences")
showhidden = input(false, title="Show Hidden Divergences")
showchan = input(false, title="Show Divergences Channel")

src = uselog ? log(srcIn) : srcIn
rsi1 = rsi(src, lengthRSI)
kk = sma(stoch(rsi1, rsi1, rsi1, lengthStoch), smoothK)
d = sma(kk, smoothD)
hm = input(false, title="Use Average of both K & D")
k = hm ? avg(kk, d) : kk
a = plot(kk, color=blue, linewidth=1, transp=0, title="K")
b = plot(d, color=orange, linewidth=1, transp=0, title="D")
f = kk >= d ? blue : orange
fill(a, b, title="KD Fill", color=f)
lower = hline(20, title="Lower Band")
upper = hline(80, title="Upper Band")
fill(upper, lower, color=aqua, transp=95, title="Background")
// plotshape(cross(kk, d) and kk > d ? 80 : na, title="Crossover", color=green, style=shape.circle, location=location.absolute)
// plotshape(cross(kk, d) and d > kk ? 20 : na, title="Crossunder", color=red, style=shape.circle, location=location.absolute)


//------------------------------
//@RicardoSantos' Divergence Script
f_top_fractal(_src)=>_src[4] < _src[2] and _src[3] < _src[2] and _src[2] > _src[1] and _src[2] > _src[0]
f_bot_fractal(_src)=>_src[4] > _src[2] and _src[3] > _src[2] and _src[2] < _src[1] and _src[2] < _src[0]
f_fractalize(_src)=>f_top_fractal(_src) ? 1 : f_bot_fractal(_src) ? -1 : 0
//-------------------------
fractal_top = f_fractalize(k) > 0 ? k[2] : na
fractal_bot = f_fractalize(k) < 0 ? k[2] : na
high_prev = valuewhen(fractal_top, k[2], 0)[2]
high_price = valuewhen(fractal_top, high[2], 0)[2]
low_prev = valuewhen(fractal_bot, k[2], 0)[2]
low_price = valuewhen(fractal_bot, low[2], 0)[2]
regular_bearish_div = fractal_top and high[2] > high_price and k[2] < high_prev
hidden_bearish_div = fractal_top and high[2] < high_price and k[2] > high_prev
regular_bullish_div = fractal_bot and low[2] < low_price and k[2] > low_prev
hidden_bullish_div = fractal_bot and low[2] > low_price and k[2] < low_prev
//-------------------------
plot(showchan?fractal_top:na, title="Top Div Channel", offset=-2, color=gray)
plot(showchan?fractal_bot:na, title="Bottom Div Channel", offset=-2, color=gray)
col1 = regular_bearish_div ? red : hidden_bearish_div and showhidden ? red : na
col2 = regular_bullish_div ? green : hidden_bullish_div and showhidden ? green : na
col3 = regular_bearish_div ? red : hidden_bearish_div and showhidden ? red : showchan ? gray : na
col4 = regular_bullish_div ? green : hidden_bullish_div and showhidden ? green : showchan ? gray : na
plot(title='H F', series=showdivs and fractal_top ? k[2] : na, color=col1, linewidth=2, offset=-2)
plot(title='L F', series=showdivs and fractal_bot ? k[2] : na, color=col2, linewidth=2, offset=-2)
plot(title='H D', series=showdivs and fractal_top ? k[2] : na, style=circles, color=col3, linewidth=3, offset=-2)
plot(title='L D', series=showdivs and fractal_bot ? k[2] : na, style=circles, color=col4, linewidth=3, offset=-2)
plotshape(title='+RBD', series=showdivs and regular_bearish_div ? k[2] : na, text='R', style=shape.labeldown, location=location.absolute, color=red, textcolor=white, offset=-2)
plotshape(title='+HBD', series=showdivs and hidden_bearish_div and showhidden ? k[2] : na, text='H', style=shape.labeldown, location=location.absolute, color=red, textcolor=white, offset=-2)
plotshape(title='-RBD', series=showdivs and regular_bullish_div ? k[2] : na, text='R', style=shape.labelup, location=location.absolute, color=green, textcolor=white, offset=-2)
plotshape(title='-HBD', series=showdivs and hidden_bullish_div and showhidden ? k[2] : na, text='H', style=shape.labelup, location=location.absolute, color=green, textcolor=white, offset=-2)
alertcondition(regular_bearish_div, "Regular Bearish Stoch RSI", "Regular Bearish div. on SRSI")
alertcondition(regular_bullish_div, "Regular Bullish Stoch RSI", "Regular Bullish div. on SRSI")
alertcondition(hidden_bearish_div, "Hidden Bearish Stoch RSI", "Hidden Bearish div. on SRSI")
alertcondition(hidden_bullish_div, "Hidden Bullish Stoch RSI", "Hidden Bullish div. on SRSI")
check the below:

CSS:
#// Indicator for TOS
#//Log RSI by @fskrypt
#//Divergences by @RicardoSantos (@JustUncleL's edit)
#//Edited by @NeoButane 8 Aug. 2018
#study(title="Stochastic RSI with Divergences", shorttitle="Stoch RSI Divs", precision=0)
# Converted by Sam4Cok@Samer800    - 01/2025
declare lower;
#// Calculate the Stochastic RSI
input displayOptions = {"Heikin-Ashi",Default "Lines"};
input ColorBar = yes;
input useLog = yes; # title="Log")
input UseAverageKAndD = no; # title="Use Average of both K & D")
input source = close;#, title="Source")
input smoothK = 3;#, minval=1, title="Stochastic %K Smoothing")
input smoothD = 3;#, minval=1, title="Stochastic %D Smoothing")
input lengthRsi = 14;#, minval=1, title="RSI Length")
input lengthStoch = 14;#, minval=1, title="Stochastic Length")
input showRegularDivergences = yes; # title="Show Divergences")
input ShowHiddenDivergences = no; #, title="Show Hidden Divergences")
input ShowDivergencesChannel = no; # title="Show Divergences Channel")

def na = Double.NaN;
def last = IsNaN(close);
def ha = displayOptions == displayOptions."Heikin-Ashi";
def n = n[1] + 1;
def bar = if !last then n else bar[1];
def src = if useLog then Log(source) else source;
#--- Color -----
DefineGlobalColor("up" , CreateColor(0, 127, 255));
DefineGlobalColor("dn" , CreateColor(255, 127, 0));
DefineGlobalColor("upBtm" , CreateColor(137, 196, 255));
DefineGlobalColor("dnTop" , CreateColor(255, 196, 137));

# stoch(source, high, low, length) =>
script stoch {
    input src = close;
    input h = high;
    input l = low;
    input len = 14;
    def hh = Highest(h, len);
    def ll = Lowest(l, len);
    def stoch = 100 * (src - ll) / (hh - ll);
    plot return = stoch;
}
def rsi1 = RSI(PRICE = src, LENGTH = lengthRSI);
def sto = stoch(rsi1, rsi1, rsi1, lengthStoch);
def kk = Average(sto, smoothK);
def d = Average(kk, smoothD);
def k = if UseAverageKAndD then (kk + d) / 2 else kk;
#// Calculate the Stochastic Heikin-Ashi candles
def cl = k;
def op = cl[1];
def hi = Max(cl, cl[1]);
def lo = Min(cl, cl[1]);
def ha_close = if ha then (hi + lo + cl + op) / 4 else na; #(kk + d) / 2 else na;
def haOpen = CompoundValue(1, (haOpen[1] + ha_close[1]) / 2, (op + cl) / 2);
def ha_open  = if haOpen then haOpen else na;
def ha_high  = Max(hi, Max(ha_open, ha_close));
def ha_low   = Min(lo, Min(ha_close, ha_open));
def price    = (ha_open + ha_close + ha_high + ha_low) / 4;

def col = if ha_close >= ha_open then if ha_close[1] >= ha_open[1] then 2 else 1 else
          if ha_close[1] < ha_open[1] then -2 else -1;

#// Plot the Heikin-Ashi Stochastic RSI

AddChart(high = if col == 2 then ha_high else na, low = ha_low , open = ha_close,  close = ha_open,
         type = ChartType.CANDLE, growcolor =  GlobalColor("up"));

AddChart(high = if col == 1 then ha_high else na, low = ha_low , open = ha_close,  close = ha_open,
         type = ChartType.CANDLE, growcolor =  GlobalColor("upBtm"));

AddChart(high = if col == -2 then ha_high else na, low = ha_low , open = ha_open,  close = ha_close,
         type = ChartType.CANDLE, growcolor =  GlobalColor("dn"));

AddChart(high = if col == -1 then ha_high else na, low = ha_low , open = ha_open,  close = ha_close,
         type = ChartType.CANDLE, growcolor =  GlobalColor("dnTop"));

#// Plot
plot kLine = if !ha and !last then kk else na;
plot dLine = if !ha and !last then d else na;
kLine.SetDefaultColor(GlobalColor("up"));
dLine.SetDefaultColor(GlobalColor("dn"));

AddCloud(kLine, dLine, GlobalColor("up"), GlobalColor("dn"));
#// Use the up and down colors in your script
plot mindline = if last then na else 50;
plot lineUp   = if last then na else 80;
plot lineDn   = if last then na else 20;

mindline.SetStyle(Curve.SHORT_DASH);
lineUp.SetPaintingStrategy(PaintingStrategy.DASHES);
lineDn.SetPaintingStrategy(PaintingStrategy.DASHES);
mindline.SetDefaultColor(Color.DARK_GRAY);
lineUp.SetDefaultColor(Color.DARK_GRAY);
lineDn.SetDefaultColor(Color.DARK_GRAY);

AddCloud(lineUp, lineDn, Color.DARK_GRAY);

AssignPriceColor( if !ColorBar then Color.CURRENT else
                  if col > 0 and price > 80 then Color.GREEN else
                  if col > 0 then Color.DARK_GREEN else
                  if col < 0 and price < 20 then GlobalColor("dn") else GlobalColor("dnTop"));

#//@RicardoSantos' Divergence Script
def f_top_fractal = k[4] < k[2] and k[3] < k[2] and k[2] > k[1] and k[2] > k[0];
def f_bot_fractal = k[4] > k[2] and k[3] > k[2] and k[2] < k[1] and k[2] < k[0];
def f_fractalize = if f_top_fractal then 1 else if f_bot_fractal then -1 else 0;
#//-------------------------
def fractal_top = if f_fractalize > 0 then k[2] else 0;
def fractal_bot = if f_fractalize < 0 then k[2] else 0;
def highBarPrev = if fractal_top then bar[2] else highBarPrev[1];
def high_prev1  = if fractal_top then k[2]   else high_prev1[1];
def high_price1 = if fractal_top then high[2] else high_price1[1];
def lowBarPrev  = if fractal_bot then bar[2]  else lowBarPrev[1];
def low_prev1   = if fractal_bot then k[2]   else low_prev1[1];
def low_price1  = if fractal_bot then low[2] else low_price1[1];
def high_prev  = high_prev1[2];
def high_price = high_price1[2];
def low_prev   = low_prev1[2];
def low_price  = low_price1[2];


def regular_bearish_div = showRegularDivergences and fractal_top and high[2] > high_price and k[2] < high_prev;
def hidden_bearish_div  = ShowHiddenDivergences and fractal_top and high[2] < high_price and k[2] > high_prev;
def regular_bullish_div = showRegularDivergences and fractal_bot and low[2] < low_price and k[2] > low_prev;
def hidden_bullish_div  = ShowHiddenDivergences and fractal_bot and low[2] > low_price and k[2] < low_prev;
def regBarBear  = if regular_bearish_div[-2] then highBarPrev[1] else 0;
def lastRegBear = if regular_bearish_div[-2] then bar else 0;
def regBarBull  = if regular_bullish_div[-2] then lowBarPrev[1] else 0;
def lastRegBull = if regular_bullish_div[-2] then bar else 0;
def hidBarBear  = if hidden_bearish_div[-2] then highBarPrev[1] else 0;
def lasthidBear = if hidden_bearish_div[-2] then bar else 0;
def hidBarBull  = if hidden_bullish_div[-2] then lowBarPrev[1] else 0;
def lasthidBull = if hidden_bullish_div[-2] then bar else 0;
#//-------------------------
plot topFract = if ShowDivergencesChannel and fractal_top[-2] then fractal_top[-2] else na;
plot botFract = if ShowDivergencesChannel and fractal_bot[-2] then fractal_bot[-2] else na;
plot topDiv = if ShowDivergencesChannel and fractal_top[-2] then fractal_top[-2] else na; # "Top Div Channel"
plot botDiv = if ShowDivergencesChannel and fractal_bot[-2] then fractal_bot[-2] else na; # "Bottom Div Channel"
topDiv.EnableApproximation();
botDiv.EnableApproximation();
topDiv.SetDefaultColor(Color.GRAY);
botDiv.SetDefaultColor(Color.GRAY);
topFract.SetDefaultColor(Color.GRAY);
botFract.SetDefaultColor(Color.GRAY);
topFract.SetPaintingStrategy(3);
botFract.SetPaintingStrategy(2);

AddChartBubble(regular_bearish_div[-2], k, "R", Color.RED);
AddChartBubble(regular_bullish_div[-2], k, "R", Color.GREEN, no);
AddChartBubble(hidden_bearish_div[-2], k, "H", Color.DARK_RED);
AddChartBubble(hidden_bullish_div[-2], k, "H", Color.DARK_GREEN, no);


plot regBearLine = if bar == HighestAll(regBarBear)  then k else
                   if bar == HighestAll(lastRegBear) then k else na;
plot regBullLine = if bar == HighestAll(regBarBull)  then k else
                   if bar == HighestAll(lastRegBull) then k else na;
plot hidBearLine = if bar == HighestAll(hidBarBear)  then k else
                   if bar == HighestAll(lasthidBear) then k else na;
plot hidBullLine = if bar == HighestAll(hidBarBull)  then k else
                   if bar == HighestAll(lasthidBull) then k else na;
regBearLine.EnableApproximation();
regBullLine.EnableApproximation();
hidBearLine.EnableApproximation();
hidBullLine.EnableApproximation();
regBearLine.SetDefaultColor(Color.RED);
regBullLine.SetDefaultColor(Color.GREEN);
hidBearLine.SetDefaultColor(Color.DARK_RED);
hidBullLine.SetDefaultColor(Color.DARK_GREEN);

#---- END CODE
 

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

Similar threads

Not the exact question you're looking for?

Start a new thread and receive assistance from our community.

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