Search code examples
pine-scriptpine-script-v5

How to address days relatively?


I would like to address days addressed relatively of today, for example "today minus 3 days". Is there any way to code this relation?

I'd like to use it in Boolean conditions.

For (just a logic) example:

ThisIsThatVeryDay = Today - 3
Event = SomethingSomething and ThisIsThatVeryDay

Solution

  • You can use the built-in timenow and time_tradingday variables to determine if the bar on which the script is currently calculating on was a certain number of days ago.

    //@version=5
    indicator("relativeDays", overlay = true)
    
    var int MILLISECONDS_PER_DAY = 86400000
    
    int daysSince1970RelativeToNow = math.floor(timenow / MILLISECONDS_PER_DAY)
    int daysSince1970RelativeToBar = math.floor(time_tradingday / MILLISECONDS_PER_DAY)
    
    wasBarFormedXDaysAgo(int daysAgo) =>
        daysSince1970RelativeToNow - daysSince1970RelativeToBar == daysAgo
    
    // Use green background for bars that were formed 3 days ago
    bgcolor(wasBarFormedXDaysAgo(3) ? color.new(color.green, 75) : na)
    
    // Debug
    plot(timenow, "timenow", display = display.data_window)
    plot(daysSince1970RelativeToNow, "daysSince1970RelativeToNow", display = display.data_window)
    
    plot(time_tradingday, "time_tradingday", display = display.data_window)
    plot(daysSince1970RelativeToBar, "daysSince1970RelativeToBar", display = display.data_window)
    

    Screenshot: enter image description here