kScript v2 Overview
A complete guide to understanding how kScript works. This page covers the core concepts, rules, and patterns you'll use to build indicators.
Learn about the two types of variables, the three-phase execution model, and how to work with data and plotting.
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
Setup
Run once at start
define()input()ohlcv()
Calculate
Run per candle
rsi()ema()- Use
var if/elselogic
Display
Run per candle
plotLine()plotBar()plotShape()
Three Ways to Store Data
kScript has three types of variables, each designed for a specific purpose:
var — For temporary calculations that reset on each candle. Use for settings, thresholds, and single-candle calculations.timeseries — For historical data you can look back through. Use for price data and indicators that need past values like rsi() or ema().static — For values that persist across candles with manual control. Use for counters, flags, and cumulative calculations like CVD.var | timeseries | static | |
|---|---|---|---|
| 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 plotsTimeSeriesFor 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 pairfunding_rate() — Funding Rates Track funding rates in perpetual futures marketsliquidations() — Liquidation Data Monitor liquidation events and volumesopen_interest() — Open Interest Track total open positions in futures marketssource() — 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
exchange = "BINANCE"symbol = "BTCUSDT"exchange = "BINANCE_FUTURES"symbol = "BTCUSDT"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;}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 propertiesinput()— Create user inputs
Plotting
Display your data on charts
plotLine()— Draw linesplotBar()— Draw barsplotCandle()— Draw candlesplotShape()— Add markers
Moving Averages
Smooth price data and identify trends
sma()— Simple moving averageema()— Exponential moving averagewma()— Weighted moving averagevwma()— Volume-weighted MA
Oscillators
Measure momentum and overbought/oversold conditions
rsi()— Relative strength indexstoch()— Stochastic oscillatorcci()— Commodity channel indexmacd()— MACD indicator
Trend Indicators
Identify and follow market trends
adx()— Average directional indexsupertrend()— Supertrend indicatorichimoku()— Ichimoku cloud
Volume Indicators
Analyze trading volume and money flow
obv()— On-balance volumemfi()— Money flow indexvwap()— Volume-weighted average price
Orderbook Functions
Analyze orderbook depth and liquidity
orderbook_depth()— Depth databid_ask_spread()— Spread analysisliquidity_score()— Liquidity metrics
Math Functions
Mathematical operations and calculations
abs()min()max()sum()avg()stddev()log()exp()pow()
String Functions
Manipulate and transform text strings
split()concat()substring()toUpperCase()toLowerCase()indexOf()startsWith()endsWith()
Utility Functions
Helper functions for common tasks
highest()lowest()crossover()crossunder()change()change_pct()
Color Functions
Create and manipulate colors
color.new()— Create colorscolor.rgb()— RGB colors- Named colors like
color.red
Loops & Control Flow
Iterate and control program flow
forloops — Iterate over rangeswhileloops — Conditional iterationif/else— Conditional logic
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=20to 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.