Accumulation/Distribution %
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Skipper86

//@version=4
study(title="Accumulation/Distribution %", shorttitle="AD%", format=format.percent, precision=0, overlay=false, resolution="")
length = input(10, minval = 2, title="Calculation Period")

ad = sum((close==high and close==low or high==low ? 0 : ((close-open)/(high-low))*volume),length)
//logic tests taken from default Tradingview A/D function, algebraic formula taken from Bollinger on Bollinger Bands textbook page 151 Table 18.4
//function would be cumulative rather than a summation if this was the standard accumulation/distribution indicator but since it's a normalized oscillator,
//it's only looking back at the previous 10 (or whatever the calculation period is set to) bars
//side note: Tradingview A/D indicator doesn't include opening price.  There are multiple versions of the A/D indicator.

norm = 100*ad/sum(volume,length)
//A/D data normalized based on calculation period, multiplied by 100 to avoid decimal values on vertical axis

normcolor = (norm > 0) and (norm > norm[1]) ? #08A515 : (norm > 0) and (norm <= norm[1]) ? #025F08: (norm < 0) and (norm < norm[1]) ? #BB0000 : (norm < 0) and (norm >= norm[1]) ? #660011 : #FF9F00
//This code sets the coloration for both the upper price plot and lower oscillator plot
//Chart type must be set to "bars" for the upper coloration to work properly

barcolor(normcolor)
//Bar Color (upper plot)

plot(norm, color=normcolor, style=plot.style_columns, title = "AD%")
//normalized ad (lower plot)

//End of Script

