RSI Accumulation/Distribution [M]
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Milvetti

//@version=5
indicator("RSI Accumulation/Distribution [M]","RSI A/D [M]",max_bars_back = 500,max_boxes_count = 500)

g1="Settings"
g2="Customize"

len = input.int(14,"Length",group = g1)
upperBand = input.int(70,"Upper Band",group = g1)
lowerBand = input.int(30,"Lower Band",group = g1)

showLevel1 = input(true,"Show 1.Level Signal",inline = "level1",group = g2)
colorLevel1 = input.color(color.new(color.green,70),"",inline = "level1",group = g2)
showLevel2 = input(true,"Show 2.Level Signal",inline = "level2",group = g2)
colorLevel2 = input.color(color.new(color.orange,70),"",inline = "level2",group = g2)
showLevel3 = input(true,"Show 3.Level Signal",inline = "level3",group = g2)
colorLevel3 = input.color(color.new(color.red,70),"",inline = "level3",group = g2)

rsi = ta.sma(ta.rsi(close,len),3)

level1 = 5
level2 = 7
level3 =9

accumulation = nz(ta.barssince(ta.crossunder(rsi,lowerBand)),0)
accumulation:= accumulation==0 ? 1 : accumulation
lowBar = ta.lowest(rsi,accumulation)

distribution  = nz(ta.barssince(ta.crossover(rsi,upperBand)),0)
distribution := distribution ==0 ? 1 : distribution 
highBar = ta.highest(rsi,distribution )

level3Support = ta.crossover(rsi,lowerBand) and accumulation>=level3
level2Support = ta.crossover(rsi,lowerBand) and accumulation>=level2 and accumulation<level3
level1Support = ta.crossover(rsi,lowerBand) and accumulation>=level1 and accumulation<level2
level3Res = ta.crossunder(rsi,upperBand) and distribution >=level3
level2Res = ta.crossunder(rsi,upperBand) and distribution >=level2 and distribution <level3
level1Res = ta.crossunder(rsi,upperBand) and distribution >=level1 and distribution <level2
boxColor= level1Support or level1Res? colorLevel1 : level2Support or level2Res ? colorLevel2 : level3Support or level3Res ? colorLevel3 :na

if level1Support or level2Support or level3Support
    box.new(bar_index-accumulation,lowerBand,bar_index,lowBar,border_color = boxColor,bgcolor = boxColor)
    alert("New Accumulation",alert.freq_once_per_bar_close)
    
if level1Res or level2Res or level3Res
    box.new(bar_index-distribution ,upperBand,bar_index,highBar,border_color = boxColor,bgcolor = boxColor)
    alert("New Distribution",alert.freq_once_per_bar_close)
plot(rsi,"RSI",#434651,2)
upperLine = hline(upperBand,"Upper Band")
lowerLine = hline(lowerBand,"Lower Band")
fill(upperLine,lowerLine,color=color.new(#434651,97),title = "Background")