RSI and ATR Trend Reversal SL/TP for ThinkOrSwim

samer800

Moderator - Expert
VIP
Lifetime
BpOB5yM.png


Author Message:

Developed this TP/SL and eventually made it into a full fledge strategy and found it did well enough to publish. This strategy can be used as a standalone or tacked onto another strategy as a TP/SL. It does function as both with a single line. This strategy has been tested with TSLA , AAPL, NVDA, on the 15 minutes timeframe.
STRATEGY:
Using the source , when it crosses up or down relative to the selected band, we enter a long or short respectively.
This may not be the most superb independent strategy, but it can be very useful as a TP/SL for your chosen entry conditions, especially in volatile markets or tickers.

More Details: https://www.tradingview.com/v/hZLgJ29l/

CODE:

CSS:
#https://www.tradingview.com/v/hZLgJ29l/
#//@joseph_lemery
#strategy("RSI Trend Reversal", "RSI and ATR Trend Reversal SL/TP")
# Converted by Sam4Cok@Samer800    - 04/2024

#//INPUTS
input showSignals = yes;
input showCloud = yes;
input timeframe = {default "Chart", "Manual"};
input manualTimeframe = AggregationPeriod.FIFTEEN_MIN;
input source = {default "Close", "HL2", "HLC3", "OHLC4", "HLCC4"}; # "Source Input"
input trendLenght = 8;                 # "Lenght"
input Multiplier = 1.50;               # "Multiplier"
input DelayToPreventIdealization = 1;  # "Delay to prevent idealization"
input MinimumDifference = 10;          # "Minimum Difference"

def na = Double.NaN;
def last = IsNaN(close);
def src;
def hi;
def cl;
def lo;
def op;# = close(Period = tf);  #(open + high + low + close) / 4;
switch (timeframe) {
case "Manual" :
    src = ohlc4(Period = manualTimeframe); #Fundamental(FundamentalType = FundamentalType.OHLC4, Period = manualTimeframe);
    op = open(Period = manualTimeframe);
    hi = high(Period = manualTimeframe);
    cl = close(Period = manualTimeframe);
    lo = low(Period = manualTimeframe);
default :
    src = ohlc4; #Fundamental(FundamentalType = source);
    op = open;
    hi = high;
    cl = close;
    lo = low;
}
def haClose = src;
def haOpen = CompoundValue(1, (haOpen[1] + haClose[1]) / 2, (op + cl) / 2);
def haHigh = Max(Max(hi, haOpen), haClose);
def haLow = Min(Min(lo, haOpen), haClose);

#"Close", "HL2", "HLC3", "OHLC4", "HLCC4"
def hclose;
switch (source) {
case "HL2":
    hclose = (haHigh + haLow) / 2;
case "HLC3" :
    hclose = (haHigh + haLow + haClose) / 3;
case "OHLC4" :
    hclose = (haOpen + haHigh + haLow + haClose) / 4;
case "HLCC4" :
    hclose = (haHigh + haLow + haClose + haClose) / 4;
default :
    hclose = haClose;
}
#/FUNCTION INITILIZATION
script highest_custom {
    input src = close;
    input len = 8;
#    def src = if !isNaN(source) then source else src[1];
    def length = if IsNaN(len) then 0 else len;
    def x = fold i = 0 to length with p = src do
            if GetValue(src, i) > p then GetValue(src, i) else p;
    plot out = x;
}
script lowest_custom {
    input src = close;
    input len = 8;
#    def src = if !isNaN(source) then source else src[1];
    def length = if IsNaN(len) then 0 else len;
    def x = fold i = 0 to length with p = src do
            if GetValue(src, i) < p then GetValue(src, i) else p;
    plot out = x;
}
script rsilev {
    input src = close;
    input length = 8;
    input mult = 1.5;
    input sltp = 10;
    input natr = 1;
    def na = Double.NaN;
    def bar = BarNumber();
    def sl = (100 - sltp) / 100;
    def tp = (100 + sltp) / 100;
    def crossup; # = na
    def crossdn; # = na
    def crossup1 = if IsNaN(crossup[1]) then 0 else crossup[1];
    def crossdn1 = if IsNaN(crossdn[1]) then 0 else crossdn[1];
    def BullGuy = if (crossup[1] or crossdn[1]) then 0 else BullGuy[1] + 1;
    def BearGuy = if IsNaN(BullGuy) then BearGuy[1] + 1 else BullGuy;
    def rsilower = RSI(Price = src, Length = length);
    def rsiupper = AbsValue(100 - rsilower);
    def atr = natr / src;
    def hi = highest_custom(src, BearGuy);
    def lo = lowest_custom(src, BearGuy);
    def hiBear = hi * (1 - (atr + (1 / rsilower * mult)));
    def loBear = lo * (1 + (atr + (1 / rsiupper * mult)));
    def hhiBear = highest_custom(hiBear, BearGuy);
    def lloBear = lowest_custom(loBear, BearGuy);
    def maxHi = Max(hhiBear, src * sl);
    def minLo = Min(lloBear, src * tp);
    def lower = highest_custom(maxHi, BearGuy);
    def upper = lowest_custom(minLo, BearGuy);
    def direction = if isNaN(direction[1]) then 1 else
                    if (crossdn1) then -1 else
                    if (crossup1) then  1 else direction[1];
    def thresh = if bar < 1 then lower else
                 if direction == 1 then lower else
                 if direction == -1 then upper else thresh[1];
    crossup = (src  crosses above thresh);
    crossdn = (src  crosses below thresh);
    plot trend = if IsNaN(thresh)  then lower else thresh;
    plot dir = if !direction then if(src>trend,1, -1) else direction;
}
def tick = tickSize();
def trRaw = TrueRange(hi, cl, lo);
def tr = if IsNaN(trRaw) then (hi - lo) else if trRaw <=0 then tick else trRaw;
def atr = WildersAverage(tr, trendLenght);
def rsiclose = rsilev(hclose, trendLenght, Multiplier, MinimumDifference, atr).trend;
def dir = rsilev(hclose, trendLenght, Multiplier, MinimumDifference, atr).dir;

#//PLOTTING
plot rsiTrendUp = if !last and dir>0 and rsiclose then rsiclose else na;
plot rsiTrendDn = if !last and dir<0 and rsiclose then rsiclose else na;
rsiTrendUp.SetDefaultColor(Color.GREEN);
rsiTrendDn.SetDefaultColor(Color.RED);

#-- Cloud
AddCloud(if showCloud then ohlc4 else na, rsiclose, Color.DARK_GREEN, Color.DARK_RED);

#/STRATEGY
def buy = (src crosses above rsiclose);
def sell = (src crosses below rsiclose);
def cntUp = if buy then 0 else cntUp[1] + 1;
def cntDn = if sell then 0 else cntDn[1] + 1;
def sigUp = cntUp == DelayToPreventIdealization;
def sigDn = cntDn == DelayToPreventIdealization;
AddChartBubble(showSignals and sigUp and !sigUp[1], low, "Buy", Color.GREEN, no);
AddChartBubble(showSignals and sigDn and !sigDn[1], high, "Sell", Color.RED);


#-- END of CODE
 

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

@sam
BpOB5yM.png


Author Message:

Developed this TP/SL and eventually made it into a full fledge strategy and found it did well enough to publish. This strategy can be used as a standalone or tacked onto another strategy as a TP/SL. It does function as both with a single line. This strategy has been tested with TSLA , AAPL, NVDA, on the 15 minutes timeframe.
STRATEGY:
Using the source , when it crosses up or down relative to the selected band, we enter a long or short respectively.
This may not be the most superb independent strategy, but it can be very useful as a TP/SL for your chosen entry conditions, especially in volatile markets or tickers.

More Details: https://www.tradingview.com/v/hZLgJ29l/

CODE:

CSS:
#https://www.tradingview.com/v/hZLgJ29l/
#//@joseph_lemery
#strategy("RSI Trend Reversal", "RSI and ATR Trend Reversal SL/TP")
# Converted by Sam4Cok@Samer800    - 04/2024

#//INPUTS
input showSignals = yes;
input showCloud = yes;
input timeframe = {default "Chart", "Manual"};
input manualTimeframe = AggregationPeriod.FIFTEEN_MIN;
input source = {default "Close", "HL2", "HLC3", "OHLC4", "HLCC4"}; # "Source Input"
input trendLenght = 8;                 # "Lenght"
input Multiplier = 1.50;               # "Multiplier"
input DelayToPreventIdealization = 1;  # "Delay to prevent idealization"
input MinimumDifference = 10;          # "Minimum Difference"

def na = Double.NaN;
def last = IsNaN(close);
def src;
def hi;
def cl;
def lo;
def op;# = close(Period = tf);  #(open + high + low + close) / 4;
switch (timeframe) {
case "Manual" :
    src = ohlc4(Period = manualTimeframe); #Fundamental(FundamentalType = FundamentalType.OHLC4, Period = manualTimeframe);
    op = open(Period = manualTimeframe);
    hi = high(Period = manualTimeframe);
    cl = close(Period = manualTimeframe);
    lo = low(Period = manualTimeframe);
default :
    src = ohlc4; #Fundamental(FundamentalType = source);
    op = open;
    hi = high;
    cl = close;
    lo = low;
}
def haClose = src;
def haOpen = CompoundValue(1, (haOpen[1] + haClose[1]) / 2, (op + cl) / 2);
def haHigh = Max(Max(hi, haOpen), haClose);
def haLow = Min(Min(lo, haOpen), haClose);

#"Close", "HL2", "HLC3", "OHLC4", "HLCC4"
def hclose;
switch (source) {
case "HL2":
    hclose = (haHigh + haLow) / 2;
case "HLC3" :
    hclose = (haHigh + haLow + haClose) / 3;
case "OHLC4" :
    hclose = (haOpen + haHigh + haLow + haClose) / 4;
case "HLCC4" :
    hclose = (haHigh + haLow + haClose + haClose) / 4;
default :
    hclose = haClose;
}
#/FUNCTION INITILIZATION
script highest_custom {
    input src = close;
    input len = 8;
#    def src = if !isNaN(source) then source else src[1];
    def length = if IsNaN(len) then 0 else len;
    def x = fold i = 0 to length with p = src do
            if GetValue(src, i) > p then GetValue(src, i) else p;
    plot out = x;
}
script lowest_custom {
    input src = close;
    input len = 8;
#    def src = if !isNaN(source) then source else src[1];
    def length = if IsNaN(len) then 0 else len;
    def x = fold i = 0 to length with p = src do
            if GetValue(src, i) < p then GetValue(src, i) else p;
    plot out = x;
}
script rsilev {
    input src = close;
    input length = 8;
    input mult = 1.5;
    input sltp = 10;
    input natr = 1;
    def na = Double.NaN;
    def bar = BarNumber();
    def sl = (100 - sltp) / 100;
    def tp = (100 + sltp) / 100;
    def crossup; # = na
    def crossdn; # = na
    def crossup1 = if IsNaN(crossup[1]) then 0 else crossup[1];
    def crossdn1 = if IsNaN(crossdn[1]) then 0 else crossdn[1];
    def BullGuy = if (crossup[1] or crossdn[1]) then 0 else BullGuy[1] + 1;
    def BearGuy = if IsNaN(BullGuy) then BearGuy[1] + 1 else BullGuy;
    def rsilower = RSI(Price = src, Length = length);
    def rsiupper = AbsValue(100 - rsilower);
    def atr = natr / src;
    def hi = highest_custom(src, BearGuy);
    def lo = lowest_custom(src, BearGuy);
    def hiBear = hi * (1 - (atr + (1 / rsilower * mult)));
    def loBear = lo * (1 + (atr + (1 / rsiupper * mult)));
    def hhiBear = highest_custom(hiBear, BearGuy);
    def lloBear = lowest_custom(loBear, BearGuy);
    def maxHi = Max(hhiBear, src * sl);
    def minLo = Min(lloBear, src * tp);
    def lower = highest_custom(maxHi, BearGuy);
    def upper = lowest_custom(minLo, BearGuy);
    def direction = if isNaN(direction[1]) then 1 else
                    if (crossdn1) then -1 else
                    if (crossup1) then  1 else direction[1];
    def thresh = if bar < 1 then lower else
                 if direction == 1 then lower else
                 if direction == -1 then upper else thresh[1];
    crossup = (src  crosses above thresh);
    crossdn = (src  crosses below thresh);
    plot trend = if IsNaN(thresh)  then lower else thresh;
    plot dir = if !direction then if(src>trend,1, -1) else direction;
}
def tick = tickSize();
def trRaw = TrueRange(hi, cl, lo);
def tr = if IsNaN(trRaw) then (hi - lo) else if trRaw <=0 then tick else trRaw;
def atr = WildersAverage(tr, trendLenght);
def rsiclose = rsilev(hclose, trendLenght, Multiplier, MinimumDifference, atr).trend;
def dir = rsilev(hclose, trendLenght, Multiplier, MinimumDifference, atr).dir;

#//PLOTTING
plot rsiTrendUp = if !last and dir>0 and rsiclose then rsiclose else na;
plot rsiTrendDn = if !last and dir<0 and rsiclose then rsiclose else na;
rsiTrendUp.SetDefaultColor(Color.GREEN);
rsiTrendDn.SetDefaultColor(Color.RED);

#-- Cloud
AddCloud(if showCloud then ohlc4 else na, rsiclose, Color.DARK_GREEN, Color.DARK_RED);

#/STRATEGY
def buy = (src crosses above rsiclose);
def sell = (src crosses below rsiclose);
def cntUp = if buy then 0 else cntUp[1] + 1;
def cntDn = if sell then 0 else cntDn[1] + 1;
def sigUp = cntUp == DelayToPreventIdealization;
def sigDn = cntDn == DelayToPreventIdealization;
AddChartBubble(showSignals and sigUp and !sigUp[1], low, "Buy", Color.GREEN, no);
AddChartBubble(showSignals and sigDn and !sigDn[1], high, "Sell", Color.RED);


#-- END of CODE

@samer800 Looks awesome, can't wait to try it out. In case you haven't noticed yet, there is a small typo with "Length"

"input trendLenght = 8; # "Lenght"
 
Any way to create a custom column? show too complex error. Thanks

To modify chart scripts to work in watchlist custom columns or scans:
1. remove any MTF code as the ToS app does not support secondary aggregations in any of its widgets
2. remove any formatting code as that only applies to charts not to ToS widgets.

The above edits were completed on the above code. Unfortunately, it still remains too complex.

Please note:
While no script is "too complex" to plot on the chart; Schwab does throttle the use of complex scripts in scans, watchlists, and conditional orders to prevent high load runs on the servers.

Many of the more complex scripts found on this forum, can only be used on charts.
They cannot be used in other widgets; such as: scans, watchlists, conditional orders, etc...

Schwab does not currently provide any workarounds.
 

Similar threads

Not the exact question you're looking for?

Start a new thread and receive assistance from our community.

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