1

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?

mike
  • 2,722
  • 6
  • 31
  • 46

1 Answers1

1

In you script you must take advantage of the serie type of the data in pinescript, no need to use a loop.

First you calculate your MA and maPercentage on each loop, so on each bar on your chart :

MA = ta.sma(close, 20)
maPercentage = (close - MA) / MA * 100

Then you can use the function 'ta.highest' to get the highest value from the X last bars (here 200). You can also use 'ta.highestbars' to get the offset from the current bar (bar_index) to the bar with the highest value.
As you are looking for the highest value of maPercentage on the 200 last bars, you should use :

maxOverMA =  ta.highest(maPercentage, 200)
BarMaxOverMA = ta.highestbars(maPercentage, 200)

You will see with this code that the bar found is 'static' (because a label is drawn each time the script makes a loop, and there is only one label visible on the screen) :

//@version=5
indicator("Secret Algo", overlay=true, max_labels_count=500, max_bars_back = 500)

// Variables
MA = ta.sma(close, 20)
maPercentage = (close - MA) / MA * 100

maxOverMA =  ta.highest(maPercentage, 200)
BarMaxOverMA = ta.highestbars(maPercentage, 200)

label.new(bar_index + BarMaxOverMA, close[-BarMaxOverMA], "X")
G.Lebret
  • 2,826
  • 2
  • 16
  • 27