FAQ

How to fix “cannot use a mutable variable as an argument of the security function” error

How to fix “cannot use a mutable variable as an argument of the security function” error

Here is an example of pivot points calculation in PineScript:

//@version=4
study("Pivot Points", overlay=true)

hprice = 0.0
swh = pivothigh(4, 4)
hprice := not na(swh) ? swh : hprice[1]

lprice = 0.0
swl = pivotlow(4, 4)
lprice := not na(swl) ? swl : lprice[1]

plot(hprice, color = color.green)
plot(lprice, color = color.red)

This works fine in PineScript:

But If you’ll try to compute the same pivots on Higher Time Frame with security function, daily in this case:

//@version=4
study("Pivot Points", overlay=true)

hprice = 0.0
swh = pivothigh(4, 4)
hprice := not na(swh) ? swh : hprice[1]

lprice = 0.0
swl = pivotlow(4, 4)
lprice := not na(swl) ? swl : lprice[1]

hprice_d = security(syminfo.tickerid, 'D', hprice)
lprice_d = security(syminfo.tickerid, 'D', lprice)

plot(hprice_d, color = color.green)
plot(lprice_d, color = color.red)

That won’t work and you will see the following error in console: ” line 12: Cannot use a mutable variable as an argument of the security function. ‘

The issue is that you can’t use mutable variables in the security function. By mutable variable, I mean variable that you define first with the equal operator, for example (hprice = 0.0), and later in the code, you update it with “:=” operator (lprice := not na(swl) ? swl : lprice[1])

To fix that error you have to create a function to calculate this variable and include all calculations related to this variable in that function. After that, you have to call this function in Security function instead of variable. Final code should look like that:

//@version=4
study("Pivot Points", overlay=true)

hprice_func() => 
    hprice = 0.0
    swh = pivothigh(4, 4)
    hprice := not na(swh) ? swh : hprice[1]

lprice_func() =>
    lprice = 0.0
    swl = pivotlow(4, 4)
    lprice := not na(swl) ? swl : lprice[1]

hprice_d = security(syminfo.tickerid, 'D', hprice_func())
lprice_d = security(syminfo.tickerid, 'D', lprice_func())

plot(hprice_d, color = color.green)
plot(lprice_d, color = color.red)

Of course, this is a bit simplistic example, and my functions code looks very simple and basically looks almost exactly like calculations before. Your case might be a bit more complicated. But the key here is to wrap all code you use to compute this variable as a function. Doing that you should be able to fix that error.


Follow me on TradingView and YouTube.

This image has an empty alt attribute; its file name is wide.png
Pine Script Programming Courses
Pine Script Programming Courses
Learn to build your own TradingView Indicators and Strategies
Sidebar Signup Form
If you want to be the first in this business, subscribe to the latest news