Series if..update Statement

Sometimes we need to be able to update the current value of a series after we have already defined that series, if some condition is met.

Let's say we have a "counter" series which starts from 0 and increments its value on each bar:

123
series counter: once: 0 rest: counter + 1

Imagine we have a function called

ShouldReset()
, which accepts the current value of our
counter
series, does some complex stuff under the hood, and returns a Boolean. If that Boolean is
true
, we should to reset our counter back to 0.

We can implement this behaviour using an if..update statement:

12345
series counter: once: 0 rest: counter + 1

if ShouldReset(counter) update counter: 0

Let's explain the syntax. We start with the

if
keyword, followed by a condition expression, which should resolve to a Boolean. Following that is the
update
keyword, the
name
of the series and a
:
colon. Finally, we have the body of the if..update statement - either a single expression on the same line, or multiple statements, indented by 2 additional spaces, on subsequent lines.

Whenever QuantScript sees an if..update statement, the following happens:

  1. QuantScript asserts that the
    name
    following the
    update
    keyword, refers to a series that's defined using the
    series
    keyword.
  2. If it is, the condition expression is evaluated
  3. If the condition expression evalutes to
    true
    , the body is evaluated
  4. The series' value for the current bar is updated to whatever the result of evaluating the body was

Another thing to note is that the body if the if..update statement is scoped and you cannot mutate any variables defined outside of it. The only thing that may change as a result of the execution of an if..update statement is the updated series' value itself:

12345678910111213
series counter: once: 0 rest: counter + 1

myVar = 5

if ShouldReset(counter) update counter:
myVar = 6
# myVar is 6 while the if..update statement executes
0

# the if..update statement has finished executing
# counter is 0, but myVar remains unchanged with a value of 5