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

//@version=5
indicator("Volume Entropy", overlay = false, format=format.price, precision=2, timeframe="", timeframe_gaps=true)

//Custom function for natural logarithm using Taylor Series
naturalLog(x, terms) =>
    a = x - 1.0
    sum = 0.0
    for i = 1 to terms
        term = math.pow(a, i) / i
        sum := sum + (i % 2 != 0 ? term : -term)
    sum

// Entropy
len = input.int(2, 'micro_pattern_len' )
micro_pattern_len = len
entropy(data) =>
    p = ta.valuewhen(data, 1, 0) / math.sum(data, micro_pattern_len)
    -p * naturalLog(p, 10)

LowEntropy = entropy(volume)

// Z-score normalization
lookback = input.int(20, 'Z-score normalization lookback') 
mean_entropy = ta.sma(LowEntropy, lookback) 
std_entropy = ta.stdev(LowEntropy, lookback) 
z_score_entropy = (LowEntropy - mean_entropy) / std_entropy 

// hline
hline(1.3)
hline(-1.3)
hline(0)

/// direction change for color
Dir = ta.change(-z_score_entropy) > 0 ? 1 : -1
Col = Dir == 1 ? color.new(#06a02c, 0) : Dir == -1 ? color.new(#94060d, 0) : color.gray
volplot = plot(-z_score_entropy, title='Smoothed and Scaled EMA', color = Col, linewidth = 2)

midLinePlot = plot(0, color = na, editable = false, display = display.none)
fill(volplot, midLinePlot, 2.5, 1, top_color = color.new(color.green, 0), bottom_color = color.new(color.green, 100), title = "Overbought Gradient Fill")
fill(volplot, midLinePlot, -1.0,-4.0,  top_color = color.new(color.red, 100), bottom_color = color.new(color.red, 0), title = "Oversold Gradient Fill")

