Dynamic Relative Strength
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// Inspired from © bharatTrader

//@version=4
study("Dynamic Relative Strength", shorttitle="Dynamic Relative Strength")

//Input
source = input(title="Source", type=input.source, defval=close)
comparativeTickerId = input("NSE:CNXSMALLCAP", type=input.symbol, title="Comparative Symbol") 
length = input(123, type=input.integer, minval=1, title="Daily Period")
inpLen2 = input(52, title= 'Weekly Period') 
length := timeframe.isweekly ? inpLen2 : length
Monthly = input(10, title='Monthly Period') 
length := timeframe.ismonthly ? Monthly : length

// Other Settings
showZeroLine = input(defval=true, type=input.bool, title="Show Zero Line")
showRefDateLbl = input(defval=false, type=input.bool, title="Show Reference Label")
toggleRSColor = input(defval=true, type=input.bool, title="Toggle RS color on crossovers")
showRSTrend = input(defval=false, type=input.bool, title="RS Trend,", group="RS Trend", inline="RS Trend")
base = input(title="Range", minval=1, defval=5, group="RS Trend", inline="RS Trend")
showMA = input(defval=false, type=input.bool, title="Show Moving Average,", group="RS Mean", inline="RS Mean")
lengthMA = input(61, type=input.integer, minval=1, title="Period", group="RS Mean", inline="RS Mean")

//Set up
baseSymbol = security(syminfo.tickerid, timeframe.period, source) 
comparativeSymbol = security(comparativeTickerId, timeframe.period, source) 

//Calculations
res = ((baseSymbol/baseSymbol[length])/(comparativeSymbol/comparativeSymbol[length]) - 1)
resColor = toggleRSColor ? res > 0 ? color.green : color.red : color.blue
refDay = showRefDateLbl and barstate.islast ? dayofmonth(time[length]) : na
refMonth = showRefDateLbl and barstate.islast ? month(time[length]) : na
refYear = showRefDateLbl and barstate.islast ? year(time[length]) : na
refLabelStyle = res[length] > 0 ? label.style_label_up : label.style_label_down
refDateLabel = showRefDateLbl and barstate.islast ? label.new(bar_index - length, 0, text="RS-" + tostring(length) + " reference, " + tostring(refDay) + "-" + tostring(refMonth) + "-" + tostring(refYear), color=color.blue, style=refLabelStyle, yloc=yloc.price) : na
y0 = res - res[base]
angle0 = atan(y0/base) // radians
zeroLineColor = iff(showRSTrend, angle0 > 0.0 ? color.green : color.maroon, color.maroon)

//Plot
plot(showZeroLine ? 0 : na, linewidth=2, color=zeroLineColor, title="Zero Line / RS Trend")
plot(res, title="RS", linewidth=2, color= resColor)
plot(showMA ? sma(res, lengthMA) : na, color=color.gray, title="MA")