Conditionals & Loops
Learn how to use for loops, while loops, and conditional statements in kScript v2 for iterative calculations and control flow logic within the per-bar execution model.
Overview
Conditional Statements
Use if/else statements to execute different code paths based on conditions. Essential for decision-making logic in your indicators.
For Loops
Use for loops when you know the number of iterations in advance. Perfect for counted iterations and array-like processing.
While Loops
Use while loops when the number of iterations depends on a condition. Ideal for search patterns and conditional iteration.
Functions Reference
if/else - conditional execution statements
if (condition) { /* body */ } else { /* alternative */ }
Parameters:
- 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)
Code Example:
for - counted iteration loop
for (var i = start; i < end; i = i + increment) { /* body */ }
Parameters:
- 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)
Code Example:
while - conditional iteration loop
while (condition) { /* body */ }
Parameters:
- condition (boolean expression) - Loop continues while this condition is true
Returns:
void (executes loop body)
Code Example:
Best Practices
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.