Variable Types & Behavior

Understanding kScript's three variable types: how to declare them, their characteristics, and how they behave during script execution.

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.

Declaration Example

Behavior 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.
  • Source functions return timeseries: All source functions (e.g: ohlcv(), open_interest() etc.) returns a timeseries.
  • ⚠️ Performance warning: Creating timeseries is a very expensive operation, so we should declare a variable as timeseries only when it's absolutely necessary.

Declaration & Usage Example

static — Persistent, manual control

  • Persistent state: static variables maintain their values between bar executions.
  • Manual updates: Values don't auto-update; must be explicitly modified by your code.
  • Global scope: static variables are declared in global scope and accessible throughout the script.
  • Manual operations: Support increment (++), decrement (--), and assignment operations.
  • State management: Ideal for counters, flags, and maintaining algorithm state across bars.
  • Cumulative calculations: Useful for calculating cumulative values for indicators like CVD (Cumulative Volume Delta).

Declaration & Usage Example

Global Context Variables

These variables are automatically available in every kScript and provide access to the current trading context.

currentSymbolstring

The current trading symbol (e.g., 'BTCUSDT')

Example:
currentExchangestring

The current exchange being used for trading (e.g., 'BINANCE', 'COINBASE')

Example:
currentCoinstring

The current trading coin (e.g., "BTC")

Example:
barIndexnumber

Current bar index in the timeseries during the per-bar loop. Represents the position in the data array, starting from 0. Useful for indicator warm-up periods and conditional logic based on bar position.

Example:
isLastBarboolean

True when processing the last bar in the dataset (most recent bar). Useful for one-time calculations, alerts, or actions that should only occur on the most recent data point.

Example:
isLiveUpdateboolean

True during live data updates with new market data. Distinguishes between initial script run and live trading updates. Note that the script can run multiple times on the same last bar during live updates.

Example:

Array Variables

Core variables that handle collections of data for multi-dimensional analysis.

colorcolor

The color to use for plotting (e.g., 'red', 'blue')

Example:plotLine(ema20, ["blue"], 2);

Common Usage Patterns

Real-world examples of how to use core variables in your trading strategies.

Dynamic Data Source

Create flexible indicators that automatically use the current market context.

Best Practices

💡

Always Use Current Context

Use currentSymbol and currentExchange instead of hardcoding values for maximum flexibility.

ohlcv(currentSymbol, currentExchange)

Cache Expensive Operations

Store references to commonly used data sources to improve performance.

timeseries ohlcvData = ohlcv(currentSymbol, currentExchange);
📖
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