Abraham Reinhardt
Abraham Reinhardt

Reputation: 107

Get last several days highest price but not considering current day

I wrote an indictor that shows the last 3 days highest price on lower timeframe charts. To get highest price of days with security(syminfo.tickerid, "D", highest(low, period+1)) so that I can view highest price of days on 4h or other lower timeframes. When I looked at the plot I realized something was wrong. For instance if the second 4h of a day reached that day's highest price. it draws at that price even at the first 4h. This is a flaw that when you try to draw higher timeframe price on lower timeframes charts. So I have to ignore the current day's price that being said I need a function like highest(..., start_index, end_index) but it doesn't exist in pine script so I decided to write a for loop.

period = 3
HH = 0.0
for int i=1 to period
    HH := max(security(syminfo.tickerid, "D", high[i]), HH)

from that I hope to get last 3 days highest price but not considering current day. Yet the compiler showed an error Cannot call 'security' or 'financial' inside 'if' or 'for'. I can't think of other methods now.

Upvotes: 0

Views: 1108

Answers (1)

Bjorgum
Bjorgum

Reputation: 2310

There is no need to run a loop on security as the function will return a variable we ask of it. In this case we can use the highest() function, then pass it through security and it does the rest for us. I have included the security function that is best use case for this, and the one recommended as "best practice" to avoid repainting and use confirmed close data only by PineCoders. I also included a background stripe that will color on the change of our time frame so it becomes easy to count and verify back. The look back and time frame - also inputs so we can adjust from the menu.

//@version=4
study("My Script", overlay=true)

tf           = input("D", "Time",     input.resolution)
lookback     = input(3,   "Lookback", input.integer)

highs        = highest(high, lookback)

threeDayHigh = security(syminfo.tickerid, tf, highs[barstate.isrealtime ? 1 : 0])[barstate.isrealtime ? 0 : 1]

bgcolor(change(time(tf)) ? color.new(color.gray, 80) : na)

plot(threeDayHigh)

Cheers! Best of luck in your trading and coding

Upvotes: 1

Related Questions