Skip to main content
Core Concept8 min read
Essential variables available globally in kScript for accessing current market context, symbols, and exchanges.

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

Variables declared with var hold values that reset each bar. Characteristics:
  • Type inference: Types are inferred from the assigned value
  • Scope: Can be declared in any scope (global, inside if/for/while, or inside func)
  • Mutability: Values are mutable within the current bar
  • No history: Cannot persist across bars - you cannot access var[1]
Declaration Example:
var threshold = 70
var labelText = "Buy Signal"
Behavior Example:
// var variables update automatically each bar
var currentBar = barIndex
var price = close[0]  // Current bar close
var volume = vol[0]   // Current bar volume

// These values are recalculated on every bar
var isHighVolume = volume > volume[1] * 1.5
var priceChange = price - price[1]

timeseries - Immutable, historical

Variables declared with timeseries hold historical data that can be indexed. Characteristics:
  • Immutable: 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: Must 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()) return a timeseries
Performance warning: Creating timeseries is an expensive operation. Only declare a variable as timeseries when absolutely necessary.
Declaration & Usage Example:
// timeseries maintain historical context
timeseries prices = ohlcv(symbol="BTCUSDT", exchange="BINANCE")

// Access historical values
var currentClose = prices.close[0]   // Current bar
var previousClose = prices.close[1]  // Previous bar
var weekAgoClose = prices.close[7]   // 7 bars ago

// Historical data is immutable
var priceMovement = currentClose > previousClose

static - Persistent, manual control

Variables declared with static maintain their values between bar executions. Characteristics:
  • Persistent state: Values maintain between bar executions
  • Manual updates: Values don’t auto-update; must be explicitly modified
  • Global scope: 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
  • Cumulative calculations: Useful for CVD (Cumulative Volume Delta) and similar indicators
Declaration & Usage Example:
// static variables maintain state with manual control
static signalCount = 0
static lastTradePrice = 0.0
static cumulativeVolume = 0.0

// Manual update operations
if (buySignal) {
  signalCount++                    // Increment counter
  lastTradePrice = currentPrice    // Manual assignment
}

// Cumulative calculations (e.g., CVD)
cumulativeVolume += currentVolume * (close > open ? 1 : -1)

// Reset operation
if (resetCondition) {
  signalCount = 0                  // Manual reset
  cumulativeVolume = 0.0           // Reset cumulative value
}

Global Context Variables

These variables are automatically available in every kScript and provide access to the current trading context.
VariableTypeDescription
currentSymbolstringThe currently active trading pair symbol
currentExchangestringThe currently active exchange
barIndexnumberCurrent bar index in the dataset

Common Usage Patterns

Dynamic Data Source

Create flexible indicators that automatically use the current market context:
//@version=2
define(title="Smart Indicator", position="offchart", axis=true);

// Automatically adapts to current context
timeseries data = ohlcv(symbol=currentSymbol, exchange=currentExchange);
var emaData = ema(source=data.close, period=21);

plotLine(value=emaData, width=2, colors=["#FF6B35"], label=["EMA"], desc=["Exponential Moving Average"]);

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);