---
title: kScript v2 Overview
description: >-
  A complete guide to understanding how kScript works. Covers core concepts,
  rules, and patterns for building indicators.
---


<div class="flex gap-3 mb-6">
  <span class="inline-flex items-center gap-1.5 px-3 py-1 rounded-full bg-green-50 text-green-600 text-sm font-medium">
    Beginner
  </span>
  <span class="inline-flex items-center gap-1.5 px-3 py-1 rounded-full bg-gray-100 text-gray-600 text-sm font-medium">
    10 min read
  </span>
</div>

## Key Concepts

kScript is designed around a few core ideas that make building indicators straightforward:


<table data-view="cards"><tbody>
<tr><td>Three-Phase Execution</td><td>Every indicator runs in three steps: Setup → Calculate → Display</td><td></td></tr>
<tr><td>Historical Data Access</td><td>`timeseries` lets you look at past values (e.g., `prices[1]` for previous candle)</td><td></td></tr>
<tr><td>Temporary Variables</td><td>`var` holds values for the current candle only, then resets</td><td></td></tr>
<tr><td>Named Parameters</td><td>Functions use clear names like `period=20` instead of just numbers</td><td></td></tr>
</tbody></table>


## How Indicators Run: Three Phases

{% stepper %}
{% step %}
### Setup Phase

Runs **once at start**. Use `define()`, `input()`, and data sources like `ohlcv()`.
{% endstep %}

{% step %}
### Calculate Phase

Runs **per candle**. Use `rsi()`, `ema()`, `if/else` logic, and `var` variables.
{% endstep %}

{% step %}
### Display Phase

Runs **per candle**. Use `plotLine()`, `plotBar()`, `plotShape()` to visualize.
{% endstep %}
{% endstepper %}


<table data-view="cards"><tbody>
<tr><td>Execution Model</td><td>View detailed execution model with examples</td><td><a href="/kscript/core-concepts/execution-model"></a></td></tr>
</tbody></table>


## Three Ways to Store Data

kScript has three types of variables, each designed for a specific purpose:

{% tabs %}
{% tab title="var" %}
**Temporary Calculations** - Resets on each candle. Use for settings, thresholds, and single-candle calculations.

```javascript lines wrap
var threshold = 70
var labelText = "Buy Signal"
```
{% endtab %}

{% tab title="timeseries" %}
**Historical Data** - For price data and indicators that need past values like `rsi()` or `ema()`.

```javascript lines wrap
timeseries ohlcvTs = ohlcv(symbol="BTCUSDT", exchange="BINANCE")
timeseries closeTs = ohlcvTs.close
var prevClose = closeTs[1]
```
{% endtab %}

{% tab title="static" %}
**Persistent Values** - For counters, flags, and cumulative calculations. Persists across candles.

```javascript lines wrap
static signalCount = 0
static cumulativeVolume = 0.0

if (buySignal) {
  signalCount++
}
cumulativeVolume += volume * (close > open ? 1 : -1)
```
{% endtab %}
{% endtabs %}

### Quick Comparison

|  | `var` | `timeseries` | `static` |
|--|-------|--------------|----------|
| Resets each candle? | Yes | N/A | No |
| Access history? | No | Yes | No |
| Where to use? | Anywhere | Top level | Top level |


<table data-view="cards"><tbody>
<tr><td>Core Variables</td><td>Learn more about variables with detailed examples</td><td><a href="/kscript/core-concepts/core-variables"></a></td></tr>
</tbody></table>


## Data Types

kScript supports several data types for building indicators:

| Type | Description | Example |
|------|-------------|---------|
| `number` | Prices, volumes, calculations | `45000.50`, `1000` |
| `string` | Text like symbols and labels | `"BTCUSDT"`, `"BINANCE"` |
| `boolean` | True/false conditions | `true`, `false` |
| `na` | Missing values (creates gaps in plots) | `na` |
| `TimeSeries` | Historical data with indexing | `prices[0]`, `prices[1]` |

{% hint style="success" %}
**Type Inference:** You don't need to specify types - kScript automatically figures out what type each variable is based on the value you assign.
{% endhint %}


<table data-view="cards"><tbody>
<tr><td>Data Types</td><td>Learn more about data types</td><td><a href="/kscript/core-concepts/data-types"></a></td></tr>
</tbody></table>


## Getting Market Data

kScript gives you access to various types of market data:

| Function | Data Type | Description |
|----------|-----------|-------------|
| `ohlcv()` | Price & Volume | Get open, high, low, close, and volume data |
| `funding_rate()` | Funding Rates | Track funding rates in perpetual futures |
| `liquidations()` | Liquidation Data | Monitor liquidation events and volumes |
| `open_interest()` | Open Interest | Track total open positions in futures |
| `source()` | Universal | Access any data type with `type=` parameter |

```javascript lines wrap
// Generic source
timeseries trades = source(type="ohlcv", symbol="BTCUSDT", exchange="BINANCE")

// OHLCV alias (preferred for price indicators)
timeseries ohlcvTs = ohlcv(symbol="BTCUSDT", exchange="BINANCE")

// Field access
timeseries openTs  = ohlcvTs.open
timeseries highTs  = ohlcvTs.high
timeseries lowTs   = ohlcvTs.low
timeseries closeTs = ohlcvTs.close
timeseries volTs   = ohlcvTs.volume
```

{% hint style="success" %}
All data source functions return `timeseries` data that you can access historically using `[0]`, `[1]`, etc.
{% endhint %}


<table data-view="cards"><tbody>
<tr><td>Data Sources</td><td>View all available data sources</td><td><a href="/kscript/core-concepts/data-sources"></a></td></tr>
</tbody></table>


## Exchange & Symbol Formats

| Exchange | `exchange` Parameter | `symbol` Format |
|----------|---------------------|-----------------|
| Binance Spot | `"BINANCE"` | `"BTCUSDT"` |
| Binance Futures | `"BINANCE_FUTURES"` | `"BTCUSDT"` |
| Coinbase | `"COINBASE"` | `"BTC-USD"` |

kScript supports data from multiple exchanges. Each exchange uses its own symbol format — some use hyphens like `BTC-USDT`, others use no separator like `BTCUSDT`. It's important to know the correct exchange and symbol format when fetching data.


<table data-view="cards"><tbody>
<tr><td>Symbol Formats</td><td>View complete list of exchanges &amp; symbol formats</td><td><a href="/kscript/faq/symbol-format"></a></td></tr>
</tbody></table>


## Writing Your Own Functions

Break down complex logic into reusable functions using `func`:

```javascript lines wrap
func calculateAverage(a, b) {
  return (a + b) / 2;
}

var avg = calculateAverage(close[0], close[1]);
```


<table data-view="cards"><tbody>
<tr><td>User Functions</td><td>Learn more about writing functions</td><td><a href="/kscript/core-concepts/user-functions"></a></td></tr>
</tbody></table>


## Available Functions

kScript provides a rich library of functions organized into categories.

### Script Setup

Define your indicator's metadata, surface user-configurable inputs, and open data feeds.

- `define(name, position, showPriceAxis?, customTitle?, format?)` — register the indicator's name, chart placement, and optional axis behavior
- `input(name, type, defaultValue?, label, constraints?)` — declare a user-configurable parameter (types: `number`, `slider`, `boolean`, `color`, `color[]`, `string`, `text`, `select`, `multiSelect`)
- `source(src, symbol, exchange)` — open a data feed (returns a `TimeSeries`)
- `print(message)` — write a value to the script console
- `printTimeSeries(source, priceIndex?)` — log a timeseries (or a single column) to the console

[View script setup functions →](/kscript/functions/script-definition)

### Plotting

Display your data on charts with line, bar, candle, shape, and annotation primitives.

- `plot(value, plotType?, ...)` — universal plot (line / bar / candle / point)
- `plotLine(value, ...)` — line chart with enhanced styling
- `plotBar(value, ...)` — OHLC bar chart
- `plotCandle(value, ...)` — candlestick chart
- `plotShape(value, shape, ...)` — markers (e.g. `'circle'`)
- `plotText(text, color, price, ...)` — text label at a price level
- `plotLabel(text, position?, ...)` — fixed-position text label
- `plotTable(data, position?, ...)` — fixed-position table
- `plotRange(time1, price1, time2, price2, color, fillColor)` — rectangular box between two time/price points
- `hline(value, color?, width?)` — horizontal reference line
- `plotBgColor(color, forceOnChart?)` — background color band

[View plotting functions →](/kscript/functions/plotting)

### Moving Averages

Smooth price data and highlight underlying trends. These helpers work from a `TimeSeries` source and return the current per-bar value.

- `sma(source, period?, priceIndex?)` — Simple Moving Average
- `ema(source, period?, priceIndex?)` — Exponential Moving Average
- `rma(source, period?, priceIndex?)` — Running Moving Average

[View moving averages →](/kscript/functions/moving-averages)

### Oscillators

Measure momentum and surface overbought / oversold conditions.

- `rsi(source, period?, priceIndex?)` — Relative Strength Index (returns `number`)
- `cci(source, period?, constant?)` — Commodity Channel Index
- `stochastic(source, kPeriod?, kSmoothing?, dPeriod?)` — Stochastic Oscillator (returns `[%K, %D]`)

[View oscillators →](/kscript/functions/oscillators)

### Trend Indicators

Identify direction, strength, momentum, and reversal points.

- `adx(source, period?)` — Average Directional Index (returns `[ADX, DI+, DI-]`)
- `macd(source, fastPeriod?, slowPeriod?, signalPeriod?)` — MACD (returns `[MACD, Signal, Histogram]`)
- `ichimoku(source, conversionPeriod?, basePeriod?, laggingSpanPeriod?, displacement?)` — Ichimoku Cloud
- `psar(source, start?, increment?, maxValue?)` — Parabolic SAR

[View trend indicators →](/kscript/functions/trend-indicators)

### Volume Indicators

Volume-weighted indicators that confirm price action.

- `mfi(source, period?)` — Money Flow Index
- `obv(source)` — On-Balance Volume

[View volume indicators →](/kscript/functions/volume-indicators)

### Orderbook Functions

Order-flow analytics across configurable depth windows. All take `(source, depthPct?)`, where `depthPct` defaults to `10`.

- `sumBids(source, depthPct?)` — total bid volume within depth
- `sumAsks(source, depthPct?)` — total ask volume within depth
- `maxBidAmount(source, depthPct?)` — largest single bid order within depth
- `maxAskAmount(source, depthPct?)` — largest single ask order within depth
- `minBidAmount(source, depthPct?)` — smallest bid order within depth
- `minAskAmount(source, depthPct?)` — smallest ask order within depth

[View orderbook functions →](/kscript/functions/orderbook-functions)

### Math Functions

Math operations and constants accessed through the `math` namespace.

- **Basic:** `math.abs`, `math.sign`, `math.random`
- **Rounding:** `math.ceil`, `math.floor`, `math.round`, `math.trunc`
- **Comparison:** `math.max`, `math.min`
- **Trig (radians):** `math.sin`, `math.cos`, `math.tan`, `math.asin`, `math.acos`, `math.atan`, `math.atan2`
- **Hyperbolic:** `math.sinh`, `math.cosh`, `math.tanh`, `math.asinh`, `math.acosh`, `math.atanh`
- **Exp / Log:** `math.exp`, `math.expm1`, `math.log`, `math.log1p`, `math.log2`, `math.log10`, `math.pow`
- **Roots:** `math.sqrt`, `math.cbrt`, `math.hypot`
- **Constants:** `math.E`, `math.PI`, `math.SQRT2`, `math.SQRT1_2`, `math.LN2`, `math.LN10`, `math.LOG2E`, `math.LOG10E`

[View math functions →](/kscript/functions/math-functions)

### Utility Functions

Series statistics, crossover detection, and value validation.

- `highest(source, period?, priceIndex?)` — highest value over a period
- `lowest(source, period?, priceIndex?)` — lowest value over a period
- `sum(source, period?, priceIndex?)` — sum across a period
- `stddev(source, period?, priceIndex?)` — standard deviation
- `donchian(source, period?)` — Donchian Channel midpoint
- `crossover(A, B)` — true when A crosses above B
- `crossunder(A, B)` — true when A crosses below B
- `cross(A, B)` — true on a cross in either direction
- `isnan(value)` — check for NaN
- `isnum(value)` — check for a finite number

[View utility functions →](/kscript/functions/utility-functions)

### Color Functions

Transform or interpolate colors at runtime so plot styles can react to indicator values.

- `brightness(color, amount)` — adjust brightness
- `darken(color, amount)` — toward black
- `lighten(color, amount)` — toward white
- `transparency(color, amount)` — set transparency level
- `opacity(color, amount)` — set opacity (inverse of transparency)
- `blend(color1, color2, amount)` — mix two colors
- `colorGradient(value, range, colorStops)` — map a numeric value to a color along a gradient

[View color functions →](/kscript/functions/color-functions) · [View color constants →](/kscript/core-concepts/color-constants)

### String Methods

String methods are called on string values via dot syntax (`text.toUpperCase()`).

- `split(separator)`, `concat(...strings)`, `substring(start, end?)`
- `toUpperCase()`, `toLowerCase()`, `trim()`
- `replace(search, replaceWith)`, `indexOf(searchValue)`
- `startsWith(prefix)`, `endsWith(suffix)`, `length()`

[View string functions →](/kscript/functions/string-functions)

### Loops & Control Flow

Iterate and branch within the per-bar calculation phase.

- `if (condition) { ... } else { ... }` — conditional execution
- `for (var i = start; i < end; i = i + 1) { ... }` — counted iteration
- `while (condition) { ... }` — conditional iteration

[View loops and control flow →](/kscript/functions/loops)


{% hint style="success" %}
**About "kwargs":** Short for "keyword arguments" - it means writing parameter names when calling functions, like `period=20` instead of just `20`. This makes your code self-documenting.

Example: `sma(source=prices, period=20)` vs `sma(prices, 20)`
{% endhint %}


<table data-view="cards"><tbody>
<tr><td>Keyword Arguments</td><td>Learn more about keyword arguments</td><td><a href="/kscript/core-concepts/keyword-arguments"></a></td></tr>
</tbody></table>


## Important Rules to Remember

- **Every indicator needs `define()`** — Always start with exactly one `define(...)` call, or your indicator won't work.
- **About `var` variables** — kScript auto-detects the type (number, text, true/false); can be used anywhere in your code; only exists for the current candle (can't access `var[1]`); text variables can be displayed as labels.
- **About `timeseries` variables** — values never change once set (read-only historical data); access history with `[0]` (now), `[1]` (previous), etc.; must be created at the top level only, not inside loops or functions; required for indicator calculations like `rsi`, `ema`, etc.; price data includes `.open`, `.high`, `.low`, `.close`, `.volume`.
- **Getting data** — use `ohlcv(symbol=..., exchange=...)` for price data, or `source(type=..., symbol=..., exchange=...)` for other data types. Both return `timeseries`.
- **Displaying results** — use named parameters like `period=20` to make code clearer; you can call multiple plot functions in one indicator.
- **Performance limits** — your indicator must finish calculating within 500 milliseconds, or it will stop with an error.
- **Debugging tips** — use `print(...)` or `printTimeSeries(...)` to see values. Check the Data Table panel to inspect your indicator's output.


## What's Next?


<table data-view="cards"><tbody>
<tr><td>Quick Start Guide</td><td>Build your first indicator in 5 minutes</td><td><a href="/kscript/getting-started/quick-start"></a></td></tr>
<tr><td>Core Concepts</td><td>Deep dive into the execution model</td><td><a href="/kscript/core-concepts/execution-model"></a></td></tr>
<tr><td>Function Reference</td><td>Browse all available functions</td><td><a href="/kscript/reference/quick-reference"></a></td></tr>
</tbody></table>

