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

//@version=5
indicator(title="Accumulation/Distribution", shorttitle="Accum/Dist", format=format.volume, overlay=false, timeframe="", timeframe_gaps=true)

// ##############################}
// Accumulation/Distribution
// ##############################{

var float cumVol = 0.
cumVol += nz(volume)

if barstate.islast and cumVol == 0
    runtime.error("No volume is provided by the data vendor.")

float ad = ta.cum(close==high and close==low or high==low ? 0 : ((2*close-low-high)/(high-low))*volume)

// ##############################}
// FUNCTIONS
// ##############################{

DEMA(source, length) =>
    float ema1 = ta.ema(source, length)
    float ema2 = ta.ema(ema1, length)
    float DEMA = 2 * ema1 - ema2
    DEMA

TEMA(source, length) =>
    float ema3 = ta.ema(source, length)
    float ema4 = ta.ema(ema3, length)
    float ema5 = ta.ema(ema4, length)
    float TEMA = 3 * (ema3 - ema4) + ema5
    TEMA

ma(length, type) =>
    switch type
        "SMA" => ta.sma(ad, length)
        "EMA" => ta.ema(ad, length)
        "SMMA (RMA)" => ta.rma(ad, length)
        "WMA" => ta.wma(ad, length)
        "VWMA" => ta.vwma(ad, length)
        "DEMA" => DEMA(ad, length)
        "TEMA" => TEMA(ad, length)

// ##############################}
// INPUTS
// ##############################{

string ma_group = "--- Moving Average Settings"
string MA_Type = input.string(title = "Method", defval = "TEMA", options=["DEMA", "EMA", "SMA", "SMMA (RMA)", "TEMA", "VWMA", "WMA"], tooltip = "DEMA: Double moving average exponential\nEMA: Moving average exponential\nSMA: Simple moving average\nSMMA: Moving average used in RSI\nTEMA: Triple moving average exponential\nVWMA: Volume-weighted moving average\nWMA: Weighted moving average", group = ma_group)
int MA_Length = input.int(20, title = "Length", minval = 1, step = 1, group = ma_group)

// ##############################}
// OUTPUTS
// ##############################{

float moving_average = ma(MA_Length, MA_Type)
plot(ad, title = "Accumulation/Distribution", color = ad > moving_average ? color.green : color.red, linewidth = 2)
plot(moving_average, title = "Moving Average", color = color.blue, display = display.none)
