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) ? color.green : na)
It will look like that:
To add session logic to your strategies you have to do 2 things:
- Add “not na(t)” condition to all your entries. You can use “and” logical operator for that.
- Add the following code to close/cancel all positions/orders:
if (na(t)) strategy.cancel_all() strategy.close_all()
As you can see it’s a pretty easy way to do that.
Entire code you can find here:
//@version=4 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) ? color.green : na) ma_fast = sma(close, ma_fast_length) ma_slow = sma(close, ma_slow_length) plot(ma_fast, color = color.red, linewidth = 2) plot(ma_slow, color = color.blue, 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)) strategy.cancel_all() strategy.close_all()