//@version=4
study("Keep data across bars (var)", overlay=true)
// Variables
var bool canGoShort = true
var bool canGoLong = true
var int myTest = 5
// Functions
f_print(_txt) => t = time + (time - time[1]) * 3, var _lbl = label.new(t, high, _txt, xloc.bar_time, yloc.price, #00000000, label.style_none, color.gray, size.large), label.set_xy(_lbl, t, high + 3 * tr)
// MAIN
if canGoShort
myTest := myTest + 1
if canGoLong
myTest := myTest + 1
f_print("myTest=" + tostring(myTest))
I'm baffled by this simple script that doesn't seem to work as intended.
I initialize a var
variable myTest
with value 5.
Since canGoShort
and canGoLong
both are always true
, I'd expect the value of myTest
to be incremented by 1, twice on each bar:
Once in the if canGoShort
, and once in the if canGoLong
.
Say we have 5000 bars, then I'd expect it to finish at 5 + (5000 * 2) = 10005.
However, when running the script, myTest=7
is printed?
I'm getting the impression that the declaration var int myTest = 5
is executed on each bar.
It was my understanding that a variable defined with the keyword var
keeps its value across all bars, but it doesn't appear to be that way.
The documentation clearly says that it should keep it's value:
- https://www.tradingview.com/pine-script-reference/#op_var
var is the keyword used for assigning and one-time initializing of the variable. - https://www.pinecoders.com/faq_and_code/#techniques
Since v4 the var keyword provides a way to initialize variables on the first bar of the dataset only, rather than on every bar the script is run on, as was the case before. This has the very useful benefit of automatically taking care of the value’s propagation throughout bars
What am I missing here?