Key Concepts

kScript is designed around a few core ideas that make building indicators straightforward. Understanding these concepts will help you write better indicators:

🔄

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

Setup

Run once at start

  • define()
  • input()
  • ohlcv()
🧮
2

Calculate

Run per candle

  • rsi() ema()
  • Use var
  • if/else logic
🎨
3

Display

Run per candle

  • plotLine()
  • plotBar()
  • plotShape()

Three Ways to Store Data

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

1
var — For temporary calculations that reset on each candle. Use for settings, thresholds, and single-candle calculations.
2
timeseries — For historical data you can look back through. Use for price data and indicators that need past values like rsi() or ema().
3
static — For values that persist across candles with manual control. Use for counters, flags, and cumulative calculations like CVD.
vartimeseriesstatic
Resets each candle?✅ Yes➖ N/A❌ No
Access history?❌ No✅ Yes❌ No
Where to use?📍 Anywhere🔝 Top level🔝 Top level

Data Types You'll Use

kScript supports several data types for building indicators:

numberFor prices, volumes, and calculations (e.g., 45000.50, 1000)
stringFor text like symbols and labels (e.g., "BTCUSDT", "BINANCE")
booleanFor true/false conditions (e.g., true, false)
naFor missing values — creates gaps in your plots
TimeSeriesFor historical market data with indexing support ([0], [1], etc.)

💡 Type Inference: You don't need to specify types — kScript automatically figures out what type each variable is based on the value you assign.

Getting Market Data

kScript gives you access to various types of market data. Here are the most common ones:

📊
ohlcv() — Price & Volume Get open, high, low, close, and volume data for any trading pair
💰
funding_rate() — Funding Rates Track funding rates in perpetual futures markets
liquidations() — Liquidation Data Monitor liquidation events and volumes
📈
open_interest() — Open Interest Track total open positions in futures markets
🔗
source() — Universal Access Use source(type="...", symbol="...", exchange="...") to access any data type

💡 What You Get: All data source functions return timeseries data that you can access historically using [0], [1], etc.

Exchange & Symbol Formats

Binance Spot
exchange = "BINANCE"symbol = "BTCUSDT"
Binance Futures
exchange = "BINANCE_FUTURES"symbol = "BTCUSDT"
Coinbase
exchange = "COINBASE"symbol = "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:

func calculateAverage(a, b) {return (a + b) / 2;}
Use it:var avg = calculateAverage(close[0], close[1]);

Available Functions

kScript provides a rich library of functions organized into categories:

📋

Script Setup

Define your indicator and create user settings

  • define() — Set indicator properties
  • input() — Create user inputs
View script setup functions →
📊

Plotting

Display your data on charts

  • plotLine() — Draw lines
  • plotBar() — Draw bars
  • plotCandle() — Draw candles
  • plotShape() — Add markers
View plotting functions →
📈

Moving Averages

Smooth price data and identify trends

  • sma() — Simple moving average
  • ema() — Exponential moving average
  • wma() — Weighted moving average
  • vwma() — Volume-weighted MA
View moving averages →
〰️

Oscillators

Measure momentum and overbought/oversold conditions

  • rsi() — Relative strength index
  • stoch() — Stochastic oscillator
  • cci() — Commodity channel index
  • macd() — MACD indicator
View oscillators →
↗️

Trend Indicators

Identify and follow market trends

  • adx() — Average directional index
  • supertrend() — Supertrend indicator
  • ichimoku() — Ichimoku cloud
View trend indicators →
📦

Volume Indicators

Analyze trading volume and money flow

  • obv() — On-balance volume
  • mfi() — Money flow index
  • vwap() — Volume-weighted average price
View volume indicators →
📖

Orderbook Functions

Analyze orderbook depth and liquidity

  • orderbook_depth() — Depth data
  • bid_ask_spread() — Spread analysis
  • liquidity_score() — Liquidity metrics
View orderbook functions →
🔢

Math Functions

Mathematical operations and calculations

  • abs() min() max()
  • sum() avg() stddev()
  • log() exp() pow()
View math functions →
📝

String Functions

Manipulate and transform text strings

  • split() concat() substring()
  • toUpperCase() toLowerCase()
  • indexOf() startsWith() endsWith()
View string functions →
🛠️

Utility Functions

Helper functions for common tasks

  • highest() lowest()
  • crossover() crossunder()
  • change() change_pct()
View utility functions →
🎨

Color Functions

Create and manipulate colors

  • color.new() — Create colors
  • color.rgb() — RGB colors
  • Named colors like color.red
View color functions → View color constants →
🔁

Loops & Control Flow

Iterate and control program flow

  • for loops — Iterate over ranges
  • while loops — Conditional iteration
  • if/else — Conditional logic
View loops and control flow →
💡

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) ← You can see exactly what each value means
vs. sma(prices, 20) ← What does 20 mean here?

Important Rules to Remember

Every indicator needs define(...)

Always start with exactly one define(...) call, or your indicator won't work.

About var

  • kScript automatically 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

  • 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

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.

📖
Introduction
Overview of kScript language
🔍
Overview
Complete technical documentation
🚀
Quick Start
Get started with kScript basics
📋
Function Reference
Complete API reference guide
📚
Type System
Understanding kScript data types
General FAQ
Frequently asked questions about kScript
Best Practices
Guidelines for writing efficient kScript code
⚠️
Limitations
Known constraints and workarounds
🌐
Exchange & Symbol Format
List of supported exchanges and symbol formats
🆕
Updates
v1 vs v2 differences and improvements
🔧
Variables
Core variables and data handling
📊
Data Sources
Subscribe to OHLCV, trades, and orderbook data
⚙️
Execution Model
Per-bar execution lifecycle and phases
🏷️
Keyword Arguments
Named parameters for clear function calls
🛠️
User-Defined Functions
Create custom reusable functions
🔗
Script Definition
Defining inputs and metadata
🎯
Utility Functions
Helper functions and calculations
📈
Moving Averages
SMA, EMA and trend-following indicators
📊
Oscillators
RSI, Stochastic and momentum indicators
📈
Trend Indicators
Trend direction and strength analysis
📉
Volume Indicators
Volume-based analysis tools
📦
Orderbook Functions
Market depth analysis tools
🎨
Plotting & Visualization
Chart rendering and styling
🌈
Color Functions
Color manipulation and styling
🔄
Loops
For loops and while loops for iteration
🧮
Math Functions
Mathematical functions and constants
📝
String Functions
String manipulation and transformation
🏠
Go Home
Return to main landing page