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:
However... that would be wrong.
In Working With Data, we said this:
gives you the opening price of the newly opened bar, while , , and are part of the closed bar.
We are comparing the opening and closing prices of two different bars.
We need to instruct thevariable 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 thetime travel operator on the variable, and tell it to go back 1 bar:
Now our strategy works as desired.
You can instruct any variable/expression to return its value from x bars ago, using thetime 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:
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