---
title: Core Variables
description: 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**

```javascript title="var declaration" lines wrap
var threshold = 70;
var labelText = 'Buy Signal';
```

**Behavior Example**

```javascript title="var behavior" lines wrap
// 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`.

{% hint style="warning" %}
**Performance warning:** Creating a `timeseries` is a very expensive operation. Declare a variable as `timeseries` only when it's absolutely necessary.
{% endhint %}

**Declaration & Usage Example**

```javascript title="timeseries behavior" lines wrap
// 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**

```javascript title="static behavior" lines wrap
// 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"`).                                                                                                                                              |

```javascript title="Context variable examples" lines wrap
// 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](/kscript/core-concepts/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:

```javascript title="timeseries indexing" lines wrap
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.

```javascript title="Dynamic Data Source" lines wrap
//@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

<table data-view="cards" data-layout="stack"><tbody>
<tr><td>Always Use Current Context</td><td><p>Use `currentSymbol` and `currentExchange` instead of hardcoding values for maximum flexibility.</p><pre><code class="language-javascript">ohlcv(currentSymbol, currentExchange)</code></pre></td><td></td></tr>
<tr><td>Cache Expensive Operations</td><td><p>Store references to commonly used data sources to improve performance.</p><pre><code class="language-javascript">timeseries ohlcvData = ohlcv(currentSymbol, currentExchange);</code></pre><p>See <a href="/kscript/core-concepts/type-system">Type System</a> for the full discussion of how `var` / `static` / `timeseries` interact with kScript's hybrid type model.</p></td><td></td></tr>
</tbody></table>
