0

In Pine Script, how do I find the price based on a certain number of days ago? I've tried something like this...

// Find the price 90 days ago
target = time - 90 * 60 * 60 * 24 * 1000
valuewhen(time < target, close, 1)

...however time < target never seems to return true – presumably because the current bar's time cannot also be in the past at the same time. Perhaps valuewhen() wasn't designed to be used with dynamic values that change on every bar?

Do I need to use a loop instead, and scan through every past bar until I find the date I'm looking for?

Simon East
  • 55,742
  • 17
  • 139
  • 133
  • Some similar (but not exact) questions asked previously: [Reference series by time - What was the value X days ago?](https://stackoverflow.com/questions/50261646/reference-series-by-time-what-was-the-value-x-days-ago), [How to get bar index on specific date](https://stackoverflow.com/questions/63025721/how-to-get-bar-index-on-specific-date) – Simon East Dec 27 '20 at 06:03

1 Answers1

0

Perhaps there's a better way, but the workaround I'm using currently using is a function with a for loop, scanning backwards until the appropriate date is found. Here is my function:

priceXDaysAgo(numDays) =>
    targetTimestamp = time - numDays*60*60*24*1000
    
    // Declare a result variable with a "void" value
    float result = if false
        1
        
    // We'll scan backwards through the preceding bars to find the first bar
    // earlier than X days ago (it might be a little greater than X days if
    // there was a break in trading: weekend, public holiday, etc.)
    for i = 1 to 1000
        if time[i] < targetTimestamp
            result := close[i]
            break
    result

You can then call the function anywhere in your script:

priceXDaysAgo(90)
Simon East
  • 55,742
  • 17
  • 139
  • 133