I am getting this warning with my user function. Error is:
The function 'foo' should be called on each calculation for consistency. It is recommended to extract the call from this scope
This warning happens for many reasons it seems, one of which is doing a for loop on a series. For example:
foo()=>
for i = 0 to 5
if close[i] > 0 or close[i] < 0
break
if close < 10
foo()
This will throw the warning. However, it makes no sense! Because without the function call, there will be no consistency either!
For example, I can do:
if close < 10
for i = 0 to 5
if close[i] > 0 or close[i] < 0
break
And there won't be any consistency anyways! For loop will only run when close < 10, maybe alaways, maybe never! But for some reason, putting this into a function, now its inconsistent?
Please explain why is it so, and is it ever possible to use for loops on series in functions without such warnings?
EDIT:
Experimenting further, it seems even touching series is a no-no in functions?
foo()=>
a = close[1]
if close < 10
foo()
Is enough to give a warning. Is it documented somewhere? Why? Is there no work around?
I can understand your disappointment and I am fully with you. But pine script isn't. It is designed the way - if considered good or not - that it is very limited what you can do with functions (eg.: you cannot modify parameter values etc.).
By built-in functions or series that use the history referencing operator or functionality, your only safe option is to do everything in the global scope, store it in a variable and use your variable in a function. Or make sure you call your function strictly on each bar without a conditional.
The cause of the warning in your tests is the if conditional that makes the calculation inconsistent, not the function itself. If you call a function on each bar from the global scope, there is no problem. But since "if" it can happen that the function won't get called and that's why the message.
You can use for loops with series and history referencing withouth a problem, but only in the global scope.
I suggest you read the execution model description for more details.