Please consider the following 2 pine script (v4) functions
rng_filt(x, rng_, n)=>
r = rng_
var rfilt = array.new_float(2, x)
array.set(rfilt, 1, array.get(rfilt, 0))
if x - r > array.get(rfilt, 1)
array.set(rfilt, 0, x - r)
if x + r < array.get(rfilt, 1)
array.set(rfilt, 0, x + r)
rng_filt1 = array.get(rfilt, 0)
hi_band = rng_filt1 + r
lo_band = rng_filt1 - r
rng_filt = rng_filt1
[hi_band, lo_band, rng_filt]
rng_filt2(x, rng_, n)=>
r = rng_
var rfilt = array.new_float(2, x)
rng_filt1 = x
if x - r > x
rng_filt1 := x - r
if x + r < x
rng_filt1 := x + r
hi_band2 = rng_filt1 + r
lo_band2 = rng_filt1 - r
rng_filt2 = rng_filt1
[hi_band2, lo_band2, rng_filt2]
The first implementation rng_filt
is part of one of the trading view indicators.
The rng_filt2
is a function I wrote aimed to make the former simpler and more readble for the purpose of converting it to c#.
The original function defines a 2 items array rfilt
, both intialized with the input x
.
Then the array.set(rfilt, 1, array.get(rfilt, 0))
assigned the array[0] into array[1], basically doing nothing.
Then two if statements, both comapre againts array[1] which is actually the input argument x
. For both, if the condition is true the array[0] is set to the condition value
So:
if x - r > array.get(rfilt, 1)
array.set(rfilt, 0, x - r)
if x + r < array.get(rfilt, 1)
array.set(rfilt, 0, x + r)
Can be converted into
rng_filt1 = x
if x - r > x
rng_filt1 := x - r
if x + r < x
rng_filt1 := x + r
If none of the conditions are true array[0] == x as intialized.
So in the 2nd implementation, rng_filt1
is initialized to x
This is how these functions are called.
[h_band, l_band, filt] = rng_filt(rng_src, rng_size(rng_src, rng_qty, rng_per), rng_per)
[h_band2, l_band2, filt2] = rng_filt2(rng_src, rng_size(rng_src, rng_qty, rng_per), rng_per)
When comparing for example
if h_band = h_band2
The result is false
What am i missing?
Then the array.set(rfilt, 1, array.get(rfilt, 0)) assigned the array[1] into array[0], basically doing nothing.
This is not correct. It does something. It assigns the second item in the array into the first one as you said. In the next two if statements, it could modify the first item of this array. So, on the next bar when it calls this function, array[0] could have a different value which would get copied to array[1].
Hence, the below statement is also not correct:
Then two if statements, both comapre againts array[1] which is actually the input argument x.