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.

Strategies

Declare strategy() instead of define() and place simulated orders; results render in the Strategy Tester. Full reference: Strategy Functions.

FunctionDescription
strategy(title, ..., initialCapital?, commissionPercent?, slippageBps?, slippageModel?, qtyType?, qtyValue?, pyramiding?, fillModel?, instrument?, leverage?, maintenanceMarginPercent?, makerFeePercent?, takerFeePercent?, funding?, onLiquidation?)Declare the strategy and configure the simulated broker. Perps-specific params are since engine 3.0.63
strategy.entry(id, direction, qty?, limit?, stop?, ocaName?, comment?)Queue an entry (market, or resting limit/stop)
strategy.exit(id, fromEntry?, qty?, qtyPercent?, profit?, limit?, loss?, stop?, trailPoints?, trailOffset?, ocaName?, comment?)Attach protective bracket legs to entries
strategy.close(id, comment?)Close a named entry at market
strategy.closeAll(comment?)Close the whole position at market
strategy.cancel(id) / strategy.cancelAll()Cancel pending unfilled orders
strategy.positionSize()Signed open quantity (0 when flat)
strategy.positionAvgPrice() / strategy.equity() / strategy.openProfit() / strategy.netProfit()Position and account getters
strategy.closedTradeCount() / strategy.winTradeCount() / strategy.lossTradeCount() / strategy.maxDrawdown()Trade-stat getters

Perps strategy declaration params (since engine 3.0.63):

ParameterType and boundsDefault
instrument"spot" or "perps""spot"
leveragenumber greater than 01
maintenanceMarginPercentnumber at least 0 and less than 1000.5
makerFeePercentnon-negative number0
takerFeePercentnon-negative number0
funding"data" or "off""data"
onLiquidation"continue" or "halt""continue"

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.
isConfirmedbooleanTrue on confirmed historical bars; use as an anti-repaint guard.
isFirstbooleanTrue only while processing bar 0.
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.
number / string / booleanScalar types with strict, sound semantics (details)
naThe missing-value sentinel: falsy, propagating, structurally equal. Test with isna(), default with nz()
colorFirst-class color type with string-literal bridging (color functions)
array / mapCollections with lambdas and reducers (collections)
type (structs)User-defined types: type Zone { top: number, handle: drawing_handle } (user types)
drawing_handleA live drawing object reference (line.new, box.new, ... then .delete() / setters)
ShapeTypeplotShape markers: circle, cross, triangle, diamond, arrowUp, arrowDown, flag, square, label, char
persistDeclaration carried across bars (the recommended spelling of static)

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.
volume_profileDataSourcePer-bar volume-profile ladder — buy/sell volume bucketed by price level. No scalar properties; read with the vp* accessors. Optional ticksPerBar (default 1) merges every N price levels into one bucket; optional currency ("USD" or "Coin", default "Coin") quotes bucket volume in USD instead of coins.

v3 Keywords

KeywordPurpose
persistCross-bar state: persist zones = []
typeStruct declaration: type Zone { ... } + Zone.new(...); methods via func inside the block, this bound to the receiver
switchFirst-match branching, no fallthrough
import ... asLibraries with versioning
for ... in / ofCollection iteration (loops)

Function Categories

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

CategoryDescriptionFunctions
Moving AveragesTrend-following indicators that smooth price data.sma, ema, alma, swma, rma
OscillatorsMomentum indicators that fluctuate between bounded values.rsi, wpr, cmo, tsi, cci, stochastic
Volume IndicatorsIndicators that incorporate volume data in their calculations.mfi, obv
Volume ProfileAccessors that extract scalar series from a volume_profile source.vpBuy, vpSell, vpDelta, vpTotal, vpPoc, vpPocVolume, vpBucketCount, vpPriceHigh, vpPriceLow
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, plotHistogram, plotCandle, plotShape, plotBatches, plotPie, 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
almaalma(source, length, offset?, sigma?)number
swmaswma(source)number
rmarma(source, period?, priceIndex?)number (legacy recurrence, not Wilder)
wmawma(source, period?, priceIndex?)number
hmahma(source, period?, priceIndex?)number
vwmavwma(source, period?, priceIndex?)number

Oscillators

FunctionSignatureReturns
rsirsi(source, period?, priceIndex?)number (Wilder, textbook seed)
wprwpr(length, source)number
cmocmo(source, length)number
tsitsi(source, short, long)number
ccicci(source, period?, constant?)number
stochasticstochastic(source, kPeriod?, kSmoothing?, dPeriod?)[%K, %D]
stochstoch(periodK?, smoothK?, periodD?)%K/%D streams
changechange(source, n?, priceIndex?)number
rocroc(source, n?, priceIndex?)number
mommom(source, n?, priceIndex?)number
mfimfi(source, period?)number

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
supertrendsupertrend(factor?, atrPeriod?)line/direction streams
bbbb(source, period?, mult?, priceIndex?)basis/upper/lower streams
keltnerkeltner(source, period?, mult?, atrPeriod?, priceIndex?)basis/upper/lower streams
trtr(source)number
hl2hl2(source?)number
hlc3hlc3(source?)number
ohlc4ohlc4(source?)number
hlcc4hlcc4(source?)number
atratr(period?, source?)number
stdevstdev(source, period?, priceIndex?)number
variancevariance(source, period?, priceIndex?)number

Volume indicators

FunctionSignatureReturns
mfimfi(source, period?)number
obvobv(source)number
vwapvwap(anchor?)number (cumulative, or "day"/"week"/"month" anchored)
cumcum(source, priceIndex?)number

Volume profile

All take a single volume_profile source and return a number for the current bar.

FunctionSignatureReturns
vpBuyvpBuy(source)number
vpSellvpSell(source)number
vpDeltavpDelta(source)number
vpTotalvpTotal(source)number
vpPocvpPoc(source)number
vpPocVolumevpPocVolume(source)number
vpBucketCountvpBucketCount(source)number
vpPriceHighvpPriceHigh(source)number
vpPriceLowvpPriceLow(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
pivothighpivothigh(source, leftbars, rightbars, priceIndex)number
pivotlowpivotlow(source, leftbars, rightbars, 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?)
plotHistogramplotHistogram(value, base?, colors?, colorIndex?, width?, showPriceDisplay?, label?, desc?)
plotCandleplotCandle(value, width?, colors?, colorIndex?, showPriceDisplay?, label?, desc?)
plotShapeplotShape(value, shape, width?, colors?, colorIndex?, fill?, showPriceDisplay?, label?, desc?)
plotBatchesplotBatches(count, callback)
plotPieplotPie(value, price, radius?, colors?, opacity?, display?)
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)
plotMiniChartGridplotMiniChartGrid(panels, position?, columns?, candleStyle?, showChange?, showVolume?, ...styling)
plotStatRowplotStatRow(value, title?, format?, polarity?, priority?, colors?)
hlinehline(value, color?, width?)
plotBgColorplotBgColor(color, forceOnChart?)

New in v3 (plotting)

FunctionSignatureNotes
barcolorbarcolor(color)Recolors the main candles per bar
fillBetweenfillBetween(series1, series2, color, opacity?)Band between two plotted series
plotShape extraslocation, char, tooltip, zOrder10 shapes incl arrowUp/Down, flag, square, char
Drawing objectsline.new / box.new / label.new / polyline.new / linefill.new / table.newStateful handles: .delete(), setters
htfhtf(source, timeframe, opts?)No-repaint higher timeframe
requestrequest(symbol, timeframe?, opts?)Other-symbol shorthand
ltfltf(source, timeframe)Finer bars as cells
requestBarsrequestBars(symbol, timeframe, type?, exchange?, { bars, anchor? })Last N native bars as a raw array for drawing; anchor: "latest" pins them to the newest market bars
plotMiniChartGridplotMiniChartGrid(panels, position?, columns?, candleStyle?, showChange?, showVolume?, ...styling)Viewport-pinned grid of mini OHLC panels
plotStatRowplotStatRow(value, title?, format?, polarity?, priority?, colors?)Per-bar statistics strip row

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.