Variables

Take a look at this strategy:

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 )

The time constraints for entering and exiting are the same and written twice - this is bad for readability and prone to errors - if you wanted to switch out Tuesday for Wednesday, you would have to do it in two places.

We can use a variable to solve this problem.

Variables are named values. We initialize them using the

=
definition operator. We put the name of the variable on the left-hand side of the
=
definition operator and a value on the right-hand side. Once we've done this, we can refer to this value by a name, instead of copy-pasting it each time we need it.

Here's an example:

1 # A variable can be a number
2 myFirstVariable = 42
3
4 # Or the result of an expression
5 mySecondVariable = 21 + 21
6
7 # You can use a variable's value in any expression simply by typing its name
8 areTheyTheSame = (myFirstVariable == mySecondVariable) # -> true
9
10 # Variables can change - they vary!
11 myFirstVariable = 100
12 # P.S. The value of areTheyTheSame is still true.
13 # Variables only change when the = operator is used.

Let's rewrite our strategy using a variable for the time constraints:

1 timeIsRight = (
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 enter long when timeIsRight
8 exit long when timeIsRight

Looks much cleaner, right?

Variables are essential for writing QuantScript. In fact, we've been using variables all along the way -

open
,
high
,
low
,
close
,
volume
,
day
and
time
are all variables. The only difference is they're built-in - you don't give them a value yourself, you just use them.

Well, there is something else that's different about them - they can travel through time.