I'm attempting to programmatically determine when the price on a given asset deviated the most from the 20 SMA.
I wrote the code below which loops over the past 200 bars and determines the % difference between closing price and 20 SMA. All of the % values get set to maHistory
. I then attempt to calculate the max % change via array.max(maHistory)
.
I'm expecting maxOverMA
to be static. However, the value seems to be dynamic. Meaning it's not correctly setting when the price on a given asset deviated the most from the 20 SMA.
//@version=5
indicator("Secret Algo", overlay=true, max_labels_count=500)
// Functions
pine_sma(source, length) =>
sum = 0.0
for i = 0 to length - 1
sum += source[i] / length
sum
// Variables
MA = ta.sma(close, 20)
maPercentage = (close - MA) / MA * 100
maHistory = array.new_float(0)
// Determine historical max, min and avg deviation from MA
for i = 1 to 200
tempMA = pine_sma(close, 20)
tempMaPercentage = (close - tempMA) / tempMA * 100
maHistory.push(tempMaPercentage)
// Set MA ranges
maxOverMA = array.max(maHistory)
maxUnderMA = array.min(maHistory)
label.new(bar_index, close, str.tostring(maxOverMA), textcolor=color.red, style=label.style_none)
How do I clean up my code to ensure I get the correct value for maxOverMA
?