Skip to main content
Advanced15 min read
kScript’s type system is specifically designed for financial data analysis, featuring a hybrid approach that combines static analysis at compile time with dynamic execution at runtime.

Introduction

The compiler performs type checking with limited implicit conversions, helping catch type mismatches early during compilation rather than encountering them at runtime. At its core, kScript distinguishes between two fundamental categories of values: primitive types (numbers, strings, booleans) and time-series types. The timeseries type is the central data structure for handling historical market data, indicators, and any values that change across chart bars.
Type Inference: In kScript, you don’t explicitly declare types like int or float. Instead, types are inferred from the values and expressions you write. The distinction you make is between regular variables (var) and time-series data (timeseries).

Variable Declarations and Type Inference

In kScript, variable declarations use two keywords: var and timeseries. The choice between them fundamentally determines how the variable behaves throughout your script’s execution.

The var Keyword

Variables declared with var hold scalar values: numbers, strings, booleans, or arrays of these types. These values can change from bar to bar, but they represent single values at any given point in time. The type of a var variable is inferred from its initialization expression. Once inferred, the type remains consistent.
var price = 100.50        // Inferred as number
var symbol = "BTCUSDT"    // Inferred as string
var isActive = true       // Inferred as boolean
var periods = [7, 14, 21] // Inferred as number[]

The timeseries Keyword

The timeseries keyword declares variables that hold historical data—values that exist across multiple bars with temporal alignment. A timeseries variable maintains a complete history that can be indexed to access past values. Timeseries variables are immutable in the sense that you cannot reassign them once declared. However, you can create new timeseries through operations on existing ones.
timeseries ohlcvData = ohlcv(symbol="BTCUSDT", exchange="BINANCE")
timeseries closes = ohlcvData.close
timeseries adjusted = closes + 100  // New timeseries through arithmetic
Common Error: Using var instead of timeseries for data source functions will cause a compilation error: "cannot assign timeseries into 'var' variable". Always use timeseries for functions like ohlcv(), source(), and technical indicators that return historical data.

Primitive Data Types

number

Represents all numeric values, including both integers and floating-point numbers. Used for prices, volumes, periods for technical indicators, thresholds, and mathematical calculations. All standard arithmetic operators (+, -, *, /, %) work with numbers.

string

Represents textual data using double quotes. Essential for identifying trading pairs, exchanges, and providing labels. Strings are immutable.
ohlcv(symbol=currentSymbol, exchange="BINANCE")

boolean

Either true or false. Fundamental to conditional logic. Comparison operators (<, >, ==, !=) and logical operators (&&, ||, !) return boolean values.
var crossedAbove = (fastMA > slowMA) && (fastMA[1] <= slowMA[1])

na - Not Available

A special constant representing “not available” or missing data. When you pass na to a plot function, that data point is skipped, creating gaps in the visualization.
//@version=2
define(title="Conditional MA", position="onchart", axis=true);

timeseries data = ohlcv(symbol=currentSymbol, exchange=currentExchange);
var ma = sma(source=data.close, period=20);
var threshold = 100000;

// Only plot MA when volume exceeds threshold
plotLine(value=(data.volume > threshold ? ma : na), width=2, colors=["blue"], label=["Conditional MA"], desc=["MA when volume is high"]);

TimeSeries: kScript’s Core Type

What is a TimeSeries?

A timeseries is not just a single value—it’s a complete history of values aligned to chart bars. You can look backward in time using the history reference operator []. Conceptually, a timeseries is like a two-dimensional array where each row represents a bar (timestamped) and each column represents a data field. Timeseries variables automatically track history.

Historical Indexing

To access previous values, use square bracket notation with an integer offset:
  • [0] (or no index) - current bar
  • [1] - previous bar
  • [2] - two bars ago
timeseries data = ohlcv(symbol=currentSymbol, exchange=currentExchange);
timeseries close = data.close;

// Calculate change over 5 bars
var change5 = close[0] - close[5];

// Detect three consecutive rising bars
var risingThree = (close > close[1]) && (close[1] > close[2]) && (close[2] > close[3]);

Immutability and Global Scope

Timeseries have two important constraints:
  1. Immutable: Cannot be reassigned after declaration. Create new timeseries through operations instead.
  2. Global scope: Must be declared at the top level of your script, not inside functions or conditional blocks.

OHLCV Data Structure

IndexFieldDescription
0timestampUnix timestamp (milliseconds)
1openOpening price for the bar
2highHighest price during the bar
3lowLowest price during the bar
4closeClosing price for the bar
5volumeTrading volume during the bar
Each field of OHLCV data is itself a complete timeseries:
timeseries ohlcvData = ohlcv(symbol=currentSymbol, exchange=currentExchange);
timeseries closes = ohlcvData.close;  // Extracts entire close price timeseries

Arrays and Collections

Array Type System

kScript supports typed arrays: number[], string[], and boolean[]. Arrays are homogeneous—all elements must be of the same type.
var maPeriods = [7, 14, 21, 50, 100];  // number[]
var colors = ["#FF6B35", "#3B82F6", "#10B981"];  // string[]
Common Use Cases:
  • Multiple indicator parameters (periods, thresholds)
  • Color schemes for multi-line plots
  • Label sets for display options
  • Configuration options for input() with type "select"

Array Constraints

  • Array size is typically fixed at declaration
  • All elements must be of the same type (enforced at compile time)
  • Arrays are passed by reference

Data Sources and Access Methods

kScript v2 provides extensive access to market data through data source functions.

Two Access Methods

  1. Generic source() function: Accepts a type parameter for any data type
  2. Specialized functions: Type-specific functions like ohlcv(), open_interest(), funding_rate()
// Using source() with type parameter
timeseries data = source(type="ohlcv", symbol="BTCUSDT", exchange="BINANCE");

// Using specialized function (preferred)
timeseries data = ohlcv(symbol="BTCUSDT", exchange="BINANCE");
Both methods return timeseries data that can be accessed historically.