Custom indicators

Write your own indicators in the script editor.

Overview

A CandL indicator is a short JavaScript script. It reads the chart’s candles, calculates with the ta library, and draws with functions such as plot(). Every built-in indicator is written the same way, so any built-in’s script is a working example you can open and read.

Scripts run in a separate, sandboxed worker in your browser. They can’t reach the network, the page or your data, and they’re stored in your browser with the rest of your workspace.

The editor

Open Indicators in the top bar and choose the Custom tab.

  • My scripts lists your saved scripts. New starts one from a simple moving average.
  • Name and On chart / New pane set what the indicator is called and where it draws.
  • Changes preview on the chart as you type. The status line under the code shows what the script draws, or its error and where it is: Line 12, column 4: foo is not defined. The code has line numbers; the line with the mistake is marked beside its number and tinted, and clicking the message puts the cursor there.
  • Save keeps the script; Save & add also puts it on the chart. The bin deletes it.

On the chart, a custom indicator works like a built-in: its inputs appear in its settings, and Edit script in its legend row reopens it here.

Editing a built-in

Edit script in a built-in’s legend row opens its script, read-only at first.

  • Edit, then Save: your version replaces the original for every copy of that indicator in this workspace.
  • View diff shows your changes against the original.
  • Save as copy makes a custom script from it and leaves the built-in alone.
  • Revert to original deletes your edits and brings the original back exactly.
  • If a newer original ships after you edited one, CandL keeps running yours and lets you view the difference, revert to the new original, or keep yours.

Script structure

A script is the body of a strict-mode function. Optional header lines at the top describe it; inputs, calculations and drawing calls follow.

//@range 0 100
const length = input.int('length', 'Length', 14, { min: 1 })
const rsi = ta.rsi(close, length)
plot(rsi, { name: 'RSI', color: '#7E57C2' })
hline(70)
hline(30)
HeaderMeaning
//@range 0 100Fixes the pane’s scale to this range (lower then upper).
//@needs volumeThe indicator needs real volume data.
//@name Relative Strength IndexName (up to 80 characters).
//@short RSIShort name for the legend (up to 16 characters).
//@placement paneoverlay (on the price chart) or pane (its own pane).
//@category OscillatorsThe group it’s listed under.

In your own scripts the editor’s Name field and placement buttons set the name and placement, and //@range and //@needs volume apply. Built-in scripts set all of these in the header.

Inputs

Inputs become the indicator’s settings. Each takes a key first: an identifier of up to 40 letters, digits or underscores, unique within the script. Saved charts and templates store settings by key, so keep keys the same when you edit a script. A script can declare up to 64 inputs.

FunctionReturns
input.int(key, title, default, options?)A whole number. options: min, max, step, legend.
input.float(key, title, default, options?)A number. Same options.
input.bool(key, title, default, options?)true or false. Option: legend.
input.source(key, title, default?)A price series: 'close' (default), 'open', 'high', 'low', 'hl2', 'hlc3' or 'ohlc4'.
input.ma(key, title, default?)A moving-average type for ta.ma(): 'SMA' (default), 'EMA', 'SMMA (RMA)', 'WMA' or 'VWMA'.
input.select(key, title, choices, default?, options?)One of 1–32 short strings; the first is the default. Option: legend.

Numbers outside min/max are clamped. legend: false leaves the input out of the indicator’s label in the legend.

Series

Series are arrays with one value per bar, oldest first: close[0] is the oldest bar and close[bar_count - 1] the newest. Unlike some charting languages, an index counts from the start, not back from the current bar.

NameValue
open, high, low, closePrices.
volumeVolume.
buyVolumeTaker buy volume, where the market provides it (otherwise missing).
timeEach bar’s open time, in milliseconds since 1 January 1970 (UTC).
hl2, hlc3, ohlc4(high + low) / 2, (high + low + close) / 3, (open + high + low + close) / 4.
bar_countThe number of bars.

The price columns are Float64Arrays, where a missing value is NaN. Library functions return ordinary arrays, with null where there is no value yet (for example, before a moving average has enough bars). Everything that takes a series accepts either.

The ta library

Every series function returns an array the same length as its input. A missing input gives a missing output, and smoothed averages carry on across gaps rather than restarting. len is a number of bars.

FunctionReturns
ta.sma(src, len)Simple moving average.
ta.ema(src, len)Exponential moving average (α = 2 / (len + 1)), seeded with an SMA.
ta.rma(src, len)Wilder’s moving average (α = 1 / len), as used by RSI and ATR.
ta.wma(src, len)Linearly weighted moving average, newest bar heaviest.
ta.hma(src, len)Hull moving average.
ta.vwma(src, vol, len)Volume-weighted moving average.
ta.dema(src, len)Double exponential moving average.
ta.tema(src, len)Triple exponential moving average.
ta.alma(src, len, offset = 0.85, sigma = 6)Arnaud Legoux moving average.
ta.swma(src)Symmetrically weighted average of 4 bars (weights 1-2-2-1).
ta.linreg(src, len, offset = 0)Linear regression line through the last len values, read offset bars back.
ta.ma(type, src, len, vol?)A moving average by type name, as returned by input.ma(). VWMA uses vol.
ta.stdev(src, len)Standard deviation of the window (population).
ta.dev(src, len)Mean absolute deviation from the window’s average.
ta.median(src, len)Median of the window.
ta.highest(src, len)Highest value in the window.
ta.lowest(src, len)Lowest value in the window.
ta.highestbars(src, len)Offset to the highest value (0 or negative).
ta.lowestbars(src, len)Offset to the lowest value (0 or negative).
ta.sum(src, len)Rolling sum of the window.
ta.cum(src)Running total from the first bar.
ta.change(src, len = 1)The value minus the value len bars earlier.
ta.mom(src, len)Momentum: the value minus the value len bars earlier.
ta.roc(src, len)Rate of change, in percent, against len bars earlier.
ta.rsi(src, len)Relative Strength Index (0–100).
ta.stoch(src, high, low, len)Stochastic: where src sits in the window’s high–low range, 0–100.
ta.cci(src, len)Commodity Channel Index.
ta.cmo(src, len)Chande Momentum Oscillator.
ta.tsi(src, short, long)True Strength Index (−1 to 1).
ta.tr(high, low, close)True range.
ta.atr(high, low, close, len)Average true range.
ta.percentrank(src, len)Percentage of the previous len values at or below the current one.
ta.correlation(a, b, len)Correlation of two series over the window (−1 to 1).
ta.crossover(a, b)true on bars where a crosses above b.
ta.crossunder(a, b)true on bars where a crosses below b.
ta.rising(src, len)true where src rose on each of the last len bars.
ta.falling(src, len)true where src fell on each of the last len bars.
ta.barssince(cond)Bars since cond was last true.
ta.na(value)true if value is missing (not a finite number).
ta.nz(src, replacement = 0)The series with missing values replaced.
ta.cross(a, b)true on bars where a crosses b either way.
ta.valuewhen(cond, src, occurrence = 0)The value of src at the bar where cond was true, occurrence times ago (0 is the latest).
ta.variance(src, len)Variance of the window (population).
ta.macd(src, fast, slow, signal)MACD: { macd, signal, hist }, the fast average minus the slow one, an average of that line, and their difference.
ta.bb(src, len, mult = 2)Bollinger Bands: { basis, upper, lower }, a simple average and mult standard deviations either side of it.
ta.bbw(src, len, mult = 2)Bollinger bandwidth: (upper − lower) / basis.
ta.vwap()Volume-weighted average price over the loaded bars.
ta.mfi(len)Money Flow Index (0–100), from the chart’s high, low, close and volume.
ta.dmi(len, adxLen = len)Directional movement: { plus, minus, adx }.
ta.adx(len)Average Directional Index, the trend’s strength (0–100).
ta.supertrend(len, mult)SuperTrend: { supertrend, direction }, a trailing line from the average true range, and 1 for up or −1 for down.
ta.obv()On-balance volume.
ta.psar(start = 0.02, step = 0.02, max = 0.2)Parabolic SAR.
ta.pivothigh(left, right)The price of a high that is the highest of left bars before and right after, on the bar that confirms it (right bars later).
ta.pivotlow(left, right)The same for a low.

The functions that take no price series (vwap, mfi, dmi, adx, supertrend, obv, psar, pivothigh, pivotlow) work on the chart’s own bars. So do tr(), atr(len) and vwma(src, len) when called without the series the first forms above take.

Math and missing values

  • math is JavaScript’s Math: math.max, math.abs, math.sqrt, math.log and the rest, with math.avg(a, b, …), math.pi and math.e.
  • array totals a whole series, skipping the bars with no value (the ta functions are the rolling ones): array.sum, avg, max, min, first, last, get(series, i) and size.
  • str works with text: str.format('{0} at {1}', name, price), tostring, tonumber, length, contains, startsWith, endsWith, replace_all, split, upper and lower.
  • na(value) and nz(series, replacement) are the same as ta.na and ta.nz.
  • sma, ema, wma, highest, lowest and change also work without ta., as in early scripts.
  • Standard JavaScript works as usual: Array.from, map, loops and so on.

Plots and fills

Values that are missing are simply not drawn.

FunctionDraws
plot(series, options?)A series. style: 'line' (default), 'stepline', 'circles', 'cross', 'columns' or 'histogram'.
histogram(series, options?)Bars from zero. upColor colors bars at or above zero and downColor those below; both default to color.
fill(series, fillTo, options?)The area between two series. fillOpacity: 0–1 (default 0.15).
hline(value, options?)A horizontal level. dash: 'dashed' (default), 'solid' or 'dotted'.
bgfill(from, to, options?)A shaded band between two levels. opacity: 0–1 (default 0.1).
barcolor(colors, options?)Recolors the candles: one color per bar, null to keep a candle’s own.
bgcolor(colors)Tints the background behind each bar: one color per bar (use a see-through one), null for none. Several calls add up, the last color given for a bar winning.

Options for plot, histogram and fill:

  • name: shown in the legend and settings (up to 60 characters).
  • color: see Colors. colors: an array with a color per bar.
  • lineWidth: 0.5–8 (default 1.5) for lines, step lines and crosses. lineStyle: 'dashed' or 'dotted' for lines and step lines.
  • offset: shifts the plot by up to 500 bars; a positive offset draws past the last bar.

hline also takes name and color; bgfill takes color.

Markers, lines, labels and boxes

Positions are bar indexes (as in close[i]) and prices. Indexes may run up to 500 bars past either end of the data.

FunctionOptions
plotshape(condition, options?)A marker on every bar where condition is true. location: 'abovebar' (default), 'belowbar' or 'absolute' (at price, a series); 'above' and 'below' work too. Plus the marker options below.
plotchar(condition, options?)A character on every bar where condition is true: char (one or two characters, default ●), location ('above', the default, or 'below'), color, text.
plotarrow(series, options?)An up arrow above each bar where series is over zero and a down arrow below each where it’s under. colorup, colordown.
marker(index, options?)position: 'above' (default), 'below' or 'price' (with price). shape, color, text (up to 40 characters), textColor.
line(i1, p1, i2, p2, options?)color, width (0.5–6), dash ('solid', 'dashed', 'dotted'), extend ('none', 'left', 'right', 'both').
label(index, price, text, options?)color, textColor, anchor ('above', 'below', 'center', 'left', 'right'). Text up to 200 characters.
box(i1, p1, i2, p2, options?)border, fill, fillOpacity (0–1), text (up to 80 characters), textColor.

Marker shapes: 'triangleUp', 'triangleDown', 'arrowUp', 'arrowDown', 'circle', 'cross', 'diamond', 'square', 'flag', 'labelUp', 'labelDown'. The earlier editor’s all-lowercase spellings work too: 'triangleup', 'arrowdown', 'xcross' and so on.

Colors

Any of: hex ('#7E57C2', with an optional alpha like '#7E57C280'), rgb(), rgba(), hsl(), hsla(), or a color name such as 'orange'. Anything else falls back to the default color.

color makes them, with a transparency from 0 (solid) to 100 (clear): color.new('#089981', 50), color.rgb(8, 153, 129, 50), and color.from_gradient(value, min, max, color1, color2) for the color between two as value goes from min to max. Named colors are there too: color.red, color.green, color.blue, color.orange, color.gray and the rest.

Other markets and time frames

request(symbol, interval, field) reads another market, or the same market on another time frame, and returns a series lined up with the chart’s bars, so it can be used like close.

ArgumentMeaning
symbolA market, such as 'ETHUSDT', from the chart’s market source. 'Binance Spot:ETHUSDT' names another source, as the source menu does. Empty or left out: the chart’s own market.
intervalA time frame such as '5m', '1H', '4H', '1D' or '1W'. Empty or left out: the chart’s own.
field'close' (default), 'open', 'high', 'low', 'volume', 'hl2', 'hlc3' or 'ohlc4'.
  • The series is lined up bar by bar, and never from the future: a value counts from the moment its bar has closed. A daily value on an hourly chart holds through the day and changes when the day closes; on the chart’s own time frame each bar has the other market’s bar.
  • On a lower time frame than the chart’s, each bar gets the last of the lower bars that had closed by its end.
  • The data comes through the same data service as the charts. A market that can’t be loaded, or isn’t one, leaves gaps and says why in the indicator’s legend.
  • A script can ask for up to 5 different markets or time frames. The same request twice counts once.

Strategies

A script that places orders is a strategy. CandL simulates it bar by bar over the chart’s bars, draws its trades and reports how it did.

FunctionDoes
strategy.position(options)The starting values of the settings: initialCapital (10,000), defaultQty (the order size, 1), qtyType ('fixed' units, or 'percentEquity' to size an order as a percent of equity), pyramiding (how many entries with one name may be open, 1), commission and slippage (0).
strategy.entry(id, options)Opens a position named id on every bar where when is true: { direction: 'long' or 'short', when, qty? }. qty sets this order’s size.
strategy.exit(id, options)Closes position id on a signal (when), at a stop or a limit price (a number, or a series with a price for each bar), or with a trailing stop (a distance in price). qty closes only a part.
strategy.close(id?, when?)Closes position id (every position, if left out) when when is true; without when, at the last bar’s close.
  • An order made on bar i fills at the open of bar i + 1, so nothing is decided with data it couldn’t have had. An order on the last bar can’t fill.
  • A stop or a target fills inside the bar at its price, or at the open if the bar gapped through it; if one bar reaches both, the stop wins. They start the bar after the entry. Given as a series, bar i is tested against its value for bar i − 1, the level known when bar i opened.
  • Commission is a cost for each unit on each side of a trade, in price terms. Slippage is a price given up against you on every fill.
  • The settings are inputs of the strategy, in its settings: Starting capital, Order size, Commission and Slippage. What strategy.position says is their starting value, and they’re kept with the indicator like its other inputs.
  • On the chart each entry and exit is an arrow with its price (green for a long entry, red for a short one, grey for an exit), and a trade still open has a dashed line from its entry.
  • Strategies run on the bars the chart has, and again as Replay plays them.

The report is a panel under the chart. It opens when you add a strategy, and from Report in the strategy’s legend row; × closes it. Overview has net profit, the number of trades, win rate, profit factor and the largest drawdown, then the settings it ran with and more figures (averages, streaks, Sharpe and Sortino ratios). List of trades has every trade, the newest first: entry, exit, size, profit, bars held and what closed it.

Alerts from a script

alertcondition(condition, title, message) names a moment a script cares about. condition is a series of true and false values, one for each bar (ta.crossover(fast, slow) is one); title is what Create alert lists it as; message is what the alert says when it goes off, unless the alert has a message of its own. A script may raise up to 8 conditions with different titles. alert(condition, message), the earlier editor’s name for it, does the same.

//@name Average cross
const fast = ta.sma(close, 9)
const slow = ta.sma(close, 21)
plot(fast, { name: 'Fast' })
plot(slow, { name: 'Slow' })
alertcondition(ta.crossover(fast, slow), 'Fast crossed up', 'The fast average crossed above the slow one')
alertcondition(ta.crossunder(fast, slow), 'Fast crossed down', 'The fast average crossed below the slow one')
  • Create alert (Alt+A, or on a phone New alert) lists the script beside the price, and its conditions by their titles. Its trigger, expiration, message and notifications are the ones of any alert.
  • The alert goes off when the condition turns true on a bar. A new bar starts afresh, so a condition that is true on every bar goes off on every bar, and one that stays true through a bar goes off once in it. Once only switches the alert off after the first; Once per bar lets one go off in each bar; Once per bar close waits for the bar to close and goes off if the condition was true on it; Every time goes off each time the condition turns true again, even within a bar. An alert never goes off for what was already true when it was made.
  • The alert keeps the script as it was when you made it, with the inputs it ran with. It goes on if you change the script, switch the indicator off or take it off the chart, and it can be edited (trigger, expiration, message, notifications), but not made to watch another condition.
  • Your browser runs it while CandL is open, on the bars of its market and time frame. It can read other markets with request() too. It stays in the browser you made it in: it isn’t kept with your account.
  • A strategy also offers Order fills: the alert goes off at each bar where one of its orders filled, and says what filled and the position after it, as in “Average cross: order buy @ 1 filled on BTCUSDT. New strategy position is 1”. It starts as Every time.

Scripts from the earlier editor

Scripts written in CandL’s earlier script editor run here as they were. Newer scripts are written the way this page describes, and these forms work as well:

  • input.int('Length', 14, { min: 1 }) and input.float: the label first, then the default. The label is the title and, as far as it is an identifier, the key.
  • The header lines // @name … and // @pane overlay (or pane).
  • close.map(fn) on a price series gives an ordinary array, in which a null stays a gap.
  • ta.atr(14), ta.tr() and ta.vwma(src, 20) on the chart’s own bars.
  • plotHistogram, the same as histogram, and these helpers: hist(series, n) (the series n bars back), scan(series, fn, init) (a running value), fold(series, fn, init) (its last value), iff(cond, a, b) (a choice for each bar), bar_index and barstate.isfirst / barstate.islast.
  • Its options: a color for each bar given as color (an array, here colors), a fill’s opacity, a line’s dashed: true, a box’s color, background and opacity, and a label’s background with color for its text. (Without a background, a label’s color is its tag’s, as on this page.)

Limits and errors

LimitValue
Time per run2 seconds. A slower script is stopped.
Script length40,000 characters
Inputs64
Plots, histograms and fills64
Levels (hline) and level fills (bgfill)32 each
Markers, lines, labels, boxes5,000, 2,000, 1,000 and 500
Different request()s5
Alert conditions (alertcondition)8
Trades in a strategy’s reportThe latest 5,000

Scripts can’t use the network, timers, import(), eval or the page. When a script throws an error or passes something invalid, the editor’s status line shows the message with its line and column, and the indicator draws nothing until the script is fixed. The mark goes when the next preview runs without the mistake.

A mistake found while the script runs, inside plot(), a ta.* call or an input, points at the line of your script that called it. Some browsers can’t say where a call into a built-in function was made; the message is shown without a line then. On the chart, an indicator whose script failed shows a red mark and the same message in its legend row.

Examples

Moving average cross

On the chart. Marks where the fast average crosses the slow one.

const fastLength = input.int('fast', 'Fast length', 9, { min: 1 })
const slowLength = input.int('slow', 'Slow length', 21, { min: 1 })
const type = input.ma('type', 'Average', 'EMA')

const fast = ta.ma(type, close, fastLength, volume)
const slow = ta.ma(type, close, slowLength, volume)

plot(fast, { name: 'Fast', color: '#2962FF' })
plot(slow, { name: 'Slow', color: '#FF6D00' })
plotshape(ta.crossover(fast, slow), { location: 'belowbar', shape: 'triangleUp', color: '#26A69A' })
plotshape(ta.crossunder(fast, slow), { location: 'abovebar', shape: 'triangleDown', color: '#EF5350' })

Oscillator in its own pane

Choose New pane. The scale is fixed from 0 to 100.

//@range 0 100
const length = input.int('length', 'Length', 14, { min: 1 })
const source = input.source('source', 'Source', 'close')

const rsi = ta.rsi(source, length)

plot(rsi, { name: 'RSI', color: '#7E57C2' })
hline(70, { name: 'Overbought', color: '#787B86' })
hline(30, { name: 'Oversold', color: '#787B86' })
bgfill(70, 30, { color: '#7E57C2', opacity: 0.08 })

Bands with a fill

On the chart. An average with bands a set number of standard deviations away.

const length = input.int('length', 'Length', 20, { min: 1 })
const width = input.float('width', 'Width', 2, { min: 0.1, step: 0.1 })

const basis = ta.sma(close, length)
const deviation = ta.stdev(close, length)
const upper = basis.map((value, i) => (value === null || deviation[i] === null ? null : value + width * deviation[i]))
const lower = basis.map((value, i) => (value === null || deviation[i] === null ? null : value - width * deviation[i]))

plot(basis, { name: 'Basis', color: '#FF6D00' })
plot(upper, { name: 'Upper', color: '#2962FF' })
plot(lower, { name: 'Lower', color: '#2962FF' })
fill(upper, lower, { name: 'Band', color: '#2962FF', fillOpacity: 0.1 })

Another market on the chart

//@name BTC against ETH
//@placement pane
const eth = request('ETHUSDT', '', 'close')
plot(close.map((c, i) => (eth[i] ? c / eth[i] : null)), { name: 'BTC / ETH', color: '#F7931A' })

A strategy

//@name Moving average cross strategy
//@placement overlay
const fastLength = input.int('fast', 'Fast', 10, { min: 1 })
const slowLength = input.int('slow', 'Slow', 30, { min: 1 })
const fast = ta.sma(close, fastLength)
const slow = ta.sma(close, slowLength)
strategy.position({ initialCapital: 10000, defaultQty: 1 })
strategy.entry('long', { direction: 'long', when: ta.crossover(fast, slow) })
strategy.close('long', ta.crossunder(fast, slow))
plot(fast, { name: 'Fast', color: '#2962FF' })
plot(slow, { name: 'Slow', color: '#FF6D00' })

A strategy with a stop and a target

//@name Cross with stop and target
//@placement overlay
const atr = ta.atr(14)
const fast = ta.ema(close, 9)
const slow = ta.ema(close, 21)
strategy.entry('long', { direction: 'long', when: ta.crossover(fast, slow) })
strategy.exit('long', {
  stop: close.map((c, i) => (atr[i] === null ? null : c - 2 * atr[i])),
  limit: close.map((c, i) => (atr[i] === null ? null : c + 4 * atr[i])),
})
plot(fast, { name: 'Fast' })
plot(slow, { name: 'Slow' })

Volume colored by candle

Choose New pane. Green where the candle closed up, red where it closed down.

//@needs volume
const colors = Array.from(close, (value, i) => (value >= open[i] ? '#26A69A' : '#EF5350'))

plot(volume, { name: 'Volume', style: 'columns', colors })