6

I'm trying to use a series as integer. Pinescript 4 is out but still no way to do this:

//@version=4 
study("Test Script", overlay=true) 

l = 1 
l := nz(l[1]) + 1 
l := l>20?1:l 
ma = sma(close, l) 
plot(ma, linewidth=4, color=color.black) 

I have also tried to use "var". This time no errors but doesn't work as expected

//@version=4 
study("Test Script", overlay=true) 

var l = 1 
l := l>=20?1:l+1 
ma = sma(close, l) 
plot(ma, linewidth=4, color=color.black)

any suggestions?

Don Coder
  • 526
  • 5
  • 24

2 Answers2

1

This will code will be faster. It's by alexgrover and lifted from the Functions Allowing Series As Length - PineCoders FAQ script:

Sma(src,p) => a = cum(src), (a - a[max(p,0)])/max(p,0)
PineCoders-LucF
  • 8,288
  • 2
  • 12
  • 21
0

I double checked but was not able to find a way to cast series to an integer.

Fortunately, in your case you can write a custom SMA function to work around the literal integer limitation of the standard sma() function.

//@version=4 
study("Test Script", overlay=true) 
moving_sma(source_series, length) =>
    if length == 1.0 // if length is 1 we actually want the close instead of an average
        source_series
    else // otherwise we can take the close and loop length-1 previous values and divide them to get the moving average
        total = source_series
        for i = 1 to length - 1
            total := total + source_series[i]
        total / length

sma_length = 1.0
sma_length := nz(sma_length[1]) == 0.0 ? 1.0 : sma_length[1]
if sma_length < 20
    sma_length := sma_length + 1
else
    sma_length := 1

plot(moving_sma(close, sma_length), linewidth=4, color=color.yellow)