Introduction

kScript is inspired by Pine Script but tailored for performant, deterministic, and secure execution inside the charting runtime. The language emphasizes:

🔄

Per-bar execution

with a clear three-phase lifecycle (Init → Calculate → Plot)

📊

Immutable, historical timeseries

objects with indexing (e.g., ts[1])

Ephemeral var values

that are recalculated each bar

🎯

Plot-first APIs

that accept kwargs for clarity and flexibility

💡

All built-in functions support kwargs, and this documentation uses kwargs in every example.

(Some functions may also offer positional shorthand, but kwargs are the recommended style and are used throughout.)

Execution Model (v2 Per-Bar)

Every script runs through three phases:

1

Initialization (runs once)

  • define(...) — required (exactly one call)
  • User inputs via input(...)
  • Data subscriptions via source(...) / or dedicated type functions like ohlcv(...)
  • Declare timeseries in global scope only
2

Calculation (runs once per bar)

  • Indicator math (rsi(...), ema(...), etc.)
  • Expressions and control-flow using var variables
  • No timeseries declarations here
3

Plotting (runs once per bar, after calculation)

  • Render via plotLine(...), plotCandle(...), plotBar(...), plotShape(...), …
kScript Execution Model Diagram

Types & Variables

var — Ephemeral, per-bar

  • Type inference: var types are inferred from the assigned value.
  • Scope: var can be declared in any scope (global, inside if/for/while, or inside func).
  • Mutability: var values are mutable within the current bar.
  • No history: var cannot persist across bars. You cannot access var[1] or previous-bar values.
  • Plotting: var strings can be used to plot labels/text; numeric var can be used as per-bar scalars (rebuilt each bar).
var Example

timeseries — Immutable, historical

  • Immutable: timeseries values are immutable snapshots of historical data.
  • Historical access: ts[0] is current bar; ts[1] is previous bar; ts[n] is n bars ago.
  • Global only: timeseries may be declared only in global scope (not inside if/for/while or within func bodies).
  • Multi-field sources: Some timeseries expose multiple fields per bar, e.g., OHLCV: .open, .high, .low, .close, .volume.
  • Indicators require timeseries: Functions like rsi, ema, ma require a timeseries source.
timeseries Example

Functions & Declarations

Script definition

Exactly one define(...) is required per script.

Script Definition Example
  • title: string shown in the UI
  • position: "onchart" | "offchart"
  • axis: whether to show price axis for the indicator
  • customTitle: custom title override

Inputs (unified input(...))

Use the unified input(...) API to collect user inputs. Bind the result to a var.

Input Examples

Implementations may support additional constraints (e.g., min, max, step, options) but are optional and UI-dependent.

User-defined functions (keyword: func)

Declare custom functions using the func keyword.

Custom Function Example

Constraints:

  • You may accept var and/or timeseries arguments.
  • You must not declare a timeseries inside a func body (timeseries are global-only).

DSL vs General-Purpose Languages

  • Ephemeral locals: var does not retain history across bars (no var[1]).
  • Immutable history: Use timeseries for historical indexing and indicator inputs.
  • Global timeseries only: Cannot declare timeseries in control blocks or inside func.
  • Sandboxed: No arbitrary I/O, filesystem, or network from scripts.
  • Deterministic & bounded: Runtime enforces a 500 ms evaluation budget (excluding data fetch).
  • Plot-centric: APIs focus on timeseries analysis + plotting, not general-purpose computation.

Data Sources

Subscribe to datasets with source(...) or convenience aliases like ohlcv(...). All source functions return a timeseries.

Data Sources Example

Plotting APIs (kwargs in all examples)

The rendering context is injected by the runtime; do not pass ctx. Multiple plot calls are allowed in a single script.

plotLine(...)

Draw a line from a numeric timeseries or scalar.

plotLine Example

plotBar(...)

Plot vertical bars (e.g., volumes, histograms).

plotBar Example

plotCandle(...)

Render candlesticks from OHLC timeseries.

plotCandle Example

plotShape(...)

Plot shapes/markers using booleans and optional text. var strings can be plotted as labels (per-bar).

plotShape Example

Standard Library (selected)

All functions accept kwargs. Indicators require a timeseries source.

Definition & Inputs

Definition & Inputs

Data Sources

Data Sources

Indicators

Indicators

Helpers

Helpers

Debugging

Debugging

Use the Data Table to inspect values of outputs and data series.

Quick Start

Quick Start Example

Example: RSI Off-Chart Grid

Demonstrates kwargs, per-bar flow, and a line plot with threshold cues.

RSI Off-Chart Grid Example

Rules & Gotchas (Read Carefully)

define(...)

Exactly one define(...) is required; otherwise the script will not run.

var

  • Types are inferred; var is mutable and can be declared anywhere.
  • var does not persist across bars (no historical access like var[1]).
  • var strings can be plotted (labels/text).

timeseries

  • Immutable, with historical indexing via [n].
  • Global-scope only — not allowed in loops, conditionals, or inside func.
  • Indicator functions require a timeseries as source.
  • Multi-field sources (e.g. OHLCV) expose .open/.high/.low/.close/.volume.

Data sources

via source(dataType=..., symbol=..., exchange=...) or aliases like ohlcv(symbol=..., exchange=...)
→ All source functions return a timeseries.

Plotting & kwargs

  • Use kwargs; do not pass ctx (injected at runtime).
  • You may call multiple plot functions in one script.

Performance

Execution must complete within ≤ 500 ms (excluding data fetch) or the script is suspended with an error.

Debugging

Use print(...), printTimeSeries(...), and the Data Table to inspect values at runtime.

Appendix: Common Patterns

Timeseries indexing

Timeseries Indexing

User function with guard

Safe Division Function
📖
Introduction
Overview of kScript language
🔍
Overview
Complete technical documentation
🚀
Quick Start
Get started with kScript basics
📋
Function Reference
Complete API reference guide
📚
Type System
Understanding kScript data types
General FAQ
Frequently asked questions about kScript
Best Practices
Guidelines for writing efficient kScript code
⚠️
Limitations
Known constraints and workarounds
🆕
Updates
v1 vs v2 differences and improvements
🔧
Core Concepts
Variables, data types & data sources
⚙️
Execution Model
Per-bar execution lifecycle and phases
🏷️
Keyword Arguments
Named parameters for clear function calls
🔗
Field Accessors
Dot notation for timeseries field access
🛠️
User-Defined Functions
Create custom reusable functions
🔗
Script Definition
Defining inputs and metadata
TimeSeries Management
Working with time-aligned data
🎯
Utility Functions
Helper functions and calculations
📈
Moving Averages
SMA, EMA and trend-following indicators
📊
Oscillators
RSI, Stochastic and momentum indicators
📈
Trend Indicators
Trend direction and strength analysis
📉
Volume Indicators
Volume-based analysis tools
📦
Orderbook Functions
Market depth analysis tools
🎨
Plotting & Visualization
Chart rendering and styling
🌈
Color Functions
Color manipulation and styling
📊
Data Subscriptions
Subscribe to OHLCV, trades, and orderbook data
🔄
Loops
For loops and while loops for iteration
🧮
Math Functions
Mathematical functions and constants
🏠
Go Home
Return to main landing page