RSI Trend Strategy
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © cultivateforex

//@version=5
indicator('RSI Trend Strategy', overlay=true)

dirmov(len) =>
    up = ta.change(high)
    down = -ta.change(low)
    truerange = ta.rma(ta.tr, len)
    plus = fixnan(100 * ta.rma(up > down and up > 0 ? up : 0, len) / truerange)
    minus = fixnan(100 * ta.rma(down > up and down > 0 ? down : 0, len) / truerange)
    [plus, minus]

adx(LWdilength, LWadxlength) =>
    [plus, minus] = dirmov(LWdilength)
    sum = plus + minus
    adx = 100 * ta.rma(math.abs(plus - minus) / (sum == 0 ? 1 : sum), LWadxlength)
    [adx, plus, minus]


CalcADX() =>
    LWadxlength = input(8, title='ADX period',group="ADX")
    LWdilength = input(9, title='DMI Length',group="ADX")
    [ADX, up, down] = adx(LWdilength, LWadxlength)
    LWADX = (ADX - 15) * 2.5
    
    [LWADX,up > down]
    
CalcRSI() =>
    len = input.int(14, minval=1, title="Length",group="RSI")
    src = input(close, "Source",group="RSI")
    up = ta.rma(math.max(ta.change(src), 0), len)
    down = ta.rma(-math.min(ta.change(src), 0), len)
    rsi = down == 0 ? 100 : up == 0 ? 0 : 100 - (100 / (1 + up / down))
    
[LWADX,adx_bull] = CalcADX()
rsi_v = CalcRSI()

ADXThreshold = input.int(100,group="Signal")
RSIBuyThreshold = input.int(70,group="Signal")
RSISellThreshold = input.int(30,group="Signal")
    
BuySignal_ = adx_bull and LWADX > ADXThreshold and rsi_v > RSIBuyThreshold
SellSignal_ = adx_bull==false and LWADX > ADXThreshold and rsi_v < RSISellThreshold

BuySignal = BuySignal_ and BuySignal_[1]==false
SellSignal = SellSignal_ and SellSignal_[1] == false

plotshape(BuySignal, title='Buy Signal', text='BUY', textcolor=color.new(color.white, 0), style=shape.labelup, size=size.normal, location=location.belowbar, color=color.new(color.green, 0))
plotshape(SellSignal, title='Sell Signal', text='SELL', textcolor=color.new(color.white, 0), style=shape.labeldown, size=size.normal, location=location.abovebar, color=color.new(color.red, 0))

alertcondition(BuySignal,'BuySignal','BuySignal')
alertcondition(SellSignal,'SellSignal','SellSignal')
