Working With Time

Important: The time data provided by QuantScript is in the UTC+0 timezone

Let's modify our Hello, World! strategy and add some time constraints to it. We need to replace our

true
condition with some code which uses the
day
and/or
time
values of the current bar.

The original strategy looks like this:

1 enter long when true
2 exit long when true

We're going to adjust it so it only opens long positions on Mondays, by using the

Monday
constant and the
==
equals operator:

1 enter long when day == Monday
2 exit long when true

Every bar our code executes against has its own

day
value. Only when the current bar falls on a Monday does the strategy open a long position.

Let's add a time constraint between 10:15 and 13:37:

1 enter long when day == Monday and time >= 10:15 and time <= 13:37
2 exit long when true

Say we want to trade on Tuesday too, between 12:00 and 12:30. The code would get a bit long for a single line, so we will use

()
parentheses to break it up into multiple lines for readability. The parentheses are also needed to group the
and
statements together so they can be combined with an
or
operator.

Here's what it looks like:

1 enter long when (
2 day == Monday and time >= 10:15 and time <= 13:37
3 ) or (
4 day == Tuesday and time >= 12:00 and time <= 12:30
5 )
6 exit long when true

The strategy is still closing positions every chance it gets. Let's apply these time constraints to exiting as well:

1 enter long when (
2 day == Monday and time >= 10:15 and time <= 13:37
3 ) or (
4 day == Tuesday and time >= 12:00 and time <= 12:30
5 )
6
7 exit long when (
8 day == Monday and time >= 10:15 and time <= 13:37
9 ) or (
10 day == Tuesday and time >= 12:00 and time <= 12:30
11 )

A bit redundant, right? Next, we will see how variables can help reduce code repetitiveness.