// Licensed under the Apache License, Version 2.0 // © mihakralj //@version=6 indicator("Variable Index Dynamic Average (VIDYA)", "VIDYA", overlay=true) //@function Calculates VIDYA using adaptive smoothing based on market volatility //@param source Series to calculate VIDYA from //@param period Length of the smoothing period //@param std_period Length of the standard deviation period, defaults to same as period //@returns VIDYA value that adapts to market volatility //@optimized Uses volatility index calculation with O(n) complexity per bar due to lookback loops vidya(series float source, simple int period, simple int std_period=0) => float alpha = 2.0 / (period + 1.0) var float vidya = na if not na(source) int p = std_period > 0 ? std_period : period float sum_p = 0.0 float sumSq_p = 0.0 float count_p = 0.0 float sum_5 = 0.0 float sumSq_5 = 0.0 float count_5 = 0.0 for i = 0 to math.max(p, 5) - 1 if not na(source[i]) float val = source[i] if i < p sum_p += val sumSq_p += val * val count_p += 1 if i < 5 sum_5 += val sumSq_5 += val * val count_5 += 1 float std = count_p > 0 ? math.sqrt(math.max((sumSq_p / count_p) - (sum_p / count_p) * (sum_p / count_p), 0.0)) : 0.0 float std_5 = count_5 > 0 ? math.sqrt(math.max((sumSq_5 / count_5) - (sum_5 / count_5) * (sum_5 / count_5), 0.0)) : 0.0 float vol_idx = std > 0 ? std_5 / std : 1.0 vol_idx := math.min(math.max(vol_idx, 0.0), 1.0) float sc = alpha * vol_idx vidya := na(vidya) ? source : source * sc + vidya * (1.0 - sc) vidya // ---------- Main loop ---------- // Inputs i_period = input.int(10, "Period", minval=1) i_std_period = input.int(0, "Std Dev Period (0=use Period)", minval=0) i_source = input.source(close, "Source") // Calculation vidya_value = vidya(i_source, i_period, i_std_period) // Plot plot(vidya_value, "VIDYA", color=color.yellow, linewidth=2)