1

I'm trying to understand a script in pine script. I can't find the reason for the different outputs for similar codes.

First code:

//@version=4
study("CE", overlay=true)
length = input(title="ATR Period", type=input.integer, defval=22)
mult = input(title="ATR Multiplier", type=input.float, step=0.1, defval=3.0)
useClose = input(title="Use Close Price for Extremums ?", type=input.bool, defval=true)

longStop = (useClose ? highest(close, length) : highest(length)) - atr
longStopPrev = nz(longStop[1], longStop)

longStop := close[1] > longStopPrev ? max(longStop, longStopPrev) : longStop
plot(longStop)

Second Code

//@version=4
study("CE", overlay=true)
length = input(title="ATR Period", type=input.integer, defval=22)
mult = input(title="ATR Multiplier", type=input.float, step=0.1, defval=3.0)
useClose = input(title="Use Close Price for Extremums ?", type=input.bool, defval=true)

longStop = (useClose ? highest(close, length) : highest(length)) - atr
longStopPrev = nz(longStop[1], longStop)

longStop2 = close[1] > longStopPrev ? max(longStop, longStopPrev) : longStop
plot(longStop2)

I couldn't understand why longStop and LongStop2 outputs are different. It seems := operator affect previous lines of the code.

denizt
  • 13
  • 2
  • I've not used pinescript myself, but does [their information here](https://www.tradingview.com/pine-script-docs/en/v4/faq/Variables_and_operators.html?highlight=assignment#whats-the-difference-between-and) possibly help? – Paul T. Oct 05 '22 at 12:15
  • Hi @PaulT. Thank you for your comment. Document says: `No. Past values in a Pine Script™ series are read-only, as is the past in real life. ` As far as I understand, the results should be the same as per the document. Both codes are doing the same calculations. The only difference is the last variables (longStop & longStop2) names and assignment types. – denizt Oct 05 '22 at 13:21

1 Answers1

2

Your script will be executed on each bar and you can access the historical values from the previous executions with the [] history reference operator.

In the first code, you re-assign a value to longStop right before you plot the output. So, you are changing its value before the execution is over.

On the next bar, when it reaches longStopPrev = nz(longStop[1], longStop), it will use the value that comes from that last assignment.

In your second example, longStop is assigned only once and it will keep its value during the execution on a bar.

In summary, longStopPrev in your two examples are not the same and that causes your observed behavior.

vitruvius
  • 15,740
  • 3
  • 16
  • 26