Candle Script language reference
Generated from the canonical @charting/candlescript registry, the same metadata that powers editor autocomplete and signature help. It updates automatically when the language surface changes.
New to Candle Script? Start with the quickstart guide, then use this page to look up signatures while writing in Script Lab.
189 callable functions across 23 namespaces, plus market sources, keywords, and diagnostic codes.
Market sources
Built-in OHLCV and composite price identifiers. History uses the @ operator (close@1). Do not redeclare these names.
| Name | Signature | Summary |
|---|---|---|
open | open | Reserved market-data source for the current bar. |
high | high | Reserved market-data source for the current bar. |
low | low | Reserved market-data source for the current bar. |
close | close | Reserved market-data source for the current bar. |
volume | volume | Reserved market-data source for the current bar. |
hl2 | hl2 | Reserved market-data source for the current bar. |
hlc3 | hlc3 | Reserved market-data source for the current bar. |
ohlc4 | ohlc4 | Reserved market-data source for the current bar. |
hlcc4 | hlcc4 | Reserved market-data source for the current bar. |
Keywords
Core language tokens. Use paint("Title", value) for output series.
| Name | Signature | Summary |
|---|---|---|
and | and | Reserved CandleScript keyword. |
as | as | Reserved CandleScript keyword. |
break | break | Reserved CandleScript keyword. |
by | by | Reserved CandleScript keyword. |
const | const | Reserved CandleScript keyword. |
continue | continue | Reserved CandleScript keyword. |
else | else | Reserved CandleScript keyword. |
enum | enum | Reserved CandleScript keyword. |
export | export | Reserved CandleScript keyword. |
false | false | Reserved CandleScript keyword. |
fn | fn | Reserved CandleScript keyword. |
for | for | Reserved CandleScript keyword. |
if | if | Reserved CandleScript keyword. |
import | import | Reserved CandleScript keyword. |
let | let | Reserved CandleScript keyword. |
not | not | Reserved CandleScript keyword. |
null | null | Reserved CandleScript keyword. |
or | or | Reserved CandleScript keyword. |
paint | paint | Reserved CandleScript keyword. |
persist | persist | Reserved CandleScript keyword. |
to | to | Reserved CandleScript keyword. |
true | true | Reserved CandleScript keyword. |
type | type | Reserved CandleScript keyword. |
array.*
Bounded arrays for rolling windows and lower-timeframe reads.
| Name | Signature | Summary |
|---|---|---|
array.sort | array.sort(array, order?) | Stable in-place numeric or UTF-16 lexical sort; returns the same array. Homogeneous finite numbers/strings only; order is "asc" (default) or "desc". |
array.sortIndices | array.sortIndices(array, order?) | Stable sorted indices without mutating the input; homogeneous finite numbers/strings, order "asc" (default) or "desc". |
array.binarySearch | array.binarySearch(array, value, order?) | First matching sorted index or -1. Validates order in O(n), then lower-bound search in O(log n); order "asc" (default) or "desc". |
array.lastIndexOf | array.lastIndexOf(array, value) | Last matching index using the same Object.is equality as array.indexOf; -1 when absent. |
array.contains | array.contains(array, value) | Whether array.indexOf finds the value, preserving its Object.is equality. |
array.new | array.new(size?, fill?) | Create a scalar array with an optional size and fill value. |
array.from | array.from(value...) | Create a scalar array from up to 64 values. |
array.size | array.size(array) | Number of items in an array. |
array.get | array.get(array, index) | Read a scalar item by zero-based index, or null when out of range. |
array.set | array.set(array, index, value) | Replace an existing scalar array item. |
array.push | array.push(array, value) | Append a scalar value and return the new size. |
array.unshift | array.unshift(array, value) | Prepend a scalar value and return the new size. |
array.pop | array.pop(array) | Remove and return the last item, or null when empty. |
array.shift | array.shift(array) | Remove and return the first item, or null when empty. |
array.clear | array.clear(array) | Remove all items from an array. |
array.min | array.min(array) | Minimum finite numeric value in an array. |
array.max | array.max(array) | Maximum finite numeric value in an array. |
array.sum | array.sum(array) | Sum of finite numeric values in an array. |
array.avg | array.avg(array) | Average of finite numeric values in an array. |
array.indexOf | array.indexOf(array, value) | Index of a scalar value, or -1 when absent. |
array.slice | array.slice(array, start, end?) | Copy a half-open scalar array range. |
avg.*
Moving averages and volume-weighted price.
| Name | Signature | Summary |
|---|---|---|
avg.exponentialRecursive | avg.exponentialRecursive(series, length, seed?) | Recursive EMA, alpha=2/(length+1). Seed "sma" (default) warms over length valid samples; "first" starts immediately. Missing samples return null without advancing; gaps/length changes reset. |
avg.wilder | avg.wilder(series, length) | Recursive Wilder smoothing, alpha=1/length, SMA-seeded over length valid samples. Missing samples return null without advancing; skipped bars/length changes reset. |
avg.simple | avg.simple(series, length) | Simple moving average of a series over the last `length` bars. |
avg.weighted | avg.weighted(series, length) | Linearly weighted moving average; the newest bar carries the largest weight. |
avg.hull | avg.hull(series, length) | Hull-style low-lag weighted average over `length` bars. |
avg.gaussian | avg.gaussian(series, length, sigma, forecast?) | RBF/Gaussian-kernel weighted average with optional forecast offset. |
avg.exponential | avg.exponential(series, length) | Exponential moving average over the trailing window (k = 2 / (length + 1)). |
avg.vwap | avg.vwap(price) | Session-anchored volume-weighted average of `price` (resets each UTC day). |
band.*
Rolling extremes, dispersion, and true range.
| Name | Signature | Summary |
|---|---|---|
band.averageTrueRangeWilder | band.averageTrueRangeWilder(length) | Call-isolated recursive Wilder ATR with length-sample SMA seed and first-bar high-low range. Repeated current-bar evaluations replace, never double-advance. |
band.pivotHigh | band.pivotHigh(series, left, right) | Confirmed pivot high emitted right bars after the candidate, requiring a full finite window. Nonnegative strengths; newest equal plateau wins. Never looks ahead. |
band.pivotLow | band.pivotLow(series, left, right) | Confirmed pivot low emitted right bars after the candidate, requiring a full finite window. Nonnegative strengths; newest equal plateau wins. Never looks ahead. |
band.highest | band.highest(series, length) | Highest value of a series over the last `length` bars. |
band.lowest | band.lowest(series, length) | Lowest value of a series over the last `length` bars. |
band.deviation | band.deviation(series, length) | Population standard deviation of a series over the last `length` bars. |
band.trueRange | band.trueRange() | Wilder true range of the current bar (high, low, prior close). |
band.averageTrueRange | band.averageTrueRange(length) | Wilder-smoothed average true range over `length` bars. |
bar.*
Current bar index, time, and confirmation state.
| Name | Signature | Summary |
|---|---|---|
bar.index | bar.index() | Zero-based index of the current bar. |
bar.count | bar.count() | Total number of bars in the current execution dataset. |
bar.time | bar.time() | Current bar open timestamp in milliseconds since Unix epoch. |
bar.timeClose | bar.timeClose() | Current bar close timestamp in milliseconds since Unix epoch when available. |
bar.isFirst | bar.isFirst() | True on the first processed bar. |
bar.isLast | bar.isLast() | True on the final processed bar. |
bar.isConfirmed | bar.isConfirmed() | True for historical/closed bars in CandleScript execution. |
bar.isLastConfirmedHistory | bar.isLastConfirmedHistory() | True on the final confirmed historical bar; with a realtime last bar, this is the penultimate bar. |
filter.*
Signal smoothing helpers.
| Name | Signature | Summary |
|---|---|---|
filter.kalman | filter.kalman(series, processNoise?, measurementNoise?) | One-dimensional Kalman smoother over a numeric series. |
filter.kahlmanGain | filter.kahlmanGain(series, gain?) | Pine-style Kahlman gain smoother (default gain 10000). |
map.*
String-keyed associative containers.
| Name | Signature | Summary |
|---|---|---|
map.new | map.new() | Create a string-keyed map for scalars, records, and draw handles. |
map.size | map.size(map) | Number of entries in a map. |
map.has | map.has(map, key) | Return true when a string key exists. |
map.get | map.get(map, key) | Read a map value by string key, or null when absent. |
map.set | map.set(map, key, value) | Set a string-keyed map value. |
map.delete | map.delete(map, key) | Delete a map entry and return whether it existed. |
map.clear | map.clear(map) | Remove all entries from a map. |
map.keys | map.keys(map) | Return map keys as an array. |
map.values | map.values(map) | Return map values as an array. |
matrix.*
Fixed-size numeric grids.
| Name | Signature | Summary |
|---|---|---|
matrix.transpose | matrix.transpose(matrix) | New transposed matrix; algebra requires non-empty rectangular finite numeric matrices and respects the cell budget. |
matrix.add | matrix.add(a, b) | New elementwise sum of equal-sized finite numeric matrices; never mutates inputs. |
matrix.subtract | matrix.subtract(a, b) | New elementwise a-b of equal-sized finite numeric matrices; never mutates inputs. |
matrix.multiply | matrix.multiply(a, b) | New matrix product, left columns must equal right rows. Finite numeric cells, bounded output cells and at most 1,000,000 multiply-adds. |
matrix.scale | matrix.scale(matrix, scalar) | New finite numeric matrix multiplied by a finite scalar; non-finite results are rejected. |
matrix.identity | matrix.identity(size) | New square identity matrix with positive integer size, subject to the matrix cell budget. |
matrix.inverse | matrix.inverse(matrix) | New inverse using scaled partial pivoting; bounded square finite matrices only. Singular or numerically ill-conditioned inputs fail explicitly. |
matrix.determinant | matrix.determinant(matrix) | Determinant using scaled partial pivoting; bounded square finite matrices, zero for singular inputs. Overflow fails explicitly. |
matrix.new | matrix.new(rows, cols, fill?) | Create a bounded matrix with an optional fill value. |
matrix.rows | matrix.rows(matrix) | Return the matrix row count. |
matrix.cols | matrix.cols(matrix) | Return the maximum matrix column count. |
matrix.get | matrix.get(matrix, row, col) | Read a matrix cell, or null when out of range. |
matrix.set | matrix.set(matrix, row, col, value) | Set an existing matrix cell. |
matrix.addRow | matrix.addRow(matrix, array) | Append a row from an array and return the new row count. |
matrix.addCol | matrix.addCol(matrix, array) | Append a column from an array and return the new column count. |
matrix.row | matrix.row(matrix, row) | Return a matrix row as an array. |
matrix.col | matrix.col(matrix, col) | Return a matrix column as an array. |
matrix.reshape | matrix.reshape(matrix, rows, cols, fill?) | Reshape a matrix in row-major order and return it. |
momentum.*
Change, rate, RSI, MACD, and stochastic helpers.
| Name | Signature | Summary |
|---|---|---|
momentum.relativeStrengthWilder | momentum.relativeStrengthWilder(series, length) | RSI from recursively Wilder-smoothed adjacent gains/losses; length valid changes warm up, missing pairs return null, flat=50, only gains=100, only losses=0. |
momentum.macdRecursive | momentum.macdRecursive(series, fastLength, slowLength) | Call-isolated fast-minus-slow recursive SMA-seeded EMAs, available after slowLength valid samples; fast must be less than slow. |
momentum.macdSignalRecursive | momentum.macdSignalRecursive(series, fastLength, slowLength, signalLength) | Recursive MACD signal EMA seeded from signalLength valid MACD lines, without legacy zero-prefilling; independent call-site and signal-length state. |
momentum.macdSpreadRecursive | momentum.macdSpreadRecursive(series, fastLength, slowLength, signalLength) | Recursive MACD line minus its valid-line-seeded signal; null until both are ready. |
momentum.macd | momentum.macd(series, fastLength, slowLength) | MACD line: fast EMA minus slow EMA of `series`. |
momentum.macdSignal | momentum.macdSignal(series, fastLength, slowLength, signalLength) | MACD signal line: EMA of the MACD line. |
momentum.macdSpread | momentum.macdSpread(series, fastLength, slowLength, signalLength) | MACD histogram: MACD line minus signal line. |
momentum.stochastic | momentum.stochastic(kLength) | Stochastic %K (0..100) from high/low/close over `kLength` bars. |
momentum.stochasticSmooth | momentum.stochasticSmooth(kLength, dLength) | Stochastic %D: simple average of %K over `dLength` bars. |
momentum.commodityChannel | momentum.commodityChannel(series, length) | Commodity Channel Index-style oscillator for the supplied series. |
momentum.change | momentum.change(series, length) | Difference between the current value and the value `length` bars ago. |
momentum.rate | momentum.rate(series, length) | Percentage rate of change versus the value `length` bars ago. |
momentum.relativeStrength | momentum.relativeStrength(series, length) | Relative strength index over the trailing window (0..100). |
num.*
Scalar numeric utilities.
| Name | Signature | Summary |
|---|---|---|
num.absolute | num.absolute(value) | Absolute value of a number. |
num.maximum | num.maximum(a, b) | Larger of two numbers. |
num.minimum | num.minimum(a, b) | Smaller of two numbers. |
num.coalesce | num.coalesce(value, fallback) | Return `value` when finite, otherwise `fallback`. |
num.round | num.round(value) | Round a number to the nearest integer. |
num.sqrt | num.sqrt(value) | Square root of a non-negative number. |
num.log | num.log(value) | Natural logarithm of a positive number. |
num.exp | num.exp(value) | Natural exponential function. |
num.power | num.power(base, exponent) | Raise `base` to `exponent`. |
num.floor | num.floor(value) | Round a number down to the nearest integer. |
num.ceil | num.ceil(value) | Round a number up to the nearest integer. |
num.sign | num.sign(value) | Return -1, 0, or 1 for the sign of `value`. |
num.clamp | num.clamp(value, min, max) | Clamp `value` to the inclusive [min, max] range. |
signal.*
Boolean crossover detectors.
| Name | Signature | Summary |
|---|---|---|
signal.valueWhen | signal.valueWhen(condition, value, occurrence) | Scalar value at the zero-based most recent true event (0=latest), null if absent. Retains occurrence+1 events and at most 16,384 text units; evaluate every bar. Skips/occurrence changes reset; same-bar calls replace. |
signal.crossOver | signal.crossOver(a, b) | True on the bar where series `a` rises above series `b`. |
signal.crossUnder | signal.crossUnder(a, b) | True on the bar where series `a` falls below series `b`. |
signal.crosses | signal.crosses(a, b) | True on the bar where series `a` crosses series `b` in either direction. |
signal.changed | signal.changed(series) | True when the current series value differs from the previous bar. |
signal.barsSince | signal.barsSince(condition) | Number of bars since `condition` was last true. |
time.*
Timestamps, calendar fields, sessions, and timeframe conversion.
| Name | Signature | Summary |
|---|---|---|
time.timestamp | time.timestamp(year, month, day, hour?, minute?) | Build a UTC timestamp in milliseconds since Unix epoch. |
time.year | time.year(timestamp, timezoneOffsetMinutes?) | UTC year for a timestamp after an optional minute offset. |
time.month | time.month(timestamp, timezoneOffsetMinutes?) | UTC month number (1-12) for a timestamp after an optional minute offset. |
time.dayOfMonth | time.dayOfMonth(timestamp, timezoneOffsetMinutes?) | UTC day of month for a timestamp after an optional minute offset. |
time.dayOfWeek | time.dayOfWeek(timestamp, timezoneOffsetMinutes?) | ISO day of week (Monday=1, Sunday=7) for a timestamp after an optional minute offset. |
time.hour | time.hour(timestamp, timezoneOffsetMinutes?) | Hour of day (0-23) for a timestamp after an optional minute offset. |
time.minute | time.minute(timestamp, timezoneOffsetMinutes?) | Minute of hour (0-59) for a timestamp after an optional minute offset. |
time.inSession | time.inSession(timestamp, "HHMM-HHMM", timezoneOffsetMinutes?) | True when a timestamp falls inside a daily session window. |
time.inNamedSession | time.inNamedSession(timestamp, "regular" | "premarket" | "postmarket" | "extended" | "crypto", timezoneOffsetMinutes?) | True when a timestamp falls inside a built-in named market session. |
time.inKillZone | time.inKillZone(timestamp, "asia" | "london" | "newyork", timezoneOffsetMinutes?) | True when a timestamp falls inside a common ICT-style kill-zone window. |
time.timeframeMinutes | time.timeframeMinutes("1H" | "1D" | minutes) | Convert a timeframe string or numeric input to minutes. |
ml.*
Machine-learning helpers (kNN, logistic probability, k-means).
| Name | Signature | Summary |
|---|---|---|
ml.knn2 | ml.knn2(featureA, featureB, label, neighbors, maxBarsBack) | Bounded two-feature nearest-neighbor vote over historical bars. |
ml.logisticProbability | ml.logisticProbability(series, target, length, learningRate, iterations) | Bounded single-feature logistic probability trained over a trailing window. |
ml.kmeans3Cluster | ml.kmeans3Cluster(series, length, highGuess, midGuess, lowGuess) | Cluster current volatility into high/medium/low buckets with bounded k-means. |
ml.kmeans3Centroid | ml.kmeans3Centroid(series, length, highGuess, midGuess, lowGuess) | Return the assigned centroid from bounded three-cluster k-means. |
osc.*
Oscillator-style transforms.
| Name | Signature | Summary |
|---|---|---|
osc.waveTrend | osc.waveTrend(series, channelLength, averageLength) | WaveTrend-style oscillator using streaming exponential smoothing. |
stats.*
Rolling statistical helpers.
| Name | Signature | Summary |
|---|---|---|
stats.covariance | stats.covariance(a, b, length, sample?) | Centered covariance of a complete finite paired window (length>=2); population denominator by default, length-1 when sample=true. Missing pairs return null. |
stats.correlation | stats.correlation(a, b, length) | Pearson correlation over a complete finite paired window (length>=2); null for incomplete windows or zero variance. |
stats.linearRegression | stats.linearRegression(series, length, offset?) | OLS fitted value at length-1-offset with oldest x=0. Full finite window, length>=2; offset defaults to 0, negative offsets extrapolate within the lookback budget. |
stats.regressionSlope | stats.regressionSlope(series, length) | OLS slope per bar over a full finite window (length>=2), oldest x=0. |
stats.regressionIntercept | stats.regressionIntercept(series, length) | OLS intercept at the oldest bar x=0 over a full finite window (length>=2). |
stats.mean | stats.mean(series, length) | Mean of a series over the trailing window. |
stats.sum | stats.sum(series, length) | Sum of a series over the trailing window. |
stats.percentile | stats.percentile(series, length, percentile) | Interpolated rolling percentile over a trailing window. |
stats.normalize | stats.normalize(series, length, min, max) | Min/max normalize the current series value over a trailing window. |
stats.meanAbsoluteError | stats.meanAbsoluteError(series, estimate, length) | Mean absolute error between two series over a trailing window. |
text.*
text.* standard-library helpers.
| Name | Signature | Summary |
|---|---|---|
text.number | text.number(value, decimals?, grouping?) | Fixed-decimal en-US number text; 0..16 decimals (default 2), optional comma grouping (default false); null input returns null. |
text.format | text.format(template, value...) | Substitute {0}..{15} scalar arguments; {{ and }} escape braces. No evaluation or format-language execution. Maximum template/result length 16,384 UTF-16 units. |
trend.*
Trend strength and supertrend utilities.
| Name | Signature | Summary |
|---|---|---|
trend.adxWilder | trend.adxWilder(length, smoothingLength?) | Wilder-smoothed DX of Wilder-smoothed range/directional movement. First bar contributes range and zero DM; first output at length+smoothingLength-2. Smoothing defaults to length. |
trend.plusDirectionalWilder | trend.plusDirectionalWilder(length) | Positive directional indicator from SMA-seeded Wilder range/DM smoothing; null during length-sample warmup, zero for zero range. |
trend.minusDirectionalWilder | trend.minusDirectionalWilder(length) | Negative directional indicator from SMA-seeded Wilder range/DM smoothing; null during length-sample warmup, zero for zero range. |
trend.adx | trend.adx(length) | Average Directional Index-style trend-strength reading. |
trend.supertrendLine | trend.supertrendLine(factor, atrValue) | SuperTrend line using a supplied ATR or volatility value. |
trend.supertrendDirection | trend.supertrendDirection(factor, atrValue) | SuperTrend direction using a supplied ATR or volatility value. |
input.*
Declare script settings; the platform builds the Inputs tab automatically.
| Name | Signature | Summary |
|---|---|---|
input.int | input.int("Label", default, min?, max?, options?) | Integer script input with optional min/max for the settings UI. Optional trailing record: group, inline, tooltip, min, max, step. |
input.float | input.float("Label", default, min?, max?, options?) | Floating-point script input with optional min/max. Optional trailing record: group, inline, tooltip, min, max, step. |
input.bool | input.bool("Label", default, options?) | Boolean checkbox input (Inputs tab in settings). Optional trailing record: group, inline, tooltip. |
input.styleBool | input.styleBool("Label", default, group?, options?) | Boolean checkbox shown on the Style tab (group: graphic | status). Optional trailing record: group, inline, tooltip. |
input.select | input.select("Label", default, option, ..., options?) | String choices with optional settings record; { control: "symbol" } opens the symbol picker. Optional trailing record: group, inline, tooltip. |
input.symbol | input.symbol("Label", defaultSymbol, options?) | Symbol selector input stored as a symbol identifier string. Optional trailing record: group, inline, tooltip. |
input.source | input.source("Label", default, options?) | Price source selector (hl2, close, hlc3, ohlc4, hlcc4). Optional trailing record: group, inline, tooltip. |
input.color | input.color("Label", defaultHex, options?) | Color picker input (hex string, e.g. "#2563eb"). Optional trailing record: group, inline, tooltip. |
input.timeframe | input.timeframe("Label", defaultMinutes, options?) | Chart timeframe input stored as resolution minutes (integer). Optional trailing record: group, inline, tooltip. |
input.session | input.session("Label", default, options?) | Trading session selector (regular, extended, all). Optional trailing record: group, inline, tooltip. |
context.*
Higher- and lower-timeframe reads when HTF/LTF bars are supplied to the runtime.
| Name | Signature | Summary |
|---|---|---|
context.heikinAshi | context.heikinAshi(symbol, timeframe, expression, mode?) | Evaluate on Heikin-Ashi OHLC calculated from authorized symbol history. Confirmed alignment; these are calculated values, never executable prices. |
context.symbol | context.symbol(symbol, timeframe, expression, mode?) | Evaluate an expression using explicitly supplied symbol history; defaults to confirmed data. |
context.atResolution | context.atResolution(source, minutes, mode?) | Read a market source from a higher-timeframe series aligned to the chart. Mode may be gaps_off, gaps_on, or lookahead_on. |
context.ohlc | context.ohlc(minutes) | Return [open, high, low, close] from an aligned higher-timeframe series. Use tuple destructuring. |
context.ohlcv | context.ohlcv(minutes) | Return [open, high, low, close, volume] from an aligned higher-timeframe series. Use tuple destructuring. |
context.security | context.security(minutes, expression, mode?) | Evaluate an expression on supplied higher-timeframe bars and align the result back to the chart. |
context.lower | context.lower(minutes, source) | Return an array of lower-timeframe source values contained by the current chart bar. |
state.*
Explicit bar-persistent and intrabar state with bounded primitive values.
| Name | Signature | Summary |
|---|---|---|
state.hold | state.hold(key, value) | Return named state initialized once per historical replay and retained across bars. |
state.set | state.set(key, value) | Set named state for subsequent statements and bars. |
state.intrabar | state.intrabar(key, value) | Return named tick state retained only within the current bar and execution session; not reproducible after reload. |
state.setIntrabar | state.setIntrabar(key, value) | Update tick state in the current bar; accepts a primitive value. |
paint.*
Chart output effects beyond the core paint("Name", value) line series.
| Name | Signature | Summary |
|---|---|---|
paint.fill | paint.fill(title, upperPaint, lowerPaint, opacity?) | Shade the area between two existing paint series. |
paint.marker | paint.marker(title, condition, style) | Draw a buy/sell marker when `condition` is true (`"buy"` or `"sell"`). |
paint.hline | paint.hline(title, price, color?) | Horizontal price level line across the chart. |
paint.bgcolor | paint.bgcolor(title, condition, color?) | Highlight the chart background on bars where `condition` is true. |
paint.shape | paint.shape(title, condition, style) | Draw a shape marker when `condition` is true (buy, sell, arrowup, arrowdown, circle, cross, diamond). |
paint.style | paint.style(title, style, color?, width?, pane?) | Style a paint series as line, area, histogram, columns, step, or linebreak; optional pane is "overlay" or "separate". |
paint.candleColor | paint.candleColor(title, condition, bodyColor, wickColor?) | Attach candle body/wick color metadata for bars where condition is true. |
draw.*
Persistent visual objects (lines, boxes, labels, tables) on the chart.
| Name | Signature | Summary |
|---|---|---|
draw.line | draw.line(x1, y1, x2, y2, color?, width?) | Create a line object and return a stable draw handle. |
draw.setLine | draw.setLine(handle, x1, y1, x2, y2) | Update a line object's endpoints. |
draw.box | draw.box(left, top, right, bottom, borderColor?, fillColor?) | Create a rectangular box object and return a stable draw handle. |
draw.setBox | draw.setBox(handle, left, top, right, bottom) | Update a box object's bounds. |
draw.label | draw.label(x, y, text, color?, textColor?) | Create a text label object and return a stable draw handle. |
draw.setLabel | draw.setLabel(handle, x, y, text) | Update a label object's location and text. |
draw.table | draw.table(anchor, rows, cols, bgcolor?, textColor?) | Create a dashboard table object and return a stable draw handle. |
draw.setTableCell | draw.setTableCell(handle, row, col, text, bgcolor?, textColor?) | Set a table cell's text and optional colors. |
draw.clearTable | draw.clearTable(handle) | Clear all populated cells on a table object. |
draw.setColor | draw.setColor(handle, color) | Update a visual object's primary color. |
draw.delete | draw.delete(handle) | Delete a visual object by handle. |
trade.*
Strategy intents for backtests and paper trading.
| Name | Signature | Summary |
|---|---|---|
trade.enter | trade.enter("long" | "short", condition, stopPrice?, takeProfit?, sizePercent?, options?) | Open a market position; optional risk/size values and an intrabar options record with id, trailOffset, or trailActivation. |
trade.exit | trade.exit("long" | "short", condition, percent?, options?) | Close all or part of a side; optional intrabar options.fromEntry links the exit to an entry ID. |
trade.entryLimit | trade.entryLimit("long" | "short", condition, limitPrice, stopPrice?, takeProfit?, sizePercent?, options?) | Open a limit-entry position when `condition` is true and the bar trades through the limit price. |
trade.entryStop | trade.entryStop("long" | "short", condition, stopEntryPrice, stopPrice?, takeProfit?, sizePercent?, options?) | Open a stop-entry position when `condition` is true and the bar trades through the entry stop price. |
trade.entryStopLimit | trade.entryStopLimit("long" | "short", condition, stopEntryPrice, limitPrice, stopPrice?, takeProfit?, sizePercent?, options?) | Stage a stop-limit entry that activates at the stop price and fills at the limit price. |
trade.cancel | trade.cancel("long" | "short", condition, options?) | Cancel pending entries for a side; optional intrabar options.id selects one pending entry ID. |
trade.positionSize | trade.positionSize("long" | "short") | Return the current script-side intended position size for a side. |
trade.openTrades | trade.openTrades("long" | "short") | Return the current script-side intended open trade count for a side. |
trade.closedTrades | trade.closedTrades("long" | "short") | Return the current script-side intended closed trade count for a side. |
alert.*
Alert conditions emitted from scripts.
| Name | Signature | Summary |
|---|---|---|
alert.condition | alert.condition(title, condition) | Register a named alert condition that is true on qualifying bars. |
Diagnostic codes
Stable compile-time and runtime error codes surfaced in Script Lab and the API.
| Name | Signature | Summary |
|---|---|---|
AS1001 | AS1001 | Unknown identifier |
AS1002 | AS1002 | Assignment to immutable const |
AS1003 | AS1003 | Invalid lookback offset |
AS1004 | AS1004 | Unknown standard-library function |
AS1005 | AS1005 | Prohibited compatibility syntax |
AS1006 | AS1006 | Syntax error |
AS1007 | AS1007 | Function arity mismatch |
AS1008 | AS1008 | Invalid namespace |
AS1009 | AS1009 | Reserved name |
AS1010 | AS1010 | Invalid trade intent |
AS2001 | AS2001 | Paint output is always null |
AS3001 | AS3001 | Sandbox budget exceeded |
Candle Script is a clean-room DSL, not Pine Script compatible. List built-ins programmatically through POST /v1/scripts/diagnostics in the REST API.