S & R RSi strat
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Kieranj

//@version=5
indicator("Support and Resistance with RSI and Trend Filter", overlay=true)

// Support and Resistance Calculation
lookbackBars = input(50, title="Lookback Bars")

highs = ta.highest(high, lookbackBars)
lows = ta.lowest(low, lookbackBars)

supportLevel = ta.valuewhen(low == lows, low, 0)
resistanceLevel = ta.valuewhen(high == highs, high, 0)

plot(supportLevel, color=color.green, linewidth=1, title="Support")
plot(resistanceLevel, color=color.red, linewidth=1, title="Resistance")

// RSI Conditions
rsiLength = input(14, title="RSI Length")
overboughtThreshold = input(70, title="Overbought Threshold")
oversoldThreshold = input(30, title="Oversold Threshold")

rsi = ta.rsi(close, rsiLength)

// Trend Filter
trendFilterSource = request.security(syminfo.tickerid, "240", close)
isUptrend = ta.sma(trendFilterSource, 50) < ta.sma(trendFilterSource, 200)

// Buy Condition
buyCondition = ta.crossover(rsi, oversoldThreshold) and isUptrend and (close >= supportLevel)

// Sell Condition
sellCondition = ta.crossunder(rsi, overboughtThreshold) and not isUptrend and (close <= resistanceLevel)

// Plotting Buy/Sell Signals
plotshape(buyCondition, title="Buy Signal", location=location.belowbar, color=color.green, style=shape.labelup, text="BUY")
plotshape(sellCondition, title="Sell Signal", location=location.abovebar, color=color.red, style=shape.labeldown, text="SELL")

// Plotting RSI
hline(overboughtThreshold, "Overbought", color=color.red)
hline(oversoldThreshold, "Oversold", color=color.green)
plot(rsi, title="RSI", color=color.orange, linewidth=2)



