[Library] VAcc
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © algotraderdev & Scott Cong
// Based on "Stocks & Commodities V. 41:09 (8–15): VAcc: A Momentum Indicator Based On Velocity And Acceleration by Scott Cong, PhD"

//@version=5
library('vacc')

// @function Caculates the velocity and acceleration with the given length and smoothness.
// @param source Series of values to process.
// @param length Number of periods to process.
// @param smoothness The smoothing period.
// @returns A tuple containing the velocity and acceleration.
export get(series float source, simple int length, simple int smoothness) =>
    float sumVel = 0
    for i = 1 to length
        sumVel += (source - source[i]) / i
    vel = ta.ema(sumVel / length, smoothness)

    float sumAcc = 0
    for i = 1 to length
        sumAcc += (vel - vel[i]) / i
    acc = sumAcc / length

    [vel, acc]


float SOURCE = input.source(close, 'Source')
int LENGTH = input.int(26, 'Length', minval = 2, step = 1)
int SMOOTH = input.int(9, 'Smooth', minval = 1, step = 1)
color VELOCITY_COLOR = input.color(color.blue, 'Velocity', group = 'Colors')
color ABOVE_GROW_COLOR = input.color(#26a69a, 'Above Zero Grow', inline = 'Above', group = 'Colors')
color ABOVE_FALL_COLOR = input.color(#b2dfdb, 'Fall', inline = 'Above', group = 'Colors')
color BELOW_GROW_COLOR = input.color(#ffcdd2, 'Below Zero Grow', inline = 'Below', group = 'Colors')
color BELOW_FALL_COLOR = input.color(#ff5252, 'Fall', inline = 'Below', group = 'Colors')

[vel, acc] = get(SOURCE, LENGTH, SMOOTH)

color accColor = if acc >= 0
    acc[1] < acc ? ABOVE_GROW_COLOR : ABOVE_FALL_COLOR
else
    acc[1] < acc ? BELOW_GROW_COLOR : BELOW_FALL_COLOR
plot(acc * 100, 'Acc', color = accColor, style = plot.style_columns)
plot(vel / LENGTH * 200, 'Vel', VELOCITY_COLOR)