Core Concepts

Core Variables

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

  • 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

var declaration
var threshold = 70;
var labelText = 'Buy Signal';

Behavior Example

var behavior
// 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

  • Immutable: timeseries values are immutable snapshots of historical data.
  • Historical access: ts[0] is the current bar; ts[1] is the 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.) return a timeseries.

Declaration & Usage Example

timeseries behavior
// 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

  • Persistent state: static variables maintain their values between bar executions.
  • Manual updates: Values don't auto-update; they 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

static behavior
// 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 current trading symbol (e.g. "BTCUSDT")
currentExchangestringThe current exchange being used for trading (e.g. "BINANCE", "COINBASE")
currentCoinstringThe current trading coin (e.g. "BTC")
barIndexnumberCurrent bar index in the timeseries during the per-bar loop. Starts at 0. Useful for indicator warm-up periods and conditional logic based on bar position.
isLastBarbooleantrue when processing the last bar (the most recent). Useful for one-time calculations, alerts, or actions that should only fire on the latest data point.
isLiveUpdatebooleantrue during live data updates with new market data. Distinguishes between initial script run and live trading updates. The script can run multiple times on the same last bar during live updates.
colorcolorThe color to use for plotting (e.g. "red", "blue").
Context variable examples
// currentSymbol / currentExchange / currentCoin
currentSymbol    // Returns "BTCUSDT"
currentExchange  // Returns "BINANCE"
currentCoin      // Returns "BTC"

// Warm-up guard: only plot the SMA after 20 bars have arrived
if (barIndex > 20) {
  timeseries sma_val = sma(close, 20);
  plotLine(value=sma_val, label=["SMA 20"], desc=["20-period Simple Moving Average"]);
}

// Fire a one-time alert on the most recent bar
if (isLastBar && crossover(fast_ma, slow_ma)) {
  print("Buy signal on latest bar!");
}

// React to live updates
if (isLiveUpdate && price > threshold) {
  print("LIVE ALERT", "#ff0000", price);
}

// color slot for plotting
plotLine(ema20, ["blue"], 2);

Array Variables

kScript exposes a named color palette as global variables (red, blue, green, etc.) that can be used directly in plotting functions. See Color Constants for the complete palette.

Indexing a timeseries

A timeseries is a sequence of bars, with index 0 being the most recent. Field access then index gives you a value at a specific lag:

timeseries indexing
var current = ohlcvData.close[0]; // current close
var prev = ohlcvData.close[1]; // previous close
var twoAgo = ohlcvData.close[2]; // close two bars ago

// Detect direction
if (ohlcvData.close[0] > ohlcvData.close[1]) {
  print('Up bar');
}

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.

Dynamic Data Source
//@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);

See Type System for the full discussion of how var / static / timeseries interact with kScript's hybrid type model.