Relative Volatility Measure (RVM)
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © AIFinPlot

//@version=5
indicator("Relative Volatility Measure (RVM)", shorttitle="RVM")

// Inputs
lookbackPeriod = input.int(15, minval=1, title="Lookback Period")
showBgColor = input.bool(true, title="Show Background Color")


// Short-term ATRs
short1    = ta.atr(3)
short2    = ta.atr(5)
short3    = ta.atr(8)
shortAvg  = (short1 + short2 + short3) / 3

// Long-term ATRs
long1   = ta.atr(55)
long2   = ta.atr(89)
long3   = ta.atr(144)
longAvg = (long1 + long2 + long3) / 3

// Combined ATR value
combinedATR = (shortAvg + longAvg) / 2

// Highest and lowest combined ATR over lookback period
highestCombinedATR = ta.highest(combinedATR, lookbackPeriod)
lowestCombinedATR = ta.lowest(combinedATR, lookbackPeriod)

// RVM Calculation
rvm = (combinedATR - lowestCombinedATR) / math.max(highestCombinedATR - lowestCombinedATR, 0.001) * 100

// Plotting
plot(rvm, title="RVM", color=color.blue, linewidth=2)
hline(50, "Midpoint", color=color.gray, linestyle=hline.style_dotted)
hline(20, "Midpoint", color=color.rgb(37, 214, 238), linestyle=hline.style_dotted)
hline(10, "Midpoint", color=color.rgb(21, 216, 34), linestyle=hline.style_dotted)


// Background color conditions
bgcolor(showBgColor and rvm >= 0 and rvm <= 10 ?  color.rgb(21, 216, 34) : na)
bgcolor(showBgColor and rvm > 10 and rvm <= 20 ? color.rgb(37, 214, 238) : na)

// Label Logic
var label myLabel = na
if barstate.islast
    myLabel := label.new(bar_index + 4, rvm, text="RVM: " + str.tostring(rvm, '#.##'), style=label.style_none, color=color.blue, textcolor=color.white, size=size.tiny, yloc=yloc.price)

// Update the label position and text on each bar
if not na(myLabel)
    label.set_xy(myLabel, bar_index + 4, rvm)
    label.set_text(myLabel, "RVM: " + str.tostring(rvm, '#.##'))
