Pine Script: optimise period of an SMA using a for loop

Viewed 27

I am trying to optimise an SMA period within a for loop such that there is at least one cross between the low series and the SMA and the high series and a multiplier of the SMA. To do this, I use a for loop over candidate period values and for each candidate period value, I generate an SMA and check whether the crosses mentioned earlier exist.

I notice some very strange behaviour which leads to garbage results.

Here's a sample code. Please try it on the daily BITSTAMP:BTCUSD chart so that the results you get are consistent with mine.

//@version=5
indicator(title="test", shorttitle="test", overlay=true)

// functions
boolCross(series1, series2) =>
    ta.cum(ta.cross(series1, series2) ? 1 : 0) > 0

// main
var int periodToUse = 0
for thisPeriod = 1400 to 1
    periodToUse := thisPeriod
    sma = ta.sma(close, thisPeriod)
    boolUpperBandTouch = boolCross(high, sma * 5) 
    boolLowerBandTouch = boolCross(low, sma)
    if boolUpperBandTouch and boolLowerBandTouch
        break

// plot
plot(ta.sma(close, periodToUse), color = color.red, linewidth = 3) // <===== plots garbage
plot(ta.sma(close, periodToUse) * 5, color = color.red, linewidth = 3) // <===== plots garbage

Here is the result: enter image description here

I checked internally, and the value of periodToUse is 1400. The SMA with a period of 1400, when plotted manually, most certainly does not look like the screenshot above.

What am I doing wrong? I suspect there is a problem using ta.sma() from within a for loop and that somehow this is "corrupting" the value of periodToUse.

PS: related to this question, but more focused.

0 Answers
Related