mcetraro
mcetraro

Reputation: 11

Pine script simple condition statement

I am trying to convert a pine script to python. I have a problem understanding these three lines of code:

trend = 1

trend := nz(trend[1], trend)

trend := trend == -1 and close > dn1 ? 1 : trend == 1 and close < up1 ? -1 : trend

My questions: (1) In the statement (trend = 1), is trend a series or an integer constant? (2) Based on the second statement (nz(trend[1], trend)), I am guessing that trend is a series. is that right? (3) Where I have the main problem is on the third statement... how the condition is checking for the value of trend and depending on the condition the result is assigned to the trend. Is this a loop? Even if it is a loop, trend never can have a value of -1. I am sure that I am missing something.

I will appreciate very much any help. THANK YOU.

Upvotes: 0

Views: 520

Answers (1)

vitruvius
vitruvius

Reputation: 21139

You can write that third line as

trend := if (trend == -1 and close > dn1)
    1
else
    if (trend == 1 and close < up1)
        -1
    else
        trend // keep its value

Now, for the very first bar of the chart, trend will be na and that's where the nz() function kicks in. It will replace the na with trend which is defined as 1.

So, when you come to the third line, trend = 1. Then this (trend == 1 and close < up1) condition will be checked and if close < up1 is true, trend will be -1.

Here is a simple code that will make the trend 1 when it is a green bar, and -1 when it is a red bar.

// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © vitruvius

//@version=5
indicator("My script")

dn1 = close[1]
up1 = close[1]

trend = 1
trend := nz(trend[1], trend)

trend := if (trend == -1 and close > dn1)
    1
else
    if (trend == 1 and close < up1)
        -1
    else
        trend // keep its value

plot(trend)

enter image description here

Upvotes: 1

Related Questions