Core Concept5 min read
Understanding how kScript v2 processes your code through its three-phase lifecycle for optimal performance and predictable behavior.
Every indicator follows a simple recipe: Setup once → Calculate per candle → Display per candle
Setup Phase
Runs once when your indicator first loadsPrepare everything your indicator needs before processing any candles.
| Task | Description |
|---|---|
Call define(...) | Required - Tells kScript about your indicator |
Create settings with input(...) | Optional - Let users adjust period, colors, etc. |
Get data with ohlcv(...) | Create all timeseries here |
Calculate Phase
Runs for each candle on the chartProcess indicator calculations. This repeats for every candle, computing values based on your defined logic.
| Task | Description |
|---|---|
| Calculate indicators | rsi(...), ema(...), sma(...) |
Store temporary values in var | For comparisons, colors, or per-candle logic |
| Make decisions | Use if/else to compare values |
Display Phase
Runs for each candle, after calculationsDraw your indicator on the chart using the calculated values.
| Function | Use Case |
|---|---|
plotLine(...) | Lines for RSI, moving averages, etc. |
plotBar(...) | Vertical bars for volume, histograms |
plotShape(...) | Markers, arrows, labels for signals |
Understanding the Flow
Key Characteristics
Deterministic Results
Given the same input data, a script will always produce identical output. 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.Efficient Memory Usage
Only current bar calculations are held in memory. Historical data is managed by the runtime with optimized caching.
Real-time Compatibility
The same script logic handles both historical analysis and live data processing without special handling.
Limitations and Constraints
No Future Data Access
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
Global Scope Timeseries Only
timeseries declarations must be in global scope. They cannot be declared inside functions, loops, or conditional blocks.Execution Time Limits
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
No Cross-Bar Variable Persistence
var variables cannot maintain state between bars. Use timeseries for values that need historical access, or static for persistent values.