Custom Loop Step

By default, when using a for loop, the loop's variable is incremented by 1 after each iteration.

Let's look at how we can specify a custom step.

All we need to do is add the keyword

step
followed by a Number, like this:

1234
sumEveryOtherOpen = 0

for distance from 0 to 100 step 2
sumEveryOtherOpen = sumEveryOtherOpen + open[distance]

In the example above, we're using a

step
of
2
, adding up every other value of
open
.

QuantScript also supports negative steps:

1234
backwardsSum = 0

for distance from 10 to 0 step -1
backwardsSum = backwardsSum + open[distance]

In the example above, we're going backwards from

10
to
0
. The code is equivalent to the following sum:
open[10] + open[9] + open[8] + open[7] + ... + open[1] + open
.

If we use a step larger than

1
, the loop's variable may "jump over" the
to
value. In this case, the loop stops and no futher iterations are performed.

123456789
sum = 0

for n from 1 to 10 step 5
sum = sum + n

# On the first iteration, n is 1 -> sum becomes 0 + 1 = 1
# On the second iteration, n is 6 -> sum becomes 1 + 6 = 7
# After the second iteration, n becomes 11, which is larger than 10
# No more iterations are performed and the final value of sum is 7