3

If I want to compare the close of today with the high of the last 4 days, what is the format? I have used

_hi = close > high[4] ? 1 : 0

But that only counts the high 4 days ago, not the days in between. I have tried

_hi = close > high[1,2,3,4] ? 1 : 0

Error message

sunspore
  • 127
  • 1
  • 4
  • 13

1 Answers1

6

You can use highest() for that purpose.

highest(source, length) → series

You need to be careful though. close > highest(close, 4) can never be true. Because, if the current bar's close price is the highest among those 4 bars, highest() will return current bar's close price. Therefore, that check would be close > close, which can never be true.

You can either do close > highest(nz(close[1]), 4) or close == highest(close, 5) (It is 5, because current bar is also included. But you want to compare the previous 4 bars).

Have a look at the following code and chart. One is using close > highest(nz(close[1]), 4) and the other one is using close == highest(close, 5). As you can see, the output is identical.

//@version=3
study(title="Compare 2", overlay=true)

_hi = close > highest(nz(close[1]), 4)
plotshape(series=_hi, title="_hi", text="hi", style=shape.triangleup, location=location.belowbar, color=color.green, size=size.small, transp=40)

enter image description here

anar khalilov
  • 16,993
  • 9
  • 47
  • 62
vitruvius
  • 15,740
  • 3
  • 16
  • 26
  • Very cool my friend, I get it. I don't understand the usage of nz. I've read the definition of it in the Pine manual, but I don't understand what it does. I ran your study both with and without the nz, and it doesn't plot any differently. – sunspore Nov 03 '18 at 01:01
  • `nz()` replaces "Not a Number" `NaN` values with `zeros`. Try to plot `close[1]` and go to the highest time frame you can. Then look for the **very first** bar. It will not have a value (**NaN**). Because, it is the first bar, and `close[1]` is asking the close price of previous bar. But there is no previous bar at that point. That's why you will get `n/a`. Now, try to plot `nz(close[1])` and look for the **very first** bar. This time you will get a `0`. So, `NaN` will be replaced by `0`. So, it is always good practice to wrap historical values with `nz()`, so your calculations should be safe. – vitruvius Nov 03 '18 at 11:41
  • Thanks Baris, now I get it. – sunspore Nov 04 '18 at 15:11