Reputation: 25
I am trying to plot something on the chart based on some conditions. But I want it to be plotted for the last day candles only. I have written this code to find a condition which is true for the last day only based on the bar index. The condition is true mathematically but pine is considering it to be false for many candles. What am I missing here? You can see the last day has 24 bars and I have found the range of the bar_index for this day which is 20349 to 20373. But the labels show that this condition is false.
//@version=5
indicator(title = "Check", overlay = true)
newDay = dayofweek != dayofweek[1]
bars_since_newday = ta.barssince(newDay )
last_bar = last_bar_index
today = bar_index >= (last_bar - bars_since_newday)
l = label.new(bar_index, high, str.tostring(today), style = label.style_none, textcolor = color.white )
l1 = label.new(bar_index, low-50, "last index = " + str.tostring(last_bar) + "\n bars since newday = " + str.tostring(bars_since_newday) + "\n difference = " + str.tostring(last_bar - bars_since_newday), style = label.style_none, textcolor = color.white )
label.delete(l1[1] )
Upvotes: 1
Views: 382
Reputation: 71
Unfortunately I gotta tell you that such a function is really not what you want, because it changes every condition, whenever you load the chart again, which is what you don't want.
The reason your code doesn't work the way you want, is because you think of the code running from the newest candle to the oldest (I guess). You have to keep in mind, that the code runs on each candle again and again. Another reason is, that you use some constants like last_bar_index
, which is always the newest candle bar_index.
Let's just go through it by looking at an example.
We are 3 hourly candles into a new day and we reload our chart. The last_bar_index
is now equal to 3003
. From now on, every candle calculates the count of bars since newDay
, and subtracts 3003 - thisCount
. Let's imagine bar_index
being equal to 3000
(new Day's bar_index). Is 3000 >= (3003 - 0)
? No, because their count is not equal to 3
, which is the case, three candles after.
You should get through this once more and see that it doesn't work.
To wrap things up, I recommend you to make your code not today_based, because then, your indicator repaints on every reload of page.
But if you really want to do this, I'd recommend the following:
_day = dayofweek(last_bar_time)
_month = month(last_bar_time)
_year = year(last_bar_time)
today = dayofweek == _day and month == _month and year == _year
l = label.new(bar_index, high, str.tostring(today), style = label.style_none, textcolor = color.white )
Upvotes: 0