Time Travel

Let's create a strategy which opens a long position whenever the latest closed bar is green and closes that position when the bar is red.

In trading, a bar is considered green when its closing price is higher than its opening price. It is considered red when its closing price is lower than its opening price.

We could do it like this:

1 isGreen = close > open
2 isRed = close < open
3
4 enter long when isGreen
5 exit long when isRed

However... that would be wrong.

In Working With Data, we said this:

open
gives you the opening price of the newly opened bar, while
high
,
low
,
close
and
volume
are part of the closed bar.

We are comparing the opening and closing prices of two different bars.

We need to instruct the

open
variable to "go back in time" one bar and return to us whatever its value was back then.

Fortunately, this is going to be super easy, barely an inconvenience.

All we need to do is use the

[]
time travel operator on the
open
variable, and tell it to go back 1 bar:

1 isGreen = close > open[1]
2 isRed = close < open[1]
3
4 enter long when isGreen
5 exit long when isRed

Now our strategy works as desired.

You can instruct any variable/expression to return its value from x bars ago, using the

[]
time travel operator.

This means that, for example, we can easily create a strategy which enters a long position whenever the last two closed bars are green, and close that position when they are red:

1 isGreen = close > open[1]
2 isRed = close < open[1]
3
4 # isGreen[1] is equivalent to close[1] > open[2]
5 enter long when isGreen and isGreen[1]
6 # isRed[1] is equivalent to close[1] < open[2]
7 exit long when isRed and isRed[1]

The ability to fetch the previous value of any variable/expression is one of the most powerful features of QuantScript.

Next, we will create a strategy which opens a long position if the sum of the last 20 close prices is smaller than the latest close price, multiplied by 20