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:
vartypes are inferred from the assigned value. - Scope:
varcan be declared in any scope (global, insideif/for/while, or insidefunc). - Mutability:
varvalues are mutable within the current bar. - No history:
varcannot persist across bars. You cannot accessvar[1]or previous-bar values.
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
- Immutable:
timeseriesvalues are immutable snapshots of historical data. - Historical access:
ts[0]is the current bar;ts[1]is the previous bar;ts[n]isnbars ago. - Global only:
timeseriesmay be declared only in global scope (not insideif/for/whileor withinfuncbodies). - 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 atimeseries.
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 > previousClosestatic — Persistent, manual control
- Persistent state:
staticvariables maintain their values between bar executions. - Manual updates: Values don't auto-update; they must be explicitly modified by your code.
- Global scope:
staticvariables 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 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.
| Variable | Type | Description |
|---|---|---|
currentSymbol | string | The current trading symbol (e.g. "BTCUSDT") |
currentExchange | string | The current exchange being used for trading (e.g. "BINANCE", "COINBASE") |
currentCoin | string | The current trading coin (e.g. "BTC") |
barIndex | number | Current 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. |
isLastBar | boolean | true 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. |
isLiveUpdate | boolean | true 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. |
color | color | The color to use for plotting (e.g. "red", "blue"). |
// 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:
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.
//@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
Use currentSymbol and currentExchange instead of hardcoding values for maximum flexibility.
ohlcv(currentSymbol, currentExchange)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.