Volume Bias
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © FlynnTheAlmighty

//@version=5
var int MAX_BARS_BACK = 500
indicator("[FTA] Volume bias", max_bars_back = MAX_BARS_BACK)

int lookBackInput = input.int(20, "Volume Look Back (bars)", minval = 2, maxval = int(MAX_BARS_BACK / 4))

// Stop the script if the chart does not contain volume data.
bool noVol = na(volume) and nz(math.sum(nz(volume), 200) == 0, true)
if noVol
    runtime.error("No volume data.")

volumeBias(lookBack, maxLookBack) =>
    bool  barUp = ta.rising(close, 1)
    bool  barDn = ta.falling(close, 1)
    float upVolume = 0.
    float dnVolume = 0.
    float avgVolume = math.sum(nz(volume), lookBack)
    int[] upBarNos = array.new_int(0)
    int[] dnBarNos = array.new_int(0)
    int   bar = 1
    bool  volumeFound = false
    while (not volumeFound) and bar < maxLookBack
        if barUp[bar] and upVolume < avgVolume
            upVolume += nz(volume[bar])
            array.push(upBarNos, bar)
        else if barDn[bar] and dnVolume < avgVolume
            dnVolume += nz(volume[bar])
            array.push(dnBarNos, bar)
        bar += 1
        volumeFound := upVolume >= avgVolume and dnVolume >= avgVolume
    float volumeBias = bar >= maxLookBack ? na : array.avg(dnBarNos) - array.avg(upBarNos)

float bias = volumeBias(lookBackInput, MAX_BARS_BACK)
plot(bias, "Volume Bias", bias > 0 ? color.aqua : color.fuchsia)
hline(0)

