Optimised RSI strategy for Reversals (by Coinrule)
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Coinrule

//@version=4
strategy(shorttitle='MARSI',title='Moving Average', overlay=true, initial_capital=1000,  default_qty_type = strategy.percent_of_equity, default_qty_value = 100)

//Backtest dates
fromMonth = input(defval = 1,    title = "From Month",      type = input.integer, minval = 1, maxval = 12)
fromDay   = input(defval = 1,    title = "From Day",        type = input.integer, minval = 1, maxval = 31)
fromYear  = input(defval = 2020, title = "From Year",       type = input.integer, minval = 1970)
thruMonth = input(defval = 1,    title = "Thru Month",      type = input.integer, minval = 1, maxval = 12)
thruDay   = input(defval = 1,    title = "Thru Day",        type = input.integer, minval = 1, maxval = 31)
thruYear  = input(defval = 2112, title = "Thru Year",       type = input.integer, minval = 1970)

showDate  = input(defval = true, title = "Show Date Range", type = input.bool)

start     = timestamp(fromYear, fromMonth, fromDay, 00, 00)        // backtest start window
finish    = timestamp(thruYear, thruMonth, thruDay, 23, 59)        // backtest finish window
window()  => time >= start and time <= finish ? true : false       // create function "within window of time"

//MA inputs and calculations
inshort=input(9, title='MA short period')
MAshort= sma(close, inshort)

// RSI inputs and calculations
lengthRSI = input(14, title = 'RSI period', minval=1)
RSI = rsi(close, lengthRSI)

//Entry 
strategy.entry(id="long", long = true, when = MAshort<close and RSI<40 and window())

//Exit
longLossPerc = input(title="Long Stop Loss (%)",
     type=input.float, minval=0.0, step=0.1, defval=1.5) * 0.01
longTakePerc = input(title="Long Take Profit (%)",
     type=input.float, minval=0.0, step=0.1, defval=3) * 0.01
longSL  = strategy.position_avg_price * (1 - longLossPerc)
longTP  = strategy.position_avg_price * (1 + longTakePerc)
if (strategy.position_size > 0 and window())
    strategy.exit(id="TP/SL", stop=longSL, limit=longTP)


bgcolor(color = showDate and window() ? color.gray : na, transp = 90)  
plot(MAshort, color=color.purple, linewidth=4)

