Bull Bear Power with Optional Normalization Function
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © LeafAlgo

//@version=5
indicator("Bull/Bear Power with Normalization Function", shorttitle="NBBP")

// Inputs
lengthInput = input.int(50, title="BBP Length")
maLength = input.int(50, title='Moving Average Length')
isNormalized = input.bool(true, title='Use Normalization Function?')

// Math
bullPower = high - ta.ema(close, lengthInput)
bearPower = low - ta.ema(close, lengthInput)

bbP = bullPower + bearPower

bbP_h = ta.max(bbP)
bbP_l = ta.min(bbP)
bbP_n = ((bbP - bbP_l) / (bbP_h - bbP_l) - 0.5) * 2

bbP_final = isNormalized ? bbP_n : bbP

zeroLine = 0

upCondition = ta.crossover(bbP_final, zeroLine)
downCondition = ta.crossunder(bbP_final, zeroLine)

movingAverage = ta.ema(bbP_final, maLength)

// Coloration
bbpColor = bbP_final > 0 ? color.green : color.red
fillColor = bbP_final > 0 ? color.new(color.lime, 50) : color.new(color.fuchsia, 50)
barcolor(bbpColor)

// Plotting
bbP_n_plot = plot(bbP_final, title='Bull/Bear Power', color=bbpColor, linewidth = 4)
zeroLineplot = plot(zeroLine, title = 'Zero Line', linewidth = 3)
plot(movingAverage, title = 'Exponential MA', color=color.white, linewidth = 3)
fill(bbP_n_plot, zeroLineplot, color=fillColor)

