Home > Software design >  variable being shadowed in trading view pinescript, saying use := instead
variable being shadowed in trading view pinescript, saying use := instead

Time:08-30

I am new to pinescript and have coded a simple indicator in trading view pinescript. I can get my buy and sell labels and also send alert when conditions are met.

I am trying to store the entry price as a variable when a sell or buy signal has been met. I also pass a var called pos which is 1 for sell and 2 for long.

i am trying to make the indicator send an alert when the entry price is above or below 20 pips. however my variable which is passed to the alert is being shadowed??? why??? im sure my code is correct?

var pos=0
var short_update = false
var entry_price = 0

if sellSignal

    longLabel = label.new(
      x=bar_index, 
      y=na, 
      text="Sell - "  str.tostring(RoundUp(hlc3,2)),
      xloc=xloc.bar_index,
      yloc=yloc.abovebar, 
      color=color.red, 
      textcolor=color.white, 
      style=label.style_label_down, 
      size=size.normal)
    entry_price=close
    pos=1
alertcondition(sellSignal, "Short Alert", "Go short")


price_lower=entry_price-20
current_price=close

if pos==1 and current_price < price_lower
    short_update=true
    
alertcondition(short_update, "Move Stop at BE", "BE")

above is my attempt at coding an alert condition if the entry price of a short is now 20 pips less...not working? please help

CodePudding user response:

Actually all your variables defined with var on top are being shadowed not only "the one" you're referring to.

Shadowing variable 'pos' which exists in parent scope. Did you want to use the ':=' operator instead of '=' ?

What does it mean?
You have declared your variables and assigned the first values correctly by the assignment operator: = in the global scope. If you want to update these values later on you'll need the reassignment operator though: :=.

The := is used to reassign a value to an existing variable. It says use this variable that was declared earlier in my script, and give it a new value. source

So in your case var pos=0, var short_update = false, var entry_price = 0 are not getting updated through your whole script, are jut being redeclared as new variables in your local scopes that have no effect on the global ones, though having the same name.
The solution is as simple as the error message says: use := instead of = if you want to update a declared variable.

Final note: try updating eg.: pos like this pos=1 in the global scope below you var pos=0 declaration. You'll get an error saying "'pos' is already defined". The same applies to your example, the only difference is that it is not illegal to redeclare a variable in a local scope, but Pine Script warns you correctly that it's probably not what you wanted.

  • Related