Strategies
Declare strategy() instead of define() and place simulated orders; results render in the Strategy Tester. Full reference: Strategy Functions .
Function Description 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):
Parameter Type and bounds Default instrument"spot" or "perps""spot"leveragenumber greater than 0 1maintenanceMarginPercentnumber at least 0 and less than 100 0.5makerFeePercentnon-negative number 0takerFeePercentnon-negative number 0funding"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
Variable Type Description currentSymbolstring The current trading symbol (e.g., 'BTCUSDT') currentExchangestring The current exchange being used for trading (e.g., 'BINANCE', 'COINBASE') currentCoinstring The current trading coin (e.g., "BTC") barIndexnumber Current bar index in the timeseries during the per-bar loop. isLastBarboolean True when processing the last bar in the dataset. isConfirmedboolean True on confirmed historical bars; use as an anti-repaint guard. isFirstboolean True only while processing bar 0. isLiveUpdateboolean True during live data updates with new market data. colorcolor The color to use for plotting (e.g., 'red', 'blue')
Color Constants
Constant Type Description yellowcolor Yellow color (#FFFF00) orangecolor Orange color (#FFA500) purplecolor Purple color (#800080) graycolor Gray color (#808080) blackcolor Black color (#000000) whitecolor White color (#FFFFFF) redcolor Red color (#FF0000) greencolor Green color (#008000) bluecolor Blue color (#0000FF) silvercolor Silver color (#C0C0C0) marooncolor Maroon color (#800000) fuchsiacolor Fuchsia color (#FF00FF) limecolor Lime color (#00FF00) olivecolor Olive color (#808000) navycolor Navy color (#000080) tealcolor Teal color (#008080) aquacolor Aqua color (#00FFFF)
Data Types
Type Description 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, charpersistDeclaration carried across bars (the recommended spelling of static)
Data Sources
Data Source Type Description binance_treasury_balanceDataSource Value of asset held by Binance. Updated monthly. Available for BTC, ETH, SOL, USDT, and USDC. buy_sell_volumeDataSource Buy/sell volume from trade data. cme_oiDataSource Open Interest for crypto futures contracts on the Chicago Mercantile Exchange. Only available for BTC and ETH. deribit_implied_volatilityDataSource Implied volatility of ticker on Deribit. Available only for BTC and ETH coins. Returns tenors of 1W, 1M, and 3M. deribit_volatility_indexDataSource Measure of implied or historical price volatility for a specific asset on Deribit. Limited to ETH and BTC coins. Returns OHLC data. etf_flowDataSource Net inflow or outflow of capital into an ETF. Only available on 1D intervals. etf_holdingDataSource Asset balance held by major ETFs. Available for BTC, ETH, and SOL based ETFs. etf_premium_rateDataSource Compares market price of an ETF with its net asset value (NAV). Available for BTC, ETH, and SOL based ETFs. ethena_positionsDataSource Amount of collateral within the Ethena protocol. funding_rateDataSource Funding rate aggregation data from derivatives markets. liquidationsDataSource Liquidation aggregation data from derivatives markets. long_short_ratioDataSource Overall ratio of long to short positions across all traders. Available for Binance, Bybit, and OKX. ohlcvDataSource Open, High, Low, Close, Volume data from trade aggregations. open_interestDataSource Open interest aggregation data from derivatives markets. options_volumeDataSource Puts and calls for a particular coin from Binance Options or Deribit based on volume. Limited to ETH and BTC coins. options_open_interestDataSource Puts and calls for a particular coin from Binance Options or Deribit based on open interest. Limited to ETH and BTC coins. orderbookDataSource Orderbook heatmap snapshot aggregation data. skewDataSource Percentage difference in implied volatility between call and put options for a specific ticker on Deribit. Limited to BTC and ETH. volume_profileDataSource Per-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
Keyword Purpose 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 versioningfor ... in / ofCollection iteration (loops )
Function Categories
Explore technical indicators, mathematical functions, and utilities organized by category.
Category Description Functions Moving Averages Trend-following indicators that smooth price data. sma, ema, alma, swma, rmaOscillators Momentum indicators that fluctuate between bounded values. rsi, wpr, cmo, tsi, cci, stochasticVolume Indicators Indicators that incorporate volume data in their calculations. mfi, obvVolume Profile Accessors that extract scalar series from a volume_profile source. vpBuy, vpSell, vpDelta, vpTotal, vpPoc, vpPocVolume, vpBucketCount, vpPriceHigh, vpPriceLowTrend Indicators Indicators that help identify trend direction and strength. adx, macd, ichimoku, psarUtility Functions Helper functions for statistical calculations and data manipulation. lowest, highest, sum, stddev, donchian, crossover, crossunder, cross, isnan, isnumPlotting & Visualization Functions for rendering data on charts. plot, plotLine, plotBar, plotHistogram, plotCandle, plotShape, plotBatches, plotPie, plotText, plotLabel, plotTable, plotRange, hline, plotBgColorScript Definition Functions for defining script metadata and input parameters. define, input, source, print, printTimeSeriesColor Functions Functions for manipulating and transforming colors. brightness, darken, lighten, transparency, opacity, blend, colorGradientOrderbook Functions Functions for working with orderbook data. sumBids, sumAsks, maxBidAmount, maxAskAmount, minBidAmount, minAskAmountMath Functions JavaScript-style math constants and numerical helpers. math.abs, math.max, math.min, math.sqrt, math.powString Functions JavaScript-style string methods for text processing. split, concat, substring, toUpperCase, toLowerCase, trim, replace, indexOf, startsWith, endsWith, lengthLoops Control-flow patterns for repeated logic. for, while, break, continue
Popular Functions
Commonly used functions for quick access and reference.
Function Category Signature Description smaMoving Averages sma(source, period?, priceIndex?)Simple Moving Average calculation. emaMoving Averages ema(source, period?, priceIndex?)Exponential Moving Average calculation. rsiOscillators rsi(source, period?, priceIndex?)Relative Strength Index oscillator. plotPlotting & Visualization plot(value, plotType?, width?, colors?, colorIndex?, fill?, smooth?, showPriceDisplay?, label?, desc?)Universal plotting function for all visualization types.
Function Quick Lookup
Moving averages
Function Signature Returns smasma(source, period?, priceIndex?)numberemaema(source, period?, priceIndex?)numberalmaalma(source, length, offset?, sigma?)numberswmaswma(source)numberrmarma(source, period?, priceIndex?)number (legacy recurrence, not Wilder)wmawma(source, period?, priceIndex?)numberhmahma(source, period?, priceIndex?)numbervwmavwma(source, period?, priceIndex?)number
Oscillators
Function Signature Returns rsirsi(source, period?, priceIndex?)number (Wilder, textbook seed)wprwpr(length, source)numbercmocmo(source, length)numbertsitsi(source, short, long)numberccicci(source, period?, constant?)numberstochasticstochastic(source, kPeriod?, kSmoothing?, dPeriod?)[%K, %D]stochstoch(periodK?, smoothK?, periodD?)%K/%D streamschangechange(source, n?, priceIndex?)numberrocroc(source, n?, priceIndex?)numbermommom(source, n?, priceIndex?)numbermfimfi(source, period?)number
Trend indicators
Function Signature Returns 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?)numbersupertrendsupertrend(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)numberhl2hl2(source?)numberhlc3hlc3(source?)numberohlc4ohlc4(source?)numberhlcc4hlcc4(source?)numberatratr(period?, source?)numberstdevstdev(source, period?, priceIndex?)numbervariancevariance(source, period?, priceIndex?)number
Volume indicators
Function Signature Returns mfimfi(source, period?)numberobvobv(source)numbervwapvwap(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.
Orderbook functions
All take (source, depthPct?) where depthPct defaults to 10.
Function Signature Returns 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
Function Signature Returns lowestlowest(source, period?, priceIndex?)numberhighesthighest(source, period?, priceIndex?)numbersumsum(source, period?, priceIndex?)numberpivothighpivothigh(source, leftbars, rightbars, priceIndex)numberpivotlowpivotlow(source, leftbars, rightbars, priceIndex)numberstddevstddev(source, period?, priceIndex?)numberdonchiandonchian(source, period?)numbercrossovercrossover(A, B)booleancrossundercrossunder(A, B)booleancrosscross(A, B)booleanisnanisnan(value)booleanisnumisnum(value)boolean
Plotting
Function Signature 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)
Function Signature Notes 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 objects line.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
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
Method Signature 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
Construct Form if/else if (cond) { ... } else { ... }for for (var i = 0; i < n; i = i + 1) { ... }while while (cond) { ... }
Timeseries helpers
Function Signature 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.