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:

series counter: once: 0 rest: counter + 1

Imagine we have a function called

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

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

series counter: once: 0 rest: counter + 1

if ShouldReset(counter) update counter: 0

Let's explain the syntax. We start with the

keyword, followed by a condition expression, which should resolve to a Boolean. Following that is the
keyword, the
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
    following the
    keyword, refers to a series that's defined using the
  2. If it is, the condition expression is evaluated
  3. If the condition expression evalutes to
    , 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:

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

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