The Easiest Way to Add a Session to PineScript Strategies

It’s fairly simple to add a session to PineScript Strategies, you can do that just in few minutes adding just a few lines of code to your script.

Forst create an input variable that will store the definition of our session. Later you’ll be able to change session variable from parameters without changing your code.

session = input("0900-1700:1234567")

In a session first, you have to specify the time range for every day. Session from 9 am to 5 pm will look like that: 0900-1700. After the colon, you can specify days of the week for your session. 1234567 trading all days, 23456 – Monday to Friday (1 is Sunday here).

To calculate your session you can use the following command:

t = time(timeframe.period, session)

This function will output you time for every bar inside your session and NA for all bars outside the session. To check that out session is correct let’s plot it using background-color:

bgcolor(not na(t) ? : na)

It will look like that:

To add session logic to your strategies you have to do 2 things:

  1. Add “not na(t)” condition to all your entries. You can use “and” logical operator for that.
  2. Add the following code to close/cancel all positions/orders:
if (na(t))

As you can see it’s a pretty easy way to do that.

Entire code you can find here:

strategy("MA Strategy", overlay=true)

// MA Inputs 
ma_fast_length = input(5)
ma_slow_length = input(25)

session = input("0900-1700:1234567")

t = time(timeframe.period, session)

bgcolor(not na(t) ? : na)

ma_fast = sma(close, ma_fast_length)
ma_slow = sma(close, ma_slow_length)

plot(ma_fast, color =,  linewidth = 2)
plot(ma_slow, color =, linewidth = 2)

strategy.entry("long",  strategy.long,  when = crossover(ma_fast, ma_slow)  and not na(t))
strategy.entry("short", strategy.short, when = crossunder(ma_fast, ma_slow) and not na(t))

if (na(t))

1 thought on “The Easiest Way to Add a Session to PineScript Strategies”

  1. Is there a code to open a trade in the strategy as soon as the session starts. I would like it for backtesting.

    My strategy is somtimes halfway through when the session starts. I would like the trade to open based on my strategy when the session starts even if it’s haflway through.

Leave a Comment

Your email address will not be published. Required fields are marked *