You may sometimes need to add some session logic to your TradingView strategies and indicators. This can be useful especially when you want to execute your entries only within a certain time window and close all positions when this window is over.
Check Session Status
The first step is to check that the current bar is inside a specific session.
You could get this done by using the hour(), minute(), and dayofweek() functions to check what the time for your session is (and if it belongs to the session you are interested in). However, there is a much better way to accomplish this using the time() function. This is because Pine Script’s time function returns the UNIX time of the current bar for the specified timeframe and session or NaN if the time point is out of session.
Here is some code I wrote to do just that.
time(timeframe.period, "9000-1500")
This line outputs your bar time if your bar is inside the 9 am to 3 pm session, and NA if otherwise. You only need to check whether the function is NA to determine if this bar is inside the session.
In this code example, I simply plot a green background if this function is not NA:
bgcolor((not na(time(timeframe.period, "0900-1500"))) ? color.new(color.green, 80) : na)
It’s that easy. It works pretty well and indicates my session as required:
Specify Days of Week
Once you check your session, you may also want to specify days of the week you want to be included in the session:
bgcolor((not na(time(timeframe.period, "0900-1500:23456"))) ? color.new(color.green, 80) : na)
In this code example, we only highlight sessions from Monday to Friday (week start with 1 here):
Follow me on TradingView and YouTube.