Search code examples
unix-timestamppine-scriptalgorithmic-trading

In Pine Script, how can you do something once per day, or keep track if something has been done yet that day?


I'm working on a TradingView script (Pine) and i'm trying to use my Daily-bar strategy on the 5-minute chart. To do this, I need to basically only check conditions once per day.

I can do this by having a boolean variable such as dailyCheck = false and set it to true when I run that code and then reset it on a new day.

Does anyone know how to go about doing this? From what I read in the pine manual it says you can get unix time...but I don't know how to work with this and I can't print anything except numbers in the form of plot, so I can't figure out how to tell when a new day has started. Thanks in advance!


Solution

  • Version 1

    There are lots of ways to detect a change of day. The Session and time information User Manual page shows a few.

    I like detecting a change in the dayofweek or dayofmonth built-in variables:

    //@version=4
    study("Once per Day")
    var dailyTaskDone = false
    newDay = change(dayofweek)
    doOncePerDay = rising(close, 2)     // Your condition here.
    dailyTaskDone := doOncePerDay or (dailyTaskDone and not newDay)
    
    plotchar(newDay, "newDay", "▼", location.top, transp = 60)
    plotchar(doOncePerDay, "doOncePerDay", "•", location.top, transp = 0)
    bgcolor(dailyTaskDone ? color.orange : na)
    

    enter image description here

    Version 2

    Following Michel's comment, this uses a more robust detection of the day change:

    //@version=4
    study("Once per Day")
    var dailyTaskDone = false
    newDay = change(time("D"))
    doOncePerDay = rising(close, 2)     // Your condition here.
    dailyTaskDone := doOncePerDay or (dailyTaskDone and not newDay)
    
    plotchar(newDay, "newDay", "▼", location.top, transp = 60)
    plotchar(doOncePerDay, "doOncePerDay", "•", location.top, transp = 0)
    bgcolor(dailyTaskDone ? color.orange : na)
    

    And for the OP, a v3 version:

    //@version=3
    study("Once per Day v3")
    dailyTaskDone = false
    newDay = change(time("D"))
    doOncePerDay = rising(close, 2)     // Your condition here.
    dailyTaskDone := doOncePerDay or (dailyTaskDone[1] and not newDay)
    
    plotchar(newDay, "newDay", "▼", location.top, transp = 60)
    plotchar(doOncePerDay, "doOncePerDay", "•", location.top, transp = 0)
    bgcolor(dailyTaskDone ? orange : na)