Buy the dips - sell the tops For ThinkOrSwim

FOTM_8888

Active member
The author states:
This script is a merge of the RSI and the Williams %R.
I've observed that in strong uptrends, we go from RSI overbought to RSI overbought, but it hardly gets oversold. (the same in the opposite direction)
To find a better entry point, Williams %R is used to find oversold conditions in an uptrend or overbought in a downtrend.

=> When W%R returns from oversold/overbought to normal, a triangle will be plotted and this is the point of entry to add to your position. (there's an option to mark all candles in the overbought/oversold region, by default it is off)
=> When RSI goes from overbought back to normal it will tell you to buy the dip. In a downtrend it will tell you to sell the tops.
=> When the RSI gets oversold and the previous RSI was overbought, it will mark to exit the position

Trading it this way is not the best idea ;-) 2 Interesting observations however:
  • Once you get the entry right, in 80% of the cases, you do reach the next RSI oversold/overbought level. Keeping your position open until you reach that level can be an option to maximize profits.
  • When a triangle is plotted and it is the low compared to the previous more or less 5 candles (same for the high), chances are high it will be taken out a few candles later, so don't take a trade yet.

C1eDcqq.png

please convert:
https://www.tradingview.com/v/snhADyBo/
 
Last edited by a moderator:

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

https://www.tradingview.com/v/snhADyBo/

//@version=5
indicator(title="Buy the dips - sell the tops", shorttitle="BTD-STT", format=format.price, precision=2, overlay=true)
var lastRSI = "neutral"
var upTrend = false
var downTrend = false
var label lbl = na
//Inputs
rsiLengthInput = input.int(14, minval=1, title="RSI Length", group="RSI Settings")
rsiSourceInput = input.source(close, "Source", group="RSI Settings")
rsiOS = input(30,"Oversold level", group="RSI Settings")
rsiOB = input(70,"Overbought level", group="RSI Settings")
length = input(24,"Period", group="Williams %R Settings")
src = input(close, "Source", group="Williams %R Settings")
showAllExtremes = input.bool(false,"Show all oversold/bought candles despite the trend")
col = input.color(color.gray, "RSI/%R Label Background Color", group="Layout")
txt_col = input.color(color.yellow, "RSI/%R Label Text Color", group="Layout")
exit_txt_col = input.color(color.gray, "EXIT Text Color", group="Layout")
//RSI calculation
up = ta.rma(math.max(ta.change(rsiSourceInput), 0), rsiLengthInput)
down = ta.rma(-math.min(ta.change(rsiSourceInput), 0), rsiLengthInput)
rsi = down == 0 ? 100 : up == 0 ? 0 : 100 - (100 / (1 + up / down))
bool oversold = false
bool overbought = false
if rsi < rsiOS
lastRSI := "Oversold"
else if rsi > rsiOB
lastRSI := "Overbought"
//WPR calculation
_pr(length) =>
max = ta.highest(length)
min = ta.lowest(length)
100 * (src - max) / (max - min)
percentR = _pr(length)
//Main program
bool WPRoversoldToNormal = false
bool WPRoverboughtToNormal = false
if lastRSI == "Overbought" and percentR < -80
upTrend := true
downTrend := false
else if lastRSI == "Oversold" and percentR > -20
upTrend := false
downTrend := true
if percentR[1] > -20 and percentR < -20
WPRoverboughtToNormal := true
else if percentR[1] < -80 and percentR > -80
WPRoversoldToNormal := true

plotshape(upTrend and not showAllExtremes and WPRoversoldToNormal ? close : na, style=shape.triangleup, location=location.belowbar, size=size.small, title="Buy the dip", color=#87cefa)
plotshape(downTrend and not showAllExtremes and WPRoverboughtToNormal ? close : na, style=shape.triangledown, location=location.abovebar, size=size.small, title="Sell the top", color=#87cefa)
plotshape(showAllExtremes and WPRoverboughtToNormal ? close : na, style=shape.triangledown, location=location.abovebar, size=size.small, title="Sell the top", color=#87cefa)
plotshape(showAllExtremes and WPRoversoldToNormal ? close : na, style=shape.triangleup, location=location.belowbar, size=size.small, title="Buy the dip", color=#87cefa)
if rsi >= rsiOS and rsi[1] < rsiOS
oversold := true
else if rsi <= 70 and rsi[1] > rsiOB
overbought := true
plotshape(oversold, style=shape.labelup, location=location.belowbar, color=color.red, text="Look to\nsell tops",textcolor=color.white, size=size.tiny, title="Sell label")
plotshape(overbought, style=shape.labeldown, location=location.abovebar, color=color.green, text="Look to\nbuy dips",textcolor=color.white, size=size.tiny, title="Buy label")
plotcross = false
if rsi >= rsiOB and downTrend
plotcross := true
downTrend := false
else if rsi <= rsiOS and upTrend
plotcross := true
upTrend := false
plotshape(plotcross, style=shape.xcross, location=location.belowbar, color=color.red, text="EXIT",textcolor=exit_txt_col, size=size.tiny, title="Warning label")

label_X_Loc = time_close + (( time_close - time_close[1] ) * 2 ) // Set Label offset
rsi_txt = math.round(rsi,2) > rsiOB ? "Overbought" : math.round(rsi,2) < rsiOS ? "Oversold" : 'Neutral'
percentR_txt = math.round(percentR,2) > -20 ? "Overbought" : math.round(percentR,2) < -80 ? "Oversold" : 'Neutral'
//l = label.new(label_X_Loc, close, "RSI:" + str.tostring(math.round(rsi,2)) + " (O/B>70, O/S<30)\n%R: " + str.tostring(math.round(percentR,2)) + " (O/B>-20, O/S<-80)", xloc.bar_time, yloc.price, color=col, textcolor=txt_col, size=size.normal, style=label.style_label_left, textalign=text.align_left)
l = label.new(label_X_Loc, close, "RSI: " + rsi_txt + " (" + str.tostring(math.round(rsi,2)) + ")\n%R: " + percentR_txt + " ("+ str.tostring(math.round(percentR,2)) +")", xloc.bar_time, yloc.price, color=col, textcolor=txt_col, size=size.normal, style=label.style_label_left, textalign=text.align_left)
label.delete(l[1])
find below

CSS:
# https://www.tradingview.com/v/snhADyBo/
# // @Greg_007
# indicator(title="Buy the dips - sell the tops", shorttitle="BTD-STT", format=format.price, precision=2, overlay=true)
# Converted by Sam4Cok@Samer800    - 01/2024
#//Inputs
input showLabel = yes;
input rsiLength = 14;#, minval=1, title="RSI Length", group="RSI Settings")
input rsiSource = close;#, "Source", group="RSI Settings")
input OversoldLevel = 30;#,"Oversold level", group="RSI Settings")
input OverboughtLevel = 70;#,"Overbought level", group="RSI Settings")
input WilliamsRLength = 24;#,"Period", group="Williams %R Settings")
input WilliamsRSrc = close;#, "Source", group="Williams %R Settings")
input showAllExtremes = no;#(false,"Show all oversold/bought candles despite the trend")

def na = Double.NaN;

#//RSI calculation
def nRSI = rsi(Price = rsiSource, Length = rsiLength);
def lastRSI = if nrsi < OversoldLevel then -1 else
              if nrsi > OverboughtLevel then 1 else lastRSI[1];
#//WPR calculation
#_pr(length) =>
def max = highest(high, WilliamsRLength);
def min = lowest(low, WilliamsRLength);
def wpr = 100 * (WilliamsRSrc - max) / (max - min);
def percentR = wpr;

#//Main program
def WPRoversoldToNormal;
def WPRoverboughtToNormal;
def upTrend;
def downTrend;
def upTrend1;
def downTrend1;
if lastRSI == 1 and percentR < -80 {
    upTrend = yes;
    downTrend = no;
    } else if lastRSI == -1 and percentR > -20 {
    upTrend = no;
    downTrend = yes;
    } else {
    upTrend = upTrend1[1];
    downTrend = downTrend1[1];
}
if percentR[1] > -20 and percentR < -20 {
    WPRoverboughtToNormal = yes;
    WPRoversoldToNormal = no;
    } else if percentR[1] < -80 and percentR > -80 {
    WPRoverboughtToNormal = no;
    WPRoversoldToNormal = yes;
    } else {
    WPRoverboughtToNormal = no;
    WPRoversoldToNormal = no;
}
#---   
plot buyDip0  = if upTrend and !showAllExtremes and WPRoversoldToNormal then low else na;# "Buy the dip"
plot SellDip0 = if downTrend and !showAllExtremes and WPRoverboughtToNormal then high else na;# "Sell the top"
plot SellDip1 = if showAllExtremes and WPRoverboughtToNormal then high else na; # "Sell the top"
plot buyDip1  = if showAllExtremes and WPRoversoldToNormal then low else na; # "Buy the dip"

buyDip0.SetDefaultColor(Color.CYAN);
buyDip1.SetDefaultColor(Color.CYAN);
SellDip0.SetDefaultColor(Color.MAGENTA);
SellDip1.SetDefaultColor(Color.MAGENTA);
buyDip0.SetPaintingStrategy(PaintingStrategy.BOOLEAN_WEDGE_DOWN);
buyDip1.SetPaintingStrategy(PaintingStrategy.BOOLEAN_WEDGE_DOWN);
SellDip0.SetPaintingStrategy(PaintingStrategy.BOOLEAN_WEDGE_UP);
SellDip1.SetPaintingStrategy(PaintingStrategy.BOOLEAN_WEDGE_UP);

def oversold;
def overbought;

if nrsi >= OversoldLevel and nrsi[1] < OversoldLevel {
    oversold = yes;
    overbought = no;
    } else if nrsi <= 70 and nrsi[1] > OverboughtLevel {
    oversold = no;
    overbought = yes;
    } else {
    oversold = no;
    overbought = no;
}

AddChartBubble(oversold, low, "sell tops", Color.RED, no);    # "Sell label"
AddChartBubble(overbought, high, "buy dips", Color.GREEN);    # "Buy label"

def plotcross;
if nrsi >= OverboughtLevel and downTrend {
    plotcross = yes;
    upTrend1 = upTrend;
    downTrend1 = no;
    } else if nrsi <= OversoldLevel and upTrend {
    plotcross = yes;
    upTrend1 = no;
    downTrend1 = downTrend;
    } else {
    plotcross = no;
    upTrend1 = upTrend;
    downTrend1 = downTrend;
}

AddChartBubble(plotcross, low, "EXIT", Color.MAGENTA, no); #"Warning label")

def roundRsi = Round(nrsi,2);
def roundWpr = Round(percentR,2);
def rsi_txt = if roundRsi > OverboughtLevel then 1 else
              if roundRsi < OversoldLevel then -1 else 0;
def percentR_txt = if roundWpr > -20 then 1 else
                   if roundWpr < -80 then -1 else 0;

AddLabel(showLabel and rsi_txt>0, "RSI: Overbought(" + roundRsi + ")", Color.RED);
AddLabel(showLabel and rsi_txt<0, "RSI: Oversold(" + roundRsi + ")", Color.GREEN);
AddLabel(showLabel and rsi_txt==0, "RSI: Neutral(" + roundRsi + ")", Color.WHITE);

AddLabel(showLabel and percentR_txt>0, "%R: Overbought(" + roundWpr + ")", Color.RED);
AddLabel(showLabel and percentR_txt<0, "%R: Oversold(" + roundWpr + ")", Color.GREEN);
AddLabel(showLabel and percentR_txt==0, "%R: Neutral(" + roundWpr + ")", Color.WHITE);

#-- END of CODE
 
Last edited:
Does this repaint?
Repainting?
This script is a merge of the RSI and the Williams %R.. These indicators generally don't repaint.
Indicators on the forum that do not have a "repaints" prefix generally don't repaint.

Almost all the indicators on the forum will have the current candle update every tick until the candle is closed.
This is because there is no way to predict the current candle close until it happens.
 
Repainting?
This script is a merge of the RSI and the Williams %R.. These indicators generally don't repaint.
Indicators on the forum that do not have a "repaints" prefix generally don't repaint.

Almost all the indicators on the forum will have the current candle update every tick until the candle is closed.
This is because there is no way to predict the current candle close until it happens.
Whoops I knew that. Some how I posted to the wrong thread.
 
AddChartBubble(oversold, low, "sell tops", Color.RED, no); # "Sell label"
AddChartBubble(overbought, high, "buy dips", Color.GREEN); # "Buy label"
I think the bubble descriptions are backwards.
I adjusted them and added @samer800 calculations (with some mods) - the calculations seem to be off a bit, not sure where it's going wrong, but it shows potential.

Code:
# https://www.tradingview.com/v/snhADyBo/
# // @Greg_007
# indicator(title="Buy the dips - sell the tops", shorttitle="BTD-STT", format=format.price, precision=2, overlay=true)
# Converted by Sam4Cok@Samer800    - 01/2024
#//Inputs
input showLabel = yes;
input rsiLength = 14;#, minval=1, title="RSI Length", group="RSI Settings")
input rsiSource = close;#, "Source", group="RSI Settings")
input OversoldLevel = 30;#,"Oversold level", group="RSI Settings")
input OverboughtLevel = 70;#,"Overbought level", group="RSI Settings")
input WilliamsRLength = 20;#,"Period", group="Williams %R Settings")
input WilliamsRSrc = close;#, "Source", group="Williams %R Settings")
input showAllExtremes = no;#(false,"Show all oversold/bought candles despite the trend")

def na = Double.NaN;

#//RSI calculation
def nRSI = RSI(Price = rsiSource, Length = rsiLength);
def lastRSI = if nRSI < OversoldLevel then -1 else
              if nRSI > OverboughtLevel then 1 else lastRSI[1];
#//WPR calculation
#_pr(length) =>
def max = Highest(high, WilliamsRLength);
def min = Lowest(low, WilliamsRLength);
def wpr = 100 * (WilliamsRSrc - max) / (max - min);
def percentR = wpr;

#//Main program
def WPRoversoldToNormal;
def WPRoverboughtToNormal;
def upTrend;
def downTrend;
def upTrend1;
def downTrend1;
if lastRSI == 1 and percentR < -80 {
    upTrend = yes;
    downTrend = no;
} else if lastRSI == -1 and percentR > -20 {
    upTrend = no;
    downTrend = yes;
} else {
    upTrend = upTrend1[1];
    downTrend = downTrend1[1];
}
if percentR[1] > -20 and percentR < -20 {
    WPRoverboughtToNormal = yes;
    WPRoversoldToNormal = no;
} else if percentR[1] < -80 and percentR > -80 {
    WPRoverboughtToNormal = no;
    WPRoversoldToNormal = yes;
} else {
    WPRoverboughtToNormal = no;
    WPRoversoldToNormal = no;
}
#--- 
plot buyDip0  = if upTrend and !showAllExtremes and WPRoversoldToNormal then low else na;# "Buy the dip"
plot SellDip0 = if downTrend and !showAllExtremes and WPRoverboughtToNormal then high else na;# "Sell the top"
plot SellDip1 = if showAllExtremes and WPRoverboughtToNormal then high else na; # "Sell the top"
plot buyDip1  = if showAllExtremes and WPRoversoldToNormal then low else na; # "Buy the dip"

buyDip0.SetDefaultColor(Color.CYAN);
buyDip1.SetDefaultColor(Color.CYAN);
SellDip0.SetDefaultColor(Color.MAGENTA);
SellDip1.SetDefaultColor(Color.MAGENTA);
buyDip0.SetPaintingStrategy(PaintingStrategy.BOOLEAN_WEDGE_DOWN);
buyDip1.SetPaintingStrategy(PaintingStrategy.BOOLEAN_WEDGE_DOWN);
SellDip0.SetPaintingStrategy(PaintingStrategy.BOOLEAN_WEDGE_UP);
SellDip1.SetPaintingStrategy(PaintingStrategy.BOOLEAN_WEDGE_UP);

def oversold;
def overbought;

if nRSI >= OversoldLevel and nRSI[1] < OversoldLevel {
    oversold = yes;
    overbought = no;
} else if nRSI <= 70 and nRSI[1] > OverboughtLevel {
    oversold = no;
    overbought = yes;
} else {
    oversold = no;
    overbought = no;
}

#AddChartBubble(oversold, low, "Buy Dips", Color.GREEN, no);    # "Sell label"
#AddChartBubble(overbought, high, "Sell Tops", Color.RED);    # "Buy label"

def plotcross;
if nRSI >= OverboughtLevel and downTrend {
    plotcross = yes;
    upTrend1 = upTrend;
    downTrend1 = no;
} else if nRSI <= OversoldLevel and upTrend {
    plotcross = yes;
    upTrend1 = no;
    downTrend1 = downTrend;
} else {
    plotcross = no;
    upTrend1 = upTrend;
    downTrend1 = downTrend;
}

#AddChartBubble(plotcross, low, "EXIT", Color.MAGENTA, no); #"Warning label")

def roundRsi = Round(nRSI, 2);
def roundWpr = Round(percentR, 2);
def rsi_txt = if roundRsi > OverboughtLevel then 1 else
              if roundRsi < OversoldLevel then -1 else 0;
def percentR_txt = if roundWpr > -20 then 1 else
                   if roundWpr < -80 then -1 else 0;

AddLabel(showLabel and rsi_txt > 0, "RSI: Overbought(" + roundRsi + ")", Color.RED);
AddLabel(showLabel and rsi_txt < 0, "RSI: Oversold(" + roundRsi + ")", Color.GREEN);
AddLabel(showLabel and rsi_txt == 0, "RSI: Neutral(" + roundRsi + ")", Color.WHITE);

AddLabel(showLabel and percentR_txt > 0, "%R: Overbought(" + roundWpr + ")", Color.RED);
AddLabel(showLabel and percentR_txt < 0, "%R: Oversold(" + roundWpr + ")", Color.GREEN);
AddLabel(showLabel and percentR_txt == 0, "%R: Neutral(" + roundWpr + ")", Color.WHITE);

#-- END of CODE


################################################ COMPUTATIONS
def buy1 = (uptrend and WPRoversoldToNormal);
def sell2 = (downtrend and WPRoverboughtToNormal);
def buy  = oversold OR  buy1;
def sell = overbought OR  sell2;

input ExitLength = 21;
input showorders = yes;
input showinfolabel = yes;
input ShowBubbles = yes;
input TargetATR = 1.25;
input TargetStop = 1.07;
input showTargetBubbles = yes;
input ShowStopBubbles = yes;
input ShowEntryBands = No;
input ShowExitBands = yes;
plot ExitHigh = Highest(high, ExitLength);
plot ExitLow = Lowest(low, ExitLength);
exithigh.setHiding(!ShowExitBands);
exitlow.setHiding(!ShowExitBands);
def LongTrade;
def ShortTrade;
def TradeisON;
def entry;
def win;
def los;
def profit;
def losses;
def TP;
def SL;
input share = 100;
plot  TakeProfit ;
plot stopLoss   ;
plot entryLine ;
input ATRLen = 30;
def mATR = Round (Average(TrueRange(high, close, low)[1], ATRLen));
def tpVar   = (2 *  (mATR * TargetATR));
def slLong  = (exitLow -(  TargetStop * mATR));
def slShort = (exitHigh + (   TargetStop * mATR));
def bar_index = AbsValue(BarNumber());

def Long  = showorders and buy  and !TradeisON[1];
def Short = showorders   and sell and !TradeisON[1];
def TradeFire = Long or Short;

if Long and !TradeisON[1] {
    LongTrade = yes;
    ShortTrade = no;
} else
if Short and !TradeisON[1] {
    LongTrade = no;
    ShortTrade = yes;
} else {
    LongTrade = LongTrade[1];
    ShortTrade = ShortTrade[1];
}


if TradeFire and !TradeisON[1] {
    entry = close[1];
    TP = if Long  then entry + tpVar else
         if Short then entry - tpVar else na;
    SL = if Long  then slLong  else
         if Short then slShort else na;
    win = if !bar_index then 0 else win[1];
    los = if !bar_index then 0 else los[1];
    profit = profit[1];
    losses = losses[1];
    TradeisON = yes;
} else
if LongTrade and TradeisON[1] {
    entry = entry[1];
    TP = TP[1];
    SL = SL[1];
    win = if high  >= TP then win[1] + 1 else win[1];
    los = if low <= SL then los[1] + 1 else los[1];
    profit = if (high > TP) then profit[1] + AbsValue(TP - entry) * share else profit[1];
    losses = if (low <= SL) then losses[1] + AbsValue(entry - close) * share else losses[1];
    TradeisON = if high >= TP then no else
                if low <= SL then no else TradeisON[1];
} else
if ShortTrade and TradeisON[1] {
    entry = entry[1];
    TP = TP[1];
    SL = SL[1];
    win = if low <= TP then win[1] + 1 else win[1];
    los = if high >= SL then los[1] + 1 else los[1];
    profit = if (low < TP) then profit[1] + AbsValue(entry - TP) * share else profit[1];
    losses = if (high >= SL) then losses[1] + AbsValue(close - entry) * share else losses[1];
    TradeisON = if low <= TP then no else
                if high >= SL then no else TradeisON[1];
} else {
    entry = na;
    win = if !bar_index then 0 else win[1];
    los = if !bar_index then 0 else los[1];
    profit = profit[1];
    losses = losses[1];
    TradeisON = TradeisON[1];
    TP = if TradeisON then TP[1] else na;
    SL = if TradeisON then SL[1] else na;
}


#-- Backtest
plot TradeEnd = if !TradeisON and TradeisON[1] then
                 if los > los[1] then SL[1] else TP[1] else na;
TradeEnd.AssignValueColor(if win > win[1] then Color.GREEN else Color.DARK_ORANGE);
TradeEnd.SetPaintingStrategy(PaintingStrategy.SQUARES);
AddChartBubble( ShowStopBubbles , TradeEnd, TradeEnd, Color.RED );#
Tradeend.setLineWeight(5);
#-- Label
def totTrade = win + los;
def winRate = Round(win / totTrade * 100, 0);
def PandL   = Round(profit - losses, 2);


AddLabel(showinfolabel, "Tot Trade: " + totTrade, Color.WHITE);
AddLabel(showinfolabel, "P/L: $" + PandL,
                        if PandL > 0 then Color.LIGHT_GREEN else
                        if PandL < 0 then Color.PINK else Color.GRAY);
AddLabel(showinfolabel, "Losses: $" + losses,  Color.RED);
AddLabel(showinfolabel, "WinRate: " + winRate + "%",
                        if winRate > 50 then Color.GREEN else
                        if winRate < 50 then Color.RED else Color.GRAY);
AddLabel(showinfolabel, "Win: " + win, Color.GREEN);
AddLabel(showinfolabel, "Loss: " + los, Color.RED);

#--BarColor


TakeProfit.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);
stopLoss.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);
entryLine.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);
TakeProfit.SetDefaultColor(Color.CYAN);
stopLoss.SetDefaultColor(Color.MAGENTA);

#--BarColor
def BearCon = TradeisON and ShortTrade;
def BullCon = TradeisON and LongTrade;
def buyCond = BullCon and !BullCon[1];
def sellCond = BearCon and !BearCon[1];
TakeProfit = if TradeisON then TP else na;
stopLoss   = if TradeisON then SL else na;
entryLine = if TradeisON then entry else na;

AddChartBubble( ShowBubbles and buyCond  , entry, "B" + entry, Color.GREEN, no );#and !buyCond[1]
AddChartBubble( ShowBubbles and sellCond  , entry, "S" + entry,  Color.RED );#and !sellcond[1]
AddChartBubble( showTargetBubbles and buyCond, TakeProfit, TakeProfit, Color.GREEN, no );#
AddChartBubble( showTargetBubbles and sellCond, TakeProfit, TakeProfit, Color.LIME );#

entryLine.AssignValueColor(if buyCond then Color.GREEN else Color.LIME);
entryLine.SetLineWeight(3);

TakeProfit.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);
TakeProfit.SetLineWeight(3);
stopLoss.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);
stopLoss.SetLineWeight(3);
entryLine.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);
TakeProfit.SetDefaultColor(Color.CYAN);
stopLoss.SetDefaultColor(Color.RED);


#alert( Long, "Buy", Alert.Bar, Sound.Bell);
#alert(short, "Sell", Alert.Bar, Sound.Bell);
#-- END of CODE
 
Last edited:
I think the bubble descriptions are backwards.
I adjusted them and added @samer800 calculations (with some mods) - the calculations seem to be off a bit, not sure where it's going wrong, but it shows potential.

Code:
# https://www.tradingview.com/v/snhADyBo/
# // @Greg_007
# indicator(title="Buy the dips - sell the tops", shorttitle="BTD-STT", format=format.price, precision=2, overlay=true)
# Converted by Sam4Cok@Samer800    - 01/2024
#//Inputs
input showLabel = yes;
input rsiLength = 14;#, minval=1, title="RSI Length", group="RSI Settings")
input rsiSource = close;#, "Source", group="RSI Settings")
input OversoldLevel = 30;#,"Oversold level", group="RSI Settings")
input OverboughtLevel = 70;#,"Overbought level", group="RSI Settings")
input WilliamsRLength = 20;#,"Period", group="Williams %R Settings")
input WilliamsRSrc = close;#, "Source", group="Williams %R Settings")
input showAllExtremes = no;#(false,"Show all oversold/bought candles despite the trend")

def na = Double.NaN;

#//RSI calculation
def nRSI = RSI(Price = rsiSource, Length = rsiLength);
def lastRSI = if nRSI < OversoldLevel then -1 else
              if nRSI > OverboughtLevel then 1 else lastRSI[1];
#//WPR calculation
#_pr(length) =>
def max = Highest(high, WilliamsRLength);
def min = Lowest(low, WilliamsRLength);
def wpr = 100 * (WilliamsRSrc - max) / (max - min);
def percentR = wpr;

#//Main program
def WPRoversoldToNormal;
def WPRoverboughtToNormal;
def upTrend;
def downTrend;
def upTrend1;
def downTrend1;
if lastRSI == 1 and percentR < -80 {
    upTrend = yes;
    downTrend = no;
} else if lastRSI == -1 and percentR > -20 {
    upTrend = no;
    downTrend = yes;
} else {
    upTrend = upTrend1[1];
    downTrend = downTrend1[1];
}
if percentR[1] > -20 and percentR < -20 {
    WPRoverboughtToNormal = yes;
    WPRoversoldToNormal = no;
} else if percentR[1] < -80 and percentR > -80 {
    WPRoverboughtToNormal = no;
    WPRoversoldToNormal = yes;
} else {
    WPRoverboughtToNormal = no;
    WPRoversoldToNormal = no;
}
#---
plot buyDip0  = if upTrend and !showAllExtremes and WPRoversoldToNormal then low else na;# "Buy the dip"
plot SellDip0 = if downTrend and !showAllExtremes and WPRoverboughtToNormal then high else na;# "Sell the top"
plot SellDip1 = if showAllExtremes and WPRoverboughtToNormal then high else na; # "Sell the top"
plot buyDip1  = if showAllExtremes and WPRoversoldToNormal then low else na; # "Buy the dip"

buyDip0.SetDefaultColor(Color.CYAN);
buyDip1.SetDefaultColor(Color.CYAN);
SellDip0.SetDefaultColor(Color.MAGENTA);
SellDip1.SetDefaultColor(Color.MAGENTA);
buyDip0.SetPaintingStrategy(PaintingStrategy.BOOLEAN_WEDGE_DOWN);
buyDip1.SetPaintingStrategy(PaintingStrategy.BOOLEAN_WEDGE_DOWN);
SellDip0.SetPaintingStrategy(PaintingStrategy.BOOLEAN_WEDGE_UP);
SellDip1.SetPaintingStrategy(PaintingStrategy.BOOLEAN_WEDGE_UP);

def oversold;
def overbought;

if nRSI >= OversoldLevel and nRSI[1] < OversoldLevel {
    oversold = yes;
    overbought = no;
} else if nRSI <= 70 and nRSI[1] > OverboughtLevel {
    oversold = no;
    overbought = yes;
} else {
    oversold = no;
    overbought = no;
}

#AddChartBubble(oversold, low, "Buy Dips", Color.GREEN, no);    # "Sell label"
#AddChartBubble(overbought, high, "Sell Tops", Color.RED);    # "Buy label"

def plotcross;
if nRSI >= OverboughtLevel and downTrend {
    plotcross = yes;
    upTrend1 = upTrend;
    downTrend1 = no;
} else if nRSI <= OversoldLevel and upTrend {
    plotcross = yes;
    upTrend1 = no;
    downTrend1 = downTrend;
} else {
    plotcross = no;
    upTrend1 = upTrend;
    downTrend1 = downTrend;
}

#AddChartBubble(plotcross, low, "EXIT", Color.MAGENTA, no); #"Warning label")

def roundRsi = Round(nRSI, 2);
def roundWpr = Round(percentR, 2);
def rsi_txt = if roundRsi > OverboughtLevel then 1 else
              if roundRsi < OversoldLevel then -1 else 0;
def percentR_txt = if roundWpr > -20 then 1 else
                   if roundWpr < -80 then -1 else 0;

AddLabel(showLabel and rsi_txt > 0, "RSI: Overbought(" + roundRsi + ")", Color.RED);
AddLabel(showLabel and rsi_txt < 0, "RSI: Oversold(" + roundRsi + ")", Color.GREEN);
AddLabel(showLabel and rsi_txt == 0, "RSI: Neutral(" + roundRsi + ")", Color.WHITE);

AddLabel(showLabel and percentR_txt > 0, "%R: Overbought(" + roundWpr + ")", Color.RED);
AddLabel(showLabel and percentR_txt < 0, "%R: Oversold(" + roundWpr + ")", Color.GREEN);
AddLabel(showLabel and percentR_txt == 0, "%R: Neutral(" + roundWpr + ")", Color.WHITE);

#-- END of CODE


################################################ COMPUTATIONS
def buy1 = (uptrend and WPRoversoldToNormal);
def sell2 = (downtrend and WPRoverboughtToNormal);
def buy  = oversold OR  buy1;
def sell = overbought OR  sell2;

input ExitLength = 21;
input showorders = yes;
input showinfolabel = yes;
input ShowBubbles = yes;
input TargetATR = 1.25;
input TargetStop = 1.07;
input showTargetBubbles = yes;
input ShowStopBubbles = yes;
input ShowEntryBands = No;
input ShowExitBands = yes;
plot ExitHigh = Highest(high, ExitLength);
plot ExitLow = Lowest(low, ExitLength);
exithigh.setHiding(!ShowExitBands);
exitlow.setHiding(!ShowExitBands);
def LongTrade;
def ShortTrade;
def TradeisON;
def entry;
def win;
def los;
def profit;
def losses;
def TP;
def SL;
input share = 100;
plot  TakeProfit ;
plot stopLoss   ;
plot entryLine ;
input ATRLen = 30;
def mATR = Round (Average(TrueRange(high, close, low)[1], ATRLen));
def tpVar   = (2 *  (mATR * TargetATR));
def slLong  = (exitLow -(  TargetStop * mATR));
def slShort = (exitHigh + (   TargetStop * mATR));
def bar_index = AbsValue(BarNumber());

def Long  = showorders and buy  and !TradeisON[1];
def Short = showorders   and sell and !TradeisON[1];
def TradeFire = Long or Short;

if Long and !TradeisON[1] {
    LongTrade = yes;
    ShortTrade = no;
} else
if Short and !TradeisON[1] {
    LongTrade = no;
    ShortTrade = yes;
} else {
    LongTrade = LongTrade[1];
    ShortTrade = ShortTrade[1];
}


if TradeFire and !TradeisON[1] {
    entry = close[1];
    TP = if Long  then entry + tpVar else
         if Short then entry - tpVar else na;
    SL = if Long  then slLong  else
         if Short then slShort else na;
    win = if !bar_index then 0 else win[1];
    los = if !bar_index then 0 else los[1];
    profit = profit[1];
    losses = losses[1];
    TradeisON = yes;
} else
if LongTrade and TradeisON[1] {
    entry = entry[1];
    TP = TP[1];
    SL = SL[1];
    win = if high  >= TP then win[1] + 1 else win[1];
    los = if low <= SL then los[1] + 1 else los[1];
    profit = if (high > TP) then profit[1] + AbsValue(TP - entry) * share else profit[1];
    losses = if (low <= SL) then losses[1] + AbsValue(entry - close) * share else losses[1];
    TradeisON = if high >= TP then no else
                if low <= SL then no else TradeisON[1];
} else
if ShortTrade and TradeisON[1] {
    entry = entry[1];
    TP = TP[1];
    SL = SL[1];
    win = if low <= TP then win[1] + 1 else win[1];
    los = if high >= SL then los[1] + 1 else los[1];
    profit = if (low < TP) then profit[1] + AbsValue(entry - TP) * share else profit[1];
    losses = if (high >= SL) then losses[1] + AbsValue(close - entry) * share else losses[1];
    TradeisON = if low <= TP then no else
                if high >= SL then no else TradeisON[1];
} else {
    entry = na;
    win = if !bar_index then 0 else win[1];
    los = if !bar_index then 0 else los[1];
    profit = profit[1];
    losses = losses[1];
    TradeisON = TradeisON[1];
    TP = if TradeisON then TP[1] else na;
    SL = if TradeisON then SL[1] else na;
}


#-- Backtest
plot TradeEnd = if !TradeisON and TradeisON[1] then
                 if los > los[1] then SL[1] else TP[1] else na;
TradeEnd.AssignValueColor(if win > win[1] then Color.GREEN else Color.DARK_ORANGE);
TradeEnd.SetPaintingStrategy(PaintingStrategy.SQUARES);
AddChartBubble( ShowStopBubbles , TradeEnd, TradeEnd, Color.RED );#
Tradeend.setLineWeight(5);
#-- Label
def totTrade = win + los;
def winRate = Round(win / totTrade * 100, 0);
def PandL   = Round(profit - losses, 2);


AddLabel(showinfolabel, "Tot Trade: " + totTrade, Color.WHITE);
AddLabel(showinfolabel, "P/L: $" + PandL,
                        if PandL > 0 then Color.LIGHT_GREEN else
                        if PandL < 0 then Color.PINK else Color.GRAY);
AddLabel(showinfolabel, "Losses: $" + losses,  Color.RED);
AddLabel(showinfolabel, "WinRate: " + winRate + "%",
                        if winRate > 50 then Color.GREEN else
                        if winRate < 50 then Color.RED else Color.GRAY);
AddLabel(showinfolabel, "Win: " + win, Color.GREEN);
AddLabel(showinfolabel, "Loss: " + los, Color.RED);

#--BarColor


TakeProfit.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);
stopLoss.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);
entryLine.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);
TakeProfit.SetDefaultColor(Color.CYAN);
stopLoss.SetDefaultColor(Color.MAGENTA);

#--BarColor
def BearCon = TradeisON and ShortTrade;
def BullCon = TradeisON and LongTrade;
def buyCond = BullCon and !BullCon[1];
def sellCond = BearCon and !BearCon[1];
TakeProfit = if TradeisON then TP else na;
stopLoss   = if TradeisON then SL else na;
entryLine = if TradeisON then entry else na;

AddChartBubble( ShowBubbles and buyCond  , entry, "B" + entry, Color.GREEN, no );#and !buyCond[1]
AddChartBubble( ShowBubbles and sellCond  , entry, "S" + entry,  Color.RED );#and !sellcond[1]
AddChartBubble( showTargetBubbles and buyCond, TakeProfit, TakeProfit, Color.GREEN, no );#
AddChartBubble( showTargetBubbles and sellCond, TakeProfit, TakeProfit, Color.LIME );#

entryLine.AssignValueColor(if buyCond then Color.GREEN else Color.LIME);
entryLine.SetLineWeight(3);

TakeProfit.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);
TakeProfit.SetLineWeight(3);
stopLoss.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);
stopLoss.SetLineWeight(3);
entryLine.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);
TakeProfit.SetDefaultColor(Color.CYAN);
stopLoss.SetDefaultColor(Color.RED);


#alert( Long, "Buy", Alert.Bar, Sound.Bell);
#alert(short, "Sell", Alert.Bar, Sound.Bell);
#-- END of CODE
After copy/paste op's original code, I am having issues with the bubbles looking out of place as well. I have changed the chart timeframes and have run into issues that you will see in these attachments. I am not a coder, I have tried many times, but sadly have struggled with pin pointing code related issues. I do like this code and agree with you that it has potential. Also, I have tried both different timeframes with pm/ah hours on and off and signals are basically the same, but the chart with pm/ah off does show more potential on the 3d15min then the others did imo. I have also included code from @sammer800 post on this thread, as i thought that would solve the issues but it does not. It just doubles up the labels from op's code.
 

Attachments

  • tos_chart1.png
    tos_chart1.png
    84 KB · Views: 114
  • tos_4hr_no_extralabel.png
    tos_4hr_no_extralabel.png
    60.7 KB · Views: 129
  • tos_4hr_with_extralabel.png
    tos_4hr_with_extralabel.png
    68.2 KB · Views: 124
  • tos_3d15m_pm.ah_off.png
    tos_3d15m_pm.ah_off.png
    61 KB · Views: 120

Similar threads

Not the exact question you're looking for?

Start a new thread and receive assistance from our community.

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