'Calling ta.lowest within an if statement returns the low of the most recent candle, not the lowest of the last "x" candles
Just getting into Pine, my only experience is with a fair bit of Java, but that was 4+ years ago and I'm beyond rusty so trying to learn even this simple language is throwing me off. Trying to mess with some simple stuff to get started and I've hit my first snag trying to understand this behavior.
I want to use an if statement to assign the value returned by ta.lowest() to a global variable. In this instance, I'm using the if to enter a position, and I want the lowest value of the last, say, 20 bars "at the time of entering the position" to serve as a stop loss to exit the position. When I plot the variable to debug, I see that when the if statement triggers for the first time, it assigns the value of the low of the most recent candle, rather than the low of the last 20. Interestingly, on the second run of the if statement for the second entry, the value of my variable drops to 0.
Any input would be helpful. I'm guessing it's either a scope issue or I'm completely misunderstanding how Pine runs.
var stopLoss = float (na)
if (ta.crossover(delta, 0)) and (close>ta.ema(close, emaCloseLength)) and (strategy.opentrades == 0)
strategy.entry("MacdLE", strategy.long, comment="Entry")
stopLoss := ta.lowest(low, 20)
strategy.close("MacdLE", ta.crossunder(close, stopLoss))
Solution 1:[1]
Yes it's due to scope. The console would have given a scope warning ( Ctrl + ` ). If you assign ta.lowest() to a global variable it can then be referenced correctly within the if statement.
ie
ll = ta.lowest(low, 20)
if (ta.crossover(delta, 0)) and (close>ta.ema(close, emaCloseLength)) and (strategy.opentrades == 0)
strategy.entry("MacdLE", strategy.long, comment="Entry")
stopLoss := ll
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | rumpypumpydumpy |
