Key Concepts
kScript is designed around a few core ideas that make building indicators straightforward:
timeseries lets you look at past values (e.g., prices[1] for previous candle)var holds values for the current candle only, then resetsperiod=20 instead of just numbersHow Indicators Run: Three Phases
- 1
Setup Phase
Runs once at start. Use
define(),input(), and data sources likeohlcv(). - 2
Calculate Phase
Runs per candle. Use
rsi(),ema(),if/elselogic, andvarvariables. - 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.
var threshold = 70
var labelText = "Buy Signal"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 |
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] |
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 |
// 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.volumeExchange & 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.
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'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 behaviorinput(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 aTimeSeries)print(message)— write a value to the script consoleprintTimeSeries(source, priceIndex?)— log a timeseries (or a single column) to the console
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 stylingplotBar(value, ...)— OHLC bar chartplotCandle(value, ...)— candlestick chartplotShape(value, shape, ...)— markers (e.g.'circle')plotText(text, color, price, ...)— text label at a price levelplotLabel(text, position?, ...)— fixed-position text labelplotTable(data, position?, ...)— fixed-position tableplotRange(time1, price1, time2, price2, color, fillColor)— rectangular box between two time/price pointshline(value, color?, width?)— horizontal reference lineplotBgColor(color, forceOnChart?)— background color band
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 Averageema(source, period?, priceIndex?)— Exponential Moving Averagerma(source, period?, priceIndex?)— Running Moving Average
Oscillators
Measure momentum and surface overbought / oversold conditions.
rsi(source, period?, priceIndex?)— Relative Strength Index (returnsnumber)cci(source, period?, constant?)— Commodity Channel Indexstochastic(source, kPeriod?, kSmoothing?, dPeriod?)— Stochastic Oscillator (returns[%K, %D])
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 Cloudpsar(source, start?, increment?, maxValue?)— Parabolic SAR
Volume Indicators
Volume-weighted indicators that confirm price action.
mfi(source, period?)— Money Flow Indexobv(source)— On-Balance Volume
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 depthsumAsks(source, depthPct?)— total ask volume within depthmaxBidAmount(source, depthPct?)— largest single bid order within depthmaxAskAmount(source, depthPct?)— largest single ask order within depthminBidAmount(source, depthPct?)— smallest bid order within depthminAskAmount(source, depthPct?)— smallest ask order within depth
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
Utility Functions
Series statistics, crossover detection, and value validation.
highest(source, period?, priceIndex?)— highest value over a periodlowest(source, period?, priceIndex?)— lowest value over a periodsum(source, period?, priceIndex?)— sum across a periodstddev(source, period?, priceIndex?)— standard deviationdonchian(source, period?)— Donchian Channel midpointcrossover(A, B)— true when A crosses above Bcrossunder(A, B)— true when A crosses below Bcross(A, B)— true on a cross in either directionisnan(value)— check for NaNisnum(value)— check for a finite number
Color Functions
Transform or interpolate colors at runtime so plot styles can react to indicator values.
brightness(color, amount)— adjust brightnessdarken(color, amount)— toward blacklighten(color, amount)— toward whitetransparency(color, amount)— set transparency levelopacity(color, amount)— set opacity (inverse of transparency)blend(color1, color2, amount)— mix two colorscolorGradient(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()
Loops & Control Flow
Iterate and branch within the per-bar calculation phase.
if (condition) { ... } else { ... }— conditional executionfor (var i = start; i < end; i = i + 1) { ... }— counted iterationwhile (condition) { ... }— conditional iteration
Important Rules to Remember
- Every indicator needs
define()— Always start with exactly onedefine(...)call, or your indicator won't work. - About
varvariables — kScript auto-detects the type (number, text, true/false); can be used anywhere in your code; only exists for the current candle (can't accessvar[1]); text variables can be displayed as labels. - About
timeseriesvariables — 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 likersi,ema, etc.; price data includes.open,.high,.low,.close,.volume. - Getting data — use
ohlcv(symbol=..., exchange=...)for price data, orsource(type=..., symbol=..., exchange=...)for other data types. Both returntimeseries. - Displaying results — use named parameters like
period=20to 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(...)orprintTimeSeries(...)to see values. Check the Data Table panel to inspect your indicator's output.