---
title: Reference
description: >-
  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

| Variable | Type | Description |
| --- | --- | --- |
| `currentSymbol` | string | The current trading symbol (e.g., `'BTCUSDT'`) |
| `currentExchange` | string | The current exchange being used for trading (e.g., `'BINANCE'`, `'COINBASE'`) |
| `currentCoin` | string | The current trading coin (e.g., `"BTC"`) |
| `barIndex` | number | Current bar index in the timeseries during the per-bar loop. |
| `isLastBar` | boolean | True when processing the last bar in the dataset. |
| `isLiveUpdate` | boolean | True during live data updates with new market data. |
| `color` | color | The color to use for plotting (e.g., `'red'`, `'blue'`) |

### Color Constants

| Constant | Type | Description |
| --- | --- | --- |
| `yellow` | color | Yellow color (`#FFFF00`) |
| `orange` | color | Orange color (`#FFA500`) |
| `purple` | color | Purple color (`#800080`) |
| `gray` | color | Gray color (`#808080`) |
| `black` | color | Black color (`#000000`) |
| `white` | color | White color (`#FFFFFF`) |
| `red` | color | Red color (`#FF0000`) |
| `green` | color | Green color (`#008000`) |
| `blue` | color | Blue color (`#0000FF`) |
| `silver` | color | Silver color (`#C0C0C0`) |
| `maroon` | color | Maroon color (`#800000`) |
| `fuchsia` | color | Fuchsia color (`#FF00FF`) |
| `lime` | color | Lime color (`#00FF00`) |
| `olive` | color | Olive color (`#808000`) |
| `navy` | color | Navy color (`#000080`) |
| `teal` | color | Teal color (`#008080`) |
| `aqua` | color | Aqua color (`#00FFFF`) |

### Data Types

| Type | Description |
| --- | --- |
| `timeseries` | Time-aligned numerical data. Only timeseries data can be passed into plot functions. |
| `ShapeType` | Shape type used by `plotShape()`. Currently supports `circle`. |
| `static` | Variable that gets declared once and persists across bar iterations. |

### Data Sources

| Data Source | Type | Description |
| --- | --- | --- |
| `binance_treasury_balance` | DataSource | Value of asset held by Binance. Updated monthly. Available for BTC, ETH, SOL, USDT, and USDC. |
| `buy_sell_volume` | DataSource | Buy/sell volume from trade data. |
| `cme_oi` | DataSource | Open Interest for crypto futures contracts on the Chicago Mercantile Exchange. Only available for BTC and ETH. |
| `deribit_implied_volatility` | DataSource | Implied volatility of ticker on Deribit. Available only for BTC and ETH coins. Returns tenors of 1W, 1M, and 3M. |
| `deribit_volatility_index` | DataSource | Measure of implied or historical price volatility for a specific asset on Deribit. Limited to ETH and BTC coins. Returns OHLC data. |
| `etf_flow` | DataSource | Net inflow or outflow of capital into an ETF. Only available on 1D intervals. |
| `etf_holding` | DataSource | Asset balance held by major ETFs. Available for BTC, ETH, and SOL based ETFs. |
| `etf_premium_rate` | DataSource | Compares market price of an ETF with its net asset value (NAV). Available for BTC, ETH, and SOL based ETFs. |
| `ethena_positions` | DataSource | Amount of collateral within the Ethena protocol. |
| `funding_rate` | DataSource | Funding rate aggregation data from derivatives markets. |
| `liquidations` | DataSource | Liquidation aggregation data from derivatives markets. |
| `long_short_ratio` | DataSource | Overall ratio of long to short positions across all traders. Available for Binance, Bybit, and OKX. |
| `ohlcv` | DataSource | Open, High, Low, Close, Volume data from trade aggregations. |
| `open_interest` | DataSource | Open interest aggregation data from derivatives markets. |
| `options_volume` | DataSource | Puts and calls for a particular coin from Binance Options or Deribit based on volume. Limited to ETH and BTC coins. |
| `options_open_interest` | DataSource | Puts and calls for a particular coin from Binance Options or Deribit based on open interest. Limited to ETH and BTC coins. |
| `orderbook` | DataSource | Orderbook heatmap snapshot aggregation data. |
| `skew` | DataSource | Percentage 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.

| Category | Description | Functions |
| --- | --- | --- |
| [Moving Averages](/kscript/functions/moving-averages) | Trend-following indicators that smooth price data. | `sma`, `ema`, `rma` |
| [Oscillators](/kscript/functions/oscillators) | Momentum indicators that fluctuate between bounded values. | `rsi`, `cci`, `stochastic` |
| [Volume Indicators](/kscript/functions/volume-indicators) | Indicators that incorporate volume data in their calculations. | `mfi`, `obv` |
| [Trend Indicators](/kscript/functions/trend-indicators) | Indicators that help identify trend direction and strength. | `adx`, `macd`, `ichimoku`, `psar` |
| [Utility Functions](/kscript/functions/utility-functions) | Helper functions for statistical calculations and data manipulation. | `lowest`, `highest`, `sum`, `stddev`, `donchian`, `crossover`, `crossunder`, `cross`, `isnan`, `isnum` |
| [Plotting & Visualization](/kscript/functions/plotting) | Functions for rendering data on charts. | `plot`, `plotLine`, `plotBar`, `plotCandle`, `plotShape`, `plotText`, `plotLabel`, `plotTable`, `plotRange`, `hline`, `plotBgColor` |
| [Script Definition](/kscript/functions/script-definition) | Functions for defining script metadata and input parameters. | `define`, `input`, `source`, `print`, `printTimeSeries` |
| [Color Functions](/kscript/functions/color-functions) | Functions for manipulating and transforming colors. | `brightness`, `darken`, `lighten`, `transparency`, `opacity`, `blend`, `colorGradient` |
| [Orderbook Functions](/kscript/functions/orderbook-functions) | Functions for working with orderbook data. | `sumBids`, `sumAsks`, `maxBidAmount`, `maxAskAmount`, `minBidAmount`, `minAskAmount` |
| [Math Functions](/kscript/functions/math-functions) | JavaScript-style math constants and numerical helpers. | `math.abs`, `math.max`, `math.min`, `math.sqrt`, `math.pow` |
| [String Functions](/kscript/functions/string-functions) | JavaScript-style string methods for text processing. | `split`, `concat`, `substring`, `toUpperCase`, `toLowerCase`, `trim`, `replace`, `indexOf`, `startsWith`, `endsWith`, `length` |
| [Loops](/kscript/functions/loops) | Control-flow patterns for repeated logic. | `for`, `while`, `break`, `continue` |

## Popular Functions

Commonly used functions for quick access and reference.

| Function | Category | Signature | Description |
| --- | --- | --- | --- |
| `sma` | Moving Averages | `sma(source, period?, priceIndex?)` | Simple Moving Average calculation. |
| `ema` | Moving Averages | `ema(source, period?, priceIndex?)` | Exponential Moving Average calculation. |
| `rsi` | Oscillators | `rsi(source, period?, priceIndex?)` | Relative Strength Index oscillator. |
| `plot` | Plotting & 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 |
| --- | --- | --- |
| [`sma`](/kscript/functions/moving-averages#sma) | `sma(source, period?, priceIndex?)` | `number` |
| [`ema`](/kscript/functions/moving-averages#ema) | `ema(source, period?, priceIndex?)` | `number` |
| [`rma`](/kscript/functions/moving-averages#rma) | `rma(source, period?, priceIndex?)` | `number` |

## Oscillators

| Function | Signature | Returns |
| --- | --- | --- |
| [`rsi`](/kscript/functions/oscillators#rsi) | `rsi(source, period?, priceIndex?)` | `number` |
| [`cci`](/kscript/functions/oscillators#cci) | `cci(source, period?, constant?)` | `number` |
| [`stochastic`](/kscript/functions/oscillators#stochastic) | `stochastic(source, kPeriod?, kSmoothing?, dPeriod?)` | `[%K, %D]` |

## Trend indicators

| Function | Signature | Returns |
| --- | --- | --- |
| [`adx`](/kscript/functions/trend-indicators#adx) | `adx(source, period?)` | `[ADX, DI+, DI-]` |
| [`macd`](/kscript/functions/trend-indicators#macd) | `macd(source, fastPeriod?, slowPeriod?, signalPeriod?)` | `[MACD, Signal, Histogram]` |
| [`ichimoku`](/kscript/functions/trend-indicators#ichimoku) | `ichimoku(source, conversionPeriod?, basePeriod?, laggingSpanPeriod?, displacement?)` | `[Tenkan, Kijun, SpanA, SpanB, Chikou]` |
| [`psar`](/kscript/functions/trend-indicators#psar) | `psar(source, start?, increment?, maxValue?)` | `number` |

## Volume indicators

| Function | Signature | Returns |
| --- | --- | --- |
| [`mfi`](/kscript/functions/volume-indicators#mfi) | `mfi(source, period?)` | `number` |
| [`obv`](/kscript/functions/volume-indicators#obv) | `obv(source)` | `number` |

## Orderbook functions

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

| Function | Signature | Returns |
| --- | --- | --- |
| [`sumBids`](/kscript/functions/orderbook-functions#sumbids) | `sumBids(source, depthPct?)` | total bid volume |
| [`sumAsks`](/kscript/functions/orderbook-functions#sumasks) | `sumAsks(source, depthPct?)` | total ask volume |
| [`maxBidAmount`](/kscript/functions/orderbook-functions#maxbidamount) | `maxBidAmount(source, depthPct?)` | largest bid order |
| [`maxAskAmount`](/kscript/functions/orderbook-functions#maxaskamount) | `maxAskAmount(source, depthPct?)` | largest ask order |
| [`minBidAmount`](/kscript/functions/orderbook-functions#minbidamount) | `minBidAmount(source, depthPct?)` | smallest bid order |
| [`minAskAmount`](/kscript/functions/orderbook-functions#minaskamount) | `minAskAmount(source, depthPct?)` | smallest ask order |

## Utility

| Function | Signature | Returns |
| --- | --- | --- |
| [`lowest`](/kscript/functions/utility-functions#lowest) | `lowest(source, period?, priceIndex?)` | `number` |
| [`highest`](/kscript/functions/utility-functions#highest) | `highest(source, period?, priceIndex?)` | `number` |
| [`sum`](/kscript/functions/utility-functions#sum) | `sum(source, period?, priceIndex?)` | `number` |
| [`stddev`](/kscript/functions/utility-functions#stddev) | `stddev(source, period?, priceIndex?)` | `number` |
| [`donchian`](/kscript/functions/utility-functions#donchian) | `donchian(source, period?)` | `number` |
| [`crossover`](/kscript/functions/utility-functions#crossover) | `crossover(A, B)` | `boolean` |
| [`crossunder`](/kscript/functions/utility-functions#crossunder) | `crossunder(A, B)` | `boolean` |
| [`cross`](/kscript/functions/utility-functions#cross) | `cross(A, B)` | `boolean` |
| [`isnan`](/kscript/functions/utility-functions#isnan) | `isnan(value)` | `boolean` |
| [`isnum`](/kscript/functions/utility-functions#isnum) | `isnum(value)` | `boolean` |

## Plotting

| Function | Signature |
| --- | --- |
| [`plot`](/kscript/functions/plotting#plot) | `plot(value, plotType?, width?, colors?, colorIndex?, fill?, smooth?, showPriceDisplay?, label?, desc?)` |
| [`plotLine`](/kscript/functions/plotting#plotline) | `plotLine(value, width?, colors?, colorIndex?, fill?, smooth?, showPriceDisplay?, label?, desc?)` |
| [`plotBar`](/kscript/functions/plotting#plotbar) | `plotBar(value, width?, colors?, colorIndex?, showPriceDisplay?, label?, desc?)` |
| [`plotCandle`](/kscript/functions/plotting#plotcandle) | `plotCandle(value, width?, colors?, colorIndex?, showPriceDisplay?, label?, desc?)` |
| [`plotShape`](/kscript/functions/plotting#plotshape) | `plotShape(value, shape, width?, colors?, colorIndex?, fill?, showPriceDisplay?, label?, desc?)` |
| [`plotText`](/kscript/functions/plotting#plottext) | `plotText(text, color, price, size?, xAlign?, yAlign?, fill?, backgroundColor?)` |
| [`plotLabel`](/kscript/functions/plotting#plotlabel) | `plotLabel(text, position?, x?, y?, color?, size?, xAlign?, yAlign?, fontFamily?, backgroundColor?)` |
| [`plotTable`](/kscript/functions/plotting#plottable) | `plotTable(data, position?, x?, y?, headerRow?, headerColumn?, ...styling)` |
| [`plotRange`](/kscript/functions/plotting#plotrange) | `plotRange(time1, price1, time2, price2, color, fillColor)` |
| [`hline`](/kscript/functions/plotting#hline) | `hline(value, color?, width?)` |
| [`plotBgColor`](/kscript/functions/plotting#plotbgcolor) | `plotBgColor(color, forceOnChart?)` |

## Color functions

| Function | Signature |
| --- | --- |
| [`brightness`](/kscript/functions/color-functions#brightness) | `brightness(color, amount)` |
| [`darken`](/kscript/functions/color-functions#darken) | `darken(color, amount)` |
| [`lighten`](/kscript/functions/color-functions#lighten) | `lighten(color, amount)` |
| [`transparency`](/kscript/functions/color-functions#transparency) | `transparency(color, amount)` |
| [`opacity`](/kscript/functions/color-functions#opacity) | `opacity(color, amount)` |
| [`blend`](/kscript/functions/color-functions#blend) | `blend(color1, color2, amount)` |
| [`colorGradient`](/kscript/functions/color-functions#colorgradient) | `colorGradient(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

| Method | Signature |
| --- | --- |
| `split` | `str.split(separator)` |
| `concat` | `str.concat(...strings)` |
| `substring` | `str.substring(start, end?)` |
| `toUpperCase` | `str.toUpperCase()` |
| `toLowerCase` | `str.toLowerCase()` |
| `trim` | `str.trim()` |
| `replace` | `str.replace(search, replaceWith)` |
| `indexOf` | `str.indexOf(searchValue)` |
| `startsWith` | `str.startsWith(prefix)` |
| `endsWith` | `str.endsWith(suffix)` |
| `length` | `str.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 |
| --- | --- |
| `buildTimeseries` | `buildTimeseries(srcTimeSeries, (bar, idx) => [...])` |
| `matchTimestamp` | `matchTimestamp(source, target, matchMode?)` |
| `timeseries` | `timeseries(arr, priceIndex)` |

## User functions

```kscript title="User Function Declaration" lines wrap
func myEma(source, period) {
  return ema(source, period, 4);
}
```

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