Velocity and Acceleration Signals
// 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("Velocity and Acceleration Signals", overlay=false)

lookback = input.int(14, title="Lookback Period")
emaLength = input.int(20, title="EMA Length for Velocity")

// Calculate Velocity
velocitySum = 0.0
for i = 1 to lookback
    velocitySum := velocitySum + (close - close[i]) / i

velocity = velocitySum / lookback

// Calculate Acceleration
accelerationSum = 0.0
for i = 1 to lookback
    accelerationSum := accelerationSum + (velocity - velocity[i]) / i

acceleration = accelerationSum / lookback

// Smooth Velocity with EMA
smoothedVelocity = ta.ema(velocity, emaLength)

// Coloration
acccolor = acceleration > 0 ? color.lime : color.fuchsia
velcolor = smoothedVelocity > 0 ? color.green : color.red
barColoration = acceleration and smoothedVelocity > 0 ? color.lime : acceleration and smoothedVelocity < 0 ? color.fuchsia : color.gray

barcolor(barColoration)

// Plot Velocity and Acceleration
plot(smoothedVelocity, color=velcolor, title="Smoothed Velocity", style = plot.style_columns)
plot(acceleration, color=acccolor, title="Acceleration", style = plot.style_histogram, linewidth = 4)
hline(0, title="Zero Line", color=color.gray)

// Strong Up and Strong Down Conditions
upthreshold = input.float(0.01, "Up Threshold")
dnthreshold = input.float(-0.01, 'Down Threshold')
strongUp = ta.crossover(smoothedVelocity, upthreshold) and (acceleration[0] > 0)
strongDown = ta.crossunder(smoothedVelocity, dnthreshold) and (acceleration[0] < 0)

plotshape(strongUp, location=location.top, color=color.green, style=shape.triangleup, title="Up", size=size.small)
plotshape(strongDown, location=location.bottom, color=color.red, style=shape.triangledown, title="Down", size=size.small)
