Reputation: 6905
//@version=4
study("PlayGround", overlay=true)
history_days = input(4, "History days")
source = close*0.95
plot(source)
This yields
(yellow highlight added manually)
I'm attempting to show the history of a series that has a user-configurable length.
In the example given, the history length is set to 4 days.
So the plot should start at april 29th.
Which means only the yellow highlight should be plotted.
However, I don't know how to implement that.
The history_days
variable is not used in the script, because I don't know how yet
The pine script execution model is such that it executes the script at each bar.
This means that we won't know the date of the last bar until it is reached.
Also, in order to calculate the date on which the plot should start, we have to take into account weekends and trading holidays.
In the example above, the last bar is on May 4th (a monday), and 4 trading days back is April 29th (wednesday).
But there are 6 calendar days between those dates, because it spans over a weekend.
Any tips on how to tackle this problem are welcomed.
Upvotes: 2
Views: 1726
Reputation: 8789
//@version=4
study("Days before", "", true)
daysBack = input(4)
_MILLISECONDS_IN_DAY = 24 * 60 * 60 * 1000
lastBarDate = timestamp(year(timenow), month(timenow), dayofmonth(timenow), hour(timenow), minute(timenow), second(timenow))
thisBarDate = timestamp(year, month, dayofmonth, hour, minute, second)
daysLeft = floor((lastBarDate - thisBarDate) / _MILLISECONDS_IN_DAY)
inRange = daysLeft <= daysBack
ma = sma(close, 30)
plot(ma, "ma", inRange ? color.orange : na)
plotchar(daysLeft, "daysLeft", "", location.top)
Upvotes: 1