// Licensed under the Apache License, Version 2.0 // © mihakralj //@version=6 indicator("Standard Deviation (STDDEV)", "STDDEV", overlay=false) //@function Calculates the standard deviation using a single pass with a circular buffer. //@param src {series float} Source series. //@param len {int} Lookback length. `len` > 0. //@returns {series float} Standard deviation of `src` for `len` bars back. Returns `na` if not enough data. stddev(series float src, int len) => if len <= 0 runtime.error("Period must be greater than 0") var int p = math.max(1, len) var array buffer = array.new_float(p, na) var int head = 0, var int count = 0 var float sum = 0.0, var float sumSq = 0.0 float oldest = array.get(buffer, head) if not na(oldest) sum -= oldest sumSq -= oldest * oldest count -= 1 float val = nz(src) sum += val sumSq += val * val count += 1 array.set(buffer, head, val) head := (head + 1) % p count > 1 ? math.sqrt(math.max(0.0, (sumSq / count) - math.pow(sum / count, 2))) : 0.0 // ---------- Main loop ---------- // Inputs i_period = input.int(14, "Period", minval=1) // Default period 14 i_source = input.source(close, "Source") // Calculation stddev_value = stddev(i_source, i_period) // Plot plot(stddev_value, "StdDev", color=color.yellow, linewidth=2) // Changed color