You need some time with closed eyes to better understand how Pine script works.
On every bar (whatever the time frame), your code will start with a clean state. When your code have run on that bar, there will be a few calculated values you made, like:
my_var = close * open + 1234
You should be thinking of my_var as a huge Array which is built by Pine, bar-by-bar. At the end of every "turn", Pine will append the current value of my_var to the end of that huge array, then RESET everything and start on the next bar.
If you are running your script on a token/ticker symbol that has 17500 candles, then your Pine script will run 17499 times, starting from the very first candle, to reach to the current candle and every variable you have created will have 17499 past values in it (one for each candle).
This is why you can have my_var[3] which is the third previous value of my_var. Thinking of arrays, my_var[0] is the same as my_var, which is the current value of my_var in the current run.
So at the end of every candle, everything will reset and start over again. Your statement:
SL_Long_active = close >= SL_Long_threshold
will be true for some candles, but will be false for others. If you calculate it this way, it will recalculate on every bar, effectively destroying its previous state, which is not what you want.
The only way to prevent this reset, Pine has a klunky solution, you need to prefix a variable with var. This will define the variable, you can even set a value to it, but it will never reset, however its value will still be appended to that huge array, so if you use such a variable in the previous example, it will also have 17499 past values at the current candle.
Changing such a variable's value on every candle has no use, you could just have used a normal variable instead. The var variables' power shows if you only change their values when a certain condition happens.
var my_var = false
if close > close[1]
my_var := true
else
my_var := false
Or better (because of more deeper, hidden klunkyness of Pine) you should use a ternary operator:
var my_var = false
my_var := close > close[1] ? true : false // You don't need to define true/false, this is just an example placeholder
The line with var my_var = false will only run once, on the very first run so it will not redefine my_var in every turn.
What to watch for:
- if you set a variable's value in your script once or first, you have to use
=, like my_var = 5
- however if you are redefining a variable's value later in the script, you must use
:= instead
- with
IF/ELSE you have to indent the second/third/... lines below the if <whatever> with exactly 4 spaces or 1 tab. Otherwise Pine will think it is a new line and not part of the IF block.
I wish Tradingview have built a debugger, that would make Pine very much understandable by stepping over the code on one bar, then seeing the "code" hop to the next bar, and running again from the 1st line.