Asif Mulla
Asif Mulla

Reputation: 1664

Dynamic date range inside pine script

I am not able to get backdate from today inside pine script. I have defined function to minus the UNIX timestamp from current time. But following code results into error as "Timestamp requires integer parameter than series parameter"

getdate() =>
    tt = timenow - 1549238400
    yr = year(tt)
    mt = month(tt)
    dt = dayofmonth(tt)
    timestamp(yr[0], mt[0], dt[0], 0 ,0)

Any help will be appreciated.

Upvotes: 1

Views: 3930

Answers (2)

T.Todua
T.Todua

Reputation: 56547

  • maybe you can just use round function to transform that into integer?
  • also, remove [0] after yr etc...

Upvotes: 0

Michel_T.
Michel_T.

Reputation: 2821

Seems that it's inconsistency of pine. If accuracy is not so important, I propose to use selfwriten function for timestamp:

//@version=3
study("Timestamp")
MILLISECONDS_IN_DAY = 86400000
TIMESTAMP_BEGIN_YEAR = 1970

myTimestamp(y, m, d) =>
    years = y - TIMESTAMP_BEGIN_YEAR
    years * MILLISECONDS_IN_DAY * 365.25 + (m - 1) * 30 * MILLISECONDS_IN_DAY + (d - 1) * MILLISECONDS_IN_DAY



// TEST:
tmspm = myTimestamp(2019, 3, 5)

y = year(tmspm)
m = month(tmspm)
d = dayofmonth(tmspm)

plot(y, color=green)
plot(m, color=red)
plot(d, color=maroon)

BTW, timenow returns a value in millesecond whereas you're trying to subtract it by a value in seconds: 1549238400

And I don't exactly understand the logic of your code, because you're subtracting two dates and then transform that difference to a new date. For me it makes no sence. But maybe it's just an example for the stackoverflow, so never mind then

UPD: Your code won't work, because you subtract timenow by 1549238400, but 29 days ago in millisecond is 2505600000. I hope the next code will helpful:

//@version=3
study("My Script")

_MILLISECONDS_IN_DAY = 86400000
_29_DAYS_MILLIS = 29 * _MILLISECONDS_IN_DAY

reqDate = timenow - _29_DAYS_MILLIS
reqYear = year(reqDate)
reqMonth = month(reqDate)
reqDay = dayofmonth(reqDate)

linePlotted = false
linePlotted := nz(linePlotted[1], false)

vertLine = na
col = color(red, 100)

//this puts a line exactlty 29 day ago or nothing if there wasn't a trading day at the date. If you want to put a line 29 days ago or closer, then:
// if year >= reqYear and month >= reqMonth and dayofmonth >= reqDay and not linePlotted
if year == reqYear and month == reqMonth and dayofmonth == reqDay and not linePlotted
    linePlotted := true
    vertLine := 1000
    col := color(red, 0)

plot(vertLine, style=histogram, color=col)

Note, that there are two possible conditions depends on what you need: put a line exactly 29 days ago (or nothing if there weren't any bars that day) and a line must be put at the date or closer to today

Upvotes: 1

Related Questions