Volume+ (Time of Day)
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Electrified

//@version=5
indicator("Volume+ (Time of Day)", "Vol+ ⏲")
import Electrified/Color/9

MEASUREMENT = "Measurement"
days = input.int(100, "Days", group = MEASUREMENT, tooltip = "The number of days to measure.")

type TimeOfDay
    float[] data

var data = array.new<TimeOfDay>()

dayStart = time("D")
// Time of day in seconds
timeOfDay = (time - dayStart) / 1000

multiple = switch
    timeframe.isminutes => 60 * timeframe.multiplier
    timeframe.isseconds => timeframe.multiplier
    => timeOfDay

barOfDay = math.floor(timeOfDay / multiple)

while barOfDay >= data.size()
    data.push(TimeOfDay.new(array.new_float()))

var empty = array.new_float()
entries = data.size() == 0 ? empty : data.get(barOfDay).data

mean = entries.avg()
diff2sum = 0.0
for e in entries
    diff2sum += e * e
variance = diff2sum / entries.size()
standardDeviation = math.sqrt(variance)

// Delay adding today's data
entries.push(nz(volume))
if entries.size() > days
    entries.shift()

plus1 = mean + standardDeviation
plus2 = plus1 + standardDeviation
plus3 = plus2 + standardDeviation

HIGHLIGHT = "Bar Highlight"
BRIGHTEN = "Brighten", DARKEN = "Darken", NONE = "None"
highLight = input.string(BRIGHTEN, "Mode", group = HIGHLIGHT, options = [BRIGHTEN, DARKEN, NONE], tooltip = "How to affect the bar color when the volume exeeds one standard deviation.")
warmRange = plus3 - plus1
warmth = 100 * (volume - plus1) / warmRange

THEME = "Theme"
barTheme = input.color(color.gray, "Bar", group = THEME, inline = THEME)
meanColor = input.color(color.orange, "Average", group = THEME, inline = THEME)
devColor = input.color(color.yellow, "Deviation", group = THEME, inline = THEME)

barColor = switch highLight
    NONE => barTheme
    BRIGHTEN => barTheme.brighten(math.max(0, warmth))
    DARKEN =>  barTheme.darken(math.max(0, warmth))

plot(volume, "Volume", barColor, style = plot.style_columns)

plot(plus1, "+1 Standard Deviation", color.new(devColor, 50), 1, display = display.pane)
plot(mean, "Average", meanColor, 1)


