Reference

Reference

Comprehensive reference for all kScript functions, variables, and data types. Build powerful trading algorithms with our extensive library of technical indicators and utilities.

Variables & Constants

Core variables, data types, and constants available in kScript for market data access and styling.

Core Data Variables

VariableTypeDescription
currentSymbolstringThe current trading symbol (e.g., 'BTCUSDT')
currentExchangestringThe current exchange being used for trading (e.g., 'BINANCE', 'COINBASE')
currentCoinstringThe current trading coin (e.g., "BTC")
barIndexnumberCurrent bar index in the timeseries during the per-bar loop.
isLastBarbooleanTrue when processing the last bar in the dataset.
isLiveUpdatebooleanTrue during live data updates with new market data.
colorcolorThe color to use for plotting (e.g., 'red', 'blue')

Color Constants

ConstantTypeDescription
yellowcolorYellow color (#FFFF00)
orangecolorOrange color (#FFA500)
purplecolorPurple color (#800080)
graycolorGray color (#808080)
blackcolorBlack color (#000000)
whitecolorWhite color (#FFFFFF)
redcolorRed color (#FF0000)
greencolorGreen color (#008000)
bluecolorBlue color (#0000FF)
silvercolorSilver color (#C0C0C0)
marooncolorMaroon color (#800000)
fuchsiacolorFuchsia color (#FF00FF)
limecolorLime color (#00FF00)
olivecolorOlive color (#808000)
navycolorNavy color (#000080)
tealcolorTeal color (#008080)
aquacolorAqua color (#00FFFF)

Data Types

TypeDescription
timeseriesTime-aligned numerical data. Only timeseries data can be passed into plot functions.
ShapeTypeShape type used by plotShape(). Currently supports circle.
staticVariable that gets declared once and persists across bar iterations.

Data Sources

Data SourceTypeDescription
binance_treasury_balanceDataSourceValue of asset held by Binance. Updated monthly. Available for BTC, ETH, SOL, USDT, and USDC.
buy_sell_volumeDataSourceBuy/sell volume from trade data.
cme_oiDataSourceOpen Interest for crypto futures contracts on the Chicago Mercantile Exchange. Only available for BTC and ETH.
deribit_implied_volatilityDataSourceImplied volatility of ticker on Deribit. Available only for BTC and ETH coins. Returns tenors of 1W, 1M, and 3M.
deribit_volatility_indexDataSourceMeasure of implied or historical price volatility for a specific asset on Deribit. Limited to ETH and BTC coins. Returns OHLC data.
etf_flowDataSourceNet inflow or outflow of capital into an ETF. Only available on 1D intervals.
etf_holdingDataSourceAsset balance held by major ETFs. Available for BTC, ETH, and SOL based ETFs.
etf_premium_rateDataSourceCompares market price of an ETF with its net asset value (NAV). Available for BTC, ETH, and SOL based ETFs.
ethena_positionsDataSourceAmount of collateral within the Ethena protocol.
funding_rateDataSourceFunding rate aggregation data from derivatives markets.
liquidationsDataSourceLiquidation aggregation data from derivatives markets.
long_short_ratioDataSourceOverall ratio of long to short positions across all traders. Available for Binance, Bybit, and OKX.
ohlcvDataSourceOpen, High, Low, Close, Volume data from trade aggregations.
open_interestDataSourceOpen interest aggregation data from derivatives markets.
options_volumeDataSourcePuts and calls for a particular coin from Binance Options or Deribit based on volume. Limited to ETH and BTC coins.
options_open_interestDataSourcePuts and calls for a particular coin from Binance Options or Deribit based on open interest. Limited to ETH and BTC coins.
orderbookDataSourceOrderbook heatmap snapshot aggregation data.
skewDataSourcePercentage difference in implied volatility between call and put options for a specific ticker on Deribit. Limited to BTC and ETH.

Function Categories

Explore technical indicators, mathematical functions, and utilities organized by category.

CategoryDescriptionFunctions
Moving AveragesTrend-following indicators that smooth price data.sma, ema, rma
OscillatorsMomentum indicators that fluctuate between bounded values.rsi, cci, stochastic
Volume IndicatorsIndicators that incorporate volume data in their calculations.mfi, obv
Trend IndicatorsIndicators that help identify trend direction and strength.adx, macd, ichimoku, psar
Utility FunctionsHelper functions for statistical calculations and data manipulation.lowest, highest, sum, stddev, donchian, crossover, crossunder, cross, isnan, isnum
Plotting & VisualizationFunctions for rendering data on charts.plot, plotLine, plotBar, plotCandle, plotShape, plotText, plotLabel, plotTable, plotRange, hline, plotBgColor
Script DefinitionFunctions for defining script metadata and input parameters.define, input, source, print, printTimeSeries
Color FunctionsFunctions for manipulating and transforming colors.brightness, darken, lighten, transparency, opacity, blend, colorGradient
Orderbook FunctionsFunctions for working with orderbook data.sumBids, sumAsks, maxBidAmount, maxAskAmount, minBidAmount, minAskAmount
Math FunctionsJavaScript-style math constants and numerical helpers.math.abs, math.max, math.min, math.sqrt, math.pow
String FunctionsJavaScript-style string methods for text processing.split, concat, substring, toUpperCase, toLowerCase, trim, replace, indexOf, startsWith, endsWith, length
LoopsControl-flow patterns for repeated logic.for, while, break, continue

Commonly used functions for quick access and reference.

FunctionCategorySignatureDescription
smaMoving Averagessma(source, period?, priceIndex?)Simple Moving Average calculation.
emaMoving Averagesema(source, period?, priceIndex?)Exponential Moving Average calculation.
rsiOscillatorsrsi(source, period?, priceIndex?)Relative Strength Index oscillator.
plotPlotting & Visualizationplot(value, plotType?, width?, colors?, colorIndex?, fill?, smooth?, showPriceDisplay?, label?, desc?)Universal plotting function for all visualization types.

Function Quick Lookup

Moving averages

FunctionSignatureReturns
smasma(source, period?, priceIndex?)number
emaema(source, period?, priceIndex?)number
rmarma(source, period?, priceIndex?)number

Oscillators

FunctionSignatureReturns
rsirsi(source, period?, priceIndex?)number
ccicci(source, period?, constant?)number
stochasticstochastic(source, kPeriod?, kSmoothing?, dPeriod?)[%K, %D]

Trend indicators

FunctionSignatureReturns
adxadx(source, period?)[ADX, DI+, DI-]
macdmacd(source, fastPeriod?, slowPeriod?, signalPeriod?)[MACD, Signal, Histogram]
ichimokuichimoku(source, conversionPeriod?, basePeriod?, laggingSpanPeriod?, displacement?)[Tenkan, Kijun, SpanA, SpanB, Chikou]
psarpsar(source, start?, increment?, maxValue?)number

Volume indicators

FunctionSignatureReturns
mfimfi(source, period?)number
obvobv(source)number

Orderbook functions

All take (source, depthPct?) where depthPct defaults to 10.

FunctionSignatureReturns
sumBidssumBids(source, depthPct?)total bid volume
sumAskssumAsks(source, depthPct?)total ask volume
maxBidAmountmaxBidAmount(source, depthPct?)largest bid order
maxAskAmountmaxAskAmount(source, depthPct?)largest ask order
minBidAmountminBidAmount(source, depthPct?)smallest bid order
minAskAmountminAskAmount(source, depthPct?)smallest ask order

Utility

FunctionSignatureReturns
lowestlowest(source, period?, priceIndex?)number
highesthighest(source, period?, priceIndex?)number
sumsum(source, period?, priceIndex?)number
stddevstddev(source, period?, priceIndex?)number
donchiandonchian(source, period?)number
crossovercrossover(A, B)boolean
crossundercrossunder(A, B)boolean
crosscross(A, B)boolean
isnanisnan(value)boolean
isnumisnum(value)boolean

Plotting

FunctionSignature
plotplot(value, plotType?, width?, colors?, colorIndex?, fill?, smooth?, showPriceDisplay?, label?, desc?)
plotLineplotLine(value, width?, colors?, colorIndex?, fill?, smooth?, showPriceDisplay?, label?, desc?)
plotBarplotBar(value, width?, colors?, colorIndex?, showPriceDisplay?, label?, desc?)
plotCandleplotCandle(value, width?, colors?, colorIndex?, showPriceDisplay?, label?, desc?)
plotShapeplotShape(value, shape, width?, colors?, colorIndex?, fill?, showPriceDisplay?, label?, desc?)
plotTextplotText(text, color, price, size?, xAlign?, yAlign?, fill?, backgroundColor?)
plotLabelplotLabel(text, position?, x?, y?, color?, size?, xAlign?, yAlign?, fontFamily?, backgroundColor?)
plotTableplotTable(data, position?, x?, y?, headerRow?, headerColumn?, ...styling)
plotRangeplotRange(time1, price1, time2, price2, color, fillColor)
hlinehline(value, color?, width?)
plotBgColorplotBgColor(color, forceOnChart?)

Color functions

FunctionSignature
brightnessbrightness(color, amount)
darkendarken(color, amount)
lightenlighten(color, amount)
transparencytransparency(color, amount)
opacityopacity(color, amount)
blendblend(color1, color2, amount)
colorGradientcolorGradient(value, range, colorStops)

Math (math namespace)

Constants: math.E, math.PI, math.SQRT2, math.SQRT1_2, math.LN2, math.LN10, math.LOG2E, math.LOG10E

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

String methods

MethodSignature
splitstr.split(separator)
concatstr.concat(...strings)
substringstr.substring(start, end?)
toUpperCasestr.toUpperCase()
toLowerCasestr.toLowerCase()
trimstr.trim()
replacestr.replace(search, replaceWith)
indexOfstr.indexOf(searchValue)
startsWithstr.startsWith(prefix)
endsWithstr.endsWith(suffix)
lengthstr.length()

Control flow

ConstructForm
if/elseif (cond) { ... } else { ... }
forfor (var i = 0; i < n; i = i + 1) { ... }
whilewhile (cond) { ... }

Timeseries helpers

FunctionSignature
buildTimeseriesbuildTimeseries(srcTimeSeries, (bar, idx) => [...])
matchTimestampmatchTimestamp(source, target, matchMode?)
timeseriestimeseries(arr, priceIndex)

User functions

User Function Declaration
func myEma(source, period) {
  return ema(source, period, 4);
}

func declarations live at global scope. timeseries cannot be declared inside a func body.