Getting Started

kScript v2 Overview

A complete guide to understanding how kScript works. Covers core concepts, rules, and patterns for building indicators.

Beginner 10 min read

Key Concepts

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

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

How Indicators Run: Three Phases

  1. 1

    Setup Phase

    Runs once at start. Use define(), input(), and data sources like ohlcv().

  2. 2

    Calculate Phase

    Runs per candle. Use rsi(), ema(), if/else logic, and var variables.

  3. 3

    Display Phase

    Runs per candle. Use plotLine(), plotBar(), plotShape() to visualize.

Three Ways to Store Data

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

Temporary Calculations - Resets on each candle. Use for settings, thresholds, and single-candle calculations.

lines wrap
var threshold = 70
var labelText = "Buy Signal"

Quick Comparison

vartimeseriesstatic
Resets each candle?YesN/ANo
Access history?NoYesNo
Where to use?AnywhereTop levelTop level

Data Types

kScript supports several data types for building indicators:

TypeDescriptionExample
numberPrices, volumes, calculations45000.50, 1000
stringText like symbols and labels"BTCUSDT", "BINANCE"
booleanTrue/false conditionstrue, false
naMissing values (creates gaps in plots)na
TimeSeriesHistorical data with indexingprices[0], prices[1]

Getting Market Data

kScript gives you access to various types of market data:

FunctionData TypeDescription
ohlcv()Price & VolumeGet open, high, low, close, and volume data
funding_rate()Funding RatesTrack funding rates in perpetual futures
liquidations()Liquidation DataMonitor liquidation events and volumes
open_interest()Open InterestTrack total open positions in futures
source()UniversalAccess any data type with type= parameter
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

Exchange & Symbol Formats

Exchangeexchange Parametersymbol 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.

Writing Your Own Functions

Break down complex logic into reusable functions using func:

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

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

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 →

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 →

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 →

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 →

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 →

Volume Indicators

Volume-weighted indicators that confirm price action.

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

View 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 →

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 →

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 →

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 → · View 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 →

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 →

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?