user1207607
user1207607

Reputation: 23

Upgrading pinescript 4 to 5

I'm currently trying to rewrite an indicator from pinescript 4 to 5 in order to include it in a strategy that I'm writing. There's a user defined function in it that I'm not sure how to rewrite to v5. The function is below. It works great in v4 but v5 complains of A, M and D being undefined. I believe it happens when it reaches the arrays A[1], M[1], D[1]. I know how to use the ternary expression but don't understand how the logic works in order to fix it.

Original code, v4:

calc_abssio( ) =>
    A=iff(close>close[1], nz(A[1])+(close/close[1])-1,nz(A[1]))
    M=iff(close==close[1], nz(M[1])+1.0/osl,nz(M[1]))
    D=iff(close<close[1], nz(D[1])+(close[1]/close)-1,nz(D[1]))
    iff (D+M/2==0, 1, 1-1/(1+(A+M/2)/(D+M/2)))

My v5 throws the errors listed below the code block.

calc_abssio() =>
    A=close>close[1] ? nz(A[1])+(close/close[1])-1 : nz(A[1])
    M=close==close[1] ? nz(M[1])+1.0/osl : nz(M[1])
    D=close<close[1]? nz(D[1])+(close[1]/close)-1 : nz(D[1])
    D+M/2==0 ? 1 : 1-1/(1+(A+M/2)/(D+M/2))

Errors: 
line 95: Undeclared identifier 'A'
line 96: Undeclared identifier 'M'
line 97: Undeclared identifier 'D'
line 95: Variable 'A' is not found in scope 'calc_abssio', cannot register side effect

I'm a seasoned developer but new to pine script. Any help is appreciated!

Upvotes: 0

Views: 403

Answers (1)

e2e4
e2e4

Reputation: 3828

The code you provided is NOT a Pine Script v4, but pine v2, where self-referencing variables were allowed while a variable declaration.

In Pine Script v3 and above, such variables should be declared prior to the self-reference call. Note that the calc_abssio() function is also using the osl variable from the global scope of the script, which is missing in your snippet:

//@version=5
indicator("My script", precision = 8)

calc_abssio() =>
    osl = 1 // missing variable
    A = 0.0
    A := close>close[1] ? nz(A[1])+(close/close[1])-1 : nz(A[1])
    M = 0.0
    M :=close==close[1] ? nz(M[1])+1.0/osl : nz(M[1])
    D = 0.0
    D :=close<close[1]? nz(D[1])+(close[1]/close)-1 : nz(D[1])
    D+M/2==0 ? 1 : 1-1/(1+(A+M/2.)/(D+M/2.))
    
abssio = calc_abssio()

plot(abssio)

See here the migration guide from v2 to v3. The newer versions of Pine use the same logic as the v3. - https://www.tradingview.com/pine-script-docs/en/v5/migration_guides/To_Pine_version_3.html#self-referenced-variables-are-removed

Upvotes: 1

Related Questions