Conditionals and loops control which code runs during each bar's calculation phase. Use them for decision-making logic, counted iteration, and conditional searches while keeping the per-bar execution model in mind.
Overview
| Control Type | Description | Features |
|---|---|---|
| Conditional Statements | Use if/else statements to execute different code paths based on conditions. Essential for decision-making logic in your indicators. | Condition-based execution, multiple branches, boolean logic |
| For Loops | Use for loops when you know the number of iterations in advance. Perfect for counted iterations and array-like processing. | Known iteration count, counter-based control, array-like processing |
| While Loops | Use while loops when the number of iterations depends on a condition. Ideal for search patterns and conditional iteration. | Condition-based control, dynamic iteration count, search patterns |
| Construct | Description |
|---|---|
if/else | Conditional execution statements |
for | Counted iteration loop |
while | Conditional iteration loop |
if/else - conditional execution statements
if (condition) { /* body */ } else { /* alternative */ }
| Parameter | Type | Description |
|---|---|---|
condition | boolean expression | Expression that evaluates to true or false |
if body | code block | Code executed when condition is true |
else body | code block | Code executed when condition is false (optional) |
Returns: void (executes conditional code).
// Basic if/else with price direction
var direction = "neutral"
if (closeTs[0] > closeTs[1]) {
direction = "up"
} else {
direction = "down"
}for - counted iteration loop
for (var i = start; i < end; i = i + increment) { /* body */ }
| Parameter | Type | Description |
|---|---|---|
initialization | var declaration | Initialize the loop counter variable |
condition | boolean expression | Loop continues while this condition is true |
increment | assignment | Update the counter variable each iteration |
Returns: void (executes loop body).
// Basic iteration
for (var i = 1; i <= 10; i = i + 1) {
print("i = ", i)
}while - conditional iteration loop
while (condition) { /* body */ }
| Parameter | Type | Description |
|---|---|---|
condition | boolean expression | Loop continues while this condition is true |
Returns: void (executes loop body).
// While (use sparingly due to execution limits)
var j = 0
while (j < 3) {
print("j = ", j)
j = j + 1
}Tips
Infinite Loop Protection
Always ensure loop conditions will eventually become false. Infinite loops will cause your script to hang and may be terminated by the runtime.
Variable Scope
Loop variables like
i are scoped to the loop. Use var declarations inside loops for temporary calculations.Performance
Loops run during the calculation phase of each bar. Keep iterations reasonable to maintain good performance across large datasets.
Timeseries Restriction
You cannot declare
timeseries inside loops. Timeseries must be declared in global scope only.