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:
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:
Let's explain the syntax. We start with thekeyword, 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:
- QuantScript asserts that the following the keyword, refers to a series that's defined using the keyword.
- If it is, the condition expression is evaluated
- If the condition expression evalutes to , the body is evaluated
- 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: