Execution Model (v2 Per-Bar)
Understanding how kScript v2 processes your code through its three-phase lifecycle for optimal performance and predictable behavior.
Every script runs through three phases:
Initialization (runs once)
define(...)
— required (exactly one call)- User inputs via
input(...)
- Data subscriptions via
source(...)
/ or dedicated type functions likeohlcv(...)
- Declare timeseries in global scope only
Calculation (runs once per bar)
- Indicator math (
rsi(...)
,ema(...)
, etc.) - Expressions and control-flow using
var
variables - No
timeseries
declarations here
Plotting (runs once per bar, after calculation)
- Render via
plotLine(...)
,plotCandle(...)
,plotBar(...)
,plotShape(...)
, …
Key Characteristics
Deterministic Results
Given the same input data, a script will always produce identical output. This property is essential for reliable backtesting and strategy validation.
Immutable Historical Data
timeseries
objects provide read-only access to historical values. Past data cannot be modified, ensuring data integrity throughout execution.
Efficient Memory Usage
Only current bar calculations are held in memory. Historical data is managed by the runtime with optimized caching strategies.
Real-time Compatibility
The same script logic handles both historical analysis and live data processing without requiring different code paths or special handling.
Limitations and Constraints
No Future Data Access
Scripts cannot access data from future bars (e.g., ts[-1]
is invalid). This prevents look-ahead bias in analysis.
Global Scope Timeseries Only
timeseries
declarations must be in global scope. They cannot be declared inside functions, loops, or conditional blocks.
Execution Time Limits
Scripts must complete execution within 500ms (excluding data fetch). This ensures responsive chart rendering and prevents infinite loops.
No Cross-Bar Variable Persistence
var
variables cannot maintain state between bars. Use timeseries
for values that need historical access.