问题
To reference a value stored in a series with Tradingview's PineScript you use an subscript integer to call a value from a series.
//What's the UNIX time of the previous bar?
time[1]
//What's the UNIX time of the 21st bar (counting from current time)
time[20]
My goal is to map an input of number of calendar days to a subscript integer to call the value of a series, such that it returns the value of that series, x days ago
Pseudo code:
SeriesIndexedByDays([series],[day,integer],[period]):
SeriesIndexedByDays(close,30):
Return close[30*Bars_per_day]
//Returns close value 30 days ago
The closest I've been able to achieve with PineScript is:
//Method 1:
days = input(title="Reference Point, # of Days", type=integer, defval=1, minval=0.01)
bars_per_day = 24*60/interval // 24 Hours per day * 60 Minutes per hour / [X (Minutes||Days||Weeks||Months||Years)] per bar
number_of_bars_reference_point = bars_per_day*days // Bars per day * Days
close[number_of_bars_reference_point]
But this isn't ideal because PineScript's interval is the prefix multiple of whatever period the bar is: [10m, 5m, 5D] -> [10, 5, 5] So if you change the period from 5 minutes to 5 days interval still outputs the same value: 5
The second attempt I made was:
//Method 2:
sec_per_day=24*60*60 // 24 hours per day * 60 minutes per hour * 60 seconds per minute = Seconds per day
t = time //Dump UNIX time into a variable
deltat=t-t[1] //Difference of UNIX time between this and previous bar, not necessarily the time of one bar (ex. session close, exchange's clock jumps due to offline or non continuous bars)
seconds_per_bar=lowest(deltat,2)/1000 // Use the lowest of the last two deltat values in case bar is the start of a session, divide by 1000convert from milliseconds to seconds
bars_per_day = sec_per_day/seconds_per_bar //Series, number of bars per day //Occationally this produces abberant values, assumption is that its because time dates
retrospective_reference_point_number_of_bars=bars_per_day*days
This produces retrospective_reference_point_number_of_bars as a series which correctly maps [days,period]->[bars]. But when used to call another series
close[retrospective_reference_point_number_of_bars]
TradingView returns an error:
out of depth at index
Other problems with Method 2 include, if period is less than the 'days' input, then it'll return a value with decimals/float which cannot be used to reference a series.
Possible Methods
If I could convert the first value of the output series of Method 2 to an integer, I could use that.
What ideas do you have for solving the mapping of [period,interval,days]->[bars]?
来源:https://stackoverflow.com/questions/50261646/reference-series-by-time-what-was-the-value-x-days-ago