Reputation: 19
I'm back-testing and RSI(6) strategy. I want it to buy on the SECOND CROSSING of the 30 oversold line(When it is going back up) and Sell on the SECOND CROSSING of the 70 oversold line(when it is going down). I can only get it to buy and sell when it immediately crosses the overbought/oversold line which is not why I'm trying to do. I'm also trying to add a 10% stop loss. Does anyone have any ideas how to implement those orders? This is my code so far.
strategy("RSI", overlay = true)
longcon = rsi(close, 6) < 30
closecon = rsi(close,6) > 70
//backtest from 2015
_year = 2015
strategy.entry("long", strategy.long, when = longcon and year >= _year)
strategy.close("long", when = closecon)
plot(close)
Upvotes: 1
Views: 1775
Reputation: 8789
This shows debugging plots so you can see the logic unfolding:
//@version=4
strategy("RSI")
r = rsi(close, 6)
_year = 2015
bool xUp = crossover(r, 30)
bool xDn = crossunder(r, 70)
var bool firstXUp = false
var bool firstXDn = false
var bool inLong = false
var bool inShort = false
var float longStop = na
if xUp
firstXDn := false
if firstXUp
inLong := true
inShort := false
firstXUp := false
else if not inLong
firstXUp := true
else if xDn
firstXUp := false
if firstXDn
inLong := false
inShort := true
firstXDn := false
else if inLong
firstXDn := true
enterLong = inLong and not inLong[1]
exitLong = not inLong and inLong[1]
longStop := enterLong ? close * 0.9 : exitLong ? na : longStop
strategy.entry("long", strategy.long, when = enterLong and year >= _year)
strategy.close("long", when = exitLong, comment = "xDn")
strategy.close("long", when = close < longStop, comment = "Stop")
plot(r)
hline(30)
hline(70)
// Debugging
plotchar(xUp, "xUp", "•", location.bottom, size = size.tiny)
plotchar(xDn, "xDn", "•", location.top, size = size.tiny)
plotchar(firstXUp, "firstXUp", "1", location.bottom, size = size.tiny)
plotchar(firstXDn, "firstXDn", "1", location.top, size = size.tiny)
plotchar(longStop, "longStop", "", location.top, size = size.tiny)
bgcolor(inLong ? color.green : an)
Upvotes: 0