Search code examples
global-variablespine-script

Cannot modify global variable 'buyLimit' in function PineScript


I am new to TradingView Pine scripting. can you help me about error " Cannot modify global variable 'buyLimit' in function". How i can modif my code to run in security() function. Thx Before When i Compile i found error "Cannot modify global variable 'buyLimit' in function".

float buyLimit = na
ShortSignalFunc() => 
buyLimit := (highestHigh - base) / base > bounce and low < base * (1 - baseCrack) ? base * (1 - baseCrack) : na

Solution

  • Try declaring variables locally to your function. eg.

    ShortSignalFunc() => 
        float buyLimit = na
        buyLimit := (highestHigh - base) / base > bounce and low < base * (1 - baseCrack) ? base * (1 - baseCrack) : na
    

    Also, since you only have the one conditional statement for this variable, the following will likely work as well where we just use "=" and dont bother re-assigning.

    ShortSignalFunc() => 
        buyLimit = (highestHigh - base) / base > bounce and low < base * (1 - baseCrack) ? base * (1 - baseCrack) : na
    

    If a global variable does need to be altered, you can create a new one and then use the funciton to assign it within the global scope.

    Cheers my friend