Script API reference

Every function, series and constant a script can use, with its parameters and an example. The code editor shows the same help when you hover a name, complete it or type its arguments. Generated from oakscriptjs 0.26.2.

Prices and bar values

Series of the chart's bars: one value per bar. Combine them with the Series methods and pass them to the functions.

bar_index

bar_index: Series

Index of each bar, as a Series: 0 on the oldest bar, then 1, 2... In a bar loop, c.i is the same number.

plotshape(bar_index.mod(10).eq(0), "Every 10 bars", { style: shape.circle });

close

close: Series

Closing price of each bar, as a Series (on the forming bar, the latest price). The usual source of indicators. In a bar loop, c.close is the value of the current bar.

plot(ta.sma(close, 20), "SMA");

high

high: Series

Highest price of each bar, as a Series. In a bar loop, c.high is the value of the current bar.

plot(ta.highest(high, 20), "20-bar high");

hl2

hl2: Series

Median price of each bar, (high + low) / 2, as a Series.

plot(ta.sma(hl2, 10), "Median SMA");

hlc3

hlc3: Series

Typical price of each bar, (high + low + close) / 3, as a Series.

plot(ta.sma(hlc3, 20), "Typical SMA");

hlcc4

hlcc4: Series

Weighted close of each bar, (high + low + close + close) / 4, as a Series.

plot(ta.ema(hlcc4, 20), "Weighted close EMA");

last_bar_index

last_bar_index: Series

Index of the last bar of the chart, the same on every bar, as a Series. In a bar loop, c.n - 1.

bgcolor(color.when(bar_index.gte(last_bar_index.sub(9)), color.new(color.blue, 90)), { title: "Last 10 bars" });

low

low: Series

Lowest price of each bar, as a Series. In a bar loop, c.low is the value of the current bar.

plot(ta.lowest(low, 20), "20-bar low");

ohlc4

ohlc4: Series

Average price of each bar, (open + high + low + close) / 4, as a Series.

plot(ohlc4, "OHLC average");

open

open: Series

Opening price of each bar, as a Series. In a bar loop, c.open is the value of the current bar.

const body = close.sub(open);
plot(body, "Body", { style: plot.style_columns });

time_tradingday

time_tradingday: Series

00:00 UTC of the trading day of each bar, in ms.

timenow

timenow: Series

The current time in ms, the same on every bar of a run (ChartContext.now).

volume

volume: Series

Traded volume of each bar, as a Series (NaN when the data has no volume). In a bar loop, c.volume.

plot(volume, "Volume", { style: plot.style_columns });

Series methods

Arithmetic, comparisons, logic and history on any Series: close.sub(open), close.gt(ta.sma(close, 20)), close.offset(1).

series.add()

series.add(other: number | Series): Series

Adds a Series or a number to this series, bar by bar (the + of two values). NaN on either side gives NaN.

other
Series or number to add.

Returns A Series of the sums.

const mid = high.add(low).div(2);

series.and()

series.and(other: number | Series): Series

Logical "and" of two conditions, bar by bar. A value is true when it is not 0 and not NaN.

other
The other condition: a Series or a number.

Returns A Series of 1 where both are true, 0 elsewhere.

const strongUp = close.gt(open).and(volume.gt(ta.sma(volume, 20)));

series.div()

series.div(other: number | Series): Series

Divides this series by a Series or a number, bar by bar (the / of two values). A division by 0 gives +/-Infinity (which na() treats as na), 0 / 0 and NaN on either side give NaN.

other
Series or number to divide by.

Returns A Series of the quotients.

const range = high.sub(low);
const ratio = range.gt(0).iff(close.sub(open).div(range), 0);

series.eq()

series.eq(other: number | Series): Series

Tests whether this series equals a Series or a number, bar by bar (a == b). Values closer than 1e-10 count as equal, and a NaN on either side gives 0 (false), never NaN.

other
Series or number to compare with.

Returns A Series of 1 where it is true, 0 where it is false.

const doji = close.eq(open);

series.get()

series.get(index: number): number

Reads the value of one bar by its position: 0 is the oldest bar, bar_index counts the same way. This is not the "bars back" of offset(): inside a bar loop, read the current bar with c.get(series) and earlier bars with c.get(series, k).

index
Bar position, 0 for the oldest bar.

Returns The value of that bar; NaN when there is no such bar.

const firstClose = close.get(0);

series.gt()

series.gt(other: number | Series): Series

Tests whether this series is above a Series or a number, bar by bar (a > b). Values closer than 1e-10 count as equal, and a NaN on either side gives 0 (false), never NaN.

other
Series or number to compare with.

Returns A Series of 1 where it is true, 0 where it is false.

const up = close.gt(open);

series.gte()

series.gte(other: number | Series): Series

Tests whether this series is above or equal to a Series or a number, bar by bar (a >= b). Values closer than 1e-10 count as equal, and a NaN on either side gives 0 (false), never NaN.

other
Series or number to compare with.

Returns A Series of 1 where it is true, 0 where it is false.

const atOrAbove = close.gte(ta.sma(close, 50));

series.iff()

series.iff(trueValue: number | Series, falseValue: number | Series): Series

Picks one of two values on each bar, with this series as the condition (the cond ? x : y of a series). The condition is true when it is not 0 and not NaN; 0 and NaN pick falseValue.

trueValue
Series or number used where the condition is true.
falseValue
Series or number used where the condition is false.

Returns A Series of the picked values.

const range = high.sub(low);
const ratio = range.gt(0).iff(close.sub(open).div(range), 0);
plot(ratio, "Body / range");

series.last()

series.last(): number

Reads the value of the newest bar.

Returns The value of the last bar; NaN when there are no bars.

const lastRsi = ta.rsi(close, 14).last();

series.length()

series.length(): number

Gives the number of bars of the series (a method, not a property).

Returns The number of bars.

const bars = close.length();

series.lt()

series.lt(other: number | Series): Series

Tests whether this series is below a Series or a number, bar by bar (a < b). Values closer than 1e-10 count as equal, and a NaN on either side gives 0 (false), never NaN.

other
Series or number to compare with.

Returns A Series of 1 where it is true, 0 where it is false.

const oversold = ta.rsi(close, 14).lt(30);

series.lte()

series.lte(other: number | Series): Series

Tests whether this series is below or equal to a Series or a number, bar by bar (a <= b). Values closer than 1e-10 count as equal, and a NaN on either side gives 0 (false), never NaN.

other
Series or number to compare with.

Returns A Series of 1 where it is true, 0 where it is false.

const atOrBelow = low.lte(ta.lowest(low, 20).offset(1));

series.materialize()

series.materialize(): Series

Computes the values now and returns a Series that stores them, without links to the series it was built from. Use it on a long chain of methods to compute it once and free the steps in between.

Returns A Series of the same values, stored.

const spread = high.sub(low).div(close).mul(100).materialize();

series.mod()

series.mod(other: number | Series): Series

Remainder of the division of this series by a Series or a number, bar by bar (the % of two values). The remainder has the sign of this series; a divisor of 0 and NaN on either side give NaN.

other
Series or number to divide by.

Returns A Series of the remainders.

const everyFifth = bar_index.mod(5).eq(0);

series.mul()

series.mul(other: number | Series): Series

Multiplies this series by a Series or a number, bar by bar (the * of two values). NaN on either side gives NaN.

other
Series or number to multiply by.

Returns A Series of the products.

const upper = ta.sma(close, 20).mul(1.02);

series.neg()

series.neg(): Series

Changes the sign of every value (the unary -). NaN stays NaN.

Returns A Series of the opposite values.

const drop = close.sub(close.offset(1)).neg();

series.neq()

series.neq(other: number | Series): Series

Tests whether this series differs from a Series or a number, bar by bar (a != b). Values closer than 1e-10 count as equal, and a NaN on either side gives 0 (false), never NaN.

other
Series or number to compare with.

Returns A Series of 1 where it is true, 0 where it is false.

const moved = close.neq(close.offset(1));

series.not()

series.not(): Series

Logical "not" of a condition, bar by bar: true (not 0, not NaN) becomes 0, and 0 or NaN becomes 1.

Returns A Series of 1 where this series is false, 0 where it is true.

const notUp = close.gt(open).not();

series.offset()

series.offset(offset: number): Series

Shifts the series back in time: on each bar, the value offset bars earlier (close.offset(1) is the previous close). The first offset bars, which have no earlier bar, get NaN.

offset
Number of bars back: 0 (the series itself) or more, a whole number. A series computed by the script can look back at most 5000 bars; the price series (close, high...) any number.

Returns A Series of the earlier values.

Throws RangeError when offset is negative (it would read a future bar); an error past 5000 bars.

const change = close.sub(close.offset(1));
const higherHigh = high.gt(high.offset(1));

series.or()

series.or(other: number | Series): Series

Logical "or" of two conditions, bar by bar. A value is true when it is not 0 and not NaN.

other
The other condition: a Series or a number.

Returns A Series of 1 where at least one is true, 0 elsewhere.

const extreme = ta.rsi(close, 14).gt(70).or(ta.rsi(close, 14).lt(30));

series.pow()

series.pow(exponent: number | Series): Series

Raises this series to a power, bar by bar (math.pow on a series). NaN on either side gives NaN; a negative base with a fractional exponent gives NaN.

exponent
Series or number exponent.

Returns A Series of this ** exponent.

const squared = close.sub(ta.sma(close, 20)).pow(2);

series.sub()

series.sub(other: number | Series): Series

Subtracts a Series or a number from this series, bar by bar (the - of two values). NaN on either side gives NaN.

other
Series or number to subtract.

Returns A Series of the differences.

const body = close.sub(open);

series.toArray()

series.toArray(): number[]

Gives the values of all the bars as a plain array, oldest bar first (NaN for na). The values are computed on the first read and kept until the bars change; the array is shared, so copy it before changing it.

Returns One number per bar, oldest first.

const values = ta.sma(close, 20).toArray();
const shifted = seriesOf(values.map((v) => v * 1.01));

series.toTimeValuePairs()

series.toTimeValuePairs(): { time: any; value: number; }[]

Gives the values as { time, value } points for a chart line, oldest first, leaving out the NaN bars.

Returns The points; time is the bar time, in the unit of the bars.

const points = ta.sma(close, 20).toTimeValuePairs();

Functions

Declarations, plots, alerts and helpers called without a namespace.

alertcondition()

alertcondition(condition: Series, title: string, message?: string): void

Declares a condition users can create an alert on (in the app's alert dialog). It does not send an alert itself.

condition
Series that is true (non-zero) on the bars where the alert fires.
title
Name of the condition in the alert dialog.
message
Default text of the alert. Default: the title.
const cross = ta.crossover(close, ta.sma(close, 50));
alertcondition(cross, "Price above SMA 50", "Close crossed above its 50-bar average");

barcolor()

barcolor(colors: string | string[], options?: { title?: string; editable?: boolean; }): void

Colours the chart's candles or bars, replacing their usual colours.

colors
One colour for every bar, or one per bar from color.when() (usual colour on an na entry).
options
title (default "Bar Color") and editable. Default: {}.
const trendUp = close.gt(ta.sma(close, 50));
barcolor(color.when(trendUp, color.green, color.red));

bgcolor()

bgcolor(colors: string | string[], options?: { offset?: number; title?: string; force_overlay?: boolean; editable?: boolean; }): void

Colours the background of the script's pane behind each bar.

colors
One colour for every bar, or one per bar from color.when() (no colour on an na entry).
options
offset (bars to move the colours by), title (default "Background Color"), force_overlay (true: colour the price chart's pane), editable. Default: {}.
const rsi = ta.rsi(close, 14);
bgcolor(color.when(rsi.gt(70), color.new(color.red, 85)));

dayofmonth()

dayofmonth(time: number, timezone?: string): number
dayofmonth(time: Series, timezone?: string): Series

The calendar field (year, month, day, hour...) of a time.

time
A time in UNIX milliseconds.
timezone
Time zone to read the time in: "America/New_York", "UTC+2"... Default: the exchange's.

Returns The calendar field of that time.

plot(dayofmonth(time, "UTC"), "Day of month");

The calendar field (year, month, day, hour...) of each time of a Series, e.g. year(time).

time
A Series of times in UNIX milliseconds, e.g. time.
timezone
Time zone to read the times in: "America/New_York", "UTC+2"... Default: the exchange's.

Returns Series of the calendar field of each time.

plot(dayofmonth(time, "UTC"), "Day of month");

defineEnum()

defineEnum<K extends string>(fields: Record<K, string>): { readonly [P in K]: EnumField; }

Makes an enum: a fixed set of named fields, each with a title, for a choice list (input.enum()) or a state with a few values. Fields compare with ===; field.name is the name, field.title and String(field) the title.

fields
An object of field names and titles, e.g. { sma: "Simple", ema: "Exponential" }; an empty title is the name.

Returns A frozen object with one EnumField per name.

const MaType = defineEnum({ sma: "Simple", ema: "Exponential" });
const maType = input.enum(MaType.sma, "Average");
plot(maType === MaType.ema ? ta.ema(close, 20) : ta.sma(close, 20), "MA");

eachBar()

eachBar(fn: (c: BarContext) => number | boolean | void): Series

Runs a function on every bar, oldest first, for logic that needs the bar's values one at a time (state, ifs, loops). The function reads the bar through c (c.close, c.get(series), c.get(series, 1) for one bar back) and returns the bar's value of the Series that eachBar gives back (na when it returns nothing).

fn
Called once per bar with the bar's context; returns a number (or true / false) for that bar.

Returns Series of the values the function returned.

const fast = ta.sma(close, 10);
let count = 0;
const streak = eachBar((c) => (count = c.get(close) > c.get(fast) ? count + 1 : 0));
plot(streak, "Bars above");

evaluateFormula()

evaluateFormula(text: string, variables?: FormulaVariables): number | Series

Like formula, but gives a number when the formula uses no Series ("length * 2").

text
The formula.
variables
Other names the formula can use: numbers or Series. Default: {}.

Returns A Series, or a number for a formula without Series.

const length = input.int(10, "Length");
const slow = evaluateFormula("length * 2", { length });

fill()

fill(a: PlotHandle, b: PlotHandle, options?: ScriptFillOptions): void
fill(a: PlotHandle, b: PlotHandle, color: ScriptFillColor, title?: string, ...rest: unknown[]): void
fill(a: PlotHandle, b: PlotHandle, top_value: ScriptFillValue, bottom_value: ScriptFillValue, top_color: ScriptFillColor, bottom_color: ScriptFillColor, title?: string, ...rest: unknown[]): void

Colours the space between two plots or two hlines, with an options object.

a
First plot or hline (the handle plot() / hline() returned).
b
Second plot or hline, of the same kind as a.
options
Colour (one, or one per bar from color.when()), title, editable. Default: {}.
color? string | string[]
Fill colour: one colour, or one per bar from color.when().
title? string
Name of the fill in the settings. Default: "Plots Background" / "Hlines Background".
editable? boolean
false: not listed in the style settings of the script. Default: true.
const upper = plot(ta.sma(high, 20), "Upper");
const lower = plot(ta.sma(low, 20), "Lower");
fill(upper, lower, { color: color.new(color.blue, 85), title: "Channel" });

Colours the space between two plots or two hlines with one colour (or one per bar).

a
First plot or hline (the handle plot() / hline() returned).
b
Second plot or hline, of the same kind as a.
color
Fill colour, or one per bar from color.when(); na (null) leaves a bar unfilled.
title
Name of the fill in the settings. Default: "Plots Background" / "Hlines Background".
rest
editable (false keeps it out of the settings); show_last, fillgaps and display are accepted and not used.
const top = hline(70), bottom = hline(30);
fill(top, bottom, color.new(color.purple, 90), "Zone");

Colours the space between two plots with a gradient: top_color at top_value, bottom_color at bottom_value; the values and colours may change from bar to bar.

a
First plot (the handle plot() returned).
b
Second plot.
top_value
Price of the top colour: a number or a Series.
bottom_value
Price of the bottom colour: a number or a Series.
top_color
Colour at the top, or one per bar.
bottom_color
Colour at the bottom, or one per bar.
title
Name of the fill in the settings. Default: "Plots Background".
rest
editable (false keeps it out of the settings); other arguments are accepted and not used.
const basis = ta.sma(close, 20);
const p = plot(close), q = plot(basis);
fill(p, q, high, basis, color.green, color.new(color.green, 100));

fixnan()

fixnan(source: Series): Series
fixnan(source: string[]): string[]

Fills the gaps of a Series: each na value (NaN) becomes the last value that was not na. Values before the first non-na value stay na; +/-Infinity is kept.

source
The Series to fill.

Returns A Series without gaps after its first value.

const pivot = fixnan(ta.pivothigh(5, 5));
plot(pivot, "Last pivot high", { style: plot.style_stepline });

Fills the gaps of a per-bar colour array: each na entry (undefined) becomes the last colour that was not na.

source
One colour per bar, as made by color.when().

Returns A colour array without gaps after its first colour.

const trendColor = fixnan(color.when(ta.crossover(close, ta.sma(close, 20)), color.green));
barcolor(trendColor);

formula()

formula(text: string, variables?: FormulaVariables): Series

The Series a formula written as text gives, e.g. a formula a user typed in a setting. A condition gives 1 where it is true and 0 where it is false. A mistake throws an error that shows where it is.

text
The formula: prices (open, high, low, close, volume, hl2, hlc3, ohlc4, hlcc4, bar_index), numbers, operators and functions such as sma(close, 20) or rsi(close, length) > 70.
variables
Other names the formula can use: numbers (settings) or Series (other calculations). Default: {}.

Returns Series of the formula's values.

const length = input.int(14, "Length");
plot(formula("rsi(close, length) - 50", { length }), "Centered RSI");

holdDrawing()

holdDrawing<T extends object>(obj: T): T

Marks a drawing as held, so the max_*_count limit of the script never deletes it (it still counts towards the limit). Each call adds one hold; releaseDrawing removes one. Most scripts use varDrawing() instead, which holds and releases for them.

obj
The drawing to hold (a line, label, box, polyline, linefill or table).

Returns The same object, so the call can wrap a *.new() call.

eachBar((c) => {
  if (c.i === 0) holdDrawing(label.new(c.i, c.high, "First bar"));
});

hour()

hour(time: number, timezone?: string): number
hour(time: Series, timezone?: string): Series

The calendar field (year, month, day, hour...) of a time.

time
A time in UNIX milliseconds.
timezone
Time zone to read the time in: "America/New_York", "UTC+2"... Default: the exchange's.

Returns The calendar field of that time.

const morning = hour(time).lt(12);
bgcolor(color.when(morning, color.new(color.orange, 90)));

The calendar field (year, month, day, hour...) of each time of a Series, e.g. year(time).

time
A Series of times in UNIX milliseconds, e.g. time.
timezone
Time zone to read the times in: "America/New_York", "UTC+2"... Default: the exchange's.

Returns Series of the calendar field of each time.

const morning = hour(time).lt(12);
bgcolor(color.when(morning, color.new(color.orange, 90)));

indicator()

indicator(title: string, options?: IndicatorOptions): void

Declares the script as an indicator: its title, its pane and how its values are shown. Call it once, at the top of the script (a script declares either indicator() or strategy()). A script without a declaration runs with the title "Untitled" in its own pane.

title
Name of the script, shown in the legend and the settings.
options
Pane, short title, number format and drawing limits. Default: {} (own pane).
shorttitle? string
Short name shown in the chart legend. Default: the title.
overlay? boolean
true: drawn on the price pane; false: in its own pane below the chart. Default: false.
precision? number
Number of decimals of the values shown in the legend and on the price scale. Default: the host's choice (the symbol's precision).
format? string
Number format of the values: format.price, format.volume, format.percent, format.mintick or format.inherit. Default: format.inherit.
scale? "right" | "left" | "none"
The price scale the script uses: scale.right, scale.left or scale.none. Default: the host's choice.
max_lines_count? number
Most lines kept alive; above it the oldest are deleted (a few more may stay for a moment). Default: 50.
max_labels_count? number
Most labels kept alive; above it the oldest are deleted. Default: 50.
max_boxes_count? number
Most boxes kept alive; above it the oldest are deleted. Default: 50.
max_polylines_count? number
Most polylines kept alive; above it the oldest are deleted. Default: 50.
pane? "price" | "separate" | "auto"
Where the script is drawn, instead of overlay (give one of the two): 'price' (on the price pane), 'separate' (its own pane) or 'auto' (chosen from the plotted values: the price pane when they are prices, like an average; its own pane otherwise, like an RSI). Default: not set (overlay decides).
indicator("My SMA", { overlay: true, precision: 2 });
plot(ta.sma(close, 20), "SMA");

inSession()

inSession(time: number, session: string, timezone?: string): boolean

Whether a time is inside a session (trading hours).

time
A time in UNIX milliseconds, e.g. c.time in eachBar().
session
Session hours and days: "0930-1600", "0930-1600:23456" (Monday to Friday), "1800-0500" (overnight).
timezone
Time zone of the session hours. Default: the exchange's.

Returns true when the time is in the session.

const regular = eachBar((c) => inSession(c.time, "0930-1600"));
bgcolor(color.when(regular, color.new(color.blue, 92)));

minute()

minute(time: number, timezone?: string): number
minute(time: Series, timezone?: string): Series

The calendar field (year, month, day, hour...) of a time.

time
A time in UNIX milliseconds.
timezone
Time zone to read the time in: "America/New_York", "UTC+2"... Default: the exchange's.

Returns The calendar field of that time.

plot(minute(time), "Minute");

The calendar field (year, month, day, hour...) of each time of a Series, e.g. year(time).

time
A Series of times in UNIX milliseconds, e.g. time.
timezone
Time zone to read the times in: "America/New_York", "UTC+2"... Default: the exchange's.

Returns Series of the calendar field of each time.

plot(minute(time), "Minute");

month()

month(time: number, timezone?: string): number
month(time: Series, timezone?: string): Series

The calendar field (year, month, day, hour...) of a time.

time
A time in UNIX milliseconds.
timezone
Time zone to read the time in: "America/New_York", "UTC+2"... Default: the exchange's.

Returns The calendar field of that time.

const january = month(time).eq(1);
bgcolor(color.when(january, color.new(color.teal, 85)));

The calendar field (year, month, day, hour...) of each time of a Series, e.g. year(time).

time
A Series of times in UNIX milliseconds, e.g. time.
timezone
Time zone to read the times in: "America/New_York", "UTC+2"... Default: the exchange's.

Returns Series of the calendar field of each time.

const january = month(time).eq(1);
bgcolor(color.when(january, color.new(color.teal, 85)));

na()

na(x: Series): Series
na(x: unknown): boolean

Tells, bar by bar, whether a Series is na (NaN or +/-Infinity): a Series of 1 where it is, 0 elsewhere.

x
The Series to test.

Returns A Series of 1 / 0.

const ma = ta.sma(close, 50);
bgcolor(color.when(na(ma), color.new(color.gray, 90)), { title: "Warming up" });

Tells whether one value is na: NaN, +/-Infinity, undefined or null (a colour or a drawing), a deleted drawing, or an empty text. Use it on the numbers of a bar loop.

x
The value to test.

Returns true when the value is na.

const ma = ta.sma(close, 50);
eachBar((c) => { if (!na(c.get(ma)) && c.close > c.get(ma)) label.new(c.i, c.high, "Above"); });

nz()

nz(source: Series, replacement?: number | Series): Series
nz<T>(source: T, replacement?: T): T

Replaces the na values of a Series (NaN or +/-Infinity) with a replacement, bar by bar, e.g. to start a sum at 0.

source
The Series to clean.
replacement
The value for the na bars: a number, or a Series (its value on the same bar). Default: 0.

Returns A Series without na values (unless the replacement is na).

const change = nz(close.sub(close.offset(1)));
plot(change, "Change", { style: plot.style_columns });

Returns a value, or a replacement when it is na (NaN, +/-Infinity, undefined, null). Use it on the numbers of a bar loop.

source
The value to check.
replacement
The value returned when source is na. Default: 0.

Returns source, or replacement when source is na.

const total = eachBar((c) => nz(c.prev()) + c.volume);
plot(total, "Cumulative volume");

persist()

persist<T>(initial: T): PersistVariable<T>

A variable that keeps its value from one bar to the next, kept by the runtime. Declare it in the script body (outside the callbacks), in the same order on each run, and read and write .value in one eachBar() callback. On a live chart the runtime saves its value at the end of the last confirmed bar and puts it back before the forming bar is calculated again, so only the newest bar is calculated: prefer it to a let variable outside the callback. The script is calculated in full on each update (same results, slower) when the variable is used outside an eachBar() callback, by two eachBar() blocks, or holds something else than plain data (numbers, strings, booleans, arrays, plain objects, Map, Set). Calling it inside a bar loop throws.

initial
The value before the first bar.

Returns A box whose .value reads and writes the variable.

const dir = persist(0);
const trend = eachBar((c) => {
  if (c.close > c.get(close, 1)) dir.value = 1;
  else if (c.close < c.get(close, 1)) dir.value = -1;
  return dir.value;
});

plotarrow()

plotarrow(series: Series, title?: string, options?: PlotArrowOptions): void

Draws an up arrow below the bar where the value is positive and a down arrow above it where it is negative; nothing for 0 or na. The larger the value, the longer the arrow (between minheight and maxheight).

series
Series whose sign gives the arrow's direction and whose size gives its length.
title
Name of the arrows in the settings and the alerts. Default: "Arrows".
options
Colours, heights, offset, display. Default: {} (green up, red down).
colorup? string | string[]
Colour of the up arrows: one colour or one per bar. Default: #00FF00.
colordown? string | string[]
Colour of the down arrows: one colour or one per bar. Default: #FF0000.
offset? number
Moves the arrows by this many bars (the arrow of bar i is drawn on bar i + offset). Default: 0.
minheight? number
Height of the smallest arrow, in pixels. Default: 5.
maxheight? number
Height of the largest arrow, in pixels. Default: 100.
display? "none" | "all" | "data_window" | "status_line" | "pane"
Where the arrows are shown: display.all, display.none... Default: everywhere.
force_overlay? boolean
Draw on the main chart pane even when the script is not an overlay; default false.
editable? boolean
False: not listed in the Style settings of the study; default true.
const change = close.sub(close.offset(1));
plotarrow(change, "Change", { colorup: color.teal, colordown: color.orange });

plotbar()

plotbar(open: Series, high: Series, low: Series, close: Series, title?: string, options?: PlotBarOptions): void

Draws open-high-low-close bars from four Series. A bar where one of the four values is na is not drawn.

open
Open of each bar.
high
High of each bar.
low
Low of each bar.
close
Close of each bar.
title
Name of the bars in the settings. Default: "PlotBar".
options
Colour, display, force_overlay, editable. Default: {}.
color? ScriptCandleColor
Bar colour: one colour or one per bar (color.when()); an na entry gives a see-through bar. Default: #2962FF.
display? "none" | "all" | "data_window" | "status_line" | "pane"
Where the bars are shown: display.all, display.none... Default: everywhere.
force_overlay? boolean
Draw on the main chart pane even when the script is not an overlay; default false.
editable? boolean
False: not listed in the Style settings of the study; default true.
plotbar(open, high, low, close, "Bars", { color: color.when(close.gt(open), color.green, color.red) });

plotcandle()

plotcandle(open: Series, high: Series, low: Series, close: Series, title?: string, options?: PlotCandleOptions): void

Draws candles from four Series (for example the candles of another symbol, or smoothed prices). A bar where one of the four values is na has no candle.

open
Open of each candle.
high
High of each candle.
low
Low of each candle.
close
Close of each candle.
title
Name of the candles in the settings. Default: "PlotCandle".
options
Body, wick and border colours, display, force_overlay, editable. Default: {}.
color? ScriptCandleColor
Body colour: one colour or one per bar (color.when()); an na entry gives a see-through body. Default: #2962FF.
wickcolor? ScriptCandleColor
Wick colour: one colour or one per bar. Default: #737375.
bordercolor? ScriptCandleColor
Border colour: one colour or one per bar. Default: #000000.
display? "none" | "all" | "data_window" | "status_line" | "pane"
Where the candles are shown: display.all, display.none... Default: everywhere.
force_overlay? boolean
Draw on the main chart pane even when the script is not an overlay; default false.
editable? boolean
False: not listed in the Style settings of the study; default true.
const o = ta.ema(open, 5), h = ta.ema(high, 5), l = ta.ema(low, 5), c = ta.ema(close, 5);
plotcandle(o, h, l, c, "Smoothed", { color: color.when(c.gt(o), color.teal, color.red) });

plotchar()

plotchar(condition: Series, title?: string, options?: PlotCharOptions): void

Draws a character (a letter, an emoji...) on each bar where the condition is true.

condition
Series that is true (non-zero) on the bars that get the character. With location.absolute, its value is the price of the character.
title
Name of the characters in the settings and the alerts. Default: "Chars".
options
Character (char), place (location.*), colour, text, size (size.*), offset... Default: {} (a star above the bar).
offset? number
Display offset in bars (marker shown at bar i + offset).
tooltip? string
Text shown when the mouse is over the marker.
force_overlay? boolean
Draw on the main chart pane even when the script is not an overlay; default false.
editable? boolean
False: not listed in the Style settings of the study; default true.
const gapUp = open.gt(high.offset(1));
plotchar(gapUp, "Gap up", { char: "▲", location: location.abovebar, color: color.teal });

plotshape()

plotshape(condition: Series, title?: string, options?: PlotShapeOptions): void

Draws a shape (triangle, arrow, circle, label...) on each bar where the condition is true: buy and sell signals.

condition
Series that is true (non-zero) on the bars that get a shape. With location.absolute, its value is the price of the shape.
title
Name of the shapes in the settings and the alerts. Default: "Shapes".
options
Shape (shape.*), place (location.*), colour, text, size (size.*), offset... Default: {} (a cross above the bar).
offset? number
Display offset in bars (marker shown at bar i + offset).
tooltip? string
Text shown when the mouse is over the marker.
force_overlay? boolean
Draw on the main chart pane even when the script is not an overlay; default false.
editable? boolean
False: not listed in the Style settings of the study; default true.
const up = ta.crossover(ta.ema(close, 9), ta.ema(close, 21));
plotshape(up, "Buy", { style: shape.triangleup, location: location.belowbar, color: color.green });

releaseDrawing()

releaseDrawing(obj: object): void

Removes one hold made by holdDrawing: once no hold is left, the max_*_count limit can delete the drawing again. Does nothing for na or an object that is not held.

obj
The held drawing, or null / undefined (nothing to release).
let kept;
eachBar((c) => {
  if (c.i % 50 === 0) { releaseDrawing(kept); kept = holdDrawing(label.new(c.i, c.high, "Mark")); }
});

second()

second(time: number, timezone?: string): number
second(time: Series, timezone?: string): Series

The calendar field (year, month, day, hour...) of a time.

time
A time in UNIX milliseconds.
timezone
Time zone to read the time in: "America/New_York", "UTC+2"... Default: the exchange's.

Returns The calendar field of that time.

plot(second(time), "Second");

The calendar field (year, month, day, hour...) of each time of a Series, e.g. year(time).

time
A Series of times in UNIX milliseconds, e.g. time.
timezone
Time zone to read the times in: "America/New_York", "UTC+2"... Default: the exchange's.

Returns Series of the calendar field of each time.

plot(second(time), "Second");

seriesOf()

seriesOf(values: number[]): Series

Makes a Series from an array of numbers, one per bar (oldest first), e.g. values collected inside eachBar().

values
One value per bar; NaN is na.

Returns Series of the values.

const ranges = [];
eachBar((c) => { ranges.push(c.high - c.low); });
plot(seriesOf(ranges), "Range");

timestamp()

timestamp(dateString: string): number
timestamp(timezone: string, year: number, month: number, day: number, hour?: number, minute?: number, second?: number): number
timestamp(year: number, month: number, day: number, hour?: number, minute?: number, second?: number): number

The UNIX time (milliseconds) of a date written as text.

dateString
A date such as "2024-03-15", "2024-03-15T09:30" or "15 Mar 2024 09:30 GMT+1"; without a time zone it is UTC.

Returns The time in UNIX milliseconds.

const start = timestamp("2024-01-01");
bgcolor(color.when(time.gte(start), color.new(color.green, 92)));

The UNIX time (milliseconds) of a date and time in a time zone.

timezone
Time zone: "America/New_York", "UTC+2"...
year
Year, e.g. 2024.
month
Month, 1 to 12.
day
Day of the month, 1 to 31.
hour
Hour, 0 to 23. Default: 0.
minute
Minute. Default: 0.
second
Second. Default: 0.

Returns The time in UNIX milliseconds.

const open = timestamp("America/New_York", 2024, 3, 15, 9, 30);

The UNIX time (milliseconds) of a date and time in the exchange's time zone.

year
Year, e.g. 2024.
month
Month, 1 to 12.
day
Day of the month, 1 to 31.
hour
Hour, 0 to 23. Default: 0.
minute
Minute. Default: 0.
second
Second. Default: 0.

Returns The time in UNIX milliseconds.

const from = timestamp(2024, 1, 1);
plotshape(time.eq(from), "Start");

varDrawing()

varDrawing<T extends object = any>(initial?: T): DrawingVariable<T>

A variable that holds one drawing (a line, label, box...) from bar to bar and keeps it alive: the object it holds is never deleted by the max_*_count limit of the script. Use it to create one object and move it, instead of a new object on each bar. Assigning another object (or undefined for na) releases the one before, which the limit can delete again. Declare it in the script body (outside the bar loops), then read and write .value in a bar loop.

initial
The object held from the start. Default: none (.value is undefined).

Returns A box whose .value is the held object, or undefined.

const level = varDrawing();
eachBar((c) => {
  if (c.i === c.n - 1) level.value = line.new(c.i - 20, c.close, c.i, c.close, { color: color.orange });
});

varip()

varip<T>(initial: T): VaripVariable<T>

A strategy variable that keeps the changes made while a bar is calculated again inside the bar (on order fills or ticks). A plain variable comes back to its value at the start of the bar on each of those runs; a varip one does not, so it can count fills or ticks. Declare it once in the script body (outside the callbacks), in the same order on each run; read and write .value in strategy.eachBar(). Without intrabar runs it is a plain variable.

initial
The starting value.

Returns A box whose .value reads and writes the variable.

const updatesInTrade = varip(0);
strategy.eachBar((c) => {
  if (strategy.position_size !== 0) updatesInTrade.value += 1;
});

weekofyear()

weekofyear(time: number, timezone?: string): number
weekofyear(time: Series, timezone?: string): Series

The calendar field (year, month, day, hour...) of a time.

time
A time in UNIX milliseconds.
timezone
Time zone to read the time in: "America/New_York", "UTC+2"... Default: the exchange's.

Returns The calendar field of that time.

plot(weekofyear(time), "Week");

The calendar field (year, month, day, hour...) of each time of a Series, e.g. year(time).

time
A Series of times in UNIX milliseconds, e.g. time.
timezone
Time zone to read the times in: "America/New_York", "UTC+2"... Default: the exchange's.

Returns Series of the calendar field of each time.

plot(weekofyear(time), "Week");

year()

year(time: number, timezone?: string): number
year(time: Series, timezone?: string): Series

The calendar field (year, month, day, hour...) of a time.

time
A time in UNIX milliseconds.
timezone
Time zone to read the time in: "America/New_York", "UTC+2"... Default: the exchange's.

Returns The calendar field of that time.

const newYear = year(time).neq(year(time).offset(1));
bgcolor(color.when(newYear, color.new(color.blue, 80)));

The calendar field (year, month, day, hour...) of each time of a Series, e.g. year(time).

time
A Series of times in UNIX milliseconds, e.g. time.
timezone
Time zone to read the times in: "America/New_York", "UTC+2"... Default: the exchange's.

Returns Series of the calendar field of each time.

const newYear = year(time).neq(year(time).offset(1));
bgcolor(color.when(newYear, color.new(color.blue, 80)));

Other values

box

box: Omit<ScriptDrawing<typeof import("/mnt/data/projects/opentrader/node_modules/oakscriptjs/dist/esm/box/index")>, "all"> & { readonly all: Box[]; } & { new: ((args: BoxNewArgs) => Box) & ((left: Numeric, top: Numeric, right: Numeric, bottom: Numeric, args: BoxNewArgs) => Box) & ((top_left: ChartPoint, bottom_right: ChartPoint, args: BoxNewArgs) => Box); }

Rectangles between two x coordinates and two prices, with optional text: box.new() draws one, box.set_* / box.get_* change and read it, box.all lists the live boxes.

FORMULA_FUNCTIONS

FORMULA_FUNCTIONS: Record<string, FormulaFunction>

The functions a formula can call (lowercase names; a formula may write them in any case).

label

label: Omit<ScriptDrawing<typeof import("/mnt/data/projects/opentrader/node_modules/oakscriptjs/dist/esm/label/index") & { readonly style_none: "none"; readonly style_xcross: "xcross"; readonly style_cross: "cross"; readonly style_triangleup: "triangleup"; readonly style_triangledown: "triangledown"; readonly style_flag: "flag"; readonly style_circle: "circle"; readonly style_arrowup: "arrowup"; readonly style_arrowdown: "arrowdown"; readonly style_label_up: "label_up"; readonly style_label_down: "label_down"; readonly style_label_left: "label_left"; readonly style_label_right: "label_right"; readonly style_label_lower_left: "label_lower_left"; readonly style_label_lower_right: "label_lower_right"; readonly style_label_upper_left: "label_upper_left"; readonly style_label_upper_right: "label_upper_right"; readonly style_label_center: "label_center"; readonly style_square: "square"; readonly style_diamond: "diamond"; readonly style_text_outline: "text_outline"; }>, "all"> & { readonly all: Label[]; } & { new: ((args: LabelNewArgs) => Label) & ((x: Numeric, y: Numeric, args: LabelNewArgs) => Label) & ((x: Numeric, y: Numeric, text: string, args: LabelNewArgs) => Label) & ((point: ChartPoint, args: LabelNewArgs) => Label) & ((point: ChartPoint, text: string, args: LabelNewArgs) => Label); }

Text boxes and shapes at a chart point: label.new() draws one, label.set_* / label.get_* change and read it, label.style_* are its styles, label.all lists the live labels.

line

line: Omit<ScriptDrawing<typeof import("/mnt/data/projects/opentrader/node_modules/oakscriptjs/dist/esm/line/index") & { readonly style_solid: "solid"; readonly style_dotted: "dotted"; readonly style_dashed: "dashed"; readonly style_arrow_left: "arrow_left"; readonly style_arrow_right: "arrow_right"; readonly style_arrow_both: "arrow_both"; }>, "all"> & { readonly all: Line[]; } & { new: ((args: LineNewArgs) => Line) & ((x1: Numeric, y1: Numeric, x2: Numeric, y2: Numeric, args: LineNewArgs) => Line) & ((first_point: ChartPoint, second_point: ChartPoint, args: LineNewArgs) => Line); }

Lines between two chart points: line.new() draws one, line.set_* / line.get_* move and read it, line.style_* are its styles, line.all lists the live lines.

linefill

linefill: Omit<ScriptDrawing<typeof import("/mnt/data/projects/opentrader/node_modules/oakscriptjs/dist/esm/linefill/index")>, "all"> & { readonly all: Linefill[]; } & { new: ((args: LinefillNewArgs) => Linefill) & ((line1: Line, line2: Line, args: LinefillNewArgs) => Linefill); }

Colour fills between two lines that follow the lines when they move: linefill.new(), linefill.set_color(), linefill.all.

MAX_LOG_ENTRIES

MAX_LOG_ENTRIES: 10000

The most messages a run keeps: the newest ones.

polyline

polyline: Omit<ScriptDrawing<Omit<typeof import("/mnt/data/projects/opentrader/node_modules/oakscriptjs/dist/esm/polyline/index"), "clear_all" | "reset_id_counter">>, "all"> & { readonly all: Polyline[]; } & { new: ((args: PolylineNewArgs) => Polyline) & ((points: ChartPoint[], args: PolylineNewArgs) => Polyline); }

Shapes through many chart points, straight or curved, open or closed and filled: polyline.new(), polyline.delete(), polyline.all.

adjustment

Price adjustment of a ticker. Kept for compatibility: no function of the library reads it yet.

alert

alert()

alert(message: string | readonly string[], freq?: "all" | "once_per_bar" | "once_per_bar_close"): void

Sends an alert message. Inside eachBar() / strategy.eachBar() it is a call on the current bar (put it in an if); at the top level of the script it is a call on every bar. The app fires the calls of the live bar for the alerts that the user created on the script.

message
The alert text. At the top level it can also be an array with one text per bar; a bar whose text is undefined makes no call.
freq
How often the alert may fire: alert.freq_all (on every call), alert.freq_once_per_bar (the first call of each bar) or alert.freq_once_per_bar_close (when the bar closes). Another value throws. Default: alert.freq_once_per_bar.
const up = ta.crossover(close, ta.sma(close, 20));
eachBar((c) => {
  if (c.get(up) === 1) alert("Close crossed above the average", alert.freq_once_per_bar_close);
});

alert.freq_all

alert.freq_all: "all"

Frequency for alert(): the alert fires on every call, several times per bar if need be.

alert.freq_once_per_bar

alert.freq_once_per_bar: "once_per_bar"

Frequency for alert(): the alert fires on the first call of a bar only. The default.

alert.freq_once_per_bar_close

alert.freq_once_per_bar_close: "once_per_bar_close"

Frequency for alert(): the alert fires only when the bar closes, if the call was made on it.

barmerge

Options of request.security: gaps (barmerge.gaps_on / gaps_off) and lookahead (barmerge.lookahead_on / lookahead_off).

barmerge.gaps_on

barmerge.gaps_on: "gaps_on"

A value shows only on the bar where it appears; the bars between are na.

barmerge.gaps_off

barmerge.gaps_off: "gaps_off"

A value stays on every bar until the next one (the default).

barmerge.lookahead_on

barmerge.lookahead_on: "lookahead_on"

A period's value shows from the first chart bar of that period. On history it reads values that were not known yet: use it with values of the previous period (high.offset(1)).

barmerge.lookahead_off

barmerge.lookahead_off: "lookahead_off"

A period's value shows from the chart bar that completes the period (the default, no future values).

barstate

The state of each bar (1 / 0 per bar): first, last, confirmed, realtime... All bars but the last are confirmed history bars. The last bar is confirmed only when the host says so (ChartContext.lastBarConfirmed, e.g. the closing update of a realtime bar), and is a realtime bar only when it receives live updates (ChartContext.realtime); without live updates it is a history bar. islastconfirmedhistory is the last bar when it is confirmed and not realtime, else the bar before it.

barstate.isconfirmed

barstate.isconfirmed: Series

1 on closed bars: every bar but the last, and the last bar once the app says it has closed.

barstate.isrealtime

barstate.isrealtime: Series

1 on the last bar when it receives live updates.

barstate.isnew

barstate.isnew: Series

1 on every history bar, and on a live last bar at its first update.

barstate.islastconfirmedhistory

barstate.islastconfirmedhistory: Series

1 on the last closed history bar: the last bar when it is closed and not live, else the bar before it.

calc

Plain-English names for the most used calculations (calc.average, calc.crossesAbove...), beside the ta.* ones. They take Series or numbers and give a Series; a condition gives 1 where true and 0 where false.

calc.average()

calc.average(source: number | Series, length: number, kind?: string): Series

Moving average of the last length values, of the kind you choose. Use it to smooth a price or any Series. NaN on the first bars, until the window is full.

source
Values to average: a Series such as close, or a number.
length
Number of bars in the window: a whole number, 1 or more.
kind
'simple', 'exponential', 'weighted', 'smoothed' (the average of ta.rsi), 'hull' or 'volume-weighted' (weighted by volume). Another text throws. Default: 'simple'.

Returns Series of the averages.

const fast = calc.average(close, 9, 'exponential');
plot(fast, "Fast average");

calc.crossesAbove()

calc.crossesAbove(a: number | Series, b: number | Series): Series

Tests whether a crosses above b: 1 on the bar where a goes from at or below b to above it, else 0. Use it for buy signals such as a fast average crossing a slow one.

a
The line that crosses: a Series or a number.
b
The line it crosses: a Series or a level.

Returns Series of 1 on the crossing bars, 0 elsewhere.

const up = calc.crossesAbove(calc.average(close, 9), calc.average(close, 21));
plotshape(up, "Up", { style: shape.triangleup, location: location.belowbar });

calc.crossesBelow()

calc.crossesBelow(a: number | Series, b: number | Series): Series

Tests whether a crosses below b: 1 on the bar where a goes from at or above b to below it, else 0.

a
The line that crosses: a Series or a number.
b
The line it crosses: a Series or a level.

Returns Series of 1 on the crossing bars, 0 elsewhere.

const down = calc.crossesBelow(ta.rsi(close, 14), 70);
plotshape(down, "Down", { style: shape.triangledown, location: location.abovebar });

calc.crosses()

calc.crosses(a: number | Series, b: number | Series): Series

Tests whether a and b cross, in either direction: 1 on the bar where they swap sides, else 0.

a
The first line: a Series or a number.
b
The second line: a Series or a number.

Returns Series of 1 on the crossing bars, 0 elsewhere.

const crossed = calc.crosses(close, calc.average(close, 50));
bgcolor(color.when(crossed, color.new(color.yellow, 80)));

calc.above()

calc.above(a: number | Series, b: number | Series): Series

Tests whether a is above b on each bar. Values closer than 1e-10 count as equal; a NaN on either side gives 0.

a
The value tested: a Series or a number.
b
The value it is compared with: a Series or a number.

Returns Series of 1 where a is above b, 0 elsewhere.

const uptrend = calc.above(close, calc.average(close, 200));

calc.below()

calc.below(a: number | Series, b: number | Series): Series

Tests whether a is below b on each bar. Values closer than 1e-10 count as equal; a NaN on either side gives 0.

a
The value tested: a Series or a number.
b
The value it is compared with: a Series or a number.

Returns Series of 1 where a is below b, 0 elsewhere.

const oversold = calc.below(ta.rsi(close, 14), 30);

calc.between()

calc.between(value: number | Series, lowLimit: number | Series, highLimit: number | Series): Series

Tests whether value is between two limits on each bar, both limits included. A NaN gives 0.

value
The value tested: a Series or a number.
lowLimit
The lower limit: a Series or a number.
highLimit
The upper limit: a Series or a number.

Returns Series of 1 where lowLimit <= value <= highLimit, 0 elsewhere.

const neutral = calc.between(ta.rsi(close, 14), 40, 60);

calc.previous()

calc.previous(source: number | Series, bars?: number): Series

The value from bars bars before, on each bar (calc.previous(close) is the previous close). The first bars, which have no earlier bar, get NaN.

source
A Series or a number.
bars
How many bars back: a whole number, 1 or more. Default: 1.

Returns Series of the earlier values.

const gapUp = calc.above(open, calc.previous(high));

calc.change()

calc.change(source: number | Series, bars?: number): Series

The difference between the value and the value bars bars before (close - close 1 bar ago). NaN on the first bars.

source
A Series or a number.
bars
How many bars back: a whole number, 1 or more. Default: 1.

Returns Series of the differences, in the units of the source.

plot(calc.change(close, 5), "5-bar change", { style: plot.style_histogram });

calc.percentChange()

calc.percentChange(source: number | Series, bars?: number): Series

The change in percent since bars bars before: (value - earlier) / earlier * 100. NaN on the first bars and where the earlier value is 0.

source
A Series or a number.
bars
How many bars back: a whole number, 1 or more. Default: 1.

Returns Series of the changes in percent (5 means +5 %).

const roc = calc.percentChange(close, 10);
plot(roc, "10-bar change %");

calc.highest()

calc.highest(source: number | Series, length: number): Series

The highest value of the last length bars, the current bar included.

source
A Series such as high, or a number.
length
Number of bars in the window: a whole number, 1 or more.

Returns Series of the highest values.

plot(calc.highest(high, 20), "20-bar high");

calc.lowest()

calc.lowest(source: number | Series, length: number): Series

The lowest value of the last length bars, the current bar included.

source
A Series such as low, or a number.
length
Number of bars in the window: a whole number, 1 or more.

Returns Series of the lowest values.

plot(calc.lowest(low, 20), "20-bar low");

calc.isRising()

calc.isRising(source: number | Series, bars?: number): Series

Tests whether the value rose on each of the last bars bars (each bar above the one before it).

source
A Series or a number.
bars
How many rises in a row: a whole number, 1 or more. Default: 1.

Returns Series of 1 where the value rose on each of those bars, 0 elsewhere.

const climbing = calc.isRising(calc.average(close, 20), 3);

calc.isFalling()

calc.isFalling(source: number | Series, bars?: number): Series

Tests whether the value fell on each of the last bars bars (each bar below the one before it).

source
A Series or a number.
bars
How many falls in a row: a whole number, 1 or more. Default: 1.

Returns Series of 1 where the value fell on each of those bars, 0 elsewhere.

const sliding = calc.isFalling(close, 3);

calc.standardDeviation()

calc.standardDeviation(source: number | Series, length: number): Series

Standard deviation of the last length values (dividing by length): how far the values spread around their mean. NaN until the window is full.

source
A Series or a number.
length
Number of bars in the window: a whole number, 1 or more.

Returns Series of the deviations, in the units of the source.

const spread = calc.standardDeviation(close, 20);
plot(calc.average(close, 20).add(spread.mul(2)), "Upper band");

calc.ifElse()

calc.ifElse(condition: number | Series, whenTrue: number | Series, whenFalse: number | Series): Series

Picks one of two values on each bar: whenTrue where the condition holds, whenFalse elsewhere. A condition holds when it is not 0 and not NaN.

condition
The condition: a Series of 1 / 0, or a number.
whenTrue
Value used where the condition holds: a Series or a number.
whenFalse
Value used elsewhere: a Series or a number.

Returns Series of the picked values.

const body = calc.ifElse(calc.above(close, open), close.sub(open), 0);
plot(body, "Up body");

calc.all()

calc.all(...conditions: (number | Series)[]): Series

Tests whether every condition holds on each bar (a logical "and"). A condition holds when it is not 0 and not NaN. Give at least one condition.

conditions
The conditions: Series of 1 / 0, or numbers.

Returns Series of 1 where all of them hold, 0 elsewhere.

const buy = calc.all(calc.above(close, open), calc.below(ta.rsi(close, 14), 40));

calc.any()

calc.any(...conditions: (number | Series)[]): Series

Tests whether at least one condition holds on each bar (a logical "or"). A condition holds when it is not 0 and not NaN. Give at least one condition.

conditions
The conditions: Series of 1 / 0, or numbers.

Returns Series of 1 where one of them holds, 0 elsewhere.

const extreme = calc.any(calc.above(ta.rsi(close, 14), 70), calc.below(ta.rsi(close, 14), 30));

chart

The chart the script runs on (its colours, visible bars and chart type) and chart.point.*, which makes the points of drawings. chart.point.now(price?) is the point of the current bar (index, time, and price, default the close), so it runs inside eachBar().

chart.fg_color

chart.fg_color: string

Foreground (text) colour of the chart, e.g. "#DBDBDB" on a dark chart.

chart.bg_color

chart.bg_color: string

Background colour of the chart, e.g. "#0F0F0F" on a dark chart.

chart.left_visible_bar_time

chart.left_visible_bar_time: number

Time (UNIX ms) of the first bar in view; the first bar's time when the app does not give it. A script that reads it is calculated again when the chart scrolls.

chart.right_visible_bar_time

chart.right_visible_bar_time: number

Time (UNIX ms) of the last bar in view; the last bar's time when the app does not give it. A script that reads it is calculated again when the chart scrolls.

chart.is_standard

chart.is_standard: boolean

True when the chart shows standard bars or candles (none of the types below).

chart.is_pnf

chart.is_pnf: boolean

True on a Point and figure chart.

chart.point

Chart points (time or bar index, and price) for drawings.

chart.point.new()

chart.point.new(time: number, index: number, price: number): ChartPoint

A point with every coordinate. Give the time or the bar index (the other one can be null), as the drawing's xloc expects.

time
UNIX time in ms, or null.
index
Bar index, or null.
price
Price of the point.

Returns The new point.

eachBar((c) => {
  if (c.i === c.n - 1) polyline.new([chart.point.new(null, c.i - 10, c.low), chart.point.new(null, c.i, c.high)]);
});

chart.point.new_point()

chart.point.new_point(time: number, index: number, price: number): ChartPoint

A point with every coordinate (the same as chart.point.new).

time
UNIX time in ms, or null.
index
Bar index, or null.
price
Price of the point.

Returns The new point.

const p = chart.point.new_point(null, 0, 100);

chart.point.from_time()

chart.point.from_time(time: number, price: number): ChartPoint

A point at a time and a price (its bar index is null), for drawings placed with xloc.bar_time.

time
UNIX time in ms.
price
Price of the point.

Returns The new point.

eachBar((c) => {
  const points = [chart.point.from_time(c.time, c.low), chart.point.from_time(c.time, c.high)];
  if (c.i === c.n - 1) polyline.new(points, { xloc: xloc.bar_time });
});

chart.point.from_index()

chart.point.from_index(index: number, price: number): ChartPoint

A point at a bar index and a price (its time is null), for drawings placed with xloc.bar_index.

index
Bar index.
price
Price of the point.

Returns The new point.

eachBar((c) => {
  const points = [chart.point.from_index(c.i - 20, c.low), chart.point.from_index(c.i, c.high)];
  if (c.i === c.n - 1) polyline.new(points);
});

chart.point.copy()

chart.point.copy(point: ChartPoint): ChartPoint

A copy of a point.

point
The point to copy.

Returns A new point with the same time, index and price.

const a = chart.point.from_index(0, 100);
const b = chart.point.copy(a);

chart.point.now()

chart.point.now(price?: number): ChartPoint

The point of the current bar: its time, its bar index and a price. Call it inside a bar loop.

price
Price of the point. Default: the close of the bar.

Returns The point of the current bar.

eachBar((c) => {
  if (c.i === c.n - 1) polyline.new([chart.point.from_index(c.i - 10, c.low), chart.point.now(c.high)]);
});

color

Colours: named colours (color.red, color.teal...), color.new for transparency, color.rgb, gradients, and color.when to pick a colour per bar for plot(), fill(), bgcolor() and barcolor().

color.rgb()

color.rgb(red: number, green: number, blue: number, transp?: number): string

Makes a colour from its red, green and blue parts, with an optional transparency. A part is clamped to 0-255 and a fraction is truncated; a NaN part counts as 0.

red
Red part, 0-255.
green
Green part, 0-255.
blue
Blue part, 0-255.
transp
Transparency, 0 (opaque) to 100 (invisible), clamped to that range; NaN is invisible. Default: 0.

Returns The colour as "rgb(r, g, b)", or "rgba(r, g, b, alpha)" when it is transparent.

const orange = color.rgb(255, 140, 0);
plot(close, "Close", { color: orange });

color.from_hex()

color.from_hex(hex: string, transp?: number): string

Makes a colour from a hexadecimal text "RRGGBB" ("#" optional), with an optional transparency.

hex
The colour as six hexadecimal digits, e.g. "#FF9800" or "ff9800".
transp
Transparency, 0 (opaque) to 100 (invisible). Default: 0.

Returns The colour as "rgb(r, g, b)" or "rgba(r, g, b, alpha)".

plot(close, "Close", { color: color.from_hex("#FF9800", 20) });

color.new()

color.new(baseColor: string | number, transp: number): string

The same colour with another transparency: use it for fills and backgrounds you can see through. Its red, green and blue parts are kept, its own transparency is replaced. A missing colour (undefined) gives black with that transparency.

baseColor
The colour to start from: a constant such as color.red, a "#RRGGBB" or "rgb(...)" text.
transp
The new transparency, 0 (opaque) to 100 (invisible), clamped to that range; NaN is invisible.

Returns The colour with the new transparency.

bgcolor(color.when(close.gt(open), color.new(color.green, 85)));

color.new_color()

color.new_color(baseColor: string | number, transp: number): string

Another name of color.new(): the same colour with another transparency.

baseColor
The colour to start from.
transp
The new transparency, 0 (opaque) to 100 (invisible).

Returns The colour with the new transparency.

const shade = color.new_color(color.blue, 70);

color.fade()

color.fade(c: string, amount: number): string

The colour faded by amount, from 0 (unchanged) to 1 (invisible): color.fade(color.red, 0.8) is color.new(color.red, 80).

c
The colour to fade.
amount
How much to fade it: 0 (unchanged) to 1 (invisible). A value outside 0-1 throws.

Returns The faded colour.

bgcolor(color.when(close.lt(open), color.fade(color.red, 0.9)));

color.when()

color.when(cond: Series, colorTrue: string, colorFalse: string): string[]
color.when(cond: Series, colorTrue: string, colorFalse?: string): string[]

One colour per bar, picked by a condition: colorTrue on the bars where cond holds (not 0 and not NaN), colorFalse on the others. Pass the result as the color of plot(), fill(), bgcolor() or barcolor().

cond
The condition: a Series of 1 / 0, e.g. close.gt(open).
colorTrue
Colour of the bars where the condition holds.
colorFalse
Colour of the other bars.

Returns An array with one colour per bar.

plot(close, "Close", { color: color.when(close.gt(open), color.green, color.red) });

One colour per bar, picked by a condition: colorTrue on the bars where cond holds (not 0 and not NaN), no colour (undefined) on the others, which bgcolor() and barcolor() leave as they are.

cond
The condition: a Series of 1 / 0, e.g. close.gt(open).
colorTrue
Colour of the bars where the condition holds.
colorFalse
Colour of the other bars. Default: none (undefined).

Returns An array with one colour, or undefined, per bar.

bgcolor(color.when(ta.rsi(close, 14).gt(70), color.new(color.red, 85)));

color.from_gradient()

color.from_gradient(value: number, bottom_value: number, top_value: number, bottom_color: string, top_color: string): string
color.from_gradient(value: number | Series, bottom_value: number | Series, top_value: number | Series, bottom_color: string | readonly string[], top_color: string | readonly string[]): string | string[]

A colour between two colours, in proportion to where value lies between bottom_value and top_value (with numbers: one colour). bottom_color at or below the bottom, top_color at or above the top, a mix in between. A NaN value or limit, or equal limits, give a fully transparent colour; limits in the wrong order give bottom_color.

value
The value that sets the position in the gradient.
bottom_value
The value that gets bottom_color.
top_value
The value that gets top_color.
bottom_color
Colour at the bottom; a missing colour (undefined) counts as fully transparent.
top_color
Colour at the top; a missing colour (undefined) counts as fully transparent.

Returns The colour of that position.

const mid = color.from_gradient(50, 0, 100, color.red, color.green);

One colour per bar, between two colours, in proportion to where value lies between bottom_value and top_value on that bar. Use it to shade a plot or a background by an oscillator. Any argument can be a Series (a colour: an array with one colour per bar, as made by color.when); with only numbers and colours it gives one colour. Same rules as the number form on each bar.

value
The value that sets the position in the gradient: a Series or a number.
bottom_value
The value that gets bottom_color: a Series or a number.
top_value
The value that gets top_color: a Series or a number.
bottom_color
Colour at the bottom, or one colour per bar.
top_color
Colour at the top, or one colour per bar.

Returns An array with one colour per bar (one colour when no argument varies per bar).

const rsi = ta.rsi(close, 14);
plot(rsi, "RSI", { color: color.from_gradient(rsi, 30, 70, color.red, color.green) });

color.r()

color.r(clr: string | number): number

The red part of a colour.

clr
The colour, e.g. color.orange or "#FF9800".

Returns The red part, 0-255.

const red = color.r(color.orange);

color.g()

color.g(clr: string | number): number

The green part of a colour.

clr
The colour, e.g. color.orange or "#FF9800".

Returns The green part, 0-255.

const green = color.g(color.orange);

color.b()

color.b(clr: string | number): number

The blue part of a colour.

clr
The colour, e.g. color.orange or "#FF9800".

Returns The blue part, 0-255.

const blue = color.b(color.orange);

color.t()

color.t(clr: string | number): number

The transparency of a colour, a whole number from 0 (opaque) to 100 (invisible). A missing colour (undefined) gives 100.

clr
The colour.

Returns The transparency, 0-100.

const lighter = color.new(color.blue, Math.min(color.t(color.blue) + 50, 100));

color.aqua

color.aqua: "#00BCD4"

Aqua, "#00BCD4".

color.black

color.black: "#363A45"

Black (a dark grey-blue), "#363A45".

color.blue

color.blue: "#2962FF"

Blue, "#2962FF": the default colour of plot().

color.gray

color.gray: "#787B86"

Gray, "#787B86".

color.lime

color.lime: "#00E676"

Lime (a bright green), "#00E676".

color.navy

color.navy: "#311B92"

Navy, "#311B92".

color.red

color.red: "#F23645"

Red, "#F23645".

color.silver

color.silver: "#B2B5BE"

Silver (a light grey), "#B2B5BE".

color.teal

color.teal: "#089981"

Teal, "#089981".

compare

Comparisons of two numbers with a tolerance of 1e-10 (compare.eq(0.1 + 0.2, 0.3) is true), for the plain numbers of a bar loop.

compare.eq()

compare.eq(a: number, b: number): boolean

Tests whether two numbers are equal, within a tolerance of 1e-10. False when either number is na (NaN).

a
The first number.
b
The second number.

Returns True when |a - b| <= 1e-10.

eachBar((c) => {
  if (compare.eq(c.close, c.open)) label.new(c.i, c.high, "Doji");
});

compare.ne()

compare.ne(a: number, b: number): boolean

Tests whether two numbers differ by more than 1e-10. False when either number is na (NaN), unlike JavaScript's !==.

a
The first number.
b
The second number.

Returns True when |a - b| > 1e-10.

const moved = eachBar((c) => (compare.ne(c.close, c.get(close, 1)) ? 1 : 0));

compare.lt()

compare.lt(a: number, b: number): boolean

Tests whether a is less than b by more than 1e-10. False when either number is na (NaN).

a
The first number.
b
The second number.

Returns True when b - a > 1e-10.

const below = eachBar((c) => (compare.lt(c.close, c.open) ? 1 : 0));

compare.le()

compare.le(a: number, b: number): boolean

Tests whether a is less than or equal to b, within a tolerance of 1e-10. False when either number is na (NaN).

a
The first number.
b
The second number.

Returns True when a - b <= 1e-10.

const notAbove = eachBar((c) => (compare.le(c.close, c.open) ? 1 : 0));

compare.gt()

compare.gt(a: number, b: number): boolean

Tests whether a is greater than b by more than 1e-10. False when either number is na (NaN).

a
The first number.
b
The second number.

Returns True when a - b > 1e-10.

const ma = ta.sma(close, 20);
const above = eachBar((c) => (compare.gt(c.close, c.get(ma)) ? 1 : 0));

compare.ge()

compare.ge(a: number, b: number): boolean

Tests whether a is greater than or equal to b, within a tolerance of 1e-10. False when either number is na (NaN).

a
The first number.
b
The second number.

Returns True when b - a <= 1e-10.

const notBelow = eachBar((c) => (compare.ge(c.close, c.open) ? 1 : 0));

compare.EPSILON

compare.EPSILON: 1e-10

Tolerance of the comparisons: two numbers closer than 1e-10 are equal.

currency

Currency codes, such as the currency option of strategy() or the value of syminfo.currency (currency.USD is "USD"). currency.NONE means no currency (na).

currency.AED

currency.AED: "AED"

United Arab Emirates dirham.

dayofweek

dayofweek()

dayofweek(time: number, timezone?: string): number
dayofweek(time: Series, timezone?: string): Series

The calendar field (year, month, day, hour...) of a time.

time
A time in UNIX milliseconds.
timezone
Time zone to read the time in: "America/New_York", "UTC+2"... Default: the exchange's.

Returns The calendar field of that time.

const monday = dayofweek(time).eq(dayofweek.monday);
bgcolor(color.when(monday, color.new(color.gray, 90)));

The calendar field (year, month, day, hour...) of each time of a Series, e.g. year(time).

time
A Series of times in UNIX milliseconds, e.g. time.
timezone
Time zone to read the times in: "America/New_York", "UTC+2"... Default: the exchange's.

Returns Series of the calendar field of each time.

const monday = dayofweek(time).eq(dayofweek.monday);
bgcolor(color.when(monday, color.new(color.gray, 90)));

DEFAULT_CANDLE_COLORS

Colours of a plotcandle / plotbar argument left out, as scripts declare them and the chart draws them (reference: body / bar #2962FF, wick #737375, border #000000; the wick and border do not follow the body).

DEFAULT_OUTPUT_TITLES

The titles an output gets when the script gives none (plot is "Plot", hline is "Level"...): the style settings and the alert lists show them.

DEFAULT_PALETTE

The colours given in turn to plots without a colour when ScriptOptions.palette is true.

DEFAULT_PALETTE.toLocaleString()

DEFAULT_PALETTE.toLocaleString(): string
DEFAULT_PALETTE.toLocaleString(locales: string | string[], options?: NumberFormatOptions & DateTimeFormatOptions): string

Returns a string representation of an array. The elements are converted to string using their toLocaleString methods.

DEFAULT_PALETTE.concat()

DEFAULT_PALETTE.concat(...items: ConcatArray<string>[]): string[]
DEFAULT_PALETTE.concat(...items: (string | ConcatArray<string>)[]): string[]

Combines two or more arrays.

items
Additional items to add to the end of array1.

DEFAULT_PALETTE.join()

DEFAULT_PALETTE.join(separator?: string): string

Adds all the elements of an array separated by the specified separator string.

separator
A string used to separate one element of an array from the next in the resulting String. If omitted, the array elements are separated with a comma.

DEFAULT_PALETTE.slice()

DEFAULT_PALETTE.slice(start?: number, end?: number): string[]

Returns a section of an array.

start
The beginning of the specified portion of the array.
end
The end of the specified portion of the array. This is exclusive of the element at the index 'end'.

DEFAULT_PALETTE.indexOf()

DEFAULT_PALETTE.indexOf(searchElement: string, fromIndex?: number): number

Returns the index of the first occurrence of a value in an array.

searchElement
The value to locate in the array.
fromIndex
The array index at which to begin the search. If fromIndex is omitted, the search starts at index 0.

DEFAULT_PALETTE.lastIndexOf()

DEFAULT_PALETTE.lastIndexOf(searchElement: string, fromIndex?: number): number

Returns the index of the last occurrence of a specified value in an array.

searchElement
The value to locate in the array.
fromIndex
The array index at which to begin the search. If fromIndex is omitted, the search starts at the last index in the array.

DEFAULT_PALETTE.every()

DEFAULT_PALETTE.every<S extends string>(predicate: (value: string, index: number, array: readonly string[]) => value is S, thisArg?: any): this is readonly S[]
DEFAULT_PALETTE.every(predicate: (value: string, index: number, array: readonly string[]) => unknown, thisArg?: any): boolean

Determines whether all the members of an array satisfy the specified test.

predicate
A function that accepts up to three arguments. The every method calls the predicate function for each element in the array until the predicate returns a value which is coercible to the Boolean value false, or until the end of the array.
thisArg
An object to which the this keyword can refer in the predicate function. If thisArg is omitted, undefined is used as the this value.

DEFAULT_PALETTE.some()

DEFAULT_PALETTE.some(predicate: (value: string, index: number, array: readonly string[]) => unknown, thisArg?: any): boolean

Determines whether the specified callback function returns true for any element of an array.

predicate
A function that accepts up to three arguments. The some method calls the predicate function for each element in the array until the predicate returns a value which is coercible to the Boolean value true, or until the end of the array.
thisArg
An object to which the this keyword can refer in the predicate function. If thisArg is omitted, undefined is used as the this value.

DEFAULT_PALETTE.forEach()

DEFAULT_PALETTE.forEach(callbackfn: (value: string, index: number, array: readonly string[]) => void, thisArg?: any): void

Performs the specified action for each element in an array.

callbackfn
A function that accepts up to three arguments. forEach calls the callbackfn function one time for each element in the array.
thisArg
An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.

DEFAULT_PALETTE.map()

DEFAULT_PALETTE.map<U>(callbackfn: (value: string, index: number, array: readonly string[]) => U, thisArg?: any): U[]

Calls a defined callback function on each element of an array, and returns an array that contains the results.

callbackfn
A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array.
thisArg
An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.

DEFAULT_PALETTE.filter()

DEFAULT_PALETTE.filter<S extends string>(predicate: (value: string, index: number, array: readonly string[]) => value is S, thisArg?: any): S[]
DEFAULT_PALETTE.filter(predicate: (value: string, index: number, array: readonly string[]) => unknown, thisArg?: any): string[]

Returns the elements of an array that meet the condition specified in a callback function.

predicate
A function that accepts up to three arguments. The filter method calls the predicate function one time for each element in the array.
thisArg
An object to which the this keyword can refer in the predicate function. If thisArg is omitted, undefined is used as the this value.

DEFAULT_PALETTE.reduce()

DEFAULT_PALETTE.reduce(callbackfn: (previousValue: string, currentValue: string, currentIndex: number, array: readonly string[]) => string): string
DEFAULT_PALETTE.reduce(callbackfn: (previousValue: string, currentValue: string, currentIndex: number, array: readonly string[]) => string, initialValue: string): string
DEFAULT_PALETTE.reduce<U>(callbackfn: (previousValue: U, currentValue: string, currentIndex: number, array: readonly string[]) => U, initialValue: U): U

Calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function.

callbackfn
A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array.
initialValue
If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value.

Calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function.

callbackfn
A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array.
initialValue
If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value.
callbackfn
A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array.
initialValue
If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value.

DEFAULT_PALETTE.reduceRight()

DEFAULT_PALETTE.reduceRight(callbackfn: (previousValue: string, currentValue: string, currentIndex: number, array: readonly string[]) => string): string
DEFAULT_PALETTE.reduceRight(callbackfn: (previousValue: string, currentValue: string, currentIndex: number, array: readonly string[]) => string, initialValue: string): string
DEFAULT_PALETTE.reduceRight<U>(callbackfn: (previousValue: U, currentValue: string, currentIndex: number, array: readonly string[]) => U, initialValue: U): U

Calls the specified callback function for all the elements in an array, in descending order. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function.

callbackfn
A function that accepts up to four arguments. The reduceRight method calls the callbackfn function one time for each element in the array.
initialValue
If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value.

Calls the specified callback function for all the elements in an array, in descending order. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function.

callbackfn
A function that accepts up to four arguments. The reduceRight method calls the callbackfn function one time for each element in the array.
initialValue
If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value.
callbackfn
A function that accepts up to four arguments. The reduceRight method calls the callbackfn function one time for each element in the array.
initialValue
If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value.

DEFAULT_PALETTE.find()

DEFAULT_PALETTE.find<S extends string>(predicate: (value: string, index: number, obj: readonly string[]) => value is S, thisArg?: any): S
DEFAULT_PALETTE.find(predicate: (value: string, index: number, obj: readonly string[]) => unknown, thisArg?: any): string

Returns the value of the first element in the array where predicate is true, and undefined otherwise.

predicate
find calls predicate once for each element of the array, in ascending order, until it finds one where predicate returns true. If such an element is found, find immediately returns that element value. Otherwise, find returns undefined.
thisArg
If provided, it will be used as the this value for each invocation of predicate. If it is not provided, undefined is used instead.

DEFAULT_PALETTE.findIndex()

DEFAULT_PALETTE.findIndex(predicate: (value: string, index: number, obj: readonly string[]) => unknown, thisArg?: any): number

Returns the index of the first element in the array where predicate is true, and -1 otherwise.

predicate
find calls predicate once for each element of the array, in ascending order, until it finds one where predicate returns true. If such an element is found, findIndex immediately returns that element index. Otherwise, findIndex returns -1.
thisArg
If provided, it will be used as the this value for each invocation of predicate. If it is not provided, undefined is used instead.

DEFAULT_PALETTE.entries()

DEFAULT_PALETTE.entries(): ArrayIterator<[number, string]>

Returns an iterable of key, value pairs for every entry in the array

DEFAULT_PALETTE.keys()

DEFAULT_PALETTE.keys(): ArrayIterator<number>

Returns an iterable of keys in the array

DEFAULT_PALETTE.includes()

DEFAULT_PALETTE.includes(searchElement: string, fromIndex?: number): boolean

Determines whether an array includes a certain element, returning true or false as appropriate.

searchElement
The element to search for.
fromIndex
The position in this array at which to begin searching for searchElement.

DEFAULT_PALETTE.flatMap()

DEFAULT_PALETTE.flatMap<U, This = undefined>(callback: (this: This, value: string, index: number, array: string[]) => U | readonly U[], thisArg?: This): U[]

Calls a defined callback function on each element of an array. Then, flattens the result into a new array. This is identical to a map followed by flat with depth 1.

callback
A function that accepts up to three arguments. The flatMap method calls the callback function one time for each element in the array.
thisArg
An object to which the this keyword can refer in the callback function. If thisArg is omitted, undefined is used as the this value.

DEFAULT_PALETTE.flat()

DEFAULT_PALETTE.flat<A, D extends number = 1>(this: A, depth?: D): FlatArray<A, D>[]

Returns a new array with all sub-array elements concatenated into it recursively up to the specified depth.

depth
The maximum recursion depth

DEFAULT_PALETTE.at()

DEFAULT_PALETTE.at(index: number): string

Returns the item located at the specified index.

index
The zero-based index of the desired code unit. A negative index will count back from the last item.

DEFAULT_PALETTE.findLast()

DEFAULT_PALETTE.findLast<S extends string>(predicate: (value: string, index: number, array: readonly string[]) => value is S, thisArg?: any): S
DEFAULT_PALETTE.findLast(predicate: (value: string, index: number, array: readonly string[]) => unknown, thisArg?: any): string

Returns the value of the last element in the array where predicate is true, and undefined otherwise.

predicate
findLast calls predicate once for each element of the array, in descending order, until it finds one where predicate returns true. If such an element is found, findLast immediately returns that element value. Otherwise, findLast returns undefined.
thisArg
If provided, it will be used as the this value for each invocation of predicate. If it is not provided, undefined is used instead.

DEFAULT_PALETTE.findLastIndex()

DEFAULT_PALETTE.findLastIndex(predicate: (value: string, index: number, array: readonly string[]) => unknown, thisArg?: any): number

Returns the index of the last element in the array where predicate is true, and -1 otherwise.

predicate
findLastIndex calls predicate once for each element of the array, in descending order, until it finds one where predicate returns true. If such an element is found, findLastIndex immediately returns that element index. Otherwise, findLastIndex returns -1.
thisArg
If provided, it will be used as the this value for each invocation of predicate. If it is not provided, undefined is used instead.

DEFAULT_PALETTE.toReversed()

DEFAULT_PALETTE.toReversed(): string[]

Copies the array and returns the copied array with all of its elements reversed.

DEFAULT_PALETTE.toSorted()

DEFAULT_PALETTE.toSorted(compareFn?: (a: string, b: string) => number): string[]

Copies and sorts the array.

compareFn
Function used to determine the order of the elements. It is expected to return a negative value if the first argument is less than the second argument, zero if they're equal, and a positive value otherwise. If omitted, the elements are sorted in ascending, ASCII character order. ``ts [11, 2, 22, 1].toSorted((a, b) => a - b) // [1, 2, 11, 22] ``

DEFAULT_PALETTE.toSpliced()

DEFAULT_PALETTE.toSpliced(start: number, deleteCount: number, ...items: string[]): string[]
DEFAULT_PALETTE.toSpliced(start: number, deleteCount?: number): string[]

Copies an array and removes elements while, if necessary, inserting new elements in their place, returning the remaining elements.

start
The zero-based location in the array from which to start removing elements.
deleteCount
The number of elements to remove.
items
Elements to insert into the copied array in place of the deleted elements.

Returns A copy of the original array with the remaining elements.

Copies an array and removes elements while returning the remaining elements.

start
The zero-based location in the array from which to start removing elements.
deleteCount
The number of elements to remove.

Returns A copy of the original array with the remaining elements.

DEFAULT_PALETTE.with()

DEFAULT_PALETTE.with(index: number, value: string): string[]

Copies an array, then overwrites the value at the provided index with the given value. If the index is negative, then it replaces from the end of the array

index
The index of the value to overwrite. If the index is negative, then it replaces from the end of the array.
value
The value to insert into the copied array.

Returns A copy of the original array with the inserted value.

DEFAULT_PALETTE.length

DEFAULT_PALETTE.length: number

Gets the length of the array. This is a number one higher than the highest element defined in an array.

DEFAULT_PALETTE.__@unscopables@73

Is an object whose properties have the value 'true' when they will be absent when used in a 'with' statement.

DEFAULT_PALETTE.__@unscopables@73.concat

DEFAULT_PALETTE.__@unscopables@73.concat: boolean

Combines two or more arrays.

items
Additional items to add to the end of array1.
items
Additional items to add to the end of array1.

DEFAULT_PALETTE.__@unscopables@73.join

DEFAULT_PALETTE.__@unscopables@73.join: boolean

Adds all the elements of an array separated by the specified separator string.

separator
A string used to separate one element of an array from the next in the resulting String. If omitted, the array elements are separated with a comma.

DEFAULT_PALETTE.__@unscopables@73.slice

DEFAULT_PALETTE.__@unscopables@73.slice: boolean

Returns a section of an array.

start
The beginning of the specified portion of the array.
end
The end of the specified portion of the array. This is exclusive of the element at the index 'end'.

DEFAULT_PALETTE.__@unscopables@73.indexOf

DEFAULT_PALETTE.__@unscopables@73.indexOf: boolean

Returns the index of the first occurrence of a value in an array.

searchElement
The value to locate in the array.
fromIndex
The array index at which to begin the search. If fromIndex is omitted, the search starts at index 0.

DEFAULT_PALETTE.__@unscopables@73.lastIndexOf

DEFAULT_PALETTE.__@unscopables@73.lastIndexOf: boolean

Returns the index of the last occurrence of a specified value in an array.

searchElement
The value to locate in the array.
fromIndex
The array index at which to begin the search. If fromIndex is omitted, the search starts at the last index in the array.

DEFAULT_PALETTE.__@unscopables@73.every

DEFAULT_PALETTE.__@unscopables@73.every: boolean

Determines whether all the members of an array satisfy the specified test.

predicate
A function that accepts up to three arguments. The every method calls the predicate function for each element in the array until the predicate returns a value which is coercible to the Boolean value false, or until the end of the array.
thisArg
An object to which the this keyword can refer in the predicate function. If thisArg is omitted, undefined is used as the this value.
predicate
A function that accepts up to three arguments. The every method calls the predicate function for each element in the array until the predicate returns a value which is coercible to the Boolean value false, or until the end of the array.
thisArg
An object to which the this keyword can refer in the predicate function. If thisArg is omitted, undefined is used as the this value.

DEFAULT_PALETTE.__@unscopables@73.some

DEFAULT_PALETTE.__@unscopables@73.some: boolean

Determines whether the specified callback function returns true for any element of an array.

predicate
A function that accepts up to three arguments. The some method calls the predicate function for each element in the array until the predicate returns a value which is coercible to the Boolean value true, or until the end of the array.
thisArg
An object to which the this keyword can refer in the predicate function. If thisArg is omitted, undefined is used as the this value.

DEFAULT_PALETTE.__@unscopables@73.forEach

DEFAULT_PALETTE.__@unscopables@73.forEach: boolean

Performs the specified action for each element in an array.

callbackfn
A function that accepts up to three arguments. forEach calls the callbackfn function one time for each element in the array.
thisArg
An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.

DEFAULT_PALETTE.__@unscopables@73.map

DEFAULT_PALETTE.__@unscopables@73.map: boolean

Calls a defined callback function on each element of an array, and returns an array that contains the results.

callbackfn
A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array.
thisArg
An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.

DEFAULT_PALETTE.__@unscopables@73.filter

DEFAULT_PALETTE.__@unscopables@73.filter: boolean

Returns the elements of an array that meet the condition specified in a callback function.

predicate
A function that accepts up to three arguments. The filter method calls the predicate function one time for each element in the array.
thisArg
An object to which the this keyword can refer in the predicate function. If thisArg is omitted, undefined is used as the this value.
predicate
A function that accepts up to three arguments. The filter method calls the predicate function one time for each element in the array.
thisArg
An object to which the this keyword can refer in the predicate function. If thisArg is omitted, undefined is used as the this value.

DEFAULT_PALETTE.__@unscopables@73.reduce

DEFAULT_PALETTE.__@unscopables@73.reduce: boolean

Calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function.

callbackfn
A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array.
initialValue
If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value.
callbackfn
A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array.
initialValue
If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value.

DEFAULT_PALETTE.__@unscopables@73.reduceRight

DEFAULT_PALETTE.__@unscopables@73.reduceRight: boolean

Calls the specified callback function for all the elements in an array, in descending order. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function.

callbackfn
A function that accepts up to four arguments. The reduceRight method calls the callbackfn function one time for each element in the array.
initialValue
If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value.
callbackfn
A function that accepts up to four arguments. The reduceRight method calls the callbackfn function one time for each element in the array.
initialValue
If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value.

DEFAULT_PALETTE.__@unscopables@73.find

DEFAULT_PALETTE.__@unscopables@73.find: boolean

Returns the value of the first element in the array where predicate is true, and undefined otherwise.

predicate
find calls predicate once for each element of the array, in ascending order, until it finds one where predicate returns true. If such an element is found, find immediately returns that element value. Otherwise, find returns undefined.
thisArg
If provided, it will be used as the this value for each invocation of predicate. If it is not provided, undefined is used instead.

DEFAULT_PALETTE.__@unscopables@73.findIndex

DEFAULT_PALETTE.__@unscopables@73.findIndex: boolean

Returns the index of the first element in the array where predicate is true, and -1 otherwise.

predicate
find calls predicate once for each element of the array, in ascending order, until it finds one where predicate returns true. If such an element is found, findIndex immediately returns that element index. Otherwise, findIndex returns -1.
thisArg
If provided, it will be used as the this value for each invocation of predicate. If it is not provided, undefined is used instead.

DEFAULT_PALETTE.__@unscopables@73.includes

DEFAULT_PALETTE.__@unscopables@73.includes: boolean

Determines whether an array includes a certain element, returning true or false as appropriate.

searchElement
The element to search for.
fromIndex
The position in this array at which to begin searching for searchElement.

DEFAULT_PALETTE.__@unscopables@73.flatMap

DEFAULT_PALETTE.__@unscopables@73.flatMap: boolean

Calls a defined callback function on each element of an array. Then, flattens the result into a new array. This is identical to a map followed by flat with depth 1.

callback
A function that accepts up to three arguments. The flatMap method calls the callback function one time for each element in the array.
thisArg
An object to which the this keyword can refer in the callback function. If thisArg is omitted, undefined is used as the this value.

DEFAULT_PALETTE.__@unscopables@73.flat

DEFAULT_PALETTE.__@unscopables@73.flat: boolean

Returns a new array with all sub-array elements concatenated into it recursively up to the specified depth.

depth
The maximum recursion depth

DEFAULT_PALETTE.__@unscopables@73.at

DEFAULT_PALETTE.__@unscopables@73.at: boolean

Returns the item located at the specified index.

index
The zero-based index of the desired code unit. A negative index will count back from the last item.

DEFAULT_PALETTE.__@unscopables@73.findLast

DEFAULT_PALETTE.__@unscopables@73.findLast: boolean

Returns the value of the last element in the array where predicate is true, and undefined otherwise.

predicate
findLast calls predicate once for each element of the array, in descending order, until it finds one where predicate returns true. If such an element is found, findLast immediately returns that element value. Otherwise, findLast returns undefined.
thisArg
If provided, it will be used as the this value for each invocation of predicate. If it is not provided, undefined is used instead.

DEFAULT_PALETTE.__@unscopables@73.findLastIndex

DEFAULT_PALETTE.__@unscopables@73.findLastIndex: boolean

Returns the index of the last element in the array where predicate is true, and -1 otherwise.

predicate
findLastIndex calls predicate once for each element of the array, in descending order, until it finds one where predicate returns true. If such an element is found, findLastIndex immediately returns that element index. Otherwise, findLastIndex returns -1.
thisArg
If provided, it will be used as the this value for each invocation of predicate. If it is not provided, undefined is used instead.

DEFAULT_PALETTE.__@unscopables@73.toSorted

DEFAULT_PALETTE.__@unscopables@73.toSorted: boolean

Copies and sorts the array.

compareFn
Function used to determine the order of the elements. It is expected to return a negative value if the first argument is less than the second argument, zero if they're equal, and a positive value otherwise. If omitted, the elements are sorted in ascending, ASCII character order. ``ts [11, 2, 22, 1].toSorted((a, b) => a - b) // [1, 2, 11, 22] ``

DEFAULT_PALETTE.__@unscopables@73.toSpliced

DEFAULT_PALETTE.__@unscopables@73.toSpliced: boolean

Copies an array and removes elements while, if necessary, inserting new elements in their place, returning the remaining elements. Copies an array and removes elements while returning the remaining elements.

start
The zero-based location in the array from which to start removing elements.
deleteCount
The number of elements to remove.
items
Elements to insert into the copied array in place of the deleted elements.
start
The zero-based location in the array from which to start removing elements.
deleteCount
The number of elements to remove.

Returns A copy of the original array with the remaining elements.

DEFAULT_PALETTE.__@unscopables@73.with

DEFAULT_PALETTE.__@unscopables@73.with: boolean

Copies an array, then overwrites the value at the provided index with the given value. If the index is negative, then it replaces from the end of the array

index
The index of the value to overwrite. If the index is negative, then it replaces from the end of the array.
value
The value to insert into the copied array.

Returns A copy of the original array with the inserted value.

display

Where a plot or an input value is shown (display option).

display.none

display.none: "none"

Not shown anywhere; the values still exist for alerts and other scripts.

display.all

display.all: "all"

Shown everywhere: on the pane, in the status line and in the data window.

display.status_line

display.status_line: "status_line"

Shown only in the status line of the script.

display.pane

display.pane: "pane"

Drawn only on the pane, not in the status line or the data window.

dividends

Dividends: the fields of request.dividends (dividends.gross, dividends.net) and the next announced dividend of the chart symbol.

dividends.net

dividends.net: "net"

The dividend after taxes (the default field of request.dividends).

dividends.future_amount

dividends.future_amount: number

Amount of the next announced dividend (net); na when none is announced.

dividends.future_ex_date

dividends.future_ex_date: number

Ex-date of the next announced dividend (UNIX time in ms); na when none is announced.

dividends.future_pay_date

dividends.future_pay_date: number

Payment date of the next announced dividend (UNIX time in ms); na when none is announced.

earnings

Earnings: the fields of request.earnings (earnings.actual, earnings.estimate...) and the next earnings release of the chart symbol.

earnings.actual

earnings.actual: "actual"

The reported earnings per share (the default field of request.earnings).

earnings.estimate

earnings.estimate: "estimate"

The analysts' estimate of the earnings per share.

earnings.future_eps

earnings.future_eps: number

Estimated earnings per share of the next release; na when none is announced.

earnings.future_revenue

earnings.future_revenue: number

Estimated revenue of the next release; na when none is announced.

earnings.future_time

earnings.future_time: number

Time of the next release (UNIX time in ms); na when none is announced.

earnings.future_period_end_time

earnings.future_period_end_time: number

End of the fiscal period of the next release (UNIX time in ms); na when none is announced.

extend

How far a line (or a box's top and bottom) is drawn past its two points (extend option).

extend.none

extend.none: "none"

Not extended: drawn between its two points only (the default).

extend.left

extend.left: "left"

Extended to the left edge of the chart, past the first point.

extend.right

extend.right: "right"

Extended to the right edge of the chart, past the second point.

extend.both

extend.both: "both"

Extended in both directions.

font

Font families of labels, boxes and table cells (text_font_family option).

font.family_monospace

font.family_monospace: "monospace"

A monospace font: every character has the same width.

format

Number formats: the format option of indicator() and the format of str.tostring().

format.inherit

format.inherit: "inherit"

The same format as the chart symbol.

format.price

format.price: "price"

A price, with the precision of the script or of the symbol.

format.volume

format.volume: "volume"

A volume, shortened with K, M, B, T (12345 shows as "12.345K").

format.percent

format.percent: "percent"

A percentage: two decimals and a "%" sign; the value is not multiplied by 100.

format.mintick

format.mintick: "mintick"

Rounded to the tick size of the symbol (syminfo.mintick).

hline

hline()

hline(price: number, title?: string, options?: ScriptHLineOptions): PlotHandle

Draws a horizontal line at a fixed price (a level such as 70 / 30 on an oscillator).

price
Price of the line.
title
Name of the line in the settings. Default: "Level".
options
Colour, line style and width. Default: {} (a dashed line).
color? string
Colour of the line. Default: the host's (grey).
linestyle? "solid" | "dashed" | "dotted"
Line style: hline.style_solid, hline.style_dotted or hline.style_dashed. Default: dashed.
linewidth? number
Width of the line in pixels. Default: 1.
editable? boolean
false: not listed in the style settings of the script. Default: true.

Returns A handle to pass to fill().

const top = hline(70, "Overbought", { color: color.red });
const bottom = hline(30, "Oversold", { linestyle: hline.style_dotted });
fill(top, bottom, color.new(color.purple, 90));

input

Script inputs: each input.* call declares a setting the user can change AND returns its current value (the user's value when there is one, else the default). The arguments after the default can be named: input.int(14, "Length", { minval: 1 }), input.int(14, { title: "Length", minval: 1 }) or input.int({ defval: 14, title: "Length" }). The input id is the title in snake case ("Fast length" is fast_length); keep titles stable, a renamed input loses the user's value.

input.int()

input.int(defval: number | InputArgs<NumericInputOptions, number>, title?: string | InputArgs<NumericInputOptions, number>, opts?: NumericInputOptions): number

Declares a whole-number setting (a length, a count) and returns its value, rounded to an integer.

defval
Default value, or every argument by name ({ defval, title, minval... }).
title
Label in the settings, or the options with title in them. Default: none (id input_int).
opts
minval, maxval, step, options (a choice list) and the common input options.
minval? number
Smallest value the user can enter. Default: no minimum.
maxval? number
Largest value the user can enter. Default: no maximum.
step? number
Step of the arrows of the number field. Default: the host's choice (1 for an int).
options? number[]
The values to choose from (the host shows a drop-down list). Default: a free number field.
group? string
Group title: every input with the same group is listed under it, at the place of the group's first input. Default: no group.
inline? string
Inputs with the same inline id share one row of their group (ungrouped inputs share rows among themselves). Default: a row of its own.
tooltip? string
Help text shown next to the input. Default: none.
confirm? boolean
true: the host asks for the value when the script is added to a chart. Default: false.
display? "none" | "all" | "data_window" | "status_line"
Where the value is shown besides the settings: display.all, display.none, display.status_line or display.data_window. Default: 'none' for bool, color, time and text_area inputs, 'all' for the others.
active? boolean | InputCondition
false greys the input out in the settings (it keeps its value). A boolean (active: showMa), or a condition on input ids that a host can apply without running the script (active: 'ma_1', active: { input: 'type', ne: 'None' }). Default: true.
id? string
The id of the input (letters, digits and _): the name of its value in the inputs given to the run. Default: made from the title ("Fast length" gives fast_length), which changes when the title changes.

Returns The current value: the user's value, else defval.

const length = input.int(14, "Length", { minval: 1, maxval: 500 });
plot(ta.rsi(close, length), "RSI");

input.float()

input.float(defval: number | InputArgs<NumericInputOptions, number>, title?: string | InputArgs<NumericInputOptions, number>, opts?: NumericInputOptions): number

Declares a decimal-number setting (a multiplier, a percent, a level) and returns its value.

defval
Default value, or every argument by name ({ defval, title, minval... }).
title
Label in the settings, or the options with title in them. Default: none (id input_float).
opts
minval, maxval, step, options (a choice list) and the common input options.
minval? number
Smallest value the user can enter. Default: no minimum.
maxval? number
Largest value the user can enter. Default: no maximum.
step? number
Step of the arrows of the number field. Default: the host's choice (1 for an int).
options? number[]
The values to choose from (the host shows a drop-down list). Default: a free number field.
group? string
Group title: every input with the same group is listed under it, at the place of the group's first input. Default: no group.
inline? string
Inputs with the same inline id share one row of their group (ungrouped inputs share rows among themselves). Default: a row of its own.
tooltip? string
Help text shown next to the input. Default: none.
confirm? boolean
true: the host asks for the value when the script is added to a chart. Default: false.
display? "none" | "all" | "data_window" | "status_line"
Where the value is shown besides the settings: display.all, display.none, display.status_line or display.data_window. Default: 'none' for bool, color, time and text_area inputs, 'all' for the others.
active? boolean | InputCondition
false greys the input out in the settings (it keeps its value). A boolean (active: showMa), or a condition on input ids that a host can apply without running the script (active: 'ma_1', active: { input: 'type', ne: 'None' }). Default: true.
id? string
The id of the input (letters, digits and _): the name of its value in the inputs given to the run. Default: made from the title ("Fast length" gives fast_length), which changes when the title changes.

Returns The current value: the user's value, else defval.

const mult = input.float(2.0, "Multiplier", { minval: 0.1, step: 0.1 });
const [basis, upper, lower] = ta.bb(close, 20, mult);

input.bool()

input.bool(defval: boolean | InputArgs<InputOptions, boolean>, title?: string | InputArgs<InputOptions, boolean>, opts?: InputOptions): boolean

Declares an on / off setting (a checkbox) and returns its value. Shown only in the settings by default.

defval
Default value, or every argument by name ({ defval, title... }).
title
Label in the settings, or the options with title in them. Default: none (id input_bool).
opts
The common input options (group, inline, tooltip, confirm, display, active, id).
group? string
Group title: every input with the same group is listed under it, at the place of the group's first input. Default: no group.
inline? string
Inputs with the same inline id share one row of their group (ungrouped inputs share rows among themselves). Default: a row of its own.
tooltip? string
Help text shown next to the input. Default: none.
confirm? boolean
true: the host asks for the value when the script is added to a chart. Default: false.
display? "none" | "all" | "data_window" | "status_line"
Where the value is shown besides the settings: display.all, display.none, display.status_line or display.data_window. Default: 'none' for bool, color, time and text_area inputs, 'all' for the others.
active? boolean | InputCondition
false greys the input out in the settings (it keeps its value). A boolean (active: showMa), or a condition on input ids that a host can apply without running the script (active: 'ma_1', active: { input: 'type', ne: 'None' }). Default: true.
id? string
The id of the input (letters, digits and _): the name of its value in the inputs given to the run. Default: made from the title ("Fast length" gives fast_length), which changes when the title changes.

Returns The current value: the user's value, else defval.

const showMa = input.bool(true, "Show MA");
plot(ta.sma(close, 20), "MA", { display: showMa ? display.all : display.none });

input.string()

input.string(defval: string | InputArgs<StringInputOptions, string>, title?: string | InputArgs<StringInputOptions, string>, opts?: StringInputOptions): string

Declares a text setting and returns its value; with options, a drop-down list of choices.

defval
Default value (one of options when they are given), or every argument by name.
title
Label in the settings, or the options with title in them. Default: none (id input_string).
opts
options (a choice list) and the common input options.
options? string[]
The values to choose from (the host shows a drop-down list). Default: a free text field (or the kind's own picker).
group? string
Group title: every input with the same group is listed under it, at the place of the group's first input. Default: no group.
inline? string
Inputs with the same inline id share one row of their group (ungrouped inputs share rows among themselves). Default: a row of its own.
tooltip? string
Help text shown next to the input. Default: none.
confirm? boolean
true: the host asks for the value when the script is added to a chart. Default: false.
display? "none" | "all" | "data_window" | "status_line"
Where the value is shown besides the settings: display.all, display.none, display.status_line or display.data_window. Default: 'none' for bool, color, time and text_area inputs, 'all' for the others.
active? boolean | InputCondition
false greys the input out in the settings (it keeps its value). A boolean (active: showMa), or a condition on input ids that a host can apply without running the script (active: 'ma_1', active: { input: 'type', ne: 'None' }). Default: true.
id? string
The id of the input (letters, digits and _): the name of its value in the inputs given to the run. Default: made from the title ("Fast length" gives fast_length), which changes when the title changes.

Returns The current value: the user's value, else defval.

const maType = input.string("EMA", "MA type", { options: ["SMA", "EMA"] });
const ma = maType === "SMA" ? ta.sma(close, 20) : ta.ema(close, 20);

input.text_area()

input.text_area(defval: string | InputArgs<InputOptions, string>, title?: string | InputArgs<InputOptions, string>, opts?: InputOptions): string

Declares a multi-line text setting (lines separated by a newline) and returns its value, e.g. a list of levels the script parses. Shown only in the settings by default.

defval
Default text, or every argument by name.
title
Label in the settings, or the options with title in them. Default: none (id input_text_area).
opts
The common input options.
group? string
Group title: every input with the same group is listed under it, at the place of the group's first input. Default: no group.
inline? string
Inputs with the same inline id share one row of their group (ungrouped inputs share rows among themselves). Default: a row of its own.
tooltip? string
Help text shown next to the input. Default: none.
confirm? boolean
true: the host asks for the value when the script is added to a chart. Default: false.
display? "none" | "all" | "data_window" | "status_line"
Where the value is shown besides the settings: display.all, display.none, display.status_line or display.data_window. Default: 'none' for bool, color, time and text_area inputs, 'all' for the others.
active? boolean | InputCondition
false greys the input out in the settings (it keeps its value). A boolean (active: showMa), or a condition on input ids that a host can apply without running the script (active: 'ma_1', active: { input: 'type', ne: 'None' }). Default: true.
id? string
The id of the input (letters, digits and _): the name of its value in the inputs given to the run. Default: made from the title ("Fast length" gives fast_length), which changes when the title changes.

Returns The current text: the user's text, else defval.

const text = input.text_area("100\n105\n110", "Levels");
for (const lvl of text.split("\n")) hline(Number(lvl), "Level " + lvl);

input.color()

input.color(defval: string | InputArgs<InputOptions, string>, title?: string | InputArgs<InputOptions, string>, opts?: InputOptions): string

Declares a colour setting (a colour picker) and returns its value. The default's transparency is kept to 2 decimals (color.new(c, 90) gives the alpha byte 26); a value given by the host is used as it is. Shown only in the settings by default.

defval
Default colour (color.blue, "#2962FF", color.new(...)), or every argument by name.
title
Label in the settings, or the options with title in them. Default: none (id input_color).
opts
The common input options.
group? string
Group title: every input with the same group is listed under it, at the place of the group's first input. Default: no group.
inline? string
Inputs with the same inline id share one row of their group (ungrouped inputs share rows among themselves). Default: a row of its own.
tooltip? string
Help text shown next to the input. Default: none.
confirm? boolean
true: the host asks for the value when the script is added to a chart. Default: false.
display? "none" | "all" | "data_window" | "status_line"
Where the value is shown besides the settings: display.all, display.none, display.status_line or display.data_window. Default: 'none' for bool, color, time and text_area inputs, 'all' for the others.
active? boolean | InputCondition
false greys the input out in the settings (it keeps its value). A boolean (active: showMa), or a condition on input ids that a host can apply without running the script (active: 'ma_1', active: { input: 'type', ne: 'None' }). Default: true.
id? string
The id of the input (letters, digits and _): the name of its value in the inputs given to the run. Default: made from the title ("Fast length" gives fast_length), which changes when the title changes.

Returns The current colour string: the user's colour, else defval.

const lineColor = input.color(color.teal, "Line colour");
plot(ta.ema(close, 20), "EMA", { color: lineColor });

input.source()

input.source(defval?: string | Series, title?: string | InputArgs<InputOptions, string | Series>, opts?: InputOptions): Series

Declares a source setting (the price a calculation reads) and returns it as a Series. The choices are open, high, low, close, volume, hl2, hlc3, ohlc4, hlcc4, and the outputs of other scripts on the chart when the host allows it (an unknown source gives close).

defval
Default source, by name ("close") or as the built-in Series (close), or every argument by name. Default: "close".
title
Label in the settings, or the options with title in them. Default: none (id input_source).
opts
The common input options.
group? string
Group title: every input with the same group is listed under it, at the place of the group's first input. Default: no group.
inline? string
Inputs with the same inline id share one row of their group (ungrouped inputs share rows among themselves). Default: a row of its own.
tooltip? string
Help text shown next to the input. Default: none.
confirm? boolean
true: the host asks for the value when the script is added to a chart. Default: false.
display? "none" | "all" | "data_window" | "status_line"
Where the value is shown besides the settings: display.all, display.none, display.status_line or display.data_window. Default: 'none' for bool, color, time and text_area inputs, 'all' for the others.
active? boolean | InputCondition
false greys the input out in the settings (it keeps its value). A boolean (active: showMa), or a condition on input ids that a host can apply without running the script (active: 'ma_1', active: { input: 'type', ne: 'None' }). Default: true.
id? string
The id of the input (letters, digits and _): the name of its value in the inputs given to the run. Default: made from the title ("Fast length" gives fast_length), which changes when the title changes.

Returns The chosen source as a Series.

const src = input.source(close, "Source");
plot(ta.sma(src, 20), "SMA");

input.timeframe()

input.timeframe(defval: string | InputArgs<StringInputOptions, string>, title?: string | InputArgs<StringInputOptions, string>, opts?: StringInputOptions): string

Declares a timeframe setting (a timeframe picker) and returns its value, for request.security() or timeframe.change().

defval
Default timeframe: "60" (60 minutes), "D", "W", "M"...; "" is the chart's timeframe. Or every argument by name.
title
Label in the settings, or the options with title in them. Default: none (id input_timeframe).
opts
options (a choice list of timeframes) and the common input options.
options? string[]
The values to choose from (the host shows a drop-down list). Default: a free text field (or the kind's own picker).
group? string
Group title: every input with the same group is listed under it, at the place of the group's first input. Default: no group.
inline? string
Inputs with the same inline id share one row of their group (ungrouped inputs share rows among themselves). Default: a row of its own.
tooltip? string
Help text shown next to the input. Default: none.
confirm? boolean
true: the host asks for the value when the script is added to a chart. Default: false.
display? "none" | "all" | "data_window" | "status_line"
Where the value is shown besides the settings: display.all, display.none, display.status_line or display.data_window. Default: 'none' for bool, color, time and text_area inputs, 'all' for the others.
active? boolean | InputCondition
false greys the input out in the settings (it keeps its value). A boolean (active: showMa), or a condition on input ids that a host can apply without running the script (active: 'ma_1', active: { input: 'type', ne: 'None' }). Default: true.
id? string
The id of the input (letters, digits and _): the name of its value in the inputs given to the run. Default: made from the title ("Fast length" gives fast_length), which changes when the title changes.

Returns The current timeframe string ("": the chart's timeframe).

const tf = input.timeframe("D", "Higher timeframe");
const htfClose = request.security("", tf, () => close);

input.session()

input.session(defval: string | InputArgs<StringInputOptions, string>, title?: string | InputArgs<StringInputOptions, string>, opts?: StringInputOptions): string

Declares a trading-hours setting and returns its value, a session string for time() or inSession().

defval
Default session: "HHMM-HHMM", optionally followed by : and the days (1 = Sunday ... 7 = Saturday), e.g. "0930-1600" or "0930-1600:23456". Or every argument by name.
title
Label in the settings, or the options with title in them. Default: none (id input_session).
opts
options (a choice list of sessions) and the common input options.
options? string[]
The values to choose from (the host shows a drop-down list). Default: a free text field (or the kind's own picker).
group? string
Group title: every input with the same group is listed under it, at the place of the group's first input. Default: no group.
inline? string
Inputs with the same inline id share one row of their group (ungrouped inputs share rows among themselves). Default: a row of its own.
tooltip? string
Help text shown next to the input. Default: none.
confirm? boolean
true: the host asks for the value when the script is added to a chart. Default: false.
display? "none" | "all" | "data_window" | "status_line"
Where the value is shown besides the settings: display.all, display.none, display.status_line or display.data_window. Default: 'none' for bool, color, time and text_area inputs, 'all' for the others.
active? boolean | InputCondition
false greys the input out in the settings (it keeps its value). A boolean (active: showMa), or a condition on input ids that a host can apply without running the script (active: 'ma_1', active: { input: 'type', ne: 'None' }). Default: true.
id? string
The id of the input (letters, digits and _): the name of its value in the inputs given to the run. Default: made from the title ("Fast length" gives fast_length), which changes when the title changes.

Returns The current session string.

const sess = input.session("0930-1600", "Session");
bgcolor(color.when(na(time("", sess)).not(), color.new(color.blue, 90)));

input.symbol()

input.symbol(defval: string | InputArgs<StringInputOptions, string>, title?: string | InputArgs<StringInputOptions, string>, opts?: StringInputOptions): string

Declares a symbol setting (a symbol search) and returns its value, a ticker id for request.security() of another symbol.

defval
Default ticker id, "EXCHANGE:TICKER" ("NASDAQ:MSFT"), or every argument by name.
title
Label in the settings, or the options with title in them. Default: none (id input_symbol).
opts
options (a choice list of symbols) and the common input options.
options? string[]
The values to choose from (the host shows a drop-down list). Default: a free text field (or the kind's own picker).
group? string
Group title: every input with the same group is listed under it, at the place of the group's first input. Default: no group.
inline? string
Inputs with the same inline id share one row of their group (ungrouped inputs share rows among themselves). Default: a row of its own.
tooltip? string
Help text shown next to the input. Default: none.
confirm? boolean
true: the host asks for the value when the script is added to a chart. Default: false.
display? "none" | "all" | "data_window" | "status_line"
Where the value is shown besides the settings: display.all, display.none, display.status_line or display.data_window. Default: 'none' for bool, color, time and text_area inputs, 'all' for the others.
active? boolean | InputCondition
false greys the input out in the settings (it keeps its value). A boolean (active: showMa), or a condition on input ids that a host can apply without running the script (active: 'ma_1', active: { input: 'type', ne: 'None' }). Default: true.
id? string
The id of the input (letters, digits and _): the name of its value in the inputs given to the run. Default: made from the title ("Fast length" gives fast_length), which changes when the title changes.

Returns The current ticker id.

const other = input.symbol("NASDAQ:MSFT", "Compare with");
plot(request.security(other, "", () => close), "Other close");

input.price()

input.price(defval: number | InputArgs<InputOptions, number>, title?: string | InputArgs<InputOptions, number>, opts?: InputOptions): number

Declares a price-level setting (a number field) and returns its value. With confirm: true the host can ask the user to pick it on the chart; an inline id shared with an input.time() makes one chart point of both.

defval
Default price, or every argument by name.
title
Label in the settings, or the options with title in them. Default: none (id input_float).
opts
The common input options.
group? string
Group title: every input with the same group is listed under it, at the place of the group's first input. Default: no group.
inline? string
Inputs with the same inline id share one row of their group (ungrouped inputs share rows among themselves). Default: a row of its own.
tooltip? string
Help text shown next to the input. Default: none.
confirm? boolean
true: the host asks for the value when the script is added to a chart. Default: false.
display? "none" | "all" | "data_window" | "status_line"
Where the value is shown besides the settings: display.all, display.none, display.status_line or display.data_window. Default: 'none' for bool, color, time and text_area inputs, 'all' for the others.
active? boolean | InputCondition
false greys the input out in the settings (it keeps its value). A boolean (active: showMa), or a condition on input ids that a host can apply without running the script (active: 'ma_1', active: { input: 'type', ne: 'None' }). Default: true.
id? string
The id of the input (letters, digits and _): the name of its value in the inputs given to the run. Default: made from the title ("Fast length" gives fast_length), which changes when the title changes.

Returns The current price: the user's value, else defval.

const level = input.price(100, "Level", { confirm: true });
hline(level, "Level");

input.enum()

input.enum<F extends EnumField>(defval: F | InputArgs<EnumInputOptions, F>, title?: string | InputArgs<EnumInputOptions, F>, opts?: EnumInputOptions): F

Declares a choice among the fields of an enum made with defineEnum() and returns the chosen field. The settings list the fields by title; the host stores the field's name.

defval
Default field (MaType.sma), or every argument by name. It must be one of options.
title
Label in the settings, or the options with title in them. Default: none (id input_enum).
opts
options (only these fields of the enum) and the common input options.
options? EnumField[]
The fields to choose from, all of the default's enum. Default: every field of the enum.
group? string
Group title: every input with the same group is listed under it, at the place of the group's first input. Default: no group.
inline? string
Inputs with the same inline id share one row of their group (ungrouped inputs share rows among themselves). Default: a row of its own.
tooltip? string
Help text shown next to the input. Default: none.
confirm? boolean
true: the host asks for the value when the script is added to a chart. Default: false.
display? "none" | "all" | "data_window" | "status_line"
Where the value is shown besides the settings: display.all, display.none, display.status_line or display.data_window. Default: 'none' for bool, color, time and text_area inputs, 'all' for the others.
active? boolean | InputCondition
false greys the input out in the settings (it keeps its value). A boolean (active: showMa), or a condition on input ids that a host can apply without running the script (active: 'ma_1', active: { input: 'type', ne: 'None' }). Default: true.
id? string
The id of the input (letters, digits and _): the name of its value in the inputs given to the run. Default: made from the title ("Fast length" gives fast_length), which changes when the title changes.

Returns The chosen field; compare it with ===.

const MaType = defineEnum({ sma: "Simple", ema: "Exponential" });
const maType = input.enum(MaType.sma, "Average");
const ma = maType === MaType.ema ? ta.ema(close, 20) : ta.sma(close, 20);

input.time()

input.time(defval: number | InputArgs<InputOptions, number>, title?: string | InputArgs<InputOptions, number>, opts?: InputOptions): number

Declares a date-and-time setting and returns it as a UNIX time in milliseconds. With confirm: true the host can ask the user to pick it on the chart. Shown only in the settings by default.

defval
Default time in ms, usually from timestamp(), or every argument by name.
title
Label in the settings, or the options with title in them. Default: none (id input_time).
opts
The common input options.
group? string
Group title: every input with the same group is listed under it, at the place of the group's first input. Default: no group.
inline? string
Inputs with the same inline id share one row of their group (ungrouped inputs share rows among themselves). Default: a row of its own.
tooltip? string
Help text shown next to the input. Default: none.
confirm? boolean
true: the host asks for the value when the script is added to a chart. Default: false.
display? "none" | "all" | "data_window" | "status_line"
Where the value is shown besides the settings: display.all, display.none, display.status_line or display.data_window. Default: 'none' for bool, color, time and text_area inputs, 'all' for the others.
active? boolean | InputCondition
false greys the input out in the settings (it keeps its value). A boolean (active: showMa), or a condition on input ids that a host can apply without running the script (active: 'ma_1', active: { input: 'type', ne: 'None' }). Default: true.
id? string
The id of the input (letters, digits and _): the name of its value in the inputs given to the run. Default: made from the title ("Fast length" gives fast_length), which changes when the title changes.

Returns The current time in ms: the user's value, else defval.

const start = input.time(timestamp("2024-01-01"), "Start");
bgcolor(color.when(time.gte(start), color.new(color.green, 90)));

location

Where plotshape() and plotchar() draw their marker (location option).

location.abovebar

location.abovebar: "abovebar"

Above the high of the bar (the default of plotshape() and plotchar()).

location.top

location.top: "top"

At the top edge of the pane.

location.bottom

location.bottom: "bottom"

At the bottom edge of the pane.

location.absolute

location.absolute: "absolute"

At the value of the series itself, read as a price (bars where it is na or 0 get no marker).

log

Messages for the logs panel: log.info, log.warning and log.error. Inside eachBar() a call makes a message on the current bar; at the top level, one message per bar. With arguments the message is a str.format() pattern.

log.info()

log.info(message: string | readonly string[], ...args: unknown[]): void

Writes an information message to the logs panel, on the current bar inside a bar loop, on every bar at the top level. With arguments, message is a pattern whose {0}, {1}... are replaced by the arguments, as in str.format(); a Series argument gives its value on the bar.

message
The text, or a pattern with {0}, {1}... At the top level it can also be an array with one text per bar; a bar whose text is undefined gets no message.
args
Values for the placeholders of the pattern: numbers, texts, Series... Default: none.
eachBar((c) => {
  if (c.i === c.n - 1) log.info("Last close {0}", c.close);
});

log.warning()

log.warning(message: string | readonly string[], ...args: unknown[]): void

Writes a warning message to the logs panel, on the current bar inside a bar loop, on every bar at the top level. With arguments, message is a pattern whose {0}, {1}... are replaced by the arguments, as in str.format(); a Series argument gives its value on the bar.

message
The text, or a pattern with {0}, {1}... At the top level it can also be an array with one text per bar; a bar whose text is undefined gets no message.
args
Values for the placeholders of the pattern: numbers, texts, Series... Default: none.
eachBar((c) => {
  if (c.volume === 0) log.warning("No volume on bar {0}", c.i);
});

log.error()

log.error(message: string | readonly string[], ...args: unknown[]): void

Writes an error message to the logs panel, on the current bar inside a bar loop, on every bar at the top level. It does not stop the script. With arguments, message is a pattern whose {0}, {1}... are replaced by the arguments, as in str.format(); a Series argument gives its value on the bar.

message
The text, or a pattern with {0}, {1}... At the top level it can also be an array with one text per bar; a bar whose text is undefined gets no message.
args
Values for the placeholders of the pattern: numbers, texts, Series... Default: none.
eachBar((c) => {
  if (c.high < c.low) log.error("High below low on bar {0}", c.i);
});

math

Math functions and constants for numbers and Series: rounding, min and max, powers and logarithms, trigonometry, random numbers, math.pi... A Series argument gives a Series, numbers give a number. math.round_to_mintick uses the symbol's tick size.

math.abs()

math.abs(value: Series): Series
math.abs(value: number): number

Returns the absolute value of a number.

value
The number or Series

Returns The absolute value (always non-negative)

math.abs(5) // Returns: 5
math.abs(-5) // Returns: 5
math.abs(0) // Returns: 0

math.ceil()

math.ceil(value: Series): Series
math.ceil(value: number): number

Returns the smallest integer greater than or equal to a given number (rounds up).

value
The number to round up or Series

Returns The ceiling value (smallest integer ≥ value)

math.ceil(4.2) // Returns: 5
math.ceil(4.8) // Returns: 5
math.ceil(-4.2) // Returns: -4
math.ceil(5) // Returns: 5

math.floor()

math.floor(value: Series): Series
math.floor(value: number): number

Returns the largest integer less than or equal to a given number (rounds down).

value
The number to round down or Series

Returns The floor value (largest integer ≤ value)

math.floor(4.2) // Returns: 4
math.floor(4.8) // Returns: 4
math.floor(-4.2) // Returns: -5
math.floor(5) // Returns: 5

math.round()

math.round(value: Series, precision?: number): Series
math.round(value: number, precision?: number): number

Returns the value rounded to the nearest integer or to a specified precision.

value
The number to round or Series
precision
Optional number of decimal places (default: 0)

Returns The rounded value

math.round(4.2) // Returns: 4
math.round(4.5) // Returns: 5
math.round(-2.5) // Returns: -3
math.round(4.567, 2) // Returns: 4.57
math.round(1.005, 2) // Returns: 1.01

math.constant()

math.constant(value: number): number

Rounds the result of a constant float expression (literals and constants only, e.g. 1 / 255) the way the original script language computes constants before a run: values of 0.001 or more get 16 decimals. Wrap the constant expressions of a ported script with it so its results match bit for bit.

value
The result of the constant expression, computed in JavaScript (e.g. 1 / 255)

Returns The rounded value

const i_255 = math.constant(1 / 255) // 0.003921568627451 (JavaScript: 0.00392156862745098)
math.constant(1 / 7) // 0.1428571428571428 (JavaScript: 0.14285714285714285)
math.constant(1 / 3) // 0.3333333333333333 (unchanged)

math.max()

math.max(...values: (number | Series)[]): number | Series

Returns the maximum value from the arguments.

values
Variable number of values to compare (numbers or Series)

Returns The largest value

math.max(1, 2, 3) // Returns: 3
math.max(-1, -5, -2) // Returns: -1
math.max(10) // Returns: 10
math.max(5, 10, 3, 8) // Returns: 10

math.min()

math.min(...values: (number | Series)[]): number | Series

Returns the minimum value from the arguments.

values
Variable number of values to compare (numbers or Series)

Returns The smallest value

math.min(1, 2, 3) // Returns: 1
math.min(-1, -5, -2) // Returns: -5
math.min(10) // Returns: 10
math.min(5, 10, 3, 8) // Returns: 3

math.avg()

math.avg(...values: (number | Series)[]): number | Series

Returns the average (arithmetic mean) of the arguments.

values
Variable number of values (numbers or Series)

Returns The arithmetic mean

math.avg(1, 2, 3) // Returns: 2
math.avg(10, 20) // Returns: 15
math.avg(5) // Returns: 5
math.avg(1, 2, 3, 4, 5) // Returns: 3

math.sum()

math.sum(source: Series, length: number | Series | ArrayLike<number>): Series
math.sum(source: series_float, length: number | Series | ArrayLike<number>): series_float

Returns the sum of values over a sliding window.

source
Series of values or array
length
Window length for summation, or one length per bar (a series length: array or Series)

Returns Series or array with rolling sum values

math.sum([1, 2, 3, 4, 5], 3) // Returns: [NaN, NaN, 6, 9, 12]
// Explanation: [NaN, NaN, 1+2+3, 2+3+4, 3+4+5]

math.sqrt()

math.sqrt(value: Series): Series
math.sqrt(value: number): number

Returns the square root of a number.

value
The number (must be non-negative) or Series

Returns The square root (√value)

math.sqrt(9) // Returns: 3
math.sqrt(16) // Returns: 4
math.sqrt(2) // Returns: 1.414...
math.sqrt(0) // Returns: 0

math.pow()

math.pow(base: Series, exponent: number): Series
math.pow(base: number, exponent: Series): Series
math.pow(base: Series, exponent: Series): Series
math.pow(base: number, exponent: number): number

Returns base raised to the power of exponent.

base
The base number or Series
exponent
The exponent (power) or Series

Returns base^exponent

math.pow(2, 3) // Returns: 8 (2³)
math.pow(10, 2) // Returns: 100
math.pow(5, 0) // Returns: 1
math.pow(2, -1) // Returns: 0.5

math.exp()

math.exp(value: Series): Series
math.exp(value: number): number

Returns e (Euler's number) raised to the power of value.

value
The exponent or Series

Returns e^value (where e ≈ 2.71828)

math.exp(0) // Returns: 1
math.exp(1) // Returns: 2.71828... (e)
math.exp(2) // Returns: 7.389...
math.exp(-1) // Returns: 0.3678...

math.log()

math.log(value: Series): Series
math.log(value: number): number

Returns the natural logarithm (base e) of a number.

value
The number (must be positive) or Series

Returns ln(value)

math.log(1) // Returns: 0
math.log(Math.E) // Returns: 1
math.log(10) // Returns: 2.302...
math.log(100) // Returns: 4.605...

math.log10()

math.log10(value: Series): Series
math.log10(value: number): number

Returns the base-10 logarithm of a number.

value
The number (must be positive) or Series

Returns log₁₀(value)

math.log10(10) // Returns: 1
math.log10(100) // Returns: 2
math.log10(1000) // Returns: 3
math.log10(1) // Returns: 0

math.sin()

math.sin(value: Series): Series
math.sin(value: number): number

Returns the sine of an angle in radians.

value
The angle in radians or Series

Returns The sine value (range: [-1, 1])

math.sin(0) // Returns: 0
math.sin(Math.PI / 2) // Returns: 1
math.sin(Math.PI) // Returns: 0 (approximately)
math.sin(Math.PI / 6) // Returns: 0.5

math.cos()

math.cos(value: Series): Series
math.cos(value: number): number

Returns the cosine of an angle in radians.

value
The angle in radians or Series

Returns The cosine value (range: [-1, 1])

math.cos(0) // Returns: 1
math.cos(Math.PI / 2) // Returns: 0 (approximately)
math.cos(Math.PI) // Returns: -1
math.cos(Math.PI / 3) // Returns: 0.5

math.tan()

math.tan(value: Series): Series
math.tan(value: number): number

Returns the tangent of an angle in radians.

value
The angle in radians or Series

Returns The tangent value

math.tan(0) // Returns: 0
math.tan(Math.PI / 4) // Returns: 1
math.tan(Math.PI / 6) // Returns: 0.577... (1/√3)

math.asin()

math.asin(value: Series): Series
math.asin(value: number): number

Returns the arcsine (inverse sine) of a number.

value
The value (must be in range [-1, 1]) or Series

Returns The angle in radians (range: [-π/2, π/2])

math.asin(0) // Returns: 0
math.asin(1) // Returns: 1.5707... (π/2)
math.asin(0.5) // Returns: 0.5235... (π/6)
math.asin(-1) // Returns: -1.5707... (-π/2)

math.acos()

math.acos(value: Series): Series
math.acos(value: number): number

Returns the arccosine (inverse cosine) of a number.

value
The value (must be in range [-1, 1]) or Series

Returns The angle in radians (range: [0, π])

math.acos(1) // Returns: 0
math.acos(0) // Returns: 1.5707... (π/2)
math.acos(0.5) // Returns: 1.0471... (π/3)
math.acos(-1) // Returns: 3.1415... (π)

math.atan()

math.atan(value: Series): Series
math.atan(value: number): number

Returns the arctangent (inverse tangent) of a number.

value
The value or Series

Returns The angle in radians (range: [-π/2, π/2])

math.atan(0) // Returns: 0
math.atan(1) // Returns: 0.7853... (π/4)
math.atan(-1) // Returns: -0.7853... (-π/4)
math.atan(Infinity) // Returns: 1.5707... (π/2)

math.toradians()

math.toradians(degrees: Series): Series
math.toradians(degrees: number): number

Converts an angle from degrees to radians.

degrees
The angle in degrees or Series

Returns The angle in radians

math.toradians(0) // Returns: 0
math.toradians(90) // Returns: 1.5707... (π/2)
math.toradians(180) // Returns: 3.1415... (π)
math.toradians(360) // Returns: 6.2831... (2π)

math.todegrees()

math.todegrees(radians: Series): Series
math.todegrees(radians: number): number

Converts an angle from radians to degrees.

radians
The angle in radians or Series

Returns The angle in degrees

math.todegrees(0) // Returns: 0
math.todegrees(Math.PI / 2) // Returns: 90
math.todegrees(Math.PI) // Returns: 180
math.todegrees(2 * Math.PI) // Returns: 360

math.seededRandom()

math.seededRandom(seed: number): (min?: number, max?: number) => number

Makes a repeatable random number generator: the same seed always gives the same sequence of numbers (the sequence of math.random(min, max, seed)). Each call of the generator draws the next number. In a script, prefer math.random(min, max, seed).

seed
Whole number that picks the sequence.

Returns A function (min?, max?) that gives the next number, from min (included, default 0) to max (excluded, default 1).

const draw = math.seededRandom(42);
const first = draw(0, 100);

math.random()

math.random(min?: number, max?: number, seed?: number): number

Returns a pseudo-random number.

min
Optional minimum value (inclusive), default 0
max
Optional maximum value (exclusive), default 1
seed
Optional seed: the same seed gives the same sequence on every run (the sequence of Java's java.util.Random)

Returns A random number in the specified range, or [0, 1) if no range specified

math.random() // Returns: value between 0 and 1 (e.g., 0.234...)
math.random(0, 10) // Returns: value between 0 and 10 (e.g., 7.45...)
math.random(0, 1, 42) // Returns: 0.7275636800328681 on the first call

math.sign()

math.sign(value: Series): Series
math.sign(value: number): number

Returns the sign of a number.

value
The number to check or Series

Returns 1 for positive, -1 for negative, 0 for zero, na for na

math.sign(5) // Returns: 1
math.sign(-3) // Returns: -1
math.sign(0) // Returns: 0
math.sign(0.001) // Returns: 1
math.sign(NaN) // Returns: NaN

math.round_to_mintick()

math.round_to_mintick(number: Series, mintick?: number): Series
math.round_to_mintick(number: number, mintick?: number): number

Rounds a price to the nearest tick, the smallest price step of the symbol (syminfo.mintick). Use it for levels that must be real prices (a stop, a target).

number
The price to round: a number or a Series
mintick
The tick size, e.g. 0.01. Default in a script: the chart symbol's tick (syminfo.mintick); called outside a script it is required (it throws without it)

Returns The value rounded to the tick: a Series for a Series, a number for a number

const stop = math.round_to_mintick(low.mul(0.98));
plot(stop, "Stop");
math.round_to_mintick(1.2345, 0.01) // Returns: 1.23

math.pi

math.pi: number

Pi, the ratio of a circle's circumference to its diameter: 3.141592653589793.

math.e

math.e: number

Euler's number e, the base of natural logarithms (math.log): 2.718281828459045.

math.phi

math.phi: 1.618033988749895

The golden ratio: 1.618033988749895.

math.rphi

math.rphi: 0.6180339887498948

The reciprocal of the golden ratio (1 / phi): 0.6180339887498948.

order

Sort order of array.sort(), array.sort_indices() and matrix.sort().

order.ascending

order.ascending: "ascending"

Smallest value first (the default).

plot

plot()

plot(source: number | Series, title?: string, options?: ScriptPlotOptions): PlotHandle

Draws a Series on the chart (a line by default, or a histogram, columns, area, circles...) and lists it in the legend and the settings. Bars whose value is na (NaN or +/-Infinity) are not drawn.

source
The values to draw: a Series, or a number for the same value on every bar.
title
Name of the plot in the legend, the settings and the alerts. Default: "Plot".
options
Colour, width, style, line style, offset, display... Default: {} (a blue line).
offset? number
Shift in bars: the value of bar i is drawn on bar i + offset (negative: to the left). Default: 0.
color? string | string[]
One colour, or one colour per bar (color.when(), undefined = not drawn). Default: blue #2962FF.
linewidth? number
Line width in pixels. Default: 1.
style? "line" | "stepline" | "histogram" | "area" | "circles" | "columns" | "cross" | "areabr" | "steplinebr" | "linebr" | "stepline_diamond"
How the values are drawn: plot.style_line, plot.style_histogram, plot.style_columns... Default: plot.style_line.
linestyle? "solid" | "dashed" | "dotted"
Dash pattern of the line: plot.linestyle_solid, plot.linestyle_dashed or plot.linestyle_dotted (one for all bars). Default: solid.
display? "none" | "all" | "data_window" | "status_line" | "pane"
Where the plot shows: display.all, display.none (hidden, still listed), display.pane, display.status_line, display.data_window. Default: display.all.
histbase? number
Base level the histogram bars start from (plot.style_histogram). Default: 0.
force_overlay? boolean
true: draw on the price pane even when the script has its own pane. Default: false.
editable? boolean
false: not listed in the style settings of the script. Default: true.

Returns A handle to pass to fill().

const fast = plot(ta.ema(close, 12), "Fast", { color: color.teal, linewidth: 2 });
plot(ta.rsi(close, 14), "RSI", { style: plot.style_histogram });

plot.style_line

plot.style_line: "line"

Style: a line through every value; na values are bridged.

plot.style_linebr

plot.style_linebr: "linebr"

Style: a line with a gap where the value is na.

plot.style_stepline

plot.style_stepline: "stepline"

Style: steps (horizontal then vertical moves); na values are bridged.

plot.style_steplinebr

plot.style_steplinebr: "steplinebr"

Style: steps with a gap where the value is na.

plot.style_histogram

plot.style_histogram: "histogram"

Style: a thin bar from the base line (histbase, default 0) to each value.

plot.style_columns

plot.style_columns: "columns"

Style: a wide column from the base line to each value.

plot.style_area

plot.style_area: "area"

Style: a line with the area down to the base line filled.

plot.style_areabr

plot.style_areabr: "areabr"

Style: a filled area with a gap where the value is na.

position

Where a table sits in the pane: the first argument of table.new() and of table.set_position() (table.new(position.top_right, 2, 3)).

request

Data from other symbols, timeframes and sources: request.security (another symbol or timeframe), request.security_lower_tf (the lower-timeframe bars inside each bar), request.seed (a separately published data series), dividends, splits and earnings. Call it before any eachBar() loop.

request.security()

request.security<T extends SecurityValue>(symbol: string, timeframe: string, expression: () => T, gaps?: string, lookahead?: string, ignore_invalid_symbol?: boolean): T extends unknown[] ? Series[] : Series
request.security<T extends SecurityValue>(symbol: string, timeframe: string, expression: () => T, args: SecurityArgs<T>): T extends unknown[] ? Series[] : Series
request.security<T extends SecurityValue>(args: SecurityArgs<T> & { symbol: string; timeframe: string; expression: () => T; }): T extends unknown[] ? Series[] : Series

Computes expression on the bars of another timeframe or another symbol and places its values on the chart bars. Compute every Series the expression needs inside it: a Series computed outside runs on the chart bars and stops the script. Return an array to get several Series at once.

symbol
Symbol id: "" or syminfo.tickerid for the chart symbol, "NASDAQ:AAPL" for another one, ticker.heikinashi(...) for Heikin Ashi bars.
timeframe
Timeframe string, e.g. "D", "W", "60"; "" is the chart timeframe.
expression
Function that returns a Series, a number, or an array of them, computed on those bars.
gaps
barmerge.gaps_off keeps a value on every bar until the next one; barmerge.gaps_on shows it only where it appears. Default: barmerge.gaps_off.
lookahead
barmerge.lookahead_off shows a period's value from the bar that completes it; barmerge.lookahead_on from its first bar. Default: barmerge.lookahead_off.
ignore_invalid_symbol
True to get na for a symbol that does not exist instead of stopping the script. Default: false.

Returns A Series on the chart bars, or one Series per element when the expression returns an array.

const dailyEma = request.security("", "D", () => ta.ema(close, 20));
const [prevHigh, prevLow] = request.security("", "D", () => [high.offset(1), low.offset(1)]);
plot(dailyEma, "Daily EMA");

Computes expression on the bars of another timeframe or symbol, with the other arguments by name.

symbol
Symbol id; "" is the chart symbol.
timeframe
Timeframe string; "" is the chart timeframe.
expression
Function that returns a Series, a number, or an array of them.
args
Named arguments: gaps, lookahead, ignore_invalid_symbol. currency (other than "") and calc_bars_count are not supported and stop the script.

Returns A Series on the chart bars, or one Series per element when the expression returns an array.

const weekOpen = request.security("", "W", () => open, { lookahead: barmerge.lookahead_on });
plot(weekOpen, "Week open", { style: plot.style_stepline });

Computes expression on the bars of another timeframe or symbol, with every argument by name.

args
Named arguments: symbol, timeframe, expression (required), gaps, lookahead, ignore_invalid_symbol.

Returns A Series on the chart bars, or one Series per element when the expression returns an array.

const weekly = request.security({ symbol: "", timeframe: "W", expression: () => close });
plot(weekly, "Weekly close");

request.security_lower_tf()

request.security_lower_tf<T extends SecurityValue>(symbol: string, timeframe: string, expression: () => T, ignore_invalid_symbol?: boolean): T extends unknown[] ? number[][][] : number[][]
request.security_lower_tf<T extends SecurityValue>(symbol: string, timeframe: string, expression: () => T, args: SecurityLowerTfArgs<T>): T extends unknown[] ? number[][][] : number[][]
request.security_lower_tf<T extends SecurityValue>(args: SecurityLowerTfArgs<T> & { symbol: string; timeframe: string; expression: () => T; }): T extends unknown[] ? number[][][] : number[][]

Computes expression on the bars of a lower timeframe and gives, for each chart bar, the values of all the lower bars inside it. The result is a plain array per chart bar (oldest first), not a Series: read it in a bar loop with values[c.i]. A timeframe higher than the chart's stops the script.

symbol
Symbol id; "" or syminfo.tickerid is the chart symbol.
timeframe
Lower timeframe string, e.g. "1", "15", "1T".
expression
Function that returns a Series, a number, or an array of them.
ignore_invalid_symbol
True to get empty arrays for a symbol that does not exist instead of stopping the script. Default: false.

Returns One array of numbers per chart bar (empty when no lower bar is inside it), or one such list per element when the expression returns an array.

const vols = request.security_lower_tf("", "15", () => volume);
const maxVolume = eachBar((c) => Math.max(0, ...vols[c.i]));
plot(maxVolume, "Largest 15m volume");

Lower-timeframe values per chart bar, with the other arguments by name.

symbol
Symbol id; "" is the chart symbol.
timeframe
Lower timeframe string.
expression
Function that returns a Series, a number, or an array of them.
args
Named arguments: ignore_invalid_symbol. currency, ignore_invalid_timeframe and calc_bars_count are not supported and stop the script.

Returns One array of numbers per chart bar, or one such list per element of an array expression.

const closes = request.security_lower_tf("", "5", () => close, { ignore_invalid_symbol: true });
const count = eachBar((c) => closes[c.i].length);
plot(count, "5m bars");

Lower-timeframe values per chart bar, with every argument by name.

args
Named arguments: symbol, timeframe, expression (required), ignore_invalid_symbol.

Returns One array of numbers per chart bar, or one such list per element of an array expression.

const highs = request.security_lower_tf({ symbol: "", timeframe: "1", expression: () => high });
const first = eachBar((c) => highs[c.i][0] ?? NaN);
plot(first, "First minute high");

request.seed()

request.seed<T extends SecurityValue>(source: string, symbol: string, expression: () => T, ignore_invalid_symbol?: boolean): T extends unknown[] ? Series[] : Series
request.seed<T extends SecurityValue>(source: string, symbol: string, expression: () => T, args: SeedArgs<T>): T extends unknown[] ? Series[] : Series
request.seed<T extends SecurityValue>(args: SeedArgs<T> & { source: string; symbol: string; expression: () => T; }): T extends unknown[] ? Series[] : Series

Computes expression on a seed data series (data published as a separate series), on the chart timeframe. It is request.security on the symbol the app gives that series (by default "<SOURCE>:<SYMBOL>" upper-cased).

source
Name of the seed data source.
symbol
Name of the series in that source.
expression
Function that returns a Series, a number, or an array of them.
ignore_invalid_symbol
True to get na for a series that does not exist instead of stopping the script. Default: false.

Returns A Series on the chart bars, or one Series per element when the expression returns an array.

const activity = request.seed("seed_crypto_santiment", "BTC_DEV_ACTIVITY", () => close);
plot(activity, "Dev activity");

A seed data series, with the other arguments by name.

source
Name of the seed data source.
symbol
Name of the series in that source.
expression
Function that returns a Series, a number, or an array of them.
args
Named arguments: ignore_invalid_symbol. calc_bars_count is not supported and stops the script.

Returns A Series on the chart bars, or one Series per element when the expression returns an array.

const options = { ignore_invalid_symbol: true };
const activity = request.seed("seed_crypto_santiment", "BTC_DEV_ACTIVITY", () => close, options);
plot(activity, "Dev activity");

A seed data series, with every argument by name.

args
Named arguments: source, symbol, expression (required), ignore_invalid_symbol.

Returns A Series on the chart bars, or one Series per element when the expression returns an array.

const source = "seed_crypto_santiment";
const activity = request.seed({ source, symbol: "BTC_DEV_ACTIVITY", expression: () => close });
plot(activity, "Dev activity");

request.dividends()

request.dividends(ticker: string, field?: string, gaps?: string, lookahead?: string, ignore_invalid_symbol?: boolean, currency?: string): Series
request.dividends(ticker: string, field: string, args: EventRequestArgs): Series
request.dividends(ticker: string, args: EventRequestArgs): Series
request.dividends(args: EventRequestArgs & { ticker: string; }): Series

The dividend per share of a symbol, as declared (not adjusted for later splits), on the chart bars. With the default lookahead off, a dividend shows from the first bar that closes after the end of its ex-date's period (the next day on a daily chart). na before the first dividend.

ticker
Symbol id; "" or syminfo.tickerid is the chart symbol.
field
dividends.net or dividends.gross. Default: dividends.net.
gaps
barmerge.gaps_on shows the value only on the bar where it appears. Default: barmerge.gaps_off.
lookahead
barmerge.lookahead_on shows it from the first bar of its period. Default: barmerge.lookahead_off.
ignore_invalid_symbol
True to get na for a symbol that does not exist. Default: false.
currency
Currency conversion is not supported: leave it out (any value but "" or "NONE" stops the script).

Returns Series of the last dividend.

const dividend = request.dividends(syminfo.tickerid);
plot(dividend.mul(4).div(close).mul(100), "Yield %");

The dividend per share of a symbol, with the arguments after field by name.

ticker
Symbol id; "" is the chart symbol.
field
dividends.net or dividends.gross.
args
Named arguments: gaps, lookahead, ignore_invalid_symbol.

Returns Series of the last dividend.

const gross = request.dividends("", dividends.gross, { gaps: barmerge.gaps_on });
plot(gross, "Gross dividend", { style: plot.style_circles });

The dividend per share of a symbol, with the arguments after ticker by name.

ticker
Symbol id; "" is the chart symbol.
args
Named arguments: field, gaps, lookahead, ignore_invalid_symbol.

Returns Series of the last dividend.

const dividend = request.dividends("", { field: dividends.net });
plot(dividend, "Dividend");

The dividend per share of a symbol, with every argument by name.

args
Named arguments: ticker (required), field, gaps, lookahead, ignore_invalid_symbol.

Returns Series of the last dividend.

const dividend = request.dividends({ ticker: syminfo.tickerid });
plot(dividend, "Dividend");

request.splits()

request.splits(ticker: string, field: string, gaps?: string, lookahead?: string, ignore_invalid_symbol?: boolean): Series
request.splits(ticker: string, field: string, args: SplitsRequestArgs): Series
request.splits(ticker: string, args: SplitsRequestArgs): Series
request.splits(args: SplitsRequestArgs & { ticker: string; }): Series

One number of the last split ratio of a symbol on the chart bars (2 and 1 for a 2-for-1 split). With the default lookahead off, a split shows from the first bar that closes after the end of its day's period. na before the first split.

ticker
Symbol id; "" or syminfo.tickerid is the chart symbol.
field
splits.numerator or splits.denominator (required).
gaps
barmerge.gaps_on shows the value only on the bar where it appears. Default: barmerge.gaps_off.
lookahead
barmerge.lookahead_on shows it from the first bar of its period. Default: barmerge.lookahead_off.
ignore_invalid_symbol
True to get na for a symbol that does not exist. Default: false.

Returns Series of the numerator or the denominator of the last split.

const split = request.splits(syminfo.tickerid, splits.numerator, barmerge.gaps_on);
plotshape(split.gt(0), "Split", { location: location.bottom });

One number of the last split ratio, with the arguments after field by name.

ticker
Symbol id; "" is the chart symbol.
field
splits.numerator or splits.denominator.
args
Named arguments: gaps, lookahead, ignore_invalid_symbol.

Returns Series of the numerator or the denominator of the last split.

const ratio = request.splits("", splits.denominator, { lookahead: barmerge.lookahead_off });
plot(ratio, "Split denominator");

One number of the last split ratio, with the arguments after ticker by name.

ticker
Symbol id; "" is the chart symbol.
args
Named arguments: field (required), gaps, lookahead, ignore_invalid_symbol.

Returns Series of the numerator or the denominator of the last split.

const ratio = request.splits("", { field: splits.numerator });
plot(ratio, "Split numerator");

One number of the last split ratio, with every argument by name.

args
Named arguments: ticker and field (required), gaps, lookahead, ignore_invalid_symbol.

Returns Series of the numerator or the denominator of the last split.

const ratio = request.splits({ ticker: syminfo.tickerid, field: splits.numerator });
plot(ratio, "Split numerator");

request.earnings()

request.earnings(ticker: string, field?: string, gaps?: string, lookahead?: string, ignore_invalid_symbol?: boolean, currency?: string): Series
request.earnings(ticker: string, field: string, args: EventRequestArgs): Series
request.earnings(ticker: string, args: EventRequestArgs): Series
request.earnings(args: EventRequestArgs & { ticker: string; }): Series

The earnings per share of the last release of a symbol (adjusted for later splits) on the chart bars. With the default lookahead off, a release shows from the first bar after the period of the chart timeframe it was published in (the next day on a daily chart). Releases still to come are left out; na before the first one. A field the app has no data for stops the script.

ticker
Symbol id; "" or syminfo.tickerid is the chart symbol.
field
earnings.actual, earnings.estimate or earnings.standardized. Default: earnings.actual.
gaps
barmerge.gaps_on shows the value only on the bar where it appears. Default: barmerge.gaps_off.
lookahead
barmerge.lookahead_on shows it from the first bar of its period. Default: barmerge.lookahead_off.
ignore_invalid_symbol
True to get na for a symbol that does not exist. Default: false.
currency
Currency conversion is not supported: leave it out (any value but "" or "NONE" stops the script).

Returns Series of the last earnings per share.

const eps = request.earnings(syminfo.tickerid, earnings.actual);
plot(eps, "EPS", { style: plot.style_stepline });

The earnings per share of the last release, with the arguments after field by name.

ticker
Symbol id; "" is the chart symbol.
field
earnings.actual, earnings.estimate or earnings.standardized.
args
Named arguments: gaps, lookahead, ignore_invalid_symbol.

Returns Series of the last earnings per share.

const estimate = request.earnings("", earnings.estimate, { gaps: barmerge.gaps_on });
plot(estimate, "EPS estimate", { style: plot.style_circles });

The earnings per share of the last release, with the arguments after ticker by name.

ticker
Symbol id; "" is the chart symbol.
args
Named arguments: field, gaps, lookahead, ignore_invalid_symbol.

Returns Series of the last earnings per share.

const eps = request.earnings("", { field: earnings.actual });
plot(eps, "EPS");

The earnings per share of the last release, with every argument by name.

args
Named arguments: ticker (required), field, gaps, lookahead, ignore_invalid_symbol.

Returns Series of the last earnings per share.

const eps = request.earnings({ ticker: syminfo.tickerid });
plot(eps, "EPS");

scale

Price scale a script is attached to (indicator(..., { scale })).

scale.right

scale.right: "right"

The right price scale.

scale.left

scale.left: "left"

The left price scale.

scale.none

scale.none: "none"

No price scale of its own (for overlay scripts).

session

Trading session flags of each bar (1 / 0 per bar): first and last bar of the session, market, pre-market and post-market hours; and the session types session.regular / session.extended. First and last bars are per session period; market / pre / post market use the regular hours.

session.regular

session.regular: "regular"

Session type of regular trading hours (compare with syminfo.session).

session.extended

session.extended: "extended"

Session type with the pre and post market hours (compare with syminfo.session).

session.isfirstbar

session.isfirstbar: Series

1 on the first bar of each session period (including pre market when the bars have it).

session.islastbar

session.islastbar: Series

1 on the last bar of each session period.

session.ismarket

session.ismarket: Series

1 on bars inside the regular trading hours.

session.ispremarket

session.ispremarket: Series

1 on bars before the regular hours open (pre market).

session.ispostmarket

session.ispostmarket: Series

1 on bars after the regular hours close (post market).

shape

Shapes of plotshape() (style option): plotshape(cond, "Buy", { style: shape.triangleup }).

shape.cross

shape.cross: "cross"

An upright cross (+).

shape.labelup

shape.labelup: "labelup"

A label box pointing up (its tip at the value): put it below the bar.

shape.labeldown

shape.labeldown: "labeldown"

A label box pointing down (its tip at the value): put it above the bar.

size

Sizes of shapes, characters, labels and table texts (size / text_size options).

size.auto

size.auto: "auto"

Size chosen by the chart to fit the space.

size.tiny

size.tiny: "tiny"

The smallest size.

size.huge

size.huge: "huge"

The largest size.

splits

Stock splits: the fields of request.splits (splits.numerator, splits.denominator).

splits.numerator

splits.numerator: "numerator"

The number of shares after the split (2 for a 2-for-1 split).

splits.denominator

splits.denominator: "denominator"

The number of shares before the split (1 for a 2-for-1 split).

str

Text functions: str.tostring (a number as text), str.format (a pattern with values), str.format_time (a date), search, replace, split, case... str.format_time and the dates of str.format use the exchange's time zone by default.

str.length()

str.length(str: string): number

Returns the length of a string.

str
The string to measure

Returns The number of characters in the string

str.length("Hello") // Returns: 5
str.length("") // Returns: 0

str.tostring()

str.tostring(value: any, format?: string, mintick?: number, pricescale?: number): string

Converts a value to its string representation.

value
The value to convert (number, boolean, string, etc.)
format
Optional number format: a pattern ("#.##", "#,###.00", "0.00%", "0.00E0", "#.##;(#.##)") or format.percent ("percent"), format.volume ("volume"), format.mintick ("mintick"), format.price / format.inherit
mintick
Tick size for format.mintick (the symbol's syminfo.mintick): in a script the chart's when left out; the core function cannot see the chart, so pass it there, as for math.round_to_mintick
pricescale
Price scale of the symbol for format.mintick (its syminfo.pricescale), needed for a symbol priced in fractions (32 for a 1/32 tick). Default: 10^(decimals of mintick)

Returns String representation of the value

str.tostring(123) // "123"
str.tostring(1.5, "#.##") // "1.5"
str.tostring(0.5, "#.00") // ".50"
str.tostring(12345.678, format.volume) // "12.346K"

str.tonumber()

str.tonumber(str: string): number

Converts a string to a number (float).

str
The string to convert

Returns The numeric value, or null (na) if conversion fails

str.tonumber("123") // Returns: 123
str.tonumber("45.67") // Returns: 45.67
str.tonumber("abc") // Returns: null
str.tonumber("12abc") // Returns: null
str.tonumber("1e3") // Returns: null

str.substring()

str.substring(str: string, begin: number, end?: number): string

Extracts a substring from a string.

str
The source string
begin
Starting index (0-based, inclusive)
end
Ending index (0-based, exclusive). If omitted, extracts to end of string

Returns The extracted substring

str.substring("hello world", 0, 5) // Returns: "hello"
str.substring("hello world", 6) // Returns: "world"
str.substring("test", 1, 3) // Returns: "es"

str.upper()

str.upper(str: string): string

Converts all characters in a string to uppercase.

str
The string to convert

Returns The uppercase string

str.upper("hello") // Returns: "HELLO"
str.upper("Hello World") // Returns: "HELLO WORLD"
str.upper("test123") // Returns: "TEST123"

str.lower()

str.lower(str: string): string

Converts all characters in a string to lowercase.

str
The string to convert

Returns The lowercase string

str.lower("HELLO") // Returns: "hello"
str.lower("Hello World") // Returns: "hello world"
str.lower("TEST123") // Returns: "test123"

str.contains()

str.contains(source: string, str: string): boolean

Checks if a string contains a substring.

source
The string to search in
str
The substring to search for

Returns True if source contains str, false otherwise

str.contains("hello world", "world") // Returns: true
str.contains("hello world", "World") // Returns: false (case-sensitive)
str.contains("test", "xyz") // Returns: false

str.pos()

str.pos(source: string, str: string): number

Returns the position of the first occurrence of a substring.

source
The string to search in
str
The substring to search for

Returns The 0-based index of the first occurrence, or na (NaN) if not found

str.pos("hello world", "world") // Returns: 6
str.pos("hello world", "o") // Returns: 4 (first occurrence)
str.pos("hello", "xyz") // Returns: NaN (na)

str.replace()

str.replace(source: string, target: string, replacement: string, occurrence?: number): string

Replaces the Nth occurrence of a substring.

source
The source string
target
The substring to replace
replacement
The string to replace with
occurrence
0-based occurrence to replace (default 0, the first one)

Returns The string with one occurrence replaced

str.replace("hello world hello", "hello", "hi") // Returns: "hi world hello"
str.replace("hello world hello", "hello", "hi", 1) // Returns: "hello world hi"
str.replace("test", "xyz", "abc") // Returns: "test"

str.replace_all()

str.replace_all(source: string, target: string, replacement: string): string

Replaces all occurrences of a target string with a replacement string.

source
The source string
target
The substring to find
replacement
The replacement string

Returns String with all occurrences replaced

str.replace_all("hello world hello", "hello", "hi") // Returns: "hi world hi"
str.replace_all("a-b-c", "-", "_") // Returns: "a_b_c"
str.replace_all("test", "x", "y") // Returns: "test" (no match)

str.split()

str.split(str: string, separator: string): string[]

Splits a string into an array of substrings using a separator.

str
The string to split
separator
The separator string

Returns Array of substrings

str.split("a,b,c", ",") // Returns: ["a", "b", "c"]
str.split("hello", "") // Returns: ["h", "e", "l", "l", "o"]
str.split("a,,b", ",") // Returns: ["a", "", "b"]

str.concat()

str.concat(...strings: string[]): string

Concatenates multiple strings into one.

strings
Variable number of strings to concatenate

Returns The concatenated string

str.concat("hello", " ", "world") // Returns: "hello world"
str.concat("a", "b", "c") // Returns: "abc"
str.concat("test") // Returns: "test"

str.format()

str.format(pattern: string, ...args: any[]): string

Builds a text from a pattern and values: each {0}, {1}... is replaced by the argument at that position, e.g. str.format("Close {0}, change {1,number,percent}", c.close, 0.025). Use it for labels and messages.

pattern
The text with placeholders: {0} (a number shows as "#,##0.###"), {1,number,#.##} (number pattern), {0,number,percent}, {0,number,integer}, {0,date,yyyy-MM-dd} (a time in milliseconds); '...' in single quotes is kept as it is, '' is a quote
args
The values of the placeholders, in order: numbers, texts, booleans, arrays

Returns The text with the values in place

str.format("Close: {0,number,#.##}", 101.456) // Returns: "Close: 101.46"
str.format("{0} and {1}", "a", 2) // Returns: "a and 2"

str.startswith()

str.startswith(source: string, str: string): boolean

Checks if a string starts with a specific prefix.

source
The string to check
str
The prefix to look for

Returns True if source starts with str, false otherwise

str.startswith("hello world", "hello") // Returns: true
str.startswith("hello world", "Hello") // Returns: false (case-sensitive)
str.startswith("test", "testing") // Returns: false

str.endswith()

str.endswith(source: string, str: string): boolean

Checks if a string ends with a specific suffix.

source
The string to check
str
The suffix to look for

Returns True if source ends with str, false otherwise

str.endswith("hello world", "world") // Returns: true
str.endswith("hello world", "World") // Returns: false (case-sensitive)
str.endswith("testing", "test") // Returns: false

str.charAt()

str.charAt(str: string, pos: number): string

Returns the character at a specific position in a string.

str
The source string
pos
The 0-based position

Returns The character at the position, or empty string if out of bounds

str.charAt("hello", 0) // Returns: "h"
str.charAt("hello", 4) // Returns: "o"
str.charAt("hello", 10) // Returns: ""

str.trim()

str.trim(str: string): string

Removes whitespace from both ends of a string.

str
The string to trim

Returns The trimmed string

str.trim("  hello  ") // Returns: "hello"
str.trim("  hello world  ") // Returns: "hello world"
str.trim("\thello\n") // Returns: "hello"

str.trimLeft()

str.trimLeft(str: string): string

Removes whitespace from the left (start) of a string.

str
The string to trim

Returns The trimmed string

str.trimLeft("  hello  ") // Returns: "hello  "
str.trimLeft("  hello") // Returns: "hello"
str.trimLeft("\thello") // Returns: "hello"

str.trimRight()

str.trimRight(str: string): string

Removes whitespace from the right (end) of a string.

str
The string to trim

Returns The trimmed string

str.trimRight("  hello  ") // Returns: "  hello"
str.trimRight("hello  ") // Returns: "hello"
str.trimRight("hello\t") // Returns: "hello"

str.match()

str.match(source: string, regex: string): string

Returns the first substring of source that matches the regex.

source
Source string
regex
Regular expression

Returns The first match (searched anywhere in the string), or na (null) when nothing matches or the match is empty

str.match("abc123def", "[0-9]+") // Returns: "123"
str.match("abc", "[0-9]+") // Returns: null (na)

str.repeat()

str.repeat(source: string, count: number, separator?: string): string

Constructs a new string containing the source string repeated N times with an optional separator.

source
The string to repeat
count
Number of times to repeat
separator
String to inject between repeated instances. Optional, defaults to empty string.

Returns The repeated string, or null (na) if source is na or count is 0 / negative / na

str.repeat("ab", 3) // Returns: "ababab"
str.repeat("?", 3, ",") // Returns: "?,?,?"
str.repeat("hello", 0) // Returns: null (na)
str.repeat("x", 1) // Returns: "x"

str.format_time()

str.format_time(time: number, format?: string, timezone?: string): string

Writes a time as a date text, e.g. "2024-03-15 09:30". Use it for labels, tables and log messages.

time
The time in milliseconds since 1 January 1970 UTC, e.g. time on a bar or timenow
format
Date pattern: yyyy year, MM month number, MMM month name, dd day, EEE weekday, HH hour (00-23), hh hour (01-12) with a (AM/PM), mm minutes, ss seconds, SSS milliseconds, Z / z time zone; 'text' in single quotes is kept as it is. Default: "yyyy-MM-dd'T'HH:mm:ssZ"
timezone
Time zone of the text: a UTC offset ("UTC-5", "GMT+2") or a zone name ("America/New_York"). Default in a script: the exchange time zone of the symbol; called outside a script: "Etc/UTC"

Returns The date text

eachBar((c) => {
  if (c.i === c.n - 1) label.new(c.i, c.high, str.format_time(c.get(time), "yyyy-MM-dd HH:mm"));
});

strategy

strategy()

strategy(title: string, options?: StrategyOptions): void

Declares the script as a strategy and sets its name and its backtest properties (capital, order size, commission...). Call it once, at the top of the script, instead of indicator().

title
Name of the strategy, shown on the chart and in the lists.
options
Strategy properties, e.g. overlay (default false: own pane), initial_capital (default 100000), default_qty_type (default strategy.percent_of_equity), default_qty_value (default 100), pyramiding (default 0), commission_type, commission_value (default 0), slippage (ticks, default 0), process_orders_on_close (default false). Default: all defaults.
shorttitle? string
Short name shown in the legend. Default: the title.
overlay? boolean
true: drawn over the price chart; false: in its own pane. Default: false.
format? string
Number format of the values: format.price, format.volume, format.percent... Default: the symbol's price format.
precision? number
Decimals shown for the values. Default: the symbol's.
scale? string
Price scale the strategy uses: scale.right, scale.left or scale.none.
pyramiding? number
Most entries allowed in the same direction; 0 and 1 both allow one. Default: 0.
calc_on_order_fills? boolean
true: runs the bar again after an order fills inside it, so new orders can be sent at once. Default: false.
calc_on_every_tick? boolean
true: runs on every price update of the live bar, not only when it closes. Default: false.
calc_on_every_history_tick? boolean
Runs the strategy on each tick of the history bars too (the reference app's "On history bar tick").
max_bars_back? number
History length kept for the script's Series. Default: worked out from the script.
backtest_fill_limits_assumption? number
Ticks the price must go past a limit price before the limit order fills. Default: 0.
default_qty_type? StrategyQtyType
Unit of default_qty_value: strategy.fixed (contracts / shares), strategy.cash or strategy.percent_of_equity. Default: strategy.percent_of_equity.
default_qty_value? number
Size of an order that gives no qty, in the unit of default_qty_type. Default: 100.
initial_capital? number
Money the account starts with, in the account currency. Default: 100000.
currency? string
Account currency; default: the symbol currency.
slippage? number
Ticks added to market and stop fills.
commission_type? StrategyCommissionType
How commission_value is read: strategy.commission.percent (of the order value), .cash_per_contract or .cash_per_order. Default: percent.
commission_value? number
Commission per order, in the unit of commission_type. Default: 0.
process_orders_on_close? boolean
true: orders fill at the close of the bar that sent them instead of the next bar's open. Default: false.
close_entries_rule? "FIFO" | "ANY"
Which entry an exit closes first: "FIFO" (the oldest) or "ANY" (the one named by from_entry). Default: "FIFO".
margin_long? number
Share of a long position's value the account must hold, in percent (100: no leverage). Default: 100.
margin_short? number
Share of a short position's value the account must hold, in percent. Default: 100.
explicit_plot_zorder? boolean
true: outputs are drawn in the order the script writes them. Default: false.
max_lines_count? number
Most line drawings kept on the chart (the oldest go). Default: 50.
max_labels_count? number
Most labels kept on the chart (the oldest go). Default: 50.
max_boxes_count? number
Most boxes kept on the chart (the oldest go). Default: 50.
calc_bars_count? number
Runs only on the last this many bars; 0 runs on all. Default: 0.
risk_free_rate? number
Yearly risk-free rate, in percent, for the Sharpe and Sortino ratios. Default: 2.
use_bar_magnifier? boolean
true: fills orders with the bars of a lower timeframe inside each bar, for more exact fills. Default: false.
fill_orders_on_standard_ohlc? boolean
true: on synthetic charts (Heikin Ashi...) orders fill at the real prices. Default: false.
max_polylines_count? number
Most polylines kept on the chart (the oldest go). Default: 50.

Returns Nothing.

strategy("MA Cross", { overlay: true, initial_capital: 10000, default_qty_type: strategy.percent_of_equity, default_qty_value: 50 });

strategy.eachBar()

strategy.eachBar(fn: (c: BarContext) => number | boolean | void): Series

The strategy's bar loop: runs the callback once per bar, oldest first, at the bar's close. Before each call the engine fills the orders placed earlier; place, change or cancel orders and read the results inside it. Compute every Series (ta.*) before it and read them with c.get(). A script has one strategy.eachBar().

fn
Called with the bar context c (c.i, c.close, c.get(series)...); what it returns becomes the value of that bar (true / false give 1 / 0, nothing gives NaN).

Returns A Series of the values returned by fn, one per bar.

const up = ta.crossover(ta.sma(close, 10), ta.sma(close, 30));
strategy.eachBar((c) => {
  if (c.get(up) === 1) strategy.entry("Long", strategy.long);
});

strategy.entry()

strategy.entry(id: string, direction: StrategyDirection, options?: StrategyEntryOptions): void

Places an order that opens or adds to a position. An entry in the other direction first closes the open position (a reversal); entries in the same direction beyond the first follow the pyramiding property. Without limit or stop it is a market order, filled at the next bar's open. Calling it again with the id of a pending order changes that order.

id
Name of the entry; exits refer to it with from_entry.
direction
strategy.long or strategy.short.
options
qty (default: from default_qty_type / default_qty_value), limit and stop prices, oca_name, oca_type, comment, alert_message, disable_alert. NaN values count as not given. Default: {}.
qty? number
Contracts / shares to trade. Default: from default_qty_type and default_qty_value.
limit? number
Limit price: the order fills at this price or better. Left out with stop too: a market order.
stop? number
Stop price: the order fills once the price reaches it. With limit: a stop-limit order.
oca_name? string
Name of a one-cancels-all group the order belongs to.
oca_type? StrategyOcaType
What a fill in the group does to the others: strategy.oca.cancel, .reduce or .none. Default: none.
comment? string
Text shown with the order's fill on the chart and in the trade list.
alert_message? string
Text of the alert sent when the order fills.
disable_alert? boolean
true: the order's fill sends no alert. Default: false.

Returns Nothing.

const up = ta.crossover(ta.ema(close, 12), ta.ema(close, 26));
strategy.eachBar((c) => {
  if (c.get(up) === 1) strategy.entry("Long", strategy.long, { comment: "EMA cross" });
});

strategy.order()

strategy.order(id: string, direction: StrategyDirection, options?: StrategyEntryOptions): void

Places a plain order: a buy (strategy.long) or a sell (strategy.short) that adds to or reduces the position, with no reversal and no pyramiding limit. Without limit or stop it is a market order. Calling it again with the id of a pending order changes that order.

id
Name of the order.
direction
strategy.long (buy) or strategy.short (sell).
options
qty (default: from default_qty_type / default_qty_value), limit and stop prices, oca_name, oca_type, comment, alert_message, disable_alert. NaN values count as not given. Default: {}.
qty? number
Contracts / shares to trade. Default: from default_qty_type and default_qty_value.
limit? number
Limit price: the order fills at this price or better. Left out with stop too: a market order.
stop? number
Stop price: the order fills once the price reaches it. With limit: a stop-limit order.
oca_name? string
Name of a one-cancels-all group the order belongs to.
oca_type? StrategyOcaType
What a fill in the group does to the others: strategy.oca.cancel, .reduce or .none. Default: none.
comment? string
Text shown with the order's fill on the chart and in the trade list.
alert_message? string
Text of the alert sent when the order fills.
disable_alert? boolean
true: the order's fill sends no alert. Default: false.

Returns Nothing.

strategy.eachBar((c) => {
  if (c.close > c.get(close, 1)) strategy.order("Buy", strategy.long, { qty: 1 });
});

strategy.exit()

strategy.exit(id: string, options?: StrategyExitOptions): void

Places the exit orders of an entry: a stop loss, a take profit and / or a trailing stop. They wait while the entry is pending and are cancelled with its position. Calling it again with the same id moves the orders (e.g. a stop updated on every bar).

id
Name of the exit order.
options
from_entry (default: every open entry), qty / qty_percent (default: 100 % of the position), prices stop, limit, trail_price, distances in ticks loss, profit, trail_points, trail_offset, comments and alert messages. Give at least one price or distance. NaN values count as not given. Default: {}.
from_entry? string
Id of the entry to exit. Default: every open entry.
qty? number
Contracts / shares to exit. Default: the whole position (see qty_percent).
qty_percent? number
Share of the position to exit, in percent. Default: 100.
profit? number
Take-profit distance from the entry price, in ticks.
limit? number
Take-profit price.
loss? number
Stop-loss distance from the entry price, in ticks.
stop? number
Stop-loss price.
trail_price? number
Price at which the trailing stop starts.
trail_points? number
Distance from the entry, in ticks, at which the trailing stop starts.
trail_offset? number
Distance the trailing stop keeps from the best price, in ticks.
oca_name? string
Name of the one-cancels-all group of the exit's orders. Default: one group per exit.
comment? string
Text shown with the exit fill.
comment_profit? string
Text shown when the take-profit fills. Default: comment.
comment_loss? string
Text shown when the stop-loss fills. Default: comment.
comment_trailing? string
Text shown when the trailing stop fills. Default: comment.
alert_message? string
Text of the alert sent when the exit fills.
alert_profit? string
Alert text when the take-profit fills. Default: alert_message.
alert_loss? string
Alert text when the stop-loss fills. Default: alert_message.
alert_trailing? string
Alert text when the trailing stop fills. Default: alert_message.
disable_alert? boolean
true: the exit sends no alert. Default: false.

Returns Nothing.

strategy.eachBar((c) => {
  const avg = strategy.position_avg_price;
  if (strategy.position_size > 0) strategy.exit("Exit", { from_entry: "Long", stop: avg * 0.98, limit: avg * 1.04 });
});

strategy.close()

strategy.close(id: string, options?: StrategyCloseOptions): void

Closes the open trades of an entry with a market order, filled at the next bar's open (or at this bar's close with immediately: true).

id
Name of the entry to close.
options
qty / qty_percent (default: the whole position of the entry), comment, alert_message, immediately (default false), disable_alert. Default: {}.
comment? string
Text shown with the closing fill.
qty? number
Contracts / shares to close. Default: all of the entry.
qty_percent? number
Share to close, in percent. Default: 100.
alert_message? string
Text of the alert sent when it fills.
immediately? boolean
true: closes at the current bar's close instead of the next bar's open. Default: false.
disable_alert? boolean
true: sends no alert. Default: false.

Returns Nothing.

const down = ta.crossunder(ta.ema(close, 12), ta.ema(close, 26));
strategy.eachBar((c) => {
  if (c.get(down) === 1) strategy.close("Long", { comment: "Cross down" });
});

strategy.close_all()

strategy.close_all(options?: StrategyCloseAllOptions): void

Closes the whole position, whatever entries opened it, with a market order filled at the next bar's open (or at this bar's close with immediately: true).

options
comment, alert_message, immediately (default false), disable_alert. Default: {}.
comment? string
Text shown with the closing fill.
alert_message? string
Text of the alert sent when it fills.
immediately? boolean
true: closes at the current bar's close instead of the next bar's open. Default: false.
disable_alert? boolean
true: sends no alert. Default: false.

Returns Nothing.

const rsi = ta.rsi(close, 14);
strategy.eachBar((c) => {
  if (c.get(rsi) > 70) strategy.close_all({ comment: "RSI > 70" });
});

strategy.cancel()

strategy.cancel(id: string): void

Cancels the pending orders (entries, orders or exits) with this id. Filled orders are not affected.

id
Name of the orders to cancel.

Returns Nothing.

strategy.eachBar((c) => {
  if (c.close < c.open) strategy.cancel("Breakout");
});

strategy.cancel_all()

strategy.cancel_all(): void

Cancels every pending order of the strategy. Filled orders and the position are not affected.

Returns Nothing.

strategy.eachBar((c) => {
  if (c.i === c.n - 1) strategy.cancel_all();
});

strategy.opentrade()

strategy.opentrade(index: number): StrategyTrade

Reads one open trade: its entry, size and profit so far.

index
Number of the open trade, 0 for the oldest, strategy.opentrades - 1 for the newest.

Returns The trade (entry_id, entry_price, entry_bar_index, entry_time, size, profit, commission, max_runup, max_drawdown...), or undefined when there is no such trade.

strategy.eachBar((c) => {
  const trade = strategy.opentrade(0);
  if (trade && c.i - trade.entry_bar_index >= 10) strategy.close(trade.entry_id);
});

strategy.closedtrade()

strategy.closedtrade(index: number): StrategyTrade

Reads one closed trade: its entry, exit and result.

index
Number of the closed trade, 0 for the oldest, strategy.closedtrades - 1 for the newest.

Returns The trade (entry_* and exit_* fields, size, profit, profit_percent, commission...), or undefined when there is no such trade.

strategy.eachBar((c) => {
  const last = strategy.closedtrade(strategy.closedtrades - 1);
  if (last && last.exit_bar_index === c.i && last.profit < 0) alert("Losing trade closed");
});

strategy.default_entry_qty()

strategy.default_entry_qty(fill_price: number): number

Gives the quantity an entry without qty would get if it filled at a price, from the default_qty_type and default_qty_value properties and the current equity. Not every engine provides it.

fill_price
Price the order would fill at.

Returns The quantity, in contracts (shares, units).

strategy.eachBar((c) => {
  const half = Math.floor(strategy.default_entry_qty(c.close) / 2);
  if (strategy.position_size === 0) strategy.entry("Half", strategy.long, { qty: half });
});

strategy.long

strategy.long: "long"

Direction of a long order: buys (strategy.entry("L", strategy.long)).

strategy.short

strategy.short: "short"

Direction of a short order: sells (strategy.entry("S", strategy.short)).

strategy.fixed

strategy.fixed: "fixed"

Order size type: default_qty_value is a number of contracts (shares, units).

strategy.cash

strategy.cash: "cash"

Order size type: default_qty_value is an amount of money; also the money type of the risk rules.

strategy.percent_of_equity

strategy.percent_of_equity: "percent_of_equity"

Order size type: default_qty_value is a percent of the equity; also the percent type of the risk rules.

strategy.position_size

strategy.position_size: number

Size of the current position: positive when long, negative when short, 0 when flat.

strategy.equity

strategy.equity: number

Current equity: initial capital + net profit + open profit, in the account currency.

strategy.initial_capital

strategy.initial_capital: number

Starting capital of the backtest (the initial_capital property); readable anywhere after strategy().

strategy.netprofit

strategy.netprofit: number

Profit of all closed trades, after commission, in the account currency.

strategy.openprofit

strategy.openprofit: number

Profit or loss of the open trades not yet realized, in the account currency.

strategy.grossprofit

strategy.grossprofit: number

Sum of the profits of the winning closed trades, in the account currency.

strategy.grossloss

strategy.grossloss: number

Sum of the losses of the losing closed trades, as a positive amount in the account currency.

strategy.opentrades

strategy.opentrades: number

Number of open trades (a number, not a function: read a trade with strategy.opentrade(i)).

strategy.closedtrades

strategy.closedtrades: number

Number of closed trades (a number, not a function: read a trade with strategy.closedtrade(i)).

strategy.eventrades

strategy.eventrades: number

Number of closed trades that broke even (profit 0).

strategy.avg_trade

strategy.avg_trade: number

Average profit per closed trade, in the account currency; NaN before the first closed trade.

strategy.avg_trade_percent

strategy.avg_trade_percent: number

Average profit per closed trade, in percent; NaN before the first closed trade.

strategy.avg_winning_trade

strategy.avg_winning_trade: number

Average profit of the winning trades, in the account currency; NaN before the first one.

strategy.avg_losing_trade

strategy.avg_losing_trade: number

Average loss of the losing trades, as a positive amount in the account currency; NaN before the first one.

strategy.max_drawdown

strategy.max_drawdown: number

Largest drop of the equity from a peak so far, in the account currency.

strategy.max_runup

strategy.max_runup: number

Largest rise of the equity from a low so far, in the account currency.

strategy.margin_liquidation_price

strategy.margin_liquidation_price: number

Price at which a margin call would close part of the current position; NaN when there is none.

strategy.position_entry_name

strategy.position_entry_name: string

Id of the entry that opened the current position (its oldest open trade); empty when flat.

strategy.account_currency

strategy.account_currency: string

Currency of the account the results are counted in (e.g. "USD"); readable anywhere after strategy().

strategy.commission

Commission types for the commission_type property of strategy().

strategy.commission.percent

strategy.commission.percent: "percent"

Commission in percent of the order value (commission_value: 0.1 is 0.1 %).

strategy.direction

Directions for strategy.risk.allow_entry_in().

strategy.oca

One-cancels-all group types for the oca_type option of strategy.entry() / strategy.order().

strategy.oca.none

strategy.oca.none: "none"

No group: the order does not act on other orders.

strategy.oca.cancel

strategy.oca.cancel: "cancel"

When one order of the group fills, the other orders of the group are cancelled.

strategy.oca.reduce

strategy.oca.reduce: "reduce"

When one order of the group fills, the quantity of the other orders of the group is reduced by the filled quantity.

strategy.risk

Risk rules that stop or limit trading (drawdown, daily loss, position size...).

strategy.risk.allow_entry_in()

strategy.risk.allow_entry_in(direction: StrategyRiskDirection): void

Lets entries open positions in one direction only. An entry in the other direction then only closes the open position instead of reversing it.

direction
strategy.direction.all, strategy.direction.long or strategy.direction.short.

Returns Nothing.

strategy("Long only", { overlay: true });
strategy.risk.allow_entry_in(strategy.direction.long);

strategy.risk.max_cons_loss_days()

strategy.risk.max_cons_loss_days(count: number, alert_message?: string): void

Stops trading after a number of losing days in a row: pending orders are cancelled, the position is closed and no new order is placed.

count
Number of consecutive losing days that stops trading.
alert_message
Message of the alert sent when the rule fires. Default: none.

Returns Nothing.

strategy("Guarded", { overlay: true });
strategy.risk.max_cons_loss_days(3);

strategy.risk.max_drawdown()

strategy.risk.max_drawdown(value: number, type: StrategyRiskValueType, alert_message?: string): void

Stops trading when the drawdown of the equity reaches a limit: pending orders are cancelled, the position is closed and no new order is placed.

value
Largest drawdown allowed, in percent of the equity or in money (see type).
type
"percent_of_equity" or "cash" (strategy.percent_of_equity, strategy.cash).
alert_message
Message of the alert sent when the rule fires. Default: none.

Returns Nothing.

strategy("Guarded", { overlay: true });
strategy.risk.max_drawdown(20, strategy.percent_of_equity);

strategy.risk.max_intraday_filled_orders()

strategy.risk.max_intraday_filled_orders(count: number, alert_message?: string): void

Limits the number of filled orders in one trading day: when it is reached, pending orders are cancelled, the position is closed and trading stops until the next day.

count
Largest number of filled orders per day.
alert_message
Message of the alert sent when the rule fires. Default: none.

Returns Nothing.

strategy("Intraday", { overlay: true });
strategy.risk.max_intraday_filled_orders(10);

strategy.risk.max_intraday_loss()

strategy.risk.max_intraday_loss(value: number, type: StrategyRiskValueType, alert_message?: string): void

Limits the loss of one trading day: when it is reached, pending orders are cancelled, the position is closed and trading stops until the next day.

value
Largest daily loss, in percent of the equity or in money (see type).
type
"percent_of_equity" or "cash" (strategy.percent_of_equity, strategy.cash).
alert_message
Message of the alert sent when the rule fires. Default: none.

Returns Nothing.

strategy("Intraday", { overlay: true });
strategy.risk.max_intraday_loss(500, strategy.cash);

strategy.risk.max_position_size()

strategy.risk.max_position_size(contracts: number): void

Caps the size of the position: an entry that would go past it is reduced to fit.

contracts
Largest absolute position size, in contracts (shares, units).

Returns Nothing.

strategy("Capped", { overlay: true });
strategy.risk.max_position_size(100);

STRATEGY_DEFAULTS

Default values of the strategy() options, used for every option a strategy leaves out.

syminfo

The chart symbol: ticker, exchange, currency, tick size, session, fundamentals..., from the chart context (inside request.security, the requested symbol's). A field the symbol has none of is na ("" for a text); a field the host did not give throws.

syminfo.mintick

syminfo.mintick: number

Smallest price step of the symbol, e.g. 0.01. Equals minmove / pricescale.

syminfo.minmove

syminfo.minmove: number

Number of price-scale units in one price step: mintick = minmove / pricescale (1 for most symbols).

syminfo.pricescale

syminfo.pricescale: number

Price scale of the symbol: 100 for prices with 2 decimals, 32 for prices in 1/32.

syminfo.pointvalue

syminfo.pointvalue: number

Money value of a one-point price move for one contract (1 for stocks).

syminfo.mincontract

syminfo.mincontract: number

Smallest quantity that can be traded (1 for whole shares).

syminfo.timezone

syminfo.timezone: string

Time zone of the exchange, e.g. "America/New_York". The default time zone of the date and time functions.

syminfo.tickerid

syminfo.tickerid: string

Full symbol id with its exchange prefix, e.g. "NASDAQ:AAPL". Pass it to request.security for the chart symbol.

syminfo.main_tickerid

syminfo.main_tickerid: string

Symbol id of the chart itself, also inside a request.security expression on another symbol.

syminfo.ticker

syminfo.ticker: string

Symbol name without the exchange prefix, e.g. "AAPL".

syminfo.prefix

syminfo.prefix: string

Exchange prefix of the symbol id, e.g. "NASDAQ"; "" without one.

syminfo.session

syminfo.session: string

Session type of the bars: "regular" (regular hours) or "extended" (with pre and post market).

syminfo.type

syminfo.type: string

Type of the symbol: "stock", "fund", "index", "futures", "forex", "crypto"...

syminfo.currency

syminfo.currency: string

Currency the prices are in, e.g. "USD".

syminfo.basecurrency

syminfo.basecurrency: string

Base currency of a pair: "BTC" for a BTC/USD symbol, "EUR" for EUR/USD; "" for a stock or an index.

syminfo.root

syminfo.root: string

Root of the symbol: "ES" for a continuous future "ES1!" or a contract "ESZ2026"; the ticker otherwise.

syminfo.country

syminfo.country: string

Two-letter code of the country the symbol trades in, e.g. "US".

syminfo.current_contract

syminfo.current_contract: string

Contract a continuous future stands for, e.g. "ESZ2026"; "" for other symbols.

syminfo.expiration_date

syminfo.expiration_date: number

Last trading day of a futures contract (UNIX time in ms); na for other symbols.

syminfo.sector

syminfo.sector: string

Sector of the company, e.g. "Electronic Technology"; "" when it has none.

syminfo.industry

syminfo.industry: string

Industry of the company; "" when it has none.

syminfo.isin

syminfo.isin: string

International Securities Identification Number of the symbol, e.g. "US0378331005".

syminfo.volumetype

syminfo.volumetype: string

Unit of the volume: "base" (units of the base currency), "quote", "tick" or "n/a".

syminfo.shares_outstanding_float

syminfo.shares_outstanding_float: number

Number of shares free to trade (without the shares held by insiders and large holders).

ta

Technical analysis: moving averages, oscillators, bands, crosses, pivots and volume indicators. Each function computes a whole Series in one call: call it before any eachBar() loop and read a bar's value with c.get(x).

ta.sma()

ta.sma(source: Series, length: number | Series): Series

Simple moving average: the mean of the last length values. Use it to smooth a price or any Series. Missing values are skipped (the window holds the last length valid values); NaN until length values exist.

source
Series to average, e.g. close.
length
Number of values in the window (a fraction is truncated). A Series gives one length per bar.

Returns Series of the averages.

const ma = ta.sma(close, 20);
plot(ma, "SMA 20", { color: color.blue });

ta.ema()

ta.ema(source: Series, length: number): Series

Exponential moving average with the smoothing factor 2 / (length + 1): recent values weigh more than in ta.sma. The first value is the simple average of the first length valid values; NaN before it, and on a bar whose source is missing.

source
Series to average.
length
Number of bars of the average (at least 1).

Returns Series of the averages.

const fast = ta.ema(close, 12);
plot(fast, "Fast EMA");

ta.rma()

ta.rma(source: Series, length: number): Series

Running moving average (Wilder's smoothing) with the smoothing factor 1 / length, the average used by ta.rsi and ta.atr. Starts with the simple average of the first length valid values; NaN before it.

source
Series to average.
length
Number of bars of the average (at least 1).

Returns Series of the averages.

const avgRange = ta.rma(high.sub(low), 14);
plot(avgRange, "Average range");

ta.wma()

ta.wma(source: Series, length: number | Series): Series

Weighted moving average: the newest value has the weight length, the one before length - 1, and so on down to 1. NaN on a bar whose source is missing and until length valid values exist.

source
Series to average.
length
Number of values in the window (at least 1). A Series gives one length per bar.

Returns Series of the averages.

const wma = ta.wma(close, 10);
plot(wma, "WMA 10");

ta.hma()

ta.hma(source: Series, length: number): Series

Hull moving average: a weighted average of 2 * wma(source, length / 2) - wma(source, length) over sqrt(length) bars, smooth with little lag.

source
Series to average.
length
Number of bars (at least 1).

Returns Series of the averages.

const hull = ta.hma(close, 21);
plot(hull, "HMA");

ta.alma()

ta.alma(source: Series, length?: number, offset?: number, sigma?: number, floor?: boolean): Series

Arnaud Legoux moving average: a moving average whose weights follow a bell curve placed toward the newest values, smooth with little lag. NaN on the first length - 1 bars and when the window holds a missing value.

source
Series to average.
length
Number of bars in the window. Default: 9.
offset
Where the peak of the weights sits, from 0 (oldest bar) to 1 (newest bar). Default: 0.85.
sigma
Width of the bell curve: a higher value gives flatter weights. Default: 6.
floor
When true, the peak position offset * (length - 1) is rounded down to a whole bar. Default: false.

Returns Series of the averages.

const alma = ta.alma(close, 9, 0.85, 6);
plot(alma, "ALMA");

ta.swma()

ta.swma(source: Series): Series

Symmetrically weighted moving average over 4 bars with the weights 1, 2, 2, 1 (newest to oldest). NaN on the first 3 bars and when one of the 4 values is missing.

source
Series to average.

Returns Series of the averages.

plot(ta.swma(close), "SWMA");

ta.vwma()

ta.vwma(source: Series, length: number, vol?: Series): Series

Volume-weighted moving average: sma(source * volume, length) / sma(volume, length), so bars with more volume weigh more. Uses the chart volume unless a third argument gives another one.

source
Series to average.
length
Number of bars (at least 1).
vol
Volume Series to weigh with. Default: the chart volume.

Returns Series of the averages (NaN where the summed volume is 0).

const vwma = ta.vwma(close, 20);
plot(vwma, "VWMA");

ta.vwap()

ta.vwap(source: Series, anchor?: Series): Series
ta.vwap(source: Series, anchor: Series, stdev_mult: number): [Series, Series, Series]

Volume-weighted average price with the chart volume, restarted on each anchor bar. Without an anchor it restarts on each new trading day (on daily, weekly and monthly charts every bar starts again).

source
Price Series to average, usually hlc3.
anchor
Series that is non-zero on the bars where the sums restart, e.g. timeframe.change("W"). Default: a new trading day.

Returns Series of the average price since the last anchor.

const vwap = ta.vwap(hlc3);
plot(vwap, "VWAP", { color: color.orange });

Volume-weighted average price with bands at a multiple of the volume-weighted standard deviation.

source
Price Series to average, usually hlc3.
anchor
Series that is non-zero on the bars where the sums restart, or undefined for a new trading day.
stdev_mult
Distance of the bands from the average, in standard deviations.

Returns Tuple [vwap, upper, lower] of Series.

const [vwap, upper, lower] = ta.vwap(hlc3, undefined, 2);
plot(upper, "Upper");
plot(lower, "Lower");

ta.vwapBands()

ta.vwapBands(source: Series, volume: Series, anchor: Series, stdev_mult: number): [Series, Series, Series]

Volume-weighted average price with bands, with an explicit volume. Same as ta.vwap(source, anchor, stdev_mult) with another volume Series; without an anchor the sums never restart.

source
Price Series to average.
volume
Volume Series to weigh with.
anchor
Series that is non-zero on the bars where the sums restart, or undefined for no restart.
stdev_mult
Distance of the bands from the average, in standard deviations.

Returns Tuple [vwap, upper, lower] of Series.

const [vwap, upper, lower] = ta.vwapBands(hlc3, volume, timeframe.change("D"), 1);
plot(vwap, "VWAP");

ta.rsi()

ta.rsi(source: Series, length: number): Series
ta.rsi(up: Series, down: Series): Series

Relative strength index, from 0 to 100: the share of the average gains in the average gains and losses over length bars (Wilder's smoothing). Above 70 is often read as overbought, below 30 as oversold.

source
Series to measure, e.g. close.
length
Number of bars of the averages (at least 1).

Returns Series of values from 0 to 100.

const rsi = ta.rsi(close, 14);
plot(rsi, "RSI");
hline(70, "Overbought");

Relative strength index from two averages you computed yourself: 100 - 100 / (1 + up / down); 100 when down is 0, 0 when up is 0.

up
Average of the upward changes.
down
Average of the downward changes.

Returns Series of values from 0 to 100.

const up = ta.rma(ta.change(close).mul(close.gt(close.offset(1))), 14);
const down = ta.rma(ta.change(close).neg().mul(close.lt(close.offset(1))), 14);
plot(ta.rsi(up, down), "RSI");

ta.macd()

ta.macd(source: Series, fastLength: number, slowLength: number, signalLength: number): [Series, Series, Series]

Moving average convergence divergence: the gap between a fast and a slow exponential average, its own average (the signal line) and the difference of the two (the histogram).

source
Series to measure, e.g. close.
fastLength
Length of the fast exponential average, e.g. 12.
slowLength
Length of the slow exponential average, e.g. 26.
signalLength
Length of the exponential average of the MACD line, e.g. 9.

Returns Tuple [macdLine, signalLine, histogram] of Series.

const [macdLine, signalLine, hist] = ta.macd(close, 12, 26, 9);
plot(hist, "Histogram", { style: plot.style_columns });
plot(macdLine, "MACD");

ta.stoch()

ta.stoch(source: Series, highSource: Series, lowSource: Series, length: number): Series

Stochastic %K, from 0 to 100: where source sits in the range between the lowest low and the highest high of the last length bars. Smooth it with ta.sma for the %D line. A bar where it cannot be computed keeps the previous value.

source
Series to place in the range, usually close.
highSource
Series of highs, usually high.
lowSource
Series of lows, usually low.
length
Number of bars of the range (at least 1).

Returns Series of values from 0 to 100.

const k = ta.sma(ta.stoch(close, high, low, 14), 3);
plot(k, "%K");
plot(ta.sma(k, 3), "%D");

ta.cci()

ta.cci(source: Series, length: number): Series

Commodity channel index: (source - sma) / (0.015 * mean deviation) over length bars. Readings above +100 or below -100 mark strong moves. A flat window keeps the previous value.

source
Series to measure, usually hlc3.
length
Number of bars (at least 1).

Returns Series of index values (unbounded).

const cci = ta.cci(hlc3, 20);
plot(cci, "CCI");

ta.mfi()

ta.mfi(source: Series, length: number): Series

Money flow index, from 0 to 100: a volume-weighted version of the RSI built from the chart volume. Above 80 is often read as overbought, below 20 as oversold.

source
Price Series, usually hlc3.
length
Number of bars (at least 1).

Returns Series of values from 0 to 100.

const mfi = ta.mfi(hlc3, 14);
plot(mfi, "MFI");

ta.wpr()

ta.wpr(length?: number): Series

Williams %R, from -100 to 0: where the close sits in the high-low range of the last length bars (0 = at the highest high, -100 = at the lowest low). Uses the chart high, low and close.

length
Number of bars (at least 1). Default: 14.

Returns Series of values from -100 to 0 (NaN when the range is 0).

const wpr = ta.wpr(14);
plot(wpr, "%R");

ta.tsi()

ta.tsi(source: Series, shortLength: number, longLength: number): Series

True strength index, from -1 to 1: the bar-to-bar change smoothed twice with exponential averages, divided by the change size smoothed the same way. Not multiplied by 100.

source
Series to measure, e.g. close.
shortLength
Length of the second (short) smoothing.
longLength
Length of the first (long) smoothing.

Returns Series of values from -1 to 1 (NaN when the source does not move).

const tsi = ta.tsi(close, 13, 25);
plot(tsi, "TSI");

ta.cmo()

ta.cmo(source: Series, length: number): Series

Chande momentum oscillator, from -100 to 100: 100 * (sum of gains - sum of losses) / (sum of gains + sum of losses) over the last length bars.

source
Series to measure, e.g. close.
length
Number of bars (at least 1).

Returns Series of values from -100 to 100 (NaN when every change in the window is 0).

const cmo = ta.cmo(close, 9);
plot(cmo, "CMO");

ta.cog()

ta.cog(source: Series, length?: number): Series

Center of gravity oscillator: -sum(source[i] * (i + 1)) / sum(source) over the last length bars (i = 0 for the newest bar). Turns tend to show early.

source
Series to measure, e.g. close.
length
Number of bars (at least 1). Default: 10.

Returns Series of oscillator values (NaN when the window holds a missing value).

const cog = ta.cog(close, 10);
plot(cog, "COG");

ta.rci()

ta.rci(source: Series, length: number): Series

Rank correlation index, from -100 to 100: how steadily the source rose (+100) or fell (-100) over the last length bars, from the rank order of the values. The first value is on bar length.

source
Series to measure, e.g. close.
length
Number of bars (at least 1).

Returns Series of values from -100 to 100.

const rci = ta.rci(close, 9);
plot(rci, "RCI");

ta.mom()

ta.mom(source: Series, length: number): Series

Momentum: source - source[length], the change over length bars. NaN on the first length bars.

source
Series to measure.
length
Number of bars back (at least 1).

Returns Series of differences.

const mom = ta.mom(close, 10);
plot(mom, "Momentum");

ta.roc()

ta.roc(source: Series, length: number): Series

Rate of change in percent: 100 * (source - source[length]) / source[length]. NaN on the first length bars.

source
Series to measure.
length
Number of bars back (at least 1).

Returns Series of percentages (5 means +5%).

const roc = ta.roc(close, 9);
plot(roc, "ROC");

ta.change()

ta.change(source: Series, length?: number): Series

Change over length bars: source - source[length]. With the default length, the difference from the previous bar. NaN on the first length bars.

source
Series to measure.
length
Number of bars back (at least 1). Default: 1.

Returns Series of differences.

const diff = ta.change(close);
plot(diff, "Change", { style: plot.style_histogram });

ta.tr()

ta.tr(handleNa?: boolean): Series

True range of each bar: the largest of high - low, |high - previous close| and |low - previous close|. Uses the chart high, low and close.

handleNa
What to return when the previous close is missing (the first bar): true gives high - low, false gives NaN. Default: false.

Returns Series of true ranges, in price units.

const range = ta.tr(true);
plot(range, "True range");

ta.atr()

ta.atr(length: number): Series

Average true range: the running moving average (ta.rma) of the true range over length bars, a measure of volatility in price units. Uses the chart high, low and close.

length
Number of bars (at least 1).

Returns Series of average ranges.

const atr = ta.atr(14);
plot(close.sub(atr.mul(2)), "Stop");

ta.bb()

ta.bb(source: Series, length: number, mult: number): [Series, Series, Series]

Bollinger Bands: a simple moving average with bands mult standard deviations above and below it.

source
Series to measure, e.g. close.
length
Number of bars of the average and the deviation.
mult
Distance of the bands, in standard deviations, e.g. 2.

Returns Tuple [middle, upper, lower] of Series.

const [middle, upper, lower] = ta.bb(close, 20, 2);
fill(plot(upper, "Upper"), plot(lower, "Lower"), { color: color.new(color.blue, 90) });

ta.bbw()

ta.bbw(source: Series, length: number, mult: number): Series

Bollinger Bands width in percent of the middle band: 100 * (upper - lower) / middle. Low values mark quiet markets.

source
Series to measure, e.g. close.
length
Number of bars of the average and the deviation.
mult
Distance of the bands, in standard deviations.

Returns Series of widths in percent (NaN when the middle band is 0).

const width = ta.bbw(close, 20, 2);
plot(width, "BB width");

ta.kc()

ta.kc(source: Series, length: number, mult: number, useTrueRange?: boolean): [Series, Series, Series]

Keltner Channels: an exponential average of source with bands at mult times the exponential average of the true range (or of high - low) above and below it. Uses the chart high, low and close.

source
Series of the middle line, e.g. close.
length
Number of bars of the averages.
mult
Multiplier of the range for the bands.
useTrueRange
True: the bands use the true range; false: high - low. Default: true.

Returns Tuple [middle, upper, lower] of Series.

const [middle, upper, lower] = ta.kc(close, 20, 1.5);
plot(upper, "Upper");
plot(lower, "Lower");

ta.kcw()

ta.kcw(source: Series, length?: number, mult?: number, useTrueRange?: boolean): Series

Keltner Channels width as a ratio of the middle line: (upper - lower) / middle (0.05 is a width of 5%). Uses the chart high, low and close.

source
Series of the middle line, e.g. close.
length
Number of bars of the averages. Default: 20.
mult
Multiplier of the range for the bands. Default: 2.
useTrueRange
True: the bands use the true range; false: high - low. Default: true.

Returns Series of ratios.

const width = ta.kcw(close, 20, 2);
plot(width, "KC width");

ta.stdev()

ta.stdev(source: Series, length: number | Series, biased?: boolean): Series

Standard deviation over the last length values: how far the values spread around their mean. Missing values are skipped; NaN until length values exist.

source
Series to measure.
length
Number of values in the window. A Series gives one length per bar.
biased
True divides by length (whole population); false by length - 1 (sample). Default: true.

Returns Series of deviations, in the units of the source.

const sd = ta.stdev(close, 20);
plot(sd, "Std dev");

ta.variance()

ta.variance(source: Series, length: number | Series, biased?: boolean): Series

Variance over the last length values: the mean of the squared distances to the mean (the square of ta.stdev). Missing values are skipped; NaN until length values exist.

source
Series to measure.
length
Number of values in the window. A Series gives one length per bar.
biased
True divides by length (whole population); false by length - 1 (sample). Default: true.

Returns Series of variances.

const v = ta.variance(close, 20);
plot(v, "Variance");

ta.dev()

ta.dev(source: Series, length: number): Series

Mean absolute deviation: the average distance of the last length values from their simple average. NaN when one of these values is missing.

source
Series to measure.
length
Number of bars (at least 1).

Returns Series of deviations, in the units of the source.

const md = ta.dev(close, 20);
plot(md, "Mean deviation");

ta.sar()

ta.sar(start?: number, inc?: number, max?: number): Series

Parabolic SAR (stop and reverse): a trailing level below the price in an up trend and above it in a down trend, which flips when the price crosses it. Uses the chart high, low and close. NaN on the first bar.

start
Starting acceleration factor. Default: 0.02.
inc
Step added to the acceleration on each new extreme. Default: 0.02.
max
Largest acceleration factor. Default: 0.2.

Returns Series of stop levels, in price units.

const sar = ta.sar(0.02, 0.02, 0.2);
plot(sar, "SAR", { style: plot.style_cross });

ta.supertrend()

ta.supertrend(factor: number, atrLength: number): [Series, Series]

Supertrend: a trailing line at factor average true ranges from the middle of the bar, below the price in an up trend and above it in a down trend. Uses the chart high, low and close.

factor
Multiplier of the average true range, e.g. 3.
atrLength
Number of bars of the average true range, e.g. 10.

Returns Tuple [supertrend, direction]: the line, and the direction (-1 in an up trend, 1 in a down trend).

const [line, direction] = ta.supertrend(3, 10);
plot(line, "Supertrend", { color: color.when(direction.lt(0), color.green, color.red) });

ta.dmi()

ta.dmi(diLength: number, adxSmoothing: number): [Series, Series, Series]

Directional movement index: the plus and minus directional indicators and the average directional index (trend strength, 0 to 100). Uses the chart high, low and close.

diLength
Number of bars of the directional indicators, e.g. 14.
adxSmoothing
Number of bars of the ADX smoothing, e.g. 14.

Returns Tuple [plusDI, minusDI, adx] of Series.

const [plusDI, minusDI, adx] = ta.dmi(14, 14);
plot(adx, "ADX");

ta.ichimoku()

ta.ichimoku(conversionPeriods: number, basePeriods: number, laggingSpan2Periods: number, displacement: number): [Series, Series, Series, Series, Series]

Ichimoku cloud lines, computed from the chart high, low and close. The two leading spans are already moved displacement bars forward (their value on a bar comes from displacement bars earlier). The lagging span is the close: draw it displacement bars back with plot(lagging, "Lagging", { offset: -displacement }) (no value of the tuple reads a future bar).

conversionPeriods
Bars of the conversion line (midpoint of the high-low range), e.g. 9.
basePeriods
Bars of the base line, e.g. 26.
laggingSpan2Periods
Bars of the second leading span, e.g. 52.
displacement
Number of bars the spans are moved, e.g. 26.

Returns Tuple [conversion, base, leadA, leadB, lagging] of Series.

const [conversion, base, leadA, leadB, lagging] = ta.ichimoku(9, 26, 52, 26);
plot(lagging, "Lagging", { offset: -26 });
fill(plot(leadA, "Lead A"), plot(leadB, "Lead B"), { color: color.new(color.teal, 85) });

ta.crossover()

ta.crossover(a: Series, b: number | Series): Series

Crossover: 1 on the bar where a moves above b (it was at or below b on the last bar where both had a value), 0 elsewhere.

a
Series that crosses.
b
Series or fixed level it crosses.

Returns Series of 1 / 0.

const buy = ta.crossover(ta.ema(close, 9), ta.ema(close, 21));
plotshape(buy, "Buy", { style: shape.triangleup, location: location.belowbar });

ta.crossunder()

ta.crossunder(a: Series, b: number | Series): Series

Crossunder: 1 on the bar where a moves below b (it was at or above b on the last bar where both had a value), 0 elsewhere.

a
Series that crosses.
b
Series or fixed level it crosses.

Returns Series of 1 / 0.

const exitSignal = ta.crossunder(ta.rsi(close, 14), 70);
plotshape(exitSignal, "Exit", { style: shape.xcross, location: location.abovebar });

ta.cross()

ta.cross(a: Series, b: number | Series): Series

Cross in either direction: 1 on the bar where a moves to the other side of b (bars where they are equal do not count as a side), 0 elsewhere.

a
First Series.
b
Second Series or a fixed level.

Returns Series of 1 / 0.

const [macdLine, signalLine] = ta.macd(close, 12, 26, 9);
bgcolor(color.when(ta.cross(macdLine, signalLine), color.new(color.gray, 85)));

ta.rising()

ta.rising(source: Series, length: number): Series

Rising: 1 when the source went up on each of the last length bars, 0 otherwise.

source
Series to test.
length
Number of rises in a row needed (at least 1).

Returns Series of 1 / 0.

const up3 = ta.rising(close, 3);
bgcolor(color.when(up3, color.new(color.green, 85)));

ta.falling()

ta.falling(source: Series, length: number): Series

Falling: 1 when the source went down on each of the last length bars, 0 otherwise.

source
Series to test.
length
Number of falls in a row needed (at least 1).

Returns Series of 1 / 0.

const down3 = ta.falling(close, 3);
bgcolor(color.when(down3, color.new(color.red, 85)));

ta.barssince()

ta.barssince(condition: Series): Series

Bars since a condition: 0 on a bar where the condition is true, then 1, 2, 3... until it is true again. NaN until the condition was first true.

condition
Condition Series: true on the bars where it is non-zero and not NaN.

Returns Series of bar counts.

const sinceCross = ta.barssince(ta.crossover(close, ta.sma(close, 50)));
plot(sinceCross, "Bars since cross");

ta.valuewhen()

ta.valuewhen(condition: Series, source: Series, occurrence: number): Series

Value when a condition was true: on each bar, the value source had on the bar of the occurrence-th most recent bar where the condition was true. NaN while there were not enough such bars.

condition
Condition Series: true on the bars where it is non-zero and not NaN.
source
Series whose value is taken.
occurrence
Which true bar, counting back: 0 is the most recent, 1 the one before, and so on.

Returns Series of the remembered values.

const lastCrossLow = ta.valuewhen(ta.crossover(close, ta.sma(close, 20)), low, 0);
plot(lastCrossLow, "Low at last cross");

ta.highest()

ta.highest(length: number): Series
ta.highest(source: Series, length: number | Series): Series

Highest value of the last length bars of the chart high.

length
Number of bars. A Series gives one length per bar.

Returns Series of the highest highs (NaN on the first length - 1 bars).

const top = ta.highest(20);
plot(top, "20-bar high");

Highest value of the last length values of a Series, e.g. a 20-bar high for a breakout. Missing values are skipped; NaN on the first length - 1 bars.

source
Series to search.
length
Number of bars (a fraction is truncated). A Series gives one length per bar.

Returns Series of the highest values.

const top = ta.highest(close, 20);
plotshape(close.gte(top), "New high", { location: location.abovebar });

ta.lowest()

ta.lowest(length: number): Series
ta.lowest(source: Series, length: number | Series): Series

Lowest value of the last length bars of the chart low.

length
Number of bars. A Series gives one length per bar.

Returns Series of the lowest lows (NaN on the first length - 1 bars).

const bottom = ta.lowest(20);
plot(bottom, "20-bar low");

Lowest value of the last length values of a Series. Missing values are skipped; NaN on the first length - 1 bars.

source
Series to search.
length
Number of bars (a fraction is truncated). A Series gives one length per bar.

Returns Series of the lowest values.

const bottom = ta.lowest(close, 20);
plot(bottom, "20-bar low of close");

ta.highestbars()

ta.highestbars(length: number): Series
ta.highestbars(source: Series, length: number | Series): Series

Offset to the bar with the highest chart high of the last length bars: 0 for the current bar, -1 for the bar before, and so on (always 0 or negative).

length
Number of bars. A Series gives one length per bar.

Returns Series of offsets (NaN on the first length - 1 bars).

const ago = ta.highestbars(20);
plot(ago, "Bars since 20-bar high");

Offset to the bar with the highest value of the last length values of a Series: 0 for the current bar, -1 for the bar before, and so on (always 0 or negative; the newest bar wins a tie).

source
Series to search.
length
Number of bars. A Series gives one length per bar.

Returns Series of offsets (NaN on the first length - 1 bars).

const ago = ta.highestbars(close, 20);
plot(ago, "Offset of highest close");

ta.lowestbars()

ta.lowestbars(length: number): Series
ta.lowestbars(source: Series, length: number | Series): Series

Offset to the bar with the lowest chart low of the last length bars: 0 for the current bar, -1 for the bar before, and so on (always 0 or negative).

length
Number of bars. A Series gives one length per bar.

Returns Series of offsets (NaN on the first length - 1 bars).

const ago = ta.lowestbars(20);
plot(ago, "Bars since 20-bar low");

Offset to the bar with the lowest value of the last length values of a Series: 0 for the current bar, -1 for the bar before, and so on (always 0 or negative; the newest bar wins a tie).

source
Series to search.
length
Number of bars. A Series gives one length per bar.

Returns Series of offsets (NaN on the first length - 1 bars).

const ago = ta.lowestbars(close, 20);
plot(ago, "Offset of lowest close");

ta.range()

ta.range(source: Series, length: number): Series

Range of the last length values: highest minus lowest. Missing values are skipped; NaN until length values exist.

source
Series to measure.
length
Number of values (at least 1).

Returns Series of ranges, in the units of the source.

const width = ta.range(close, 20);
plot(width, "20-bar range");

ta.max()

ta.max(source: Series): Series

All-time highest value: the highest value of the source from the first bar up to each bar. Missing values are skipped.

source
Series to search.

Returns Series of running highest values (NaN until the first value).

plot(ta.max(high), "All-time high");

ta.min()

ta.min(source: Series): Series

All-time lowest value: the lowest value of the source from the first bar up to each bar. Missing values are skipped.

source
Series to search.

Returns Series of running lowest values (NaN until the first value).

plot(ta.min(low), "All-time low");

ta.median()

ta.median(source: Series, length: number): Series

Median of the last length values (the mean of the two middle values for an even length). Missing values are skipped; NaN until length values exist.

source
Series to measure.
length
Number of values (at least 1).

Returns Series of medians.

plot(ta.median(close, 20), "Median");

ta.mode()

ta.mode(source: Series, length: number): Series

Mode of the last length values: the most frequent value (the smallest one when several are as frequent). Missing values are skipped; NaN until length values exist.

source
Series to measure.
length
Number of values (at least 1).

Returns Series of modes.

plot(ta.mode(close, 20), "Mode");

ta.percentile_linear_interpolation()

ta.percentile_linear_interpolation(source: Series, length: number, percentage: number): Series

Percentile of the last length values, interpolated between the two nearest ranks (so the result may not be one of the values). NaN on the first length - 1 bars.

source
Series to measure.
length
Number of bars (at least 1).
percentage
Percentile to return, from 0 to 100 (50 is the median).

Returns Series of percentile values.

const p90 = ta.percentile_linear_interpolation(close, 50, 90);
plot(p90, "90th percentile");

ta.percentile_nearest_rank()

ta.percentile_nearest_rank(source: Series, length: number, percentage: number): Series

Percentile of the last length values by the nearest rank: always one of the values in the window. NaN on the first length - 1 bars.

source
Series to measure.
length
Number of bars (at least 1).
percentage
Percentile to return, from 0 to 100 (100 is the largest value).

Returns Series of percentile values.

const p10 = ta.percentile_nearest_rank(close, 50, 10);
plot(p10, "10th percentile");

ta.percentrank()

ta.percentrank(source: Series, length: number): Series

Percent rank, from 0 to 100: the share of the previous length values that are at or below the current value. NaN on the first length bars.

source
Series to measure.
length
Number of previous bars to compare with (at least 1).

Returns Series of values from 0 to 100.

const rank = ta.percentrank(close, 100);
plot(rank, "Percent rank");

ta.correlation()

ta.correlation(a: Series, b: Series, length: number): Series

Correlation coefficient of two Series over the last length bars, from -1 (move in opposite directions) to 1 (move together).

a
First Series.
b
Second Series.
length
Number of bars (at least 1).

Returns Series of values from -1 to 1 (NaN when one Series is flat over the window).

const corr = ta.correlation(close, volume, 20);
plot(corr, "Price / volume correlation");

ta.linreg()

ta.linreg(source: Series, length: number, offset?: number): Series

Linear regression: the least-squares line through the last length values, read on the current bar (or offset bars back along the line). NaN when the window holds a missing value.

source
Series to fit.
length
Number of bars (at least 1).
offset
Bars back along the line where it is read: 0 is the current bar, a negative value projects ahead. Default: 0.

Returns Series of fitted values.

const fit = ta.linreg(close, 50);
plot(fit, "Regression");

ta.cum()

ta.cum(source: Series): Series

Cumulative sum of the source from the first bar. A missing value adds nothing and gives NaN on its own bar only.

source
Series to add up.

Returns Series of running totals.

const totalVolume = ta.cum(volume);
plot(totalVolume, "Cumulative volume");

ta.pivothigh()

ta.pivothigh(leftbars: number, rightbars: number | Series): Series
ta.pivothigh(source: Series, leftbars: number | Series, rightbars: number | Series): Series

Pivot high of the chart high: a bar higher than the rightbars bars after it and at least as high as the leftbars bars before it. The value appears rightbars bars after the pivot bar, when it is confirmed; NaN on the other bars.

leftbars
Bars to the left of the pivot.
rightbars
Bars to the right of the pivot.

Returns Series of the pivot high price on the confirming bar, NaN elsewhere.

const ph = ta.pivothigh(5, 5);
plot(ph, "Pivot high", { style: plot.style_circles, offset: -5 });

Pivot high of a Series: a value higher than the rightbars values after it and at least as high as the leftbars values before it. The value appears rightbars bars after the pivot bar; NaN on the other bars.

source
Series to search.
leftbars
Bars to the left of the pivot. A Series gives one length per bar.
rightbars
Bars to the right of the pivot. A Series gives one length per bar.

Returns Series of the pivot value on the confirming bar, NaN elsewhere.

const ph = ta.pivothigh(close, 3, 3);
plot(ph, "Pivot high", { style: plot.style_circles, offset: -3 });

ta.pivotlow()

ta.pivotlow(leftbars: number, rightbars: number | Series): Series
ta.pivotlow(source: Series, leftbars: number | Series, rightbars: number | Series): Series

Pivot low of the chart low: a bar lower than the rightbars bars after it and at most as low as the leftbars bars before it. The value appears rightbars bars after the pivot bar, when it is confirmed; NaN on the other bars.

leftbars
Bars to the left of the pivot.
rightbars
Bars to the right of the pivot.

Returns Series of the pivot low price on the confirming bar, NaN elsewhere.

const pl = ta.pivotlow(5, 5);
plot(pl, "Pivot low", { style: plot.style_circles, offset: -5 });

Pivot low of a Series: a value lower than the rightbars values after it and at most as low as the leftbars values before it. The value appears rightbars bars after the pivot bar; NaN on the other bars.

source
Series to search.
leftbars
Bars to the left of the pivot. A Series gives one length per bar.
rightbars
Bars to the right of the pivot. A Series gives one length per bar.

Returns Series of the pivot value on the confirming bar, NaN elsewhere.

const pl = ta.pivotlow(close, 3, 3);
plot(pl, "Pivot low", { style: plot.style_circles, offset: -3 });

ta.zigzag()

ta.zigzag(deviation?: number, depth?: number, backstep?: number): [Series, Series, Series]

ZigZag of the chart: the turning points of the price that are at least deviation percent apart, found on the chart's highs and lows. The last point may move as new bars come in.

deviation
Smallest move between two points, in percent. Default: 5.
depth
Bars at the start used to find the first point. Default: 10.
backstep
Bars a new high or low must beat, and bars a point must wait before it is confirmed. Default: 3.

Returns Tuple [price, direction, isPivot] of Series: the point price on point bars (NaN elsewhere), the direction (1 up, -1 down, 0 before the first point) and 1 / 0 on point bars.

const [points, direction, isPivot] = ta.zigzag(5, 10, 3);
plot(points, "ZigZag", { style: plot.style_circles });

ta.obv

ta.obv: Series

On-balance volume of the chart: a running total that adds the volume on up closes and subtracts it on down closes. A Series, not a function: read it as ta.obv.

plot(ta.obv, "OBV");

ta.pvt

ta.pvt: Series

Price-volume trend of the chart: a running total of the close change in fraction of the previous close times the volume. A Series, not a function.

plot(ta.pvt, "PVT");

ta.accdist

ta.accdist: Series

Accumulation / distribution of the chart: a running total of ((close - low) - (high - close)) / (high - low) * volume. Bars with high == low add nothing. A Series, not a function.

plot(ta.accdist, "Accumulation / distribution");

ta.nvi

ta.nvi: Series

Negative volume index of the chart: starts at 1 and follows the close change only on bars where the volume falls. A Series, not a function.

plot(ta.nvi, "NVI");

ta.pvi

ta.pvi: Series

Positive volume index of the chart: starts at 1 and follows the close change only on bars where the volume rises. A Series, not a function.

plot(ta.pvi, "PVI");

ta.iii

ta.iii: Series

Intraday intensity index of the chart: (2 * close - high - low) / (high - low) * volume on each bar (NaN where high == low). A Series, not a function.

plot(ta.iii, "III", { style: plot.style_histogram });

ta.wad

ta.wad: Series

Williams accumulation / distribution of the chart: a running total of the close move beyond the previous close (against the low on up closes, the high on down closes). A Series, not a function.

plot(ta.wad, "WAD");

ta.wvad

ta.wvad: Series

Williams variable accumulation / distribution of the chart: (close - open) / (high - low) * volume on each bar (NaN where high == low). A Series, not a function.

plot(ta.wvad, "WVAD", { style: plot.style_histogram });

table

Tables fixed at a place of the pane, for values and dashboards: table.new() creates one, table.cell() fills it, table.all lists the live tables. The live tables go to result.tables.

table.new()

table.new(position: "top_left" | "top_center" | "top_right" | "middle_left" | "middle_center" | "middle_right" | "bottom_left" | "bottom_center" | "bottom_right", columns: Numeric, rows: Numeric, bgcolor?: string, frame_color?: string, frame_width?: Numeric, border_color?: string, border_width?: Numeric, force_overlay?: boolean): Table
table.new(position: "top_left" | "top_center" | "top_right" | "middle_left" | "middle_center" | "middle_right" | "bottom_left" | "bottom_center" | "bottom_right", columns: Numeric, rows: Numeric, args: TableNewArgs): Table
table.new(args: TableNewArgs): Table

Creates a table fixed at a place of the pane (it does not scroll with the bars) and returns its handle; fill its cells with table.cell(). A pane holds one table per position: a live table at the same position (with the same force_overlay) is deleted. The arguments after rows can also be given by name in an object.

position
Where the table sits: position.top_left, position.top_center, position.top_right, position.middle_left, position.middle_center, position.middle_right, position.bottom_left, position.bottom_center or position.bottom_right.
columns
Number of columns.
rows
Number of rows.
bgcolor
Background colour of the whole table. Default: none (transparent).
frame_color
Colour of the outer frame. Default: none.
frame_width
Width of the outer frame in pixels. Default: 0 (no frame).
border_color
Colour of the lines between the cells. Default: none.
border_width
Width of the lines between the cells in pixels. Default: 0 (no lines).
force_overlay
When true, the table is drawn on the price pane even if the script has its own pane. Default: false.

Returns The new table.

const t = table.new(position.top_right, 2, 1, color.new(color.black, 20));
eachBar((c) => {
  if (c.i === c.n - 1) table.cell(t, 0, 0, "Close", 0, 0, color.white);
});

Creates a table, with the arguments after rows given by name (see the first form).

position
Where the table sits (position.top_right, position.bottom_left...).
columns
Number of columns.
rows
Number of rows.
args
The other arguments by name: bgcolor, frame_color, frame_width, border_color, border_width, force_overlay.

Returns The new table.

const t = table.new(position.bottom_left, 2, 3, { bgcolor: color.new(color.black, 20), border_width: 1 });

Creates a table, with every argument given by name (see the first form).

args
position, columns, rows, and optionally bgcolor, frame_color, frame_width, border_color, border_width, force_overlay.

Returns The new table.

const t = table.new({ position: position.top_center, columns: 3, rows: 1 });

table.new_table()

table.new_table(position: "top_left" | "top_center" | "top_right" | "middle_left" | "middle_center" | "middle_right" | "bottom_left" | "bottom_center" | "bottom_right", columns: Numeric, rows: Numeric, bgcolor?: string, frame_color?: string, frame_width?: Numeric, border_color?: string, border_width?: Numeric, force_overlay?: boolean): Table

Creates a table, with its arguments by position only (table.new() also takes them by name).

position
Where the table sits (position.top_right, position.bottom_left...).
columns
Number of columns.
rows
Number of rows.
bgcolor
Background colour of the whole table. Default: none.
frame_color
Colour of the outer frame. Default: none.
frame_width
Width of the outer frame in pixels. Default: 0.
border_color
Colour of the lines between the cells. Default: none.
border_width
Width of the lines between the cells in pixels. Default: 0.
force_overlay
When true, the table is drawn on the price pane. Default: false.

Returns The new table.

const t = table.new_table(position.top_right, 1, 1, color.gray);

table.cell()

table.cell(table_id: Table, column: Numeric, row: Numeric, text?: string, width?: Numeric, height?: Numeric, text_color?: string, text_halign?: HAlign, text_valign?: VAlign, text_size?: string | number, bgcolor?: string, tooltip?: string, text_font_family?: FontFamily, text_formatting?: number): void
table.cell(table_id: Table, column: Numeric, row: Numeric, args: TableCellArgs): void
table.cell(table_id: Table, column: Numeric, row: Numeric, text: string, args: TableCellArgs): void
table.cell(args: TableCellArgs): void

Writes a cell of a table: its text and look. The properties not given get their default, so calling it again replaces the whole cell; use table.cell_set_*() to change one property. A column or row outside the table is an error; on a deleted table it does nothing. The arguments after row can also be given by name in an object.

table_id
The table (from table.new()).
column
Column of the cell, from 0 (left).
row
Row of the cell, from 0 (top).
text
Text of the cell; \n starts a new line. Default: "".
width
Width of the cell in percent of the pane's width; 0 fits the text. Default: 0.
height
Height of the cell in percent of the pane's height; 0 fits the text. Default: 0.
text_color
Text colour. Default: dark gray (#363A45).
text_halign
text.align_left, text.align_center or text.align_right. Default: text.align_center.
text_valign
text.align_top, text.align_center or text.align_bottom. Default: text.align_center.
text_size
size.tiny, size.small, size.normal, size.large, size.huge, size.auto, or a size in points. Default: size.auto.
bgcolor
Background colour of the cell. Default: none (the table's background shows).
tooltip
Text shown when the pointer is over the cell. Default: none.
text_font_family
font.family_default or font.family_monospace. Default: font.family_default.
text_formatting
text.format_bold, text.format_italic, their sum, or text.format_none. Default: text.format_none.

Returns Nothing.

const t = table.new(position.bottom_right, 2, 1);
eachBar((c) => {
  if (c.i === c.n - 1) table.cell(t, 1, 0, str.tostring(c.close, "#.##"), 0, 0, color.white, text.align_right);
});

Writes a cell, with the arguments after row given by name (see the first form).

table_id
The table.
column
Column of the cell, from 0.
row
Row of the cell, from 0.
args
The other arguments by name: text, width, height, text_color, text_halign, text_valign, text_size, bgcolor, tooltip, text_font_family, text_formatting.

Returns Nothing.

const t = table.new(position.top_right, 1, 1);
table.cell(t, 0, 0, { text: "Trend", bgcolor: color.teal, text_color: color.white });

Writes a cell, with its text by position and the arguments after it by name (see the first form).

table_id
The table.
column
Column of the cell, from 0.
row
Row of the cell, from 0.
text
Text of the cell; \n starts a new line.
args
The other arguments by name: width, height, text_color, text_halign, text_valign, text_size, bgcolor, tooltip, text_font_family, text_formatting.

Returns Nothing.

const t = table.new(position.top_right, 1, 1);
table.cell(t, 0, 0, "Trend", { text_size: size.small, tooltip: "50-bar trend" });

Writes a cell, with every argument given by name (see the first form).

args
table_id, column, row, and optionally text, width, height, text_color, text_halign, text_valign, text_size, bgcolor, tooltip, text_font_family, text_formatting.

Returns Nothing.

const t = table.new(position.top_right, 1, 1);
table.cell({ table_id: t, column: 0, row: 0, text: "Trend" });

table.cell_set_text()

table.cell_set_text(table_id: Table, column: Numeric, row: Numeric, value: string): void

Changes the text of a cell and keeps its other properties. A cell that was not written yet is created.

table_id
The table.
column
Column of the cell, from 0.
row
Row of the cell, from 0.
value
New text; \n starts a new line.

Returns Nothing.

const t = table.new(position.top_right, 1, 1);
eachBar((c) => {
  if (c.i === c.n - 1) table.cell_set_text(t, 0, 0, "Close " + str.tostring(c.close, "#.##"));
});

table.cell_set_width()

table.cell_set_width(table_id: Table, column: Numeric, row: Numeric, value: Numeric): void

Changes the width of a cell. A cell that was not written yet is created.

table_id
The table.
column
Column of the cell, from 0.
row
Row of the cell, from 0.
value
Width in percent of the pane's width; 0 fits the text.

Returns Nothing.

const t = table.new(position.top_right, 1, 1);
table.cell(t, 0, 0, "Trend");
table.cell_set_width(t, 0, 0, 10);

table.cell_set_height()

table.cell_set_height(table_id: Table, column: Numeric, row: Numeric, value: Numeric): void

Changes the height of a cell. A cell that was not written yet is created.

table_id
The table.
column
Column of the cell, from 0.
row
Row of the cell, from 0.
value
Height in percent of the pane's height; 0 fits the text.

Returns Nothing.

const t = table.new(position.top_right, 1, 1);
table.cell(t, 0, 0, "Trend");
table.cell_set_height(t, 0, 0, 5);

table.cell_set_text_color()

table.cell_set_text_color(table_id: Table, column: Numeric, row: Numeric, value: string): void

Changes the text colour of a cell. A cell that was not written yet is created.

table_id
The table.
column
Column of the cell, from 0.
row
Row of the cell, from 0.
value
New text colour.

Returns Nothing.

const t = table.new(position.top_right, 1, 1);
eachBar((c) => {
  if (c.i === c.n - 1) table.cell_set_text_color(t, 0, 0, c.close > c.open ? color.green : color.red);
});

table.cell_set_text_halign()

table.cell_set_text_halign(table_id: Table, column: Numeric, row: Numeric, value: HAlign): void

Changes the horizontal alignment of the text of a cell. A cell that was not written yet is created.

table_id
The table.
column
Column of the cell, from 0.
row
Row of the cell, from 0.
value
text.align_left, text.align_center or text.align_right.

Returns Nothing.

const t = table.new(position.top_right, 1, 1);
table.cell(t, 0, 0, "Volume", { width: 15 });
table.cell_set_text_halign(t, 0, 0, text.align_left);

table.cell_set_text_valign()

table.cell_set_text_valign(table_id: Table, column: Numeric, row: Numeric, value: VAlign): void

Changes the vertical alignment of the text of a cell. A cell that was not written yet is created.

table_id
The table.
column
Column of the cell, from 0.
row
Row of the cell, from 0.
value
text.align_top, text.align_center or text.align_bottom.

Returns Nothing.

const t = table.new(position.top_right, 1, 1);
table.cell(t, 0, 0, "Volume", { height: 8 });
table.cell_set_text_valign(t, 0, 0, text.align_bottom);

table.cell_set_text_size()

table.cell_set_text_size(table_id: Table, column: Numeric, row: Numeric, value: string | number): void

Changes the text size of a cell. A cell that was not written yet is created.

table_id
The table.
column
Column of the cell, from 0.
row
Row of the cell, from 0.
value
size.tiny, size.small, size.normal, size.large, size.huge, size.auto, or a size in points.

Returns Nothing.

const t = table.new(position.top_right, 1, 1);
table.cell(t, 0, 0, "Signal");
table.cell_set_text_size(t, 0, 0, size.large);

table.cell_set_bgcolor()

table.cell_set_bgcolor(table_id: Table, column: Numeric, row: Numeric, value: string): void

Changes the background colour of a cell. A cell that was not written yet is created.

table_id
The table.
column
Column of the cell, from 0.
row
Row of the cell, from 0.
value
New background colour.

Returns Nothing.

const t = table.new(position.top_right, 1, 1);
eachBar((c) => {
  if (c.i === c.n - 1) table.cell_set_bgcolor(t, 0, 0, c.close > c.open ? color.teal : color.maroon);
});

table.cell_set_tooltip()

table.cell_set_tooltip(table_id: Table, column: Numeric, row: Numeric, value: string): void

Changes the tooltip of a cell: the text shown when the pointer is over it. A cell that was not written yet is created.

table_id
The table.
column
Column of the cell, from 0.
row
Row of the cell, from 0.
value
Tooltip text.

Returns Nothing.

const t = table.new(position.top_right, 1, 1);
table.cell(t, 0, 0, "ATR");
table.cell_set_tooltip(t, 0, 0, "Average true range over 14 bars");

table.cell_set_text_font_family()

table.cell_set_text_font_family(table_id: Table, column: Numeric, row: Numeric, value: FontFamily): void

Changes the font of a cell's text. A cell that was not written yet is created.

table_id
The table.
column
Column of the cell, from 0.
row
Row of the cell, from 0.
value
font.family_default or font.family_monospace.

Returns Nothing.

const t = table.new(position.top_right, 1, 1);
table.cell(t, 0, 0, "123.45");
table.cell_set_text_font_family(t, 0, 0, font.family_monospace);

table.cell_set_text_formatting()

table.cell_set_text_formatting(table_id: Table, column: Numeric, row: Numeric, value: number): void

Makes a cell's text bold, italic, both or plain. A cell that was not written yet is created.

table_id
The table.
column
Column of the cell, from 0.
row
Row of the cell, from 0.
value
text.format_bold, text.format_italic, their sum, or text.format_none.

Returns Nothing.

const t = table.new(position.top_right, 1, 1);
table.cell(t, 0, 0, "Summary");
table.cell_set_text_formatting(t, 0, 0, text.format_bold + text.format_italic);

table.merge_cells()

table.merge_cells(table_id: Table, start_column: Numeric, start_row: Numeric, end_column: Numeric, end_row: Numeric): void

Joins a block of cells into one cell, for a title over several columns for example. The merged cell shows the content and look of its start (top-left) cell. Merging the same block again does nothing. A cell outside the table, or an end before the start, is an error.

table_id
The table.
start_column
Column of the top-left cell of the block, from 0.
start_row
Row of the top-left cell of the block, from 0.
end_column
Column of the bottom-right cell of the block (not before start_column).
end_row
Row of the bottom-right cell of the block (not before start_row).

Returns Nothing.

const t = table.new(position.top_right, 2, 2);
table.cell(t, 0, 0, "Daily stats");
table.merge_cells(t, 0, 0, 1, 0); // the title spans both columns

table.clear()

table.clear(table_id: Table, start_column: Numeric, start_row: Numeric, end_column?: Numeric, end_row?: Numeric): void

Empties a block of cells (text and look), and removes the merges that start inside it. Without an end, only the start cell is cleared. A cell outside the table is an error.

table_id
The table.
start_column
Column of the top-left cell of the block, from 0.
start_row
Row of the top-left cell of the block, from 0.
end_column
Column of the bottom-right cell of the block. Default: start_column.
end_row
Row of the bottom-right cell of the block. Default: start_row.

Returns Nothing.

const t = table.new(position.top_right, 3, 3);
eachBar((c) => {
  if (c.i === c.n - 1) table.clear(t, 0, 0, 2, 2); // empty all nine cells
});

table.set_position()

table.set_position(table_id: Table, position: "top_left" | "top_center" | "top_right" | "middle_left" | "middle_center" | "middle_right" | "bottom_left" | "bottom_center" | "bottom_right"): void

Moves the table to another place of the pane. A live table already at that position (with the same force_overlay) is deleted. Does nothing on a deleted table.

table_id
The table.
position
New place: position.top_left, position.top_center, position.top_right, position.middle_left, position.middle_center, position.middle_right, position.bottom_left, position.bottom_center or position.bottom_right.

Returns Nothing.

const where = input.string("Top right", "Table", { options: ["Top right", "Bottom left"] });
const t = table.new(position.top_right, 1, 1);
if (where === "Bottom left") table.set_position(t, position.bottom_left);

table.set_bgcolor()

table.set_bgcolor(table_id: Table, value: string): void

Changes the background colour of the whole table (cells with their own background keep it). Does nothing on a deleted table.

table_id
The table.
value
New background colour.

Returns Nothing.

const t = table.new(position.top_right, 1, 1);
eachBar((c) => {
  if (c.i === c.n - 1) table.set_bgcolor(t, c.close > c.open ? color.new(color.green, 80) : color.new(color.red, 80));
});

table.set_frame_color()

table.set_frame_color(table_id: Table, value: string): void

Changes the colour of the outer frame of the table. Does nothing on a deleted table.

table_id
The table.
value
New frame colour.

Returns Nothing.

const t = table.new(position.top_right, 1, 1, { frame_width: 1 });
table.set_frame_color(t, color.gray);

table.set_frame_width()

table.set_frame_width(table_id: Table, value: Numeric): void

Changes the width of the outer frame of the table. Does nothing on a deleted table.

table_id
The table.
value
New frame width in pixels; 0 hides the frame.

Returns Nothing.

const t = table.new(position.top_right, 1, 1, { frame_color: color.gray });
table.set_frame_width(t, 2);

table.set_border_color()

table.set_border_color(table_id: Table, value: string): void

Changes the colour of the lines between the cells. Does nothing on a deleted table.

table_id
The table.
value
New border colour.

Returns Nothing.

const t = table.new(position.top_right, 2, 2, { border_width: 1 });
table.set_border_color(t, color.silver);

table.set_border_width()

table.set_border_width(table_id: Table, value: Numeric): void

Changes the width of the lines between the cells. Does nothing on a deleted table.

table_id
The table.
value
New border width in pixels; 0 hides the lines.

Returns Nothing.

const t = table.new(position.top_right, 2, 2, { border_color: color.silver });
table.set_border_width(t, 1);

table.delete()

table.delete(table_id: Table): void

Removes the table from the pane and from table.all. Afterwards the table functions do nothing on it; deleting it again does nothing.

table_id
The table to delete.

Returns Nothing.

const show = input.bool(true, "Show table");
const t = table.new(position.top_right, 1, 1);
if (!show) table.delete(t);

table.delete_table()

table.delete_table(table_id: Table): void

Removes the table from the pane and from table.all (the same as table.delete()).

table_id
The table to delete.

Returns Nothing.

const t = table.new(position.top_right, 1, 1);
table.delete_table(t);

table.all

The tables still on the pane, oldest first (a new array on each read).

table.all.toLocaleString()

table.all.toLocaleString(): string
table.all.toLocaleString(locales: string | string[], options?: NumberFormatOptions & DateTimeFormatOptions): string

Returns a string representation of an array. The elements are converted to string using their toLocaleString methods.

table.all.pop()

table.all.pop(): Table

Removes the last element from an array and returns it. If the array is empty, undefined is returned and the array is not modified.

table.all.push()

table.all.push(...items: Table[]): number

Appends new elements to the end of an array, and returns the new length of the array.

items
New elements to add to the array.

table.all.concat()

table.all.concat(...items: ConcatArray<Table>[]): Table[]
table.all.concat(...items: (Table | ConcatArray<Table>)[]): Table[]

Combines two or more arrays. This method returns a new array without modifying any existing arrays.

items
Additional arrays and/or items to add to the end of the array.

table.all.join()

table.all.join(separator?: string): string

Adds all the elements of an array into a string, separated by the specified separator string.

separator
A string used to separate one element of the array from the next in the resulting string. If omitted, the array elements are separated with a comma.

table.all.reverse()

table.all.reverse(): Table[]

Reverses the elements in an array in place. This method mutates the array and returns a reference to the same array.

table.all.shift()

table.all.shift(): Table

Removes the first element from an array and returns it. If the array is empty, undefined is returned and the array is not modified.

table.all.slice()

table.all.slice(start?: number, end?: number): Table[]

Returns a copy of a section of an array. For both start and end, a negative index can be used to indicate an offset from the end of the array. For example, -2 refers to the second to last element of the array.

start
The beginning index of the specified portion of the array. If start is undefined, then the slice begins at index 0.
end
The end index of the specified portion of the array. This is exclusive of the element at the index 'end'. If end is undefined, then the slice extends to the end of the array.

table.all.sort()

table.all.sort(compareFn?: (a: Table, b: Table) => number): Table[]

Sorts an array in place. This method mutates the array and returns a reference to the same array.

compareFn
Function used to determine the order of the elements. It is expected to return a negative value if the first argument is less than the second argument, zero if they're equal, and a positive value otherwise. If omitted, the elements are sorted in ascending, ASCII character order. ``ts [11,2,22,1].sort((a, b) => a - b) ``

table.all.splice()

table.all.splice(start: number, deleteCount?: number): Table[]
table.all.splice(start: number, deleteCount: number, ...items: Table[]): Table[]

Removes elements from an array and, if necessary, inserts new elements in their place, returning the deleted elements.

start
The zero-based location in the array from which to start removing elements.
deleteCount
The number of elements to remove.

Returns An array containing the elements that were deleted.

Removes elements from an array and, if necessary, inserts new elements in their place, returning the deleted elements.

start
The zero-based location in the array from which to start removing elements.
deleteCount
The number of elements to remove.
items
Elements to insert into the array in place of the deleted elements.

Returns An array containing the elements that were deleted.

table.all.unshift()

table.all.unshift(...items: Table[]): number

Inserts new elements at the start of an array, and returns the new length of the array.

items
Elements to insert at the start of the array.

table.all.indexOf()

table.all.indexOf(searchElement: Table, fromIndex?: number): number

Returns the index of the first occurrence of a value in an array, or -1 if it is not present.

searchElement
The value to locate in the array.
fromIndex
The array index at which to begin the search. If fromIndex is omitted, the search starts at index 0.

table.all.lastIndexOf()

table.all.lastIndexOf(searchElement: Table, fromIndex?: number): number

Returns the index of the last occurrence of a specified value in an array, or -1 if it is not present.

searchElement
The value to locate in the array.
fromIndex
The array index at which to begin searching backward. If fromIndex is omitted, the search starts at the last index in the array.

table.all.every()

table.all.every<S extends Table>(predicate: (value: Table, index: number, array: Table[]) => value is S, thisArg?: any): this is S[]
table.all.every(predicate: (value: Table, index: number, array: Table[]) => unknown, thisArg?: any): boolean

Determines whether all the members of an array satisfy the specified test.

predicate
A function that accepts up to three arguments. The every method calls the predicate function for each element in the array until the predicate returns a value which is coercible to the Boolean value false, or until the end of the array.
thisArg
An object to which the this keyword can refer in the predicate function. If thisArg is omitted, undefined is used as the this value.

table.all.some()

table.all.some(predicate: (value: Table, index: number, array: Table[]) => unknown, thisArg?: any): boolean

Determines whether the specified callback function returns true for any element of an array.

predicate
A function that accepts up to three arguments. The some method calls the predicate function for each element in the array until the predicate returns a value which is coercible to the Boolean value true, or until the end of the array.
thisArg
An object to which the this keyword can refer in the predicate function. If thisArg is omitted, undefined is used as the this value.

table.all.forEach()

table.all.forEach(callbackfn: (value: Table, index: number, array: Table[]) => void, thisArg?: any): void

Performs the specified action for each element in an array.

callbackfn
A function that accepts up to three arguments. forEach calls the callbackfn function one time for each element in the array.
thisArg
An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.

table.all.map()

table.all.map<U>(callbackfn: (value: Table, index: number, array: Table[]) => U, thisArg?: any): U[]

Calls a defined callback function on each element of an array, and returns an array that contains the results.

callbackfn
A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array.
thisArg
An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.

table.all.filter()

table.all.filter<S extends Table>(predicate: (value: Table, index: number, array: Table[]) => value is S, thisArg?: any): S[]
table.all.filter(predicate: (value: Table, index: number, array: Table[]) => unknown, thisArg?: any): Table[]

Returns the elements of an array that meet the condition specified in a callback function.

predicate
A function that accepts up to three arguments. The filter method calls the predicate function one time for each element in the array.
thisArg
An object to which the this keyword can refer in the predicate function. If thisArg is omitted, undefined is used as the this value.

table.all.reduce()

table.all.reduce(callbackfn: (previousValue: Table, currentValue: Table, currentIndex: number, array: Table[]) => Table): Table
table.all.reduce(callbackfn: (previousValue: Table, currentValue: Table, currentIndex: number, array: Table[]) => Table, initialValue: Table): Table
table.all.reduce<U>(callbackfn: (previousValue: U, currentValue: Table, currentIndex: number, array: Table[]) => U, initialValue: U): U

Calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function.

callbackfn
A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array.
initialValue
If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value.

Calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function.

callbackfn
A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array.
initialValue
If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value.
callbackfn
A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array.
initialValue
If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value.

table.all.reduceRight()

table.all.reduceRight(callbackfn: (previousValue: Table, currentValue: Table, currentIndex: number, array: Table[]) => Table): Table
table.all.reduceRight(callbackfn: (previousValue: Table, currentValue: Table, currentIndex: number, array: Table[]) => Table, initialValue: Table): Table
table.all.reduceRight<U>(callbackfn: (previousValue: U, currentValue: Table, currentIndex: number, array: Table[]) => U, initialValue: U): U

Calls the specified callback function for all the elements in an array, in descending order. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function.

callbackfn
A function that accepts up to four arguments. The reduceRight method calls the callbackfn function one time for each element in the array.
initialValue
If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value.

Calls the specified callback function for all the elements in an array, in descending order. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function.

callbackfn
A function that accepts up to four arguments. The reduceRight method calls the callbackfn function one time for each element in the array.
initialValue
If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value.
callbackfn
A function that accepts up to four arguments. The reduceRight method calls the callbackfn function one time for each element in the array.
initialValue
If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value.

table.all.find()

table.all.find<S extends Table>(predicate: (value: Table, index: number, obj: Table[]) => value is S, thisArg?: any): S
table.all.find(predicate: (value: Table, index: number, obj: Table[]) => unknown, thisArg?: any): Table

Returns the value of the first element in the array where predicate is true, and undefined otherwise.

predicate
find calls predicate once for each element of the array, in ascending order, until it finds one where predicate returns true. If such an element is found, find immediately returns that element value. Otherwise, find returns undefined.
thisArg
If provided, it will be used as the this value for each invocation of predicate. If it is not provided, undefined is used instead.

table.all.findIndex()

table.all.findIndex(predicate: (value: Table, index: number, obj: Table[]) => unknown, thisArg?: any): number

Returns the index of the first element in the array where predicate is true, and -1 otherwise.

predicate
find calls predicate once for each element of the array, in ascending order, until it finds one where predicate returns true. If such an element is found, findIndex immediately returns that element index. Otherwise, findIndex returns -1.
thisArg
If provided, it will be used as the this value for each invocation of predicate. If it is not provided, undefined is used instead.

table.all.fill()

table.all.fill(value: Table, start?: number, end?: number): Table[]

Changes all array elements from start to end index to a static value and returns the modified array

value
value to fill array section with
start
index to start filling the array at. If start is negative, it is treated as length+start where length is the length of the array.
end
index to stop filling the array at. If end is negative, it is treated as length+end.

table.all.copyWithin()

table.all.copyWithin(target: number, start: number, end?: number): Table[]

Returns the this object after copying a section of the array identified by start and end to the same array starting at position target

target
If target is negative, it is treated as length+target where length is the length of the array.
start
If start is negative, it is treated as length+start. If end is negative, it is treated as length+end.
end
If not specified, length of the this object is used as its default value.

table.all.entries()

table.all.entries(): ArrayIterator<[number, Table]>

Returns an iterable of key, value pairs for every entry in the array

table.all.keys()

table.all.keys(): ArrayIterator<number>

Returns an iterable of keys in the array

table.all.values()

table.all.values(): ArrayIterator<Table>

Returns an iterable of values in the array

table.all.includes()

table.all.includes(searchElement: Table, fromIndex?: number): boolean

Determines whether an array includes a certain element, returning true or false as appropriate.

searchElement
The element to search for.
fromIndex
The position in this array at which to begin searching for searchElement.

table.all.flatMap()

table.all.flatMap<U, This = undefined>(callback: (this: This, value: Table, index: number, array: Table[]) => U | readonly U[], thisArg?: This): U[]

Calls a defined callback function on each element of an array. Then, flattens the result into a new array. This is identical to a map followed by flat with depth 1.

callback
A function that accepts up to three arguments. The flatMap method calls the callback function one time for each element in the array.
thisArg
An object to which the this keyword can refer in the callback function. If thisArg is omitted, undefined is used as the this value.

table.all.flat()

table.all.flat<A, D extends number = 1>(this: A, depth?: D): FlatArray<A, D>[]

Returns a new array with all sub-array elements concatenated into it recursively up to the specified depth.

depth
The maximum recursion depth

table.all.at()

table.all.at(index: number): Table

Returns the item located at the specified index.

index
The zero-based index of the desired code unit. A negative index will count back from the last item.

table.all.findLast()

table.all.findLast<S extends Table>(predicate: (value: Table, index: number, array: Table[]) => value is S, thisArg?: any): S
table.all.findLast(predicate: (value: Table, index: number, array: Table[]) => unknown, thisArg?: any): Table

Returns the value of the last element in the array where predicate is true, and undefined otherwise.

predicate
findLast calls predicate once for each element of the array, in descending order, until it finds one where predicate returns true. If such an element is found, findLast immediately returns that element value. Otherwise, findLast returns undefined.
thisArg
If provided, it will be used as the this value for each invocation of predicate. If it is not provided, undefined is used instead.

table.all.findLastIndex()

table.all.findLastIndex(predicate: (value: Table, index: number, array: Table[]) => unknown, thisArg?: any): number

Returns the index of the last element in the array where predicate is true, and -1 otherwise.

predicate
findLastIndex calls predicate once for each element of the array, in descending order, until it finds one where predicate returns true. If such an element is found, findLastIndex immediately returns that element index. Otherwise, findLastIndex returns -1.
thisArg
If provided, it will be used as the this value for each invocation of predicate. If it is not provided, undefined is used instead.

table.all.toReversed()

table.all.toReversed(): Table[]

Returns a copy of an array with its elements reversed.

table.all.toSorted()

table.all.toSorted(compareFn?: (a: Table, b: Table) => number): Table[]

Returns a copy of an array with its elements sorted.

compareFn
Function used to determine the order of the elements. It is expected to return a negative value if the first argument is less than the second argument, zero if they're equal, and a positive value otherwise. If omitted, the elements are sorted in ascending, ASCII character order. ``ts [11, 2, 22, 1].toSorted((a, b) => a - b) // [1, 2, 11, 22] ``

table.all.toSpliced()

table.all.toSpliced(start: number, deleteCount: number, ...items: Table[]): Table[]
table.all.toSpliced(start: number, deleteCount?: number): Table[]

Copies an array and removes elements and, if necessary, inserts new elements in their place. Returns the copied array.

start
The zero-based location in the array from which to start removing elements.
deleteCount
The number of elements to remove.
items
Elements to insert into the copied array in place of the deleted elements.

Returns The copied array.

Copies an array and removes elements while returning the remaining elements.

start
The zero-based location in the array from which to start removing elements.
deleteCount
The number of elements to remove.

Returns A copy of the original array with the remaining elements.

table.all.with()

table.all.with(index: number, value: Table): Table[]

Copies an array, then overwrites the value at the provided index with the given value. If the index is negative, then it replaces from the end of the array.

index
The index of the value to overwrite. If the index is negative, then it replaces from the end of the array.
value
The value to write into the copied array.

Returns The copied array with the updated value.

table.all.length

table.all.length: number

Gets or sets the length of the array. This is a number one higher than the highest index in the array.

table.all.__@unscopables@73

Is an object whose properties have the value 'true' when they will be absent when used in a 'with' statement.

table.all.__@unscopables@73.length

table.all.__@unscopables@73.length: boolean

Gets or sets the length of the array. This is a number one higher than the highest index in the array.

table.all.__@unscopables@73.toLocaleString

table.all.__@unscopables@73.toLocaleString: boolean

Returns a string representation of an array. The elements are converted to string using their toLocaleString methods.

table.all.__@unscopables@73.pop

table.all.__@unscopables@73.pop: boolean

Removes the last element from an array and returns it. If the array is empty, undefined is returned and the array is not modified.

table.all.__@unscopables@73.push

table.all.__@unscopables@73.push: boolean

Appends new elements to the end of an array, and returns the new length of the array.

items
New elements to add to the array.

table.all.__@unscopables@73.concat

table.all.__@unscopables@73.concat: boolean

Combines two or more arrays. This method returns a new array without modifying any existing arrays.

items
Additional arrays and/or items to add to the end of the array.
items
Additional arrays and/or items to add to the end of the array.

table.all.__@unscopables@73.join

table.all.__@unscopables@73.join: boolean

Adds all the elements of an array into a string, separated by the specified separator string.

separator
A string used to separate one element of the array from the next in the resulting string. If omitted, the array elements are separated with a comma.

table.all.__@unscopables@73.reverse

table.all.__@unscopables@73.reverse: boolean

Reverses the elements in an array in place. This method mutates the array and returns a reference to the same array.

table.all.__@unscopables@73.shift

table.all.__@unscopables@73.shift: boolean

Removes the first element from an array and returns it. If the array is empty, undefined is returned and the array is not modified.

table.all.__@unscopables@73.slice

table.all.__@unscopables@73.slice: boolean

Returns a copy of a section of an array. For both start and end, a negative index can be used to indicate an offset from the end of the array. For example, -2 refers to the second to last element of the array.

start
The beginning index of the specified portion of the array. If start is undefined, then the slice begins at index 0.
end
The end index of the specified portion of the array. This is exclusive of the element at the index 'end'. If end is undefined, then the slice extends to the end of the array.

table.all.__@unscopables@73.sort

table.all.__@unscopables@73.sort: boolean

Sorts an array in place. This method mutates the array and returns a reference to the same array.

compareFn
Function used to determine the order of the elements. It is expected to return a negative value if the first argument is less than the second argument, zero if they're equal, and a positive value otherwise. If omitted, the elements are sorted in ascending, ASCII character order. ``ts [11,2,22,1].sort((a, b) => a - b) ``

table.all.__@unscopables@73.splice

table.all.__@unscopables@73.splice: boolean

Removes elements from an array and, if necessary, inserts new elements in their place, returning the deleted elements.

start
The zero-based location in the array from which to start removing elements.
deleteCount
The number of elements to remove.
start
The zero-based location in the array from which to start removing elements.
deleteCount
The number of elements to remove.
items
Elements to insert into the array in place of the deleted elements.

Returns An array containing the elements that were deleted.

table.all.__@unscopables@73.unshift

table.all.__@unscopables@73.unshift: boolean

Inserts new elements at the start of an array, and returns the new length of the array.

items
Elements to insert at the start of the array.

table.all.__@unscopables@73.indexOf

table.all.__@unscopables@73.indexOf: boolean

Returns the index of the first occurrence of a value in an array, or -1 if it is not present.

searchElement
The value to locate in the array.
fromIndex
The array index at which to begin the search. If fromIndex is omitted, the search starts at index 0.

table.all.__@unscopables@73.lastIndexOf

table.all.__@unscopables@73.lastIndexOf: boolean

Returns the index of the last occurrence of a specified value in an array, or -1 if it is not present.

searchElement
The value to locate in the array.
fromIndex
The array index at which to begin searching backward. If fromIndex is omitted, the search starts at the last index in the array.

table.all.__@unscopables@73.every

table.all.__@unscopables@73.every: boolean

Determines whether all the members of an array satisfy the specified test.

predicate
A function that accepts up to three arguments. The every method calls the predicate function for each element in the array until the predicate returns a value which is coercible to the Boolean value false, or until the end of the array.
thisArg
An object to which the this keyword can refer in the predicate function. If thisArg is omitted, undefined is used as the this value.
predicate
A function that accepts up to three arguments. The every method calls the predicate function for each element in the array until the predicate returns a value which is coercible to the Boolean value false, or until the end of the array.
thisArg
An object to which the this keyword can refer in the predicate function. If thisArg is omitted, undefined is used as the this value.

table.all.__@unscopables@73.some

table.all.__@unscopables@73.some: boolean

Determines whether the specified callback function returns true for any element of an array.

predicate
A function that accepts up to three arguments. The some method calls the predicate function for each element in the array until the predicate returns a value which is coercible to the Boolean value true, or until the end of the array.
thisArg
An object to which the this keyword can refer in the predicate function. If thisArg is omitted, undefined is used as the this value.

table.all.__@unscopables@73.forEach

table.all.__@unscopables@73.forEach: boolean

Performs the specified action for each element in an array.

callbackfn
A function that accepts up to three arguments. forEach calls the callbackfn function one time for each element in the array.
thisArg
An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.

table.all.__@unscopables@73.map

table.all.__@unscopables@73.map: boolean

Calls a defined callback function on each element of an array, and returns an array that contains the results.

callbackfn
A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array.
thisArg
An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.

table.all.__@unscopables@73.filter

table.all.__@unscopables@73.filter: boolean

Returns the elements of an array that meet the condition specified in a callback function.

predicate
A function that accepts up to three arguments. The filter method calls the predicate function one time for each element in the array.
thisArg
An object to which the this keyword can refer in the predicate function. If thisArg is omitted, undefined is used as the this value.
predicate
A function that accepts up to three arguments. The filter method calls the predicate function one time for each element in the array.
thisArg
An object to which the this keyword can refer in the predicate function. If thisArg is omitted, undefined is used as the this value.

table.all.__@unscopables@73.reduce

table.all.__@unscopables@73.reduce: boolean

Calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function.

callbackfn
A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array.
initialValue
If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value.
callbackfn
A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array.
initialValue
If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value.

table.all.__@unscopables@73.reduceRight

table.all.__@unscopables@73.reduceRight: boolean

Calls the specified callback function for all the elements in an array, in descending order. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function.

callbackfn
A function that accepts up to four arguments. The reduceRight method calls the callbackfn function one time for each element in the array.
initialValue
If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value.
callbackfn
A function that accepts up to four arguments. The reduceRight method calls the callbackfn function one time for each element in the array.
initialValue
If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value.

table.all.__@unscopables@73.find

table.all.__@unscopables@73.find: boolean

Returns the value of the first element in the array where predicate is true, and undefined otherwise.

predicate
find calls predicate once for each element of the array, in ascending order, until it finds one where predicate returns true. If such an element is found, find immediately returns that element value. Otherwise, find returns undefined.
thisArg
If provided, it will be used as the this value for each invocation of predicate. If it is not provided, undefined is used instead.

table.all.__@unscopables@73.findIndex

table.all.__@unscopables@73.findIndex: boolean

Returns the index of the first element in the array where predicate is true, and -1 otherwise.

predicate
find calls predicate once for each element of the array, in ascending order, until it finds one where predicate returns true. If such an element is found, findIndex immediately returns that element index. Otherwise, findIndex returns -1.
thisArg
If provided, it will be used as the this value for each invocation of predicate. If it is not provided, undefined is used instead.

table.all.__@unscopables@73.fill

table.all.__@unscopables@73.fill: boolean

Changes all array elements from start to end index to a static value and returns the modified array

value
value to fill array section with
start
index to start filling the array at. If start is negative, it is treated as length+start where length is the length of the array.
end
index to stop filling the array at. If end is negative, it is treated as length+end.

table.all.__@unscopables@73.copyWithin

table.all.__@unscopables@73.copyWithin: boolean

Returns the this object after copying a section of the array identified by start and end to the same array starting at position target

target
If target is negative, it is treated as length+target where length is the length of the array.
start
If start is negative, it is treated as length+start. If end is negative, it is treated as length+end.
end
If not specified, length of the this object is used as its default value.

table.all.__@unscopables@73.includes

table.all.__@unscopables@73.includes: boolean

Determines whether an array includes a certain element, returning true or false as appropriate.

searchElement
The element to search for.
fromIndex
The position in this array at which to begin searching for searchElement.

table.all.__@unscopables@73.flatMap

table.all.__@unscopables@73.flatMap: boolean

Calls a defined callback function on each element of an array. Then, flattens the result into a new array. This is identical to a map followed by flat with depth 1.

callback
A function that accepts up to three arguments. The flatMap method calls the callback function one time for each element in the array.
thisArg
An object to which the this keyword can refer in the callback function. If thisArg is omitted, undefined is used as the this value.

table.all.__@unscopables@73.flat

table.all.__@unscopables@73.flat: boolean

Returns a new array with all sub-array elements concatenated into it recursively up to the specified depth.

depth
The maximum recursion depth

table.all.__@unscopables@73.at

table.all.__@unscopables@73.at: boolean

Returns the item located at the specified index.

index
The zero-based index of the desired code unit. A negative index will count back from the last item.

table.all.__@unscopables@73.findLast

table.all.__@unscopables@73.findLast: boolean

Returns the value of the last element in the array where predicate is true, and undefined otherwise.

predicate
findLast calls predicate once for each element of the array, in descending order, until it finds one where predicate returns true. If such an element is found, findLast immediately returns that element value. Otherwise, findLast returns undefined.
thisArg
If provided, it will be used as the this value for each invocation of predicate. If it is not provided, undefined is used instead.

table.all.__@unscopables@73.findLastIndex

table.all.__@unscopables@73.findLastIndex: boolean

Returns the index of the last element in the array where predicate is true, and -1 otherwise.

predicate
findLastIndex calls predicate once for each element of the array, in descending order, until it finds one where predicate returns true. If such an element is found, findLastIndex immediately returns that element index. Otherwise, findLastIndex returns -1.
thisArg
If provided, it will be used as the this value for each invocation of predicate. If it is not provided, undefined is used instead.

table.all.__@unscopables@73.toSorted

table.all.__@unscopables@73.toSorted: boolean

Returns a copy of an array with its elements sorted.

compareFn
Function used to determine the order of the elements. It is expected to return a negative value if the first argument is less than the second argument, zero if they're equal, and a positive value otherwise. If omitted, the elements are sorted in ascending, ASCII character order. ``ts [11, 2, 22, 1].toSorted((a, b) => a - b) // [1, 2, 11, 22] ``

table.all.__@unscopables@73.toSpliced

table.all.__@unscopables@73.toSpliced: boolean

Copies an array and removes elements and, if necessary, inserts new elements in their place. Returns the copied array. Copies an array and removes elements while returning the remaining elements.

start
The zero-based location in the array from which to start removing elements.
deleteCount
The number of elements to remove.
items
Elements to insert into the copied array in place of the deleted elements.
start
The zero-based location in the array from which to start removing elements.
deleteCount
The number of elements to remove.

Returns A copy of the original array with the remaining elements.

table.all.__@unscopables@73.with

table.all.__@unscopables@73.with: boolean

Copies an array, then overwrites the value at the provided index with the given value. If the index is negative, then it replaces from the end of the array.

index
The index of the value to overwrite. If the index is negative, then it replaces from the end of the array.
value
The value to write into the copied array.

Returns The copied array with the updated value.

text

Text constants: text.format_* (bold, italic), text.align_* (alignment) and text.wrap_* (wrapping).

text.format_none

text.format_none: 0

Plain text: neither bold nor italic (the default).

text.format_bold

text.format_bold: 1

Bold text; add text.format_italic for bold italic.

text.format_italic

text.format_italic: 2

Italic text; add text.format_bold for bold italic.

text.align_left

text.align_left: "left"

Text aligned to the left (text_halign of table.cell() and box.new(), textalign of label.new()).

text.align_center

text.align_center: "center"

Text centred, horizontally or vertically.

text.align_top

text.align_top: "top"

Text aligned to the top (text_valign of table.cell() and box.new()).

text.align_bottom

text.align_bottom: "bottom"

Text aligned to the bottom (text_valign).

text.wrap_auto

text.wrap_auto: "auto"

Text wrapped onto several lines to fit the width of the box (text_wrap of box.new()).

text.wrap_none

text.wrap_none: "none"

Text not wrapped: each line of the text stays on one line.

ticker

Symbol ids for request.security: ticker.heikinashi(symbol) asks for Heikin Ashi bars, ticker.standard(symbol) for the standard ones.

ticker.heikinashi()

ticker.heikinashi(symbol: string): string

The symbol id of the Heikin Ashi bars of a symbol: request.security on it computes the expression on Heikin Ashi candles.

symbol
Symbol id, e.g. syminfo.tickerid.

Returns The symbol id that selects Heikin Ashi bars.

const haClose = request.security(ticker.heikinashi(syminfo.tickerid), "", () => close);
plot(haClose, "Heikin Ashi close");

ticker.standard()

ticker.standard(symbol: string): string

The symbol id of the standard bars of a symbol: removes the Heikin Ashi marking of ticker.heikinashi, and returns any other id unchanged.

symbol
Symbol id, e.g. syminfo.tickerid.

Returns The symbol id of the standard bars.

const realClose = request.security(ticker.standard(syminfo.tickerid), "", () => close);
plot(realClose, "Close");

time

time()

time(tf?: string, session?: string, timezone?: string): Series

The open time of the period of tf that holds each bar, in UNIX milliseconds; na on bars outside session.

tf
Timeframe of the periods: "D", "W", "60"... Default: the chart's.
session
Session hours, e.g. "0930-1600"; bars outside it give na. Default: the symbol's.
timezone
Time zone of the session hours. Default: the exchange's.

Returns Series of period open times.

const newDay = time("D").neq(time("D").offset(1));
bgcolor(color.when(newDay, color.new(color.gray, 85)));

time.add()

time.add(other: number | Series): Series

Adds a Series or a number to this series, bar by bar (the + of two values). NaN on either side gives NaN.

other
Series or number to add.

Returns A Series of the sums.

const mid = high.add(low).div(2);

time.sub()

time.sub(other: number | Series): Series

Subtracts a Series or a number from this series, bar by bar (the - of two values). NaN on either side gives NaN.

other
Series or number to subtract.

Returns A Series of the differences.

const body = close.sub(open);

time.mul()

time.mul(other: number | Series): Series

Multiplies this series by a Series or a number, bar by bar (the * of two values). NaN on either side gives NaN.

other
Series or number to multiply by.

Returns A Series of the products.

const upper = ta.sma(close, 20).mul(1.02);

time.pow()

time.pow(exponent: number | Series): Series

Raises this series to a power, bar by bar (math.pow on a series). NaN on either side gives NaN; a negative base with a fractional exponent gives NaN.

exponent
Series or number exponent.

Returns A Series of this ** exponent.

const squared = close.sub(ta.sma(close, 20)).pow(2);

time.div()

time.div(other: number | Series): Series

Divides this series by a Series or a number, bar by bar (the / of two values). A division by 0 gives +/-Infinity (which na() treats as na), 0 / 0 and NaN on either side give NaN.

other
Series or number to divide by.

Returns A Series of the quotients.

const range = high.sub(low);
const ratio = range.gt(0).iff(close.sub(open).div(range), 0);

time.mod()

time.mod(other: number | Series): Series

Remainder of the division of this series by a Series or a number, bar by bar (the % of two values). The remainder has the sign of this series; a divisor of 0 and NaN on either side give NaN.

other
Series or number to divide by.

Returns A Series of the remainders.

const everyFifth = bar_index.mod(5).eq(0);

time.neg()

time.neg(): Series

Changes the sign of every value (the unary -). NaN stays NaN.

Returns A Series of the opposite values.

const drop = close.sub(close.offset(1)).neg();

time.gt()

time.gt(other: number | Series): Series

Tests whether this series is above a Series or a number, bar by bar (a > b). Values closer than 1e-10 count as equal, and a NaN on either side gives 0 (false), never NaN.

other
Series or number to compare with.

Returns A Series of 1 where it is true, 0 where it is false.

const up = close.gt(open);

time.gte()

time.gte(other: number | Series): Series

Tests whether this series is above or equal to a Series or a number, bar by bar (a >= b). Values closer than 1e-10 count as equal, and a NaN on either side gives 0 (false), never NaN.

other
Series or number to compare with.

Returns A Series of 1 where it is true, 0 where it is false.

const atOrAbove = close.gte(ta.sma(close, 50));

time.lt()

time.lt(other: number | Series): Series

Tests whether this series is below a Series or a number, bar by bar (a < b). Values closer than 1e-10 count as equal, and a NaN on either side gives 0 (false), never NaN.

other
Series or number to compare with.

Returns A Series of 1 where it is true, 0 where it is false.

const oversold = ta.rsi(close, 14).lt(30);

time.lte()

time.lte(other: number | Series): Series

Tests whether this series is below or equal to a Series or a number, bar by bar (a <= b). Values closer than 1e-10 count as equal, and a NaN on either side gives 0 (false), never NaN.

other
Series or number to compare with.

Returns A Series of 1 where it is true, 0 where it is false.

const atOrBelow = low.lte(ta.lowest(low, 20).offset(1));

time.eq()

time.eq(other: number | Series): Series

Tests whether this series equals a Series or a number, bar by bar (a == b). Values closer than 1e-10 count as equal, and a NaN on either side gives 0 (false), never NaN.

other
Series or number to compare with.

Returns A Series of 1 where it is true, 0 where it is false.

const doji = close.eq(open);

time.neq()

time.neq(other: number | Series): Series

Tests whether this series differs from a Series or a number, bar by bar (a != b). Values closer than 1e-10 count as equal, and a NaN on either side gives 0 (false), never NaN.

other
Series or number to compare with.

Returns A Series of 1 where it is true, 0 where it is false.

const moved = close.neq(close.offset(1));

time.and()

time.and(other: number | Series): Series

Logical "and" of two conditions, bar by bar. A value is true when it is not 0 and not NaN.

other
The other condition: a Series or a number.

Returns A Series of 1 where both are true, 0 elsewhere.

const strongUp = close.gt(open).and(volume.gt(ta.sma(volume, 20)));

time.or()

time.or(other: number | Series): Series

Logical "or" of two conditions, bar by bar. A value is true when it is not 0 and not NaN.

other
The other condition: a Series or a number.

Returns A Series of 1 where at least one is true, 0 elsewhere.

const extreme = ta.rsi(close, 14).gt(70).or(ta.rsi(close, 14).lt(30));

time.not()

time.not(): Series

Logical "not" of a condition, bar by bar: true (not 0, not NaN) becomes 0, and 0 or NaN becomes 1.

Returns A Series of 1 where this series is false, 0 where it is true.

const notUp = close.gt(open).not();

time.iff()

time.iff(trueValue: number | Series, falseValue: number | Series): Series

Picks one of two values on each bar, with this series as the condition (the cond ? x : y of a series). The condition is true when it is not 0 and not NaN; 0 and NaN pick falseValue.

trueValue
Series or number used where the condition is true.
falseValue
Series or number used where the condition is false.

Returns A Series of the picked values.

const range = high.sub(low);
const ratio = range.gt(0).iff(close.sub(open).div(range), 0);
plot(ratio, "Body / range");

time.offset()

time.offset(offset: number): Series

Shifts the series back in time: on each bar, the value offset bars earlier (close.offset(1) is the previous close). The first offset bars, which have no earlier bar, get NaN.

offset
Number of bars back: 0 (the series itself) or more, a whole number. A series computed by the script can look back at most 5000 bars; the price series (close, high...) any number.

Returns A Series of the earlier values.

Throws RangeError when offset is negative (it would read a future bar); an error past 5000 bars.

const change = close.sub(close.offset(1));
const higherHigh = high.gt(high.offset(1));

time.toArray()

time.toArray(): number[]

Gives the values of all the bars as a plain array, oldest bar first (NaN for na). The values are computed on the first read and kept until the bars change; the array is shared, so copy it before changing it.

Returns One number per bar, oldest first.

const values = ta.sma(close, 20).toArray();
const shifted = seriesOf(values.map((v) => v * 1.01));

time.materialize()

time.materialize(): Series

Computes the values now and returns a Series that stores them, without links to the series it was built from. Use it on a long chain of methods to compute it once and free the steps in between.

Returns A Series of the same values, stored.

const spread = high.sub(low).div(close).mul(100).materialize();

time._invalidate()

time._invalidate(): void

Invalidate cache (when data changes)

Note: With BarData versioning, manual invalidation is rarely needed. The cache is automatically invalidated when the underlying BarData changes. This method is kept for backward compatibility and advanced use cases.

time._compute()

time._compute(): number[]

Compute all values (alias for toArray)

Returns Array of computed values

time.get()

time.get(index: number): number

Reads the value of one bar by its position: 0 is the oldest bar, bar_index counts the same way. This is not the "bars back" of offset(): inside a bar loop, read the current bar with c.get(series) and earlier bars with c.get(series, k).

index
Bar position, 0 for the oldest bar.

Returns The value of that bar; NaN when there is no such bar.

const firstClose = close.get(0);

time.last()

time.last(): number

Reads the value of the newest bar.

Returns The value of the last bar; NaN when there are no bars.

const lastRsi = ta.rsi(close, 14).last();

time.length()

time.length(): number

Gives the number of bars of the series (a method, not a property).

Returns The number of bars.

const bars = close.length();

time.toTimeValuePairs()

time.toTimeValuePairs(): { time: any; value: number; }[]

Gives the values as { time, value } points for a chart line, oldest first, leaving out the NaN bars.

Returns The points; time is the bar time, in the unit of the bars.

const points = ta.sma(close, 20).toTimeValuePairs();

time.__@toPrimitive@575()

time.__@toPrimitive@575(hint: "string" | "number" | "default"): never

A Series holds the values of all the bars, so JavaScript operators cannot use it: without this guard close - open is NaN, close > open false and ` ${rsi} ` "[object Object]", with no error. The conversion throws instead, with the Series method or bar-loop read to use.

time.fullHistory

time.fullHistory: boolean

True for the built-in price series (open, high, low, close, volume, hl2...): their history covers every bar, so offset() may reach further than 5000 bars back.

time.extractortime.dataSourcetime.cachedtime.cachedVersion

time.bars

The bars this series is aligned to ({ time, open, high, low, close, volume }, oldest first).

time.bars.toLocaleString()

time.bars.toLocaleString(): string
time.bars.toLocaleString(locales: string | string[], options?: NumberFormatOptions & DateTimeFormatOptions): string

Returns a string representation of an array. The elements are converted to string using their toLocaleString methods.

time.bars.pop()

time.bars.pop(): Bar

Removes the last element from an array and returns it. If the array is empty, undefined is returned and the array is not modified.

time.bars.push()

time.bars.push(...items: Bar[]): number

Appends new elements to the end of an array, and returns the new length of the array.

items
New elements to add to the array.

time.bars.concat()

time.bars.concat(...items: ConcatArray<Bar>[]): Bar[]
time.bars.concat(...items: (Bar | ConcatArray<Bar>)[]): Bar[]

Combines two or more arrays. This method returns a new array without modifying any existing arrays.

items
Additional arrays and/or items to add to the end of the array.

time.bars.join()

time.bars.join(separator?: string): string

Adds all the elements of an array into a string, separated by the specified separator string.

separator
A string used to separate one element of the array from the next in the resulting string. If omitted, the array elements are separated with a comma.

time.bars.reverse()

time.bars.reverse(): Bar[]

Reverses the elements in an array in place. This method mutates the array and returns a reference to the same array.

time.bars.shift()

time.bars.shift(): Bar

Removes the first element from an array and returns it. If the array is empty, undefined is returned and the array is not modified.

time.bars.slice()

time.bars.slice(start?: number, end?: number): Bar[]

Returns a copy of a section of an array. For both start and end, a negative index can be used to indicate an offset from the end of the array. For example, -2 refers to the second to last element of the array.

start
The beginning index of the specified portion of the array. If start is undefined, then the slice begins at index 0.
end
The end index of the specified portion of the array. This is exclusive of the element at the index 'end'. If end is undefined, then the slice extends to the end of the array.

time.bars.sort()

time.bars.sort(compareFn?: (a: Bar, b: Bar) => number): Bar[]

Sorts an array in place. This method mutates the array and returns a reference to the same array.

compareFn
Function used to determine the order of the elements. It is expected to return a negative value if the first argument is less than the second argument, zero if they're equal, and a positive value otherwise. If omitted, the elements are sorted in ascending, ASCII character order. ``ts [11,2,22,1].sort((a, b) => a - b) ``

time.bars.splice()

time.bars.splice(start: number, deleteCount?: number): Bar[]
time.bars.splice(start: number, deleteCount: number, ...items: Bar[]): Bar[]

Removes elements from an array and, if necessary, inserts new elements in their place, returning the deleted elements.

start
The zero-based location in the array from which to start removing elements.
deleteCount
The number of elements to remove.

Returns An array containing the elements that were deleted.

Removes elements from an array and, if necessary, inserts new elements in their place, returning the deleted elements.

start
The zero-based location in the array from which to start removing elements.
deleteCount
The number of elements to remove.
items
Elements to insert into the array in place of the deleted elements.

Returns An array containing the elements that were deleted.

time.bars.unshift()

time.bars.unshift(...items: Bar[]): number

Inserts new elements at the start of an array, and returns the new length of the array.

items
Elements to insert at the start of the array.

time.bars.indexOf()

time.bars.indexOf(searchElement: Bar, fromIndex?: number): number

Returns the index of the first occurrence of a value in an array, or -1 if it is not present.

searchElement
The value to locate in the array.
fromIndex
The array index at which to begin the search. If fromIndex is omitted, the search starts at index 0.

time.bars.lastIndexOf()

time.bars.lastIndexOf(searchElement: Bar, fromIndex?: number): number

Returns the index of the last occurrence of a specified value in an array, or -1 if it is not present.

searchElement
The value to locate in the array.
fromIndex
The array index at which to begin searching backward. If fromIndex is omitted, the search starts at the last index in the array.

time.bars.every()

time.bars.every<S extends Bar>(predicate: (value: Bar, index: number, array: Bar[]) => value is S, thisArg?: any): this is S[]
time.bars.every(predicate: (value: Bar, index: number, array: Bar[]) => unknown, thisArg?: any): boolean

Determines whether all the members of an array satisfy the specified test.

predicate
A function that accepts up to three arguments. The every method calls the predicate function for each element in the array until the predicate returns a value which is coercible to the Boolean value false, or until the end of the array.
thisArg
An object to which the this keyword can refer in the predicate function. If thisArg is omitted, undefined is used as the this value.

time.bars.some()

time.bars.some(predicate: (value: Bar, index: number, array: Bar[]) => unknown, thisArg?: any): boolean

Determines whether the specified callback function returns true for any element of an array.

predicate
A function that accepts up to three arguments. The some method calls the predicate function for each element in the array until the predicate returns a value which is coercible to the Boolean value true, or until the end of the array.
thisArg
An object to which the this keyword can refer in the predicate function. If thisArg is omitted, undefined is used as the this value.

time.bars.forEach()

time.bars.forEach(callbackfn: (value: Bar, index: number, array: Bar[]) => void, thisArg?: any): void

Performs the specified action for each element in an array.

callbackfn
A function that accepts up to three arguments. forEach calls the callbackfn function one time for each element in the array.
thisArg
An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.

time.bars.map()

time.bars.map<U>(callbackfn: (value: Bar, index: number, array: Bar[]) => U, thisArg?: any): U[]

Calls a defined callback function on each element of an array, and returns an array that contains the results.

callbackfn
A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array.
thisArg
An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.

time.bars.filter()

time.bars.filter<S extends Bar>(predicate: (value: Bar, index: number, array: Bar[]) => value is S, thisArg?: any): S[]
time.bars.filter(predicate: (value: Bar, index: number, array: Bar[]) => unknown, thisArg?: any): Bar[]

Returns the elements of an array that meet the condition specified in a callback function.

predicate
A function that accepts up to three arguments. The filter method calls the predicate function one time for each element in the array.
thisArg
An object to which the this keyword can refer in the predicate function. If thisArg is omitted, undefined is used as the this value.

time.bars.reduce()

time.bars.reduce(callbackfn: (previousValue: Bar, currentValue: Bar, currentIndex: number, array: Bar[]) => Bar): Bar
time.bars.reduce(callbackfn: (previousValue: Bar, currentValue: Bar, currentIndex: number, array: Bar[]) => Bar, initialValue: Bar): Bar
time.bars.reduce<U>(callbackfn: (previousValue: U, currentValue: Bar, currentIndex: number, array: Bar[]) => U, initialValue: U): U

Calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function.

callbackfn
A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array.
initialValue
If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value.

Calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function.

callbackfn
A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array.
initialValue
If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value.
callbackfn
A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array.
initialValue
If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value.

time.bars.reduceRight()

time.bars.reduceRight(callbackfn: (previousValue: Bar, currentValue: Bar, currentIndex: number, array: Bar[]) => Bar): Bar
time.bars.reduceRight(callbackfn: (previousValue: Bar, currentValue: Bar, currentIndex: number, array: Bar[]) => Bar, initialValue: Bar): Bar
time.bars.reduceRight<U>(callbackfn: (previousValue: U, currentValue: Bar, currentIndex: number, array: Bar[]) => U, initialValue: U): U

Calls the specified callback function for all the elements in an array, in descending order. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function.

callbackfn
A function that accepts up to four arguments. The reduceRight method calls the callbackfn function one time for each element in the array.
initialValue
If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value.

Calls the specified callback function for all the elements in an array, in descending order. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function.

callbackfn
A function that accepts up to four arguments. The reduceRight method calls the callbackfn function one time for each element in the array.
initialValue
If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value.
callbackfn
A function that accepts up to four arguments. The reduceRight method calls the callbackfn function one time for each element in the array.
initialValue
If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value.

time.bars.find()

time.bars.find<S extends Bar>(predicate: (value: Bar, index: number, obj: Bar[]) => value is S, thisArg?: any): S
time.bars.find(predicate: (value: Bar, index: number, obj: Bar[]) => unknown, thisArg?: any): Bar

Returns the value of the first element in the array where predicate is true, and undefined otherwise.

predicate
find calls predicate once for each element of the array, in ascending order, until it finds one where predicate returns true. If such an element is found, find immediately returns that element value. Otherwise, find returns undefined.
thisArg
If provided, it will be used as the this value for each invocation of predicate. If it is not provided, undefined is used instead.

time.bars.findIndex()

time.bars.findIndex(predicate: (value: Bar, index: number, obj: Bar[]) => unknown, thisArg?: any): number

Returns the index of the first element in the array where predicate is true, and -1 otherwise.

predicate
find calls predicate once for each element of the array, in ascending order, until it finds one where predicate returns true. If such an element is found, findIndex immediately returns that element index. Otherwise, findIndex returns -1.
thisArg
If provided, it will be used as the this value for each invocation of predicate. If it is not provided, undefined is used instead.

time.bars.fill()

time.bars.fill(value: Bar, start?: number, end?: number): Bar[]

Changes all array elements from start to end index to a static value and returns the modified array

value
value to fill array section with
start
index to start filling the array at. If start is negative, it is treated as length+start where length is the length of the array.
end
index to stop filling the array at. If end is negative, it is treated as length+end.

time.bars.copyWithin()

time.bars.copyWithin(target: number, start: number, end?: number): Bar[]

Returns the this object after copying a section of the array identified by start and end to the same array starting at position target

target
If target is negative, it is treated as length+target where length is the length of the array.
start
If start is negative, it is treated as length+start. If end is negative, it is treated as length+end.
end
If not specified, length of the this object is used as its default value.

time.bars.entries()

time.bars.entries(): ArrayIterator<[number, Bar]>

Returns an iterable of key, value pairs for every entry in the array

time.bars.keys()

time.bars.keys(): ArrayIterator<number>

Returns an iterable of keys in the array

time.bars.values()

time.bars.values(): ArrayIterator<Bar>

Returns an iterable of values in the array

time.bars.includes()

time.bars.includes(searchElement: Bar, fromIndex?: number): boolean

Determines whether an array includes a certain element, returning true or false as appropriate.

searchElement
The element to search for.
fromIndex
The position in this array at which to begin searching for searchElement.

time.bars.flatMap()

time.bars.flatMap<U, This = undefined>(callback: (this: This, value: Bar, index: number, array: Bar[]) => U | readonly U[], thisArg?: This): U[]

Calls a defined callback function on each element of an array. Then, flattens the result into a new array. This is identical to a map followed by flat with depth 1.

callback
A function that accepts up to three arguments. The flatMap method calls the callback function one time for each element in the array.
thisArg
An object to which the this keyword can refer in the callback function. If thisArg is omitted, undefined is used as the this value.

time.bars.flat()

time.bars.flat<A, D extends number = 1>(this: A, depth?: D): FlatArray<A, D>[]

Returns a new array with all sub-array elements concatenated into it recursively up to the specified depth.

depth
The maximum recursion depth

time.bars.at()

time.bars.at(index: number): Bar

Returns the item located at the specified index.

index
The zero-based index of the desired code unit. A negative index will count back from the last item.

time.bars.findLast()

time.bars.findLast<S extends Bar>(predicate: (value: Bar, index: number, array: Bar[]) => value is S, thisArg?: any): S
time.bars.findLast(predicate: (value: Bar, index: number, array: Bar[]) => unknown, thisArg?: any): Bar

Returns the value of the last element in the array where predicate is true, and undefined otherwise.

predicate
findLast calls predicate once for each element of the array, in descending order, until it finds one where predicate returns true. If such an element is found, findLast immediately returns that element value. Otherwise, findLast returns undefined.
thisArg
If provided, it will be used as the this value for each invocation of predicate. If it is not provided, undefined is used instead.

time.bars.findLastIndex()

time.bars.findLastIndex(predicate: (value: Bar, index: number, array: Bar[]) => unknown, thisArg?: any): number

Returns the index of the last element in the array where predicate is true, and -1 otherwise.

predicate
findLastIndex calls predicate once for each element of the array, in descending order, until it finds one where predicate returns true. If such an element is found, findLastIndex immediately returns that element index. Otherwise, findLastIndex returns -1.
thisArg
If provided, it will be used as the this value for each invocation of predicate. If it is not provided, undefined is used instead.

time.bars.toSorted()

time.bars.toSorted(compareFn?: (a: Bar, b: Bar) => number): Bar[]

Returns a copy of an array with its elements sorted.

compareFn
Function used to determine the order of the elements. It is expected to return a negative value if the first argument is less than the second argument, zero if they're equal, and a positive value otherwise. If omitted, the elements are sorted in ascending, ASCII character order. ``ts [11, 2, 22, 1].toSorted((a, b) => a - b) // [1, 2, 11, 22] ``

time.bars.toSpliced()

time.bars.toSpliced(start: number, deleteCount: number, ...items: Bar[]): Bar[]
time.bars.toSpliced(start: number, deleteCount?: number): Bar[]

Copies an array and removes elements and, if necessary, inserts new elements in their place. Returns the copied array.

start
The zero-based location in the array from which to start removing elements.
deleteCount
The number of elements to remove.
items
Elements to insert into the copied array in place of the deleted elements.

Returns The copied array.

Copies an array and removes elements while returning the remaining elements.

start
The zero-based location in the array from which to start removing elements.
deleteCount
The number of elements to remove.

Returns A copy of the original array with the remaining elements.

time.bars.with()

time.bars.with(index: number, value: Bar): Bar[]

Copies an array, then overwrites the value at the provided index with the given value. If the index is negative, then it replaces from the end of the array.

index
The index of the value to overwrite. If the index is negative, then it replaces from the end of the array.
value
The value to write into the copied array.

Returns The copied array with the updated value.

time.bars.length

time.bars.length: number

Gets or sets the length of the array. This is a number one higher than the highest index in the array.

time.bars.__@unscopables@73

Is an object whose properties have the value 'true' when they will be absent when used in a 'with' statement.

time.bars.__@unscopables@73.length

time.bars.__@unscopables@73.length: boolean

Gets or sets the length of the array. This is a number one higher than the highest index in the array.

time.bars.__@unscopables@73.toLocaleString

time.bars.__@unscopables@73.toLocaleString: boolean

Returns a string representation of an array. The elements are converted to string using their toLocaleString methods.

time.bars.__@unscopables@73.pop

time.bars.__@unscopables@73.pop: boolean

Removes the last element from an array and returns it. If the array is empty, undefined is returned and the array is not modified.

time.bars.__@unscopables@73.push

time.bars.__@unscopables@73.push: boolean

Appends new elements to the end of an array, and returns the new length of the array.

items
New elements to add to the array.

time.bars.__@unscopables@73.concat

time.bars.__@unscopables@73.concat: boolean

Combines two or more arrays. This method returns a new array without modifying any existing arrays.

items
Additional arrays and/or items to add to the end of the array.
items
Additional arrays and/or items to add to the end of the array.

time.bars.__@unscopables@73.join

time.bars.__@unscopables@73.join: boolean

Adds all the elements of an array into a string, separated by the specified separator string.

separator
A string used to separate one element of the array from the next in the resulting string. If omitted, the array elements are separated with a comma.

time.bars.__@unscopables@73.reverse

time.bars.__@unscopables@73.reverse: boolean

Reverses the elements in an array in place. This method mutates the array and returns a reference to the same array.

time.bars.__@unscopables@73.shift

time.bars.__@unscopables@73.shift: boolean

Removes the first element from an array and returns it. If the array is empty, undefined is returned and the array is not modified.

time.bars.__@unscopables@73.slice

time.bars.__@unscopables@73.slice: boolean

Returns a copy of a section of an array. For both start and end, a negative index can be used to indicate an offset from the end of the array. For example, -2 refers to the second to last element of the array.

start
The beginning index of the specified portion of the array. If start is undefined, then the slice begins at index 0.
end
The end index of the specified portion of the array. This is exclusive of the element at the index 'end'. If end is undefined, then the slice extends to the end of the array.

time.bars.__@unscopables@73.sort

time.bars.__@unscopables@73.sort: boolean

Sorts an array in place. This method mutates the array and returns a reference to the same array.

compareFn
Function used to determine the order of the elements. It is expected to return a negative value if the first argument is less than the second argument, zero if they're equal, and a positive value otherwise. If omitted, the elements are sorted in ascending, ASCII character order. ``ts [11,2,22,1].sort((a, b) => a - b) ``

time.bars.__@unscopables@73.splice

time.bars.__@unscopables@73.splice: boolean

Removes elements from an array and, if necessary, inserts new elements in their place, returning the deleted elements.

start
The zero-based location in the array from which to start removing elements.
deleteCount
The number of elements to remove.
start
The zero-based location in the array from which to start removing elements.
deleteCount
The number of elements to remove.
items
Elements to insert into the array in place of the deleted elements.

Returns An array containing the elements that were deleted.

time.bars.__@unscopables@73.unshift

time.bars.__@unscopables@73.unshift: boolean

Inserts new elements at the start of an array, and returns the new length of the array.

items
Elements to insert at the start of the array.

time.bars.__@unscopables@73.indexOf

time.bars.__@unscopables@73.indexOf: boolean

Returns the index of the first occurrence of a value in an array, or -1 if it is not present.

searchElement
The value to locate in the array.
fromIndex
The array index at which to begin the search. If fromIndex is omitted, the search starts at index 0.

time.bars.__@unscopables@73.lastIndexOf

time.bars.__@unscopables@73.lastIndexOf: boolean

Returns the index of the last occurrence of a specified value in an array, or -1 if it is not present.

searchElement
The value to locate in the array.
fromIndex
The array index at which to begin searching backward. If fromIndex is omitted, the search starts at the last index in the array.

time.bars.__@unscopables@73.every

time.bars.__@unscopables@73.every: boolean

Determines whether all the members of an array satisfy the specified test.

predicate
A function that accepts up to three arguments. The every method calls the predicate function for each element in the array until the predicate returns a value which is coercible to the Boolean value false, or until the end of the array.
thisArg
An object to which the this keyword can refer in the predicate function. If thisArg is omitted, undefined is used as the this value.
predicate
A function that accepts up to three arguments. The every method calls the predicate function for each element in the array until the predicate returns a value which is coercible to the Boolean value false, or until the end of the array.
thisArg
An object to which the this keyword can refer in the predicate function. If thisArg is omitted, undefined is used as the this value.

time.bars.__@unscopables@73.some

time.bars.__@unscopables@73.some: boolean

Determines whether the specified callback function returns true for any element of an array.

predicate
A function that accepts up to three arguments. The some method calls the predicate function for each element in the array until the predicate returns a value which is coercible to the Boolean value true, or until the end of the array.
thisArg
An object to which the this keyword can refer in the predicate function. If thisArg is omitted, undefined is used as the this value.

time.bars.__@unscopables@73.forEach

time.bars.__@unscopables@73.forEach: boolean

Performs the specified action for each element in an array.

callbackfn
A function that accepts up to three arguments. forEach calls the callbackfn function one time for each element in the array.
thisArg
An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.

time.bars.__@unscopables@73.map

time.bars.__@unscopables@73.map: boolean

Calls a defined callback function on each element of an array, and returns an array that contains the results.

callbackfn
A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array.
thisArg
An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.

time.bars.__@unscopables@73.filter

time.bars.__@unscopables@73.filter: boolean

Returns the elements of an array that meet the condition specified in a callback function.

predicate
A function that accepts up to three arguments. The filter method calls the predicate function one time for each element in the array.
thisArg
An object to which the this keyword can refer in the predicate function. If thisArg is omitted, undefined is used as the this value.
predicate
A function that accepts up to three arguments. The filter method calls the predicate function one time for each element in the array.
thisArg
An object to which the this keyword can refer in the predicate function. If thisArg is omitted, undefined is used as the this value.

time.bars.__@unscopables@73.reduce

time.bars.__@unscopables@73.reduce: boolean

Calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function.

callbackfn
A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array.
initialValue
If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value.
callbackfn
A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array.
initialValue
If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value.

time.bars.__@unscopables@73.reduceRight

time.bars.__@unscopables@73.reduceRight: boolean

Calls the specified callback function for all the elements in an array, in descending order. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function.

callbackfn
A function that accepts up to four arguments. The reduceRight method calls the callbackfn function one time for each element in the array.
initialValue
If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value.
callbackfn
A function that accepts up to four arguments. The reduceRight method calls the callbackfn function one time for each element in the array.
initialValue
If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value.

time.bars.__@unscopables@73.find

time.bars.__@unscopables@73.find: boolean

Returns the value of the first element in the array where predicate is true, and undefined otherwise.

predicate
find calls predicate once for each element of the array, in ascending order, until it finds one where predicate returns true. If such an element is found, find immediately returns that element value. Otherwise, find returns undefined.
thisArg
If provided, it will be used as the this value for each invocation of predicate. If it is not provided, undefined is used instead.

time.bars.__@unscopables@73.findIndex

time.bars.__@unscopables@73.findIndex: boolean

Returns the index of the first element in the array where predicate is true, and -1 otherwise.

predicate
find calls predicate once for each element of the array, in ascending order, until it finds one where predicate returns true. If such an element is found, findIndex immediately returns that element index. Otherwise, findIndex returns -1.
thisArg
If provided, it will be used as the this value for each invocation of predicate. If it is not provided, undefined is used instead.

time.bars.__@unscopables@73.fill

time.bars.__@unscopables@73.fill: boolean

Changes all array elements from start to end index to a static value and returns the modified array

value
value to fill array section with
start
index to start filling the array at. If start is negative, it is treated as length+start where length is the length of the array.
end
index to stop filling the array at. If end is negative, it is treated as length+end.

time.bars.__@unscopables@73.copyWithin

time.bars.__@unscopables@73.copyWithin: boolean

Returns the this object after copying a section of the array identified by start and end to the same array starting at position target

target
If target is negative, it is treated as length+target where length is the length of the array.
start
If start is negative, it is treated as length+start. If end is negative, it is treated as length+end.
end
If not specified, length of the this object is used as its default value.

time.bars.__@unscopables@73.includes

time.bars.__@unscopables@73.includes: boolean

Determines whether an array includes a certain element, returning true or false as appropriate.

searchElement
The element to search for.
fromIndex
The position in this array at which to begin searching for searchElement.

time.bars.__@unscopables@73.flatMap

time.bars.__@unscopables@73.flatMap: boolean

Calls a defined callback function on each element of an array. Then, flattens the result into a new array. This is identical to a map followed by flat with depth 1.

callback
A function that accepts up to three arguments. The flatMap method calls the callback function one time for each element in the array.
thisArg
An object to which the this keyword can refer in the callback function. If thisArg is omitted, undefined is used as the this value.

time.bars.__@unscopables@73.flat

time.bars.__@unscopables@73.flat: boolean

Returns a new array with all sub-array elements concatenated into it recursively up to the specified depth.

depth
The maximum recursion depth

time.bars.__@unscopables@73.at

time.bars.__@unscopables@73.at: boolean

Returns the item located at the specified index.

index
The zero-based index of the desired code unit. A negative index will count back from the last item.

time.bars.__@unscopables@73.findLast

time.bars.__@unscopables@73.findLast: boolean

Returns the value of the last element in the array where predicate is true, and undefined otherwise.

predicate
findLast calls predicate once for each element of the array, in descending order, until it finds one where predicate returns true. If such an element is found, findLast immediately returns that element value. Otherwise, findLast returns undefined.
thisArg
If provided, it will be used as the this value for each invocation of predicate. If it is not provided, undefined is used instead.

time.bars.__@unscopables@73.findLastIndex

time.bars.__@unscopables@73.findLastIndex: boolean

Returns the index of the last element in the array where predicate is true, and -1 otherwise.

predicate
findLastIndex calls predicate once for each element of the array, in descending order, until it finds one where predicate returns true. If such an element is found, findLastIndex immediately returns that element index. Otherwise, findLastIndex returns -1.
thisArg
If provided, it will be used as the this value for each invocation of predicate. If it is not provided, undefined is used instead.

time.bars.__@unscopables@73.toSorted

time.bars.__@unscopables@73.toSorted: boolean

Returns a copy of an array with its elements sorted.

compareFn
Function used to determine the order of the elements. It is expected to return a negative value if the first argument is less than the second argument, zero if they're equal, and a positive value otherwise. If omitted, the elements are sorted in ascending, ASCII character order. ``ts [11, 2, 22, 1].toSorted((a, b) => a - b) // [1, 2, 11, 22] ``

time.bars.__@unscopables@73.toSpliced

time.bars.__@unscopables@73.toSpliced: boolean

Copies an array and removes elements and, if necessary, inserts new elements in their place. Returns the copied array. Copies an array and removes elements while returning the remaining elements.

start
The zero-based location in the array from which to start removing elements.
deleteCount
The number of elements to remove.
items
Elements to insert into the copied array in place of the deleted elements.
start
The zero-based location in the array from which to start removing elements.
deleteCount
The number of elements to remove.

Returns A copy of the original array with the remaining elements.

time.bars.__@unscopables@73.with

time.bars.__@unscopables@73.with: boolean

Copies an array, then overwrites the value at the provided index with the given value. If the index is negative, then it replaces from the end of the array.

index
The index of the value to overwrite. If the index is negative, then it replaces from the end of the array.
value
The value to write into the copied array.

Returns The copied array with the updated value.

time.barData

The BarData holding the bars this series is aligned to.

time.barData.pop()

time.barData.pop(): Bar

Remove and return the last bar

Returns The removed bar, or undefined if empty

time.barData.set()

time.barData.set(index: number, bar: Bar): void

Replace a bar at a specific index

index
Index to update
bar
New bar data

time.barData.updateLast()

time.barData.updateLast(bar: Bar): void

Update the last bar (useful for real-time/streaming updates)

bar
New bar data

time.barData.setAll()

time.barData.setAll(bars: Bar[]): void

Replace all bars with new data

bars
New bar array

time.barData.invalidate()

time.barData.invalidate(): void

Manually increment version (for advanced use cases) Call this after direct mutations to the bars array

time.barData.at()

time.barData.at(index: number): Bar

Get a bar at a specific index

index
Bar index

Returns Bar at that index, or undefined

time.barData.version

time.barData.version: number

Get the current version number Version increments whenever data is mutated

time.barData._barstime.barData._version

time.barData.bars

Get the underlying bar array Note: Direct mutations to this array will NOT increment version Use the provided mutation methods instead

time.barData.bars.toLocaleString()

time.barData.bars.toLocaleString(): string
time.barData.bars.toLocaleString(locales: string | string[], options?: NumberFormatOptions & DateTimeFormatOptions): string

Returns a string representation of an array. The elements are converted to string using their toLocaleString methods.

time.barData.bars.pop()

time.barData.bars.pop(): Bar

Removes the last element from an array and returns it. If the array is empty, undefined is returned and the array is not modified.

time.barData.bars.push()

time.barData.bars.push(...items: Bar[]): number

Appends new elements to the end of an array, and returns the new length of the array.

items
New elements to add to the array.

time.barData.bars.concat()

time.barData.bars.concat(...items: ConcatArray<Bar>[]): Bar[]
time.barData.bars.concat(...items: (Bar | ConcatArray<Bar>)[]): Bar[]

Combines two or more arrays. This method returns a new array without modifying any existing arrays.

items
Additional arrays and/or items to add to the end of the array.

time.barData.bars.join()

time.barData.bars.join(separator?: string): string

Adds all the elements of an array into a string, separated by the specified separator string.

separator
A string used to separate one element of the array from the next in the resulting string. If omitted, the array elements are separated with a comma.

time.barData.bars.reverse()

time.barData.bars.reverse(): Bar[]

Reverses the elements in an array in place. This method mutates the array and returns a reference to the same array.

time.barData.bars.shift()

time.barData.bars.shift(): Bar

Removes the first element from an array and returns it. If the array is empty, undefined is returned and the array is not modified.

time.barData.bars.slice()

time.barData.bars.slice(start?: number, end?: number): Bar[]

Returns a copy of a section of an array. For both start and end, a negative index can be used to indicate an offset from the end of the array. For example, -2 refers to the second to last element of the array.

start
The beginning index of the specified portion of the array. If start is undefined, then the slice begins at index 0.
end
The end index of the specified portion of the array. This is exclusive of the element at the index 'end'. If end is undefined, then the slice extends to the end of the array.

time.barData.bars.sort()

time.barData.bars.sort(compareFn?: (a: Bar, b: Bar) => number): Bar[]

Sorts an array in place. This method mutates the array and returns a reference to the same array.

compareFn
Function used to determine the order of the elements. It is expected to return a negative value if the first argument is less than the second argument, zero if they're equal, and a positive value otherwise. If omitted, the elements are sorted in ascending, ASCII character order. ``ts [11,2,22,1].sort((a, b) => a - b) ``

time.barData.bars.splice()

time.barData.bars.splice(start: number, deleteCount?: number): Bar[]
time.barData.bars.splice(start: number, deleteCount: number, ...items: Bar[]): Bar[]

Removes elements from an array and, if necessary, inserts new elements in their place, returning the deleted elements.

start
The zero-based location in the array from which to start removing elements.
deleteCount
The number of elements to remove.

Returns An array containing the elements that were deleted.

Removes elements from an array and, if necessary, inserts new elements in their place, returning the deleted elements.

start
The zero-based location in the array from which to start removing elements.
deleteCount
The number of elements to remove.
items
Elements to insert into the array in place of the deleted elements.

Returns An array containing the elements that were deleted.

time.barData.bars.unshift()

time.barData.bars.unshift(...items: Bar[]): number

Inserts new elements at the start of an array, and returns the new length of the array.

items
Elements to insert at the start of the array.

time.barData.bars.indexOf()

time.barData.bars.indexOf(searchElement: Bar, fromIndex?: number): number

Returns the index of the first occurrence of a value in an array, or -1 if it is not present.

searchElement
The value to locate in the array.
fromIndex
The array index at which to begin the search. If fromIndex is omitted, the search starts at index 0.

time.barData.bars.lastIndexOf()

time.barData.bars.lastIndexOf(searchElement: Bar, fromIndex?: number): number

Returns the index of the last occurrence of a specified value in an array, or -1 if it is not present.

searchElement
The value to locate in the array.
fromIndex
The array index at which to begin searching backward. If fromIndex is omitted, the search starts at the last index in the array.

time.barData.bars.every()

time.barData.bars.every<S extends Bar>(predicate: (value: Bar, index: number, array: Bar[]) => value is S, thisArg?: any): this is S[]
time.barData.bars.every(predicate: (value: Bar, index: number, array: Bar[]) => unknown, thisArg?: any): boolean

Determines whether all the members of an array satisfy the specified test.

predicate
A function that accepts up to three arguments. The every method calls the predicate function for each element in the array until the predicate returns a value which is coercible to the Boolean value false, or until the end of the array.
thisArg
An object to which the this keyword can refer in the predicate function. If thisArg is omitted, undefined is used as the this value.

time.barData.bars.some()

time.barData.bars.some(predicate: (value: Bar, index: number, array: Bar[]) => unknown, thisArg?: any): boolean

Determines whether the specified callback function returns true for any element of an array.

predicate
A function that accepts up to three arguments. The some method calls the predicate function for each element in the array until the predicate returns a value which is coercible to the Boolean value true, or until the end of the array.
thisArg
An object to which the this keyword can refer in the predicate function. If thisArg is omitted, undefined is used as the this value.

time.barData.bars.forEach()

time.barData.bars.forEach(callbackfn: (value: Bar, index: number, array: Bar[]) => void, thisArg?: any): void

Performs the specified action for each element in an array.

callbackfn
A function that accepts up to three arguments. forEach calls the callbackfn function one time for each element in the array.
thisArg
An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.

time.barData.bars.map()

time.barData.bars.map<U>(callbackfn: (value: Bar, index: number, array: Bar[]) => U, thisArg?: any): U[]

Calls a defined callback function on each element of an array, and returns an array that contains the results.

callbackfn
A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array.
thisArg
An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.

time.barData.bars.filter()

time.barData.bars.filter<S extends Bar>(predicate: (value: Bar, index: number, array: Bar[]) => value is S, thisArg?: any): S[]
time.barData.bars.filter(predicate: (value: Bar, index: number, array: Bar[]) => unknown, thisArg?: any): Bar[]

Returns the elements of an array that meet the condition specified in a callback function.

predicate
A function that accepts up to three arguments. The filter method calls the predicate function one time for each element in the array.
thisArg
An object to which the this keyword can refer in the predicate function. If thisArg is omitted, undefined is used as the this value.

time.barData.bars.reduce()

time.barData.bars.reduce(callbackfn: (previousValue: Bar, currentValue: Bar, currentIndex: number, array: Bar[]) => Bar): Bar
time.barData.bars.reduce(callbackfn: (previousValue: Bar, currentValue: Bar, currentIndex: number, array: Bar[]) => Bar, initialValue: Bar): Bar
time.barData.bars.reduce<U>(callbackfn: (previousValue: U, currentValue: Bar, currentIndex: number, array: Bar[]) => U, initialValue: U): U

Calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function.

callbackfn
A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array.
initialValue
If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value.

Calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function.

callbackfn
A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array.
initialValue
If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value.
callbackfn
A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array.
initialValue
If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value.

time.barData.bars.reduceRight()

time.barData.bars.reduceRight(callbackfn: (previousValue: Bar, currentValue: Bar, currentIndex: number, array: Bar[]) => Bar): Bar
time.barData.bars.reduceRight(callbackfn: (previousValue: Bar, currentValue: Bar, currentIndex: number, array: Bar[]) => Bar, initialValue: Bar): Bar
time.barData.bars.reduceRight<U>(callbackfn: (previousValue: U, currentValue: Bar, currentIndex: number, array: Bar[]) => U, initialValue: U): U

Calls the specified callback function for all the elements in an array, in descending order. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function.

callbackfn
A function that accepts up to four arguments. The reduceRight method calls the callbackfn function one time for each element in the array.
initialValue
If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value.

Calls the specified callback function for all the elements in an array, in descending order. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function.

callbackfn
A function that accepts up to four arguments. The reduceRight method calls the callbackfn function one time for each element in the array.
initialValue
If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value.
callbackfn
A function that accepts up to four arguments. The reduceRight method calls the callbackfn function one time for each element in the array.
initialValue
If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value.

time.barData.bars.find()

time.barData.bars.find<S extends Bar>(predicate: (value: Bar, index: number, obj: Bar[]) => value is S, thisArg?: any): S
time.barData.bars.find(predicate: (value: Bar, index: number, obj: Bar[]) => unknown, thisArg?: any): Bar

Returns the value of the first element in the array where predicate is true, and undefined otherwise.

predicate
find calls predicate once for each element of the array, in ascending order, until it finds one where predicate returns true. If such an element is found, find immediately returns that element value. Otherwise, find returns undefined.
thisArg
If provided, it will be used as the this value for each invocation of predicate. If it is not provided, undefined is used instead.

time.barData.bars.findIndex()

time.barData.bars.findIndex(predicate: (value: Bar, index: number, obj: Bar[]) => unknown, thisArg?: any): number

Returns the index of the first element in the array where predicate is true, and -1 otherwise.

predicate
find calls predicate once for each element of the array, in ascending order, until it finds one where predicate returns true. If such an element is found, findIndex immediately returns that element index. Otherwise, findIndex returns -1.
thisArg
If provided, it will be used as the this value for each invocation of predicate. If it is not provided, undefined is used instead.

time.barData.bars.fill()

time.barData.bars.fill(value: Bar, start?: number, end?: number): Bar[]

Changes all array elements from start to end index to a static value and returns the modified array

value
value to fill array section with
start
index to start filling the array at. If start is negative, it is treated as length+start where length is the length of the array.
end
index to stop filling the array at. If end is negative, it is treated as length+end.

time.barData.bars.copyWithin()

time.barData.bars.copyWithin(target: number, start: number, end?: number): Bar[]

Returns the this object after copying a section of the array identified by start and end to the same array starting at position target

target
If target is negative, it is treated as length+target where length is the length of the array.
start
If start is negative, it is treated as length+start. If end is negative, it is treated as length+end.
end
If not specified, length of the this object is used as its default value.

time.barData.bars.entries()

time.barData.bars.entries(): ArrayIterator<[number, Bar]>

Returns an iterable of key, value pairs for every entry in the array

time.barData.bars.includes()

time.barData.bars.includes(searchElement: Bar, fromIndex?: number): boolean

Determines whether an array includes a certain element, returning true or false as appropriate.

searchElement
The element to search for.
fromIndex
The position in this array at which to begin searching for searchElement.

time.barData.bars.flatMap()

time.barData.bars.flatMap<U, This = undefined>(callback: (this: This, value: Bar, index: number, array: Bar[]) => U | readonly U[], thisArg?: This): U[]

Calls a defined callback function on each element of an array. Then, flattens the result into a new array. This is identical to a map followed by flat with depth 1.

callback
A function that accepts up to three arguments. The flatMap method calls the callback function one time for each element in the array.
thisArg
An object to which the this keyword can refer in the callback function. If thisArg is omitted, undefined is used as the this value.

time.barData.bars.flat()

time.barData.bars.flat<A, D extends number = 1>(this: A, depth?: D): FlatArray<A, D>[]

Returns a new array with all sub-array elements concatenated into it recursively up to the specified depth.

depth
The maximum recursion depth

time.barData.bars.at()

time.barData.bars.at(index: number): Bar

Returns the item located at the specified index.

index
The zero-based index of the desired code unit. A negative index will count back from the last item.

time.barData.bars.findLast()

time.barData.bars.findLast<S extends Bar>(predicate: (value: Bar, index: number, array: Bar[]) => value is S, thisArg?: any): S
time.barData.bars.findLast(predicate: (value: Bar, index: number, array: Bar[]) => unknown, thisArg?: any): Bar

Returns the value of the last element in the array where predicate is true, and undefined otherwise.

predicate
findLast calls predicate once for each element of the array, in descending order, until it finds one where predicate returns true. If such an element is found, findLast immediately returns that element value. Otherwise, findLast returns undefined.
thisArg
If provided, it will be used as the this value for each invocation of predicate. If it is not provided, undefined is used instead.

time.barData.bars.findLastIndex()

time.barData.bars.findLastIndex(predicate: (value: Bar, index: number, array: Bar[]) => unknown, thisArg?: any): number

Returns the index of the last element in the array where predicate is true, and -1 otherwise.

predicate
findLastIndex calls predicate once for each element of the array, in descending order, until it finds one where predicate returns true. If such an element is found, findLastIndex immediately returns that element index. Otherwise, findLastIndex returns -1.
thisArg
If provided, it will be used as the this value for each invocation of predicate. If it is not provided, undefined is used instead.

time.barData.bars.toSorted()

time.barData.bars.toSorted(compareFn?: (a: Bar, b: Bar) => number): Bar[]

Returns a copy of an array with its elements sorted.

compareFn
Function used to determine the order of the elements. It is expected to return a negative value if the first argument is less than the second argument, zero if they're equal, and a positive value otherwise. If omitted, the elements are sorted in ascending, ASCII character order. ``ts [11, 2, 22, 1].toSorted((a, b) => a - b) // [1, 2, 11, 22] ``

time.barData.bars.toSpliced()

time.barData.bars.toSpliced(start: number, deleteCount: number, ...items: Bar[]): Bar[]
time.barData.bars.toSpliced(start: number, deleteCount?: number): Bar[]

Copies an array and removes elements and, if necessary, inserts new elements in their place. Returns the copied array.

start
The zero-based location in the array from which to start removing elements.
deleteCount
The number of elements to remove.
items
Elements to insert into the copied array in place of the deleted elements.

Returns The copied array.

Copies an array and removes elements while returning the remaining elements.

start
The zero-based location in the array from which to start removing elements.
deleteCount
The number of elements to remove.

Returns A copy of the original array with the remaining elements.

time.barData.bars.with()

time.barData.bars.with(index: number, value: Bar): Bar[]

Copies an array, then overwrites the value at the provided index with the given value. If the index is negative, then it replaces from the end of the array.

index
The index of the value to overwrite. If the index is negative, then it replaces from the end of the array.
value
The value to write into the copied array.

Returns The copied array with the updated value.

time.barData.bars.length

time.barData.bars.length: number

Gets or sets the length of the array. This is a number one higher than the highest index in the array.

time.barData.bars.__@unscopables@73

Is an object whose properties have the value 'true' when they will be absent when used in a 'with' statement.

time.barData.bars.__@unscopables@73.pop

time.barData.bars.__@unscopables@73.pop: boolean

Removes the last element from an array and returns it. If the array is empty, undefined is returned and the array is not modified.

time.barData.bars.__@unscopables@73.push

time.barData.bars.__@unscopables@73.push: boolean

Appends new elements to the end of an array, and returns the new length of the array.

items
New elements to add to the array.

time.barData.bars.__@unscopables@73.concat

time.barData.bars.__@unscopables@73.concat: boolean

Combines two or more arrays. This method returns a new array without modifying any existing arrays.

items
Additional arrays and/or items to add to the end of the array.
items
Additional arrays and/or items to add to the end of the array.

time.barData.bars.__@unscopables@73.join

time.barData.bars.__@unscopables@73.join: boolean

Adds all the elements of an array into a string, separated by the specified separator string.

separator
A string used to separate one element of the array from the next in the resulting string. If omitted, the array elements are separated with a comma.

time.barData.bars.__@unscopables@73.reverse

time.barData.bars.__@unscopables@73.reverse: boolean

Reverses the elements in an array in place. This method mutates the array and returns a reference to the same array.

time.barData.bars.__@unscopables@73.shift

time.barData.bars.__@unscopables@73.shift: boolean

Removes the first element from an array and returns it. If the array is empty, undefined is returned and the array is not modified.

time.barData.bars.__@unscopables@73.slice

time.barData.bars.__@unscopables@73.slice: boolean

Returns a copy of a section of an array. For both start and end, a negative index can be used to indicate an offset from the end of the array. For example, -2 refers to the second to last element of the array.

start
The beginning index of the specified portion of the array. If start is undefined, then the slice begins at index 0.
end
The end index of the specified portion of the array. This is exclusive of the element at the index 'end'. If end is undefined, then the slice extends to the end of the array.

time.barData.bars.__@unscopables@73.sort

time.barData.bars.__@unscopables@73.sort: boolean

Sorts an array in place. This method mutates the array and returns a reference to the same array.

compareFn
Function used to determine the order of the elements. It is expected to return a negative value if the first argument is less than the second argument, zero if they're equal, and a positive value otherwise. If omitted, the elements are sorted in ascending, ASCII character order. ``ts [11,2,22,1].sort((a, b) => a - b) ``

time.barData.bars.__@unscopables@73.splice

time.barData.bars.__@unscopables@73.splice: boolean

Removes elements from an array and, if necessary, inserts new elements in their place, returning the deleted elements.

start
The zero-based location in the array from which to start removing elements.
deleteCount
The number of elements to remove.
start
The zero-based location in the array from which to start removing elements.
deleteCount
The number of elements to remove.
items
Elements to insert into the array in place of the deleted elements.

Returns An array containing the elements that were deleted.

time.barData.bars.__@unscopables@73.unshift

time.barData.bars.__@unscopables@73.unshift: boolean

Inserts new elements at the start of an array, and returns the new length of the array.

items
Elements to insert at the start of the array.

time.barData.bars.__@unscopables@73.indexOf

time.barData.bars.__@unscopables@73.indexOf: boolean

Returns the index of the first occurrence of a value in an array, or -1 if it is not present.

searchElement
The value to locate in the array.
fromIndex
The array index at which to begin the search. If fromIndex is omitted, the search starts at index 0.

time.barData.bars.__@unscopables@73.lastIndexOf

time.barData.bars.__@unscopables@73.lastIndexOf: boolean

Returns the index of the last occurrence of a specified value in an array, or -1 if it is not present.

searchElement
The value to locate in the array.
fromIndex
The array index at which to begin searching backward. If fromIndex is omitted, the search starts at the last index in the array.

time.barData.bars.__@unscopables@73.every

time.barData.bars.__@unscopables@73.every: boolean

Determines whether all the members of an array satisfy the specified test.

predicate
A function that accepts up to three arguments. The every method calls the predicate function for each element in the array until the predicate returns a value which is coercible to the Boolean value false, or until the end of the array.
thisArg
An object to which the this keyword can refer in the predicate function. If thisArg is omitted, undefined is used as the this value.
predicate
A function that accepts up to three arguments. The every method calls the predicate function for each element in the array until the predicate returns a value which is coercible to the Boolean value false, or until the end of the array.
thisArg
An object to which the this keyword can refer in the predicate function. If thisArg is omitted, undefined is used as the this value.

time.barData.bars.__@unscopables@73.some

time.barData.bars.__@unscopables@73.some: boolean

Determines whether the specified callback function returns true for any element of an array.

predicate
A function that accepts up to three arguments. The some method calls the predicate function for each element in the array until the predicate returns a value which is coercible to the Boolean value true, or until the end of the array.
thisArg
An object to which the this keyword can refer in the predicate function. If thisArg is omitted, undefined is used as the this value.

time.barData.bars.__@unscopables@73.forEach

time.barData.bars.__@unscopables@73.forEach: boolean

Performs the specified action for each element in an array.

callbackfn
A function that accepts up to three arguments. forEach calls the callbackfn function one time for each element in the array.
thisArg
An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.

time.barData.bars.__@unscopables@73.map

time.barData.bars.__@unscopables@73.map: boolean

Calls a defined callback function on each element of an array, and returns an array that contains the results.

callbackfn
A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array.
thisArg
An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.

time.barData.bars.__@unscopables@73.filter

time.barData.bars.__@unscopables@73.filter: boolean

Returns the elements of an array that meet the condition specified in a callback function.

predicate
A function that accepts up to three arguments. The filter method calls the predicate function one time for each element in the array.
thisArg
An object to which the this keyword can refer in the predicate function. If thisArg is omitted, undefined is used as the this value.
predicate
A function that accepts up to three arguments. The filter method calls the predicate function one time for each element in the array.
thisArg
An object to which the this keyword can refer in the predicate function. If thisArg is omitted, undefined is used as the this value.

time.barData.bars.__@unscopables@73.reduce

time.barData.bars.__@unscopables@73.reduce: boolean

Calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function.

callbackfn
A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array.
initialValue
If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value.
callbackfn
A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array.
initialValue
If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value.

time.barData.bars.__@unscopables@73.reduceRight

time.barData.bars.__@unscopables@73.reduceRight: boolean

Calls the specified callback function for all the elements in an array, in descending order. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function.

callbackfn
A function that accepts up to four arguments. The reduceRight method calls the callbackfn function one time for each element in the array.
initialValue
If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value.
callbackfn
A function that accepts up to four arguments. The reduceRight method calls the callbackfn function one time for each element in the array.
initialValue
If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value.

time.barData.bars.__@unscopables@73.find

time.barData.bars.__@unscopables@73.find: boolean

Returns the value of the first element in the array where predicate is true, and undefined otherwise.

predicate
find calls predicate once for each element of the array, in ascending order, until it finds one where predicate returns true. If such an element is found, find immediately returns that element value. Otherwise, find returns undefined.
thisArg
If provided, it will be used as the this value for each invocation of predicate. If it is not provided, undefined is used instead.

time.barData.bars.__@unscopables@73.findIndex

time.barData.bars.__@unscopables@73.findIndex: boolean

Returns the index of the first element in the array where predicate is true, and -1 otherwise.

predicate
find calls predicate once for each element of the array, in ascending order, until it finds one where predicate returns true. If such an element is found, findIndex immediately returns that element index. Otherwise, findIndex returns -1.
thisArg
If provided, it will be used as the this value for each invocation of predicate. If it is not provided, undefined is used instead.

time.barData.bars.__@unscopables@73.fill

time.barData.bars.__@unscopables@73.fill: boolean

Changes all array elements from start to end index to a static value and returns the modified array

value
value to fill array section with
start
index to start filling the array at. If start is negative, it is treated as length+start where length is the length of the array.
end
index to stop filling the array at. If end is negative, it is treated as length+end.

time.barData.bars.__@unscopables@73.copyWithin

time.barData.bars.__@unscopables@73.copyWithin: boolean

Returns the this object after copying a section of the array identified by start and end to the same array starting at position target

target
If target is negative, it is treated as length+target where length is the length of the array.
start
If start is negative, it is treated as length+start. If end is negative, it is treated as length+end.
end
If not specified, length of the this object is used as its default value.

time.barData.bars.__@unscopables@73.includes

time.barData.bars.__@unscopables@73.includes: boolean

Determines whether an array includes a certain element, returning true or false as appropriate.

searchElement
The element to search for.
fromIndex
The position in this array at which to begin searching for searchElement.

time.barData.bars.__@unscopables@73.flatMap

time.barData.bars.__@unscopables@73.flatMap: boolean

Calls a defined callback function on each element of an array. Then, flattens the result into a new array. This is identical to a map followed by flat with depth 1.

callback
A function that accepts up to three arguments. The flatMap method calls the callback function one time for each element in the array.
thisArg
An object to which the this keyword can refer in the callback function. If thisArg is omitted, undefined is used as the this value.

time.barData.bars.__@unscopables@73.flat

time.barData.bars.__@unscopables@73.flat: boolean

Returns a new array with all sub-array elements concatenated into it recursively up to the specified depth.

depth
The maximum recursion depth

time.barData.bars.__@unscopables@73.at

time.barData.bars.__@unscopables@73.at: boolean

Returns the item located at the specified index.

index
The zero-based index of the desired code unit. A negative index will count back from the last item.

time.barData.bars.__@unscopables@73.findLast

time.barData.bars.__@unscopables@73.findLast: boolean

Returns the value of the last element in the array where predicate is true, and undefined otherwise.

predicate
findLast calls predicate once for each element of the array, in descending order, until it finds one where predicate returns true. If such an element is found, findLast immediately returns that element value. Otherwise, findLast returns undefined.
thisArg
If provided, it will be used as the this value for each invocation of predicate. If it is not provided, undefined is used instead.

time.barData.bars.__@unscopables@73.findLastIndex

time.barData.bars.__@unscopables@73.findLastIndex: boolean

Returns the index of the last element in the array where predicate is true, and -1 otherwise.

predicate
findLastIndex calls predicate once for each element of the array, in descending order, until it finds one where predicate returns true. If such an element is found, findLastIndex immediately returns that element index. Otherwise, findLastIndex returns -1.
thisArg
If provided, it will be used as the this value for each invocation of predicate. If it is not provided, undefined is used instead.

time.barData.bars.__@unscopables@73.toSorted

time.barData.bars.__@unscopables@73.toSorted: boolean

Returns a copy of an array with its elements sorted.

compareFn
Function used to determine the order of the elements. It is expected to return a negative value if the first argument is less than the second argument, zero if they're equal, and a positive value otherwise. If omitted, the elements are sorted in ascending, ASCII character order. ``ts [11, 2, 22, 1].toSorted((a, b) => a - b) // [1, 2, 11, 22] ``

time.barData.bars.__@unscopables@73.toSpliced

time.barData.bars.__@unscopables@73.toSpliced: boolean

Copies an array and removes elements and, if necessary, inserts new elements in their place. Returns the copied array. Copies an array and removes elements while returning the remaining elements.

start
The zero-based location in the array from which to start removing elements.
deleteCount
The number of elements to remove.
items
Elements to insert into the copied array in place of the deleted elements.
start
The zero-based location in the array from which to start removing elements.
deleteCount
The number of elements to remove.

Returns A copy of the original array with the remaining elements.

time.barData.bars.__@unscopables@73.with

time.barData.bars.__@unscopables@73.with: boolean

Copies an array, then overwrites the value at the provided index with the given value. If the index is negative, then it replaces from the end of the array.

index
The index of the value to overwrite. If the index is negative, then it replaces from the end of the array.
value
The value to write into the copied array.

Returns The copied array with the updated value.

time_close

time_close()

time_close(tf?: string, session?: string, timezone?: string): Series

The close time of the period of tf that holds each bar, in UNIX milliseconds; na on bars outside session.

tf
Timeframe of the periods: "D", "W", "60"... Default: the chart's.
session
Session hours, e.g. "0930-1600"; bars outside it give na. Default: the symbol's.
timezone
Time zone of the session hours. Default: the exchange's.

Returns Series of period close times.

plot(time_close.sub(time).div(60000), "Bar minutes");

time_close.add()

time_close.add(other: number | Series): Series

Adds a Series or a number to this series, bar by bar (the + of two values). NaN on either side gives NaN.

other
Series or number to add.

Returns A Series of the sums.

const mid = high.add(low).div(2);

time_close.sub()

time_close.sub(other: number | Series): Series

Subtracts a Series or a number from this series, bar by bar (the - of two values). NaN on either side gives NaN.

other
Series or number to subtract.

Returns A Series of the differences.

const body = close.sub(open);

time_close.mul()

time_close.mul(other: number | Series): Series

Multiplies this series by a Series or a number, bar by bar (the * of two values). NaN on either side gives NaN.

other
Series or number to multiply by.

Returns A Series of the products.

const upper = ta.sma(close, 20).mul(1.02);

time_close.pow()

time_close.pow(exponent: number | Series): Series

Raises this series to a power, bar by bar (math.pow on a series). NaN on either side gives NaN; a negative base with a fractional exponent gives NaN.

exponent
Series or number exponent.

Returns A Series of this ** exponent.

const squared = close.sub(ta.sma(close, 20)).pow(2);

time_close.div()

time_close.div(other: number | Series): Series

Divides this series by a Series or a number, bar by bar (the / of two values). A division by 0 gives +/-Infinity (which na() treats as na), 0 / 0 and NaN on either side give NaN.

other
Series or number to divide by.

Returns A Series of the quotients.

const range = high.sub(low);
const ratio = range.gt(0).iff(close.sub(open).div(range), 0);

time_close.mod()

time_close.mod(other: number | Series): Series

Remainder of the division of this series by a Series or a number, bar by bar (the % of two values). The remainder has the sign of this series; a divisor of 0 and NaN on either side give NaN.

other
Series or number to divide by.

Returns A Series of the remainders.

const everyFifth = bar_index.mod(5).eq(0);

time_close.neg()

time_close.neg(): Series

Changes the sign of every value (the unary -). NaN stays NaN.

Returns A Series of the opposite values.

const drop = close.sub(close.offset(1)).neg();

time_close.gt()

time_close.gt(other: number | Series): Series

Tests whether this series is above a Series or a number, bar by bar (a > b). Values closer than 1e-10 count as equal, and a NaN on either side gives 0 (false), never NaN.

other
Series or number to compare with.

Returns A Series of 1 where it is true, 0 where it is false.

const up = close.gt(open);

time_close.gte()

time_close.gte(other: number | Series): Series

Tests whether this series is above or equal to a Series or a number, bar by bar (a >= b). Values closer than 1e-10 count as equal, and a NaN on either side gives 0 (false), never NaN.

other
Series or number to compare with.

Returns A Series of 1 where it is true, 0 where it is false.

const atOrAbove = close.gte(ta.sma(close, 50));

time_close.lt()

time_close.lt(other: number | Series): Series

Tests whether this series is below a Series or a number, bar by bar (a < b). Values closer than 1e-10 count as equal, and a NaN on either side gives 0 (false), never NaN.

other
Series or number to compare with.

Returns A Series of 1 where it is true, 0 where it is false.

const oversold = ta.rsi(close, 14).lt(30);

time_close.lte()

time_close.lte(other: number | Series): Series

Tests whether this series is below or equal to a Series or a number, bar by bar (a <= b). Values closer than 1e-10 count as equal, and a NaN on either side gives 0 (false), never NaN.

other
Series or number to compare with.

Returns A Series of 1 where it is true, 0 where it is false.

const atOrBelow = low.lte(ta.lowest(low, 20).offset(1));

time_close.eq()

time_close.eq(other: number | Series): Series

Tests whether this series equals a Series or a number, bar by bar (a == b). Values closer than 1e-10 count as equal, and a NaN on either side gives 0 (false), never NaN.

other
Series or number to compare with.

Returns A Series of 1 where it is true, 0 where it is false.

const doji = close.eq(open);

time_close.neq()

time_close.neq(other: number | Series): Series

Tests whether this series differs from a Series or a number, bar by bar (a != b). Values closer than 1e-10 count as equal, and a NaN on either side gives 0 (false), never NaN.

other
Series or number to compare with.

Returns A Series of 1 where it is true, 0 where it is false.

const moved = close.neq(close.offset(1));

time_close.and()

time_close.and(other: number | Series): Series

Logical "and" of two conditions, bar by bar. A value is true when it is not 0 and not NaN.

other
The other condition: a Series or a number.

Returns A Series of 1 where both are true, 0 elsewhere.

const strongUp = close.gt(open).and(volume.gt(ta.sma(volume, 20)));

time_close.or()

time_close.or(other: number | Series): Series

Logical "or" of two conditions, bar by bar. A value is true when it is not 0 and not NaN.

other
The other condition: a Series or a number.

Returns A Series of 1 where at least one is true, 0 elsewhere.

const extreme = ta.rsi(close, 14).gt(70).or(ta.rsi(close, 14).lt(30));

time_close.not()

time_close.not(): Series

Logical "not" of a condition, bar by bar: true (not 0, not NaN) becomes 0, and 0 or NaN becomes 1.

Returns A Series of 1 where this series is false, 0 where it is true.

const notUp = close.gt(open).not();

time_close.iff()

time_close.iff(trueValue: number | Series, falseValue: number | Series): Series

Picks one of two values on each bar, with this series as the condition (the cond ? x : y of a series). The condition is true when it is not 0 and not NaN; 0 and NaN pick falseValue.

trueValue
Series or number used where the condition is true.
falseValue
Series or number used where the condition is false.

Returns A Series of the picked values.

const range = high.sub(low);
const ratio = range.gt(0).iff(close.sub(open).div(range), 0);
plot(ratio, "Body / range");

time_close.offset()

time_close.offset(offset: number): Series

Shifts the series back in time: on each bar, the value offset bars earlier (close.offset(1) is the previous close). The first offset bars, which have no earlier bar, get NaN.

offset
Number of bars back: 0 (the series itself) or more, a whole number. A series computed by the script can look back at most 5000 bars; the price series (close, high...) any number.

Returns A Series of the earlier values.

Throws RangeError when offset is negative (it would read a future bar); an error past 5000 bars.

const change = close.sub(close.offset(1));
const higherHigh = high.gt(high.offset(1));

time_close.toArray()

time_close.toArray(): number[]

Gives the values of all the bars as a plain array, oldest bar first (NaN for na). The values are computed on the first read and kept until the bars change; the array is shared, so copy it before changing it.

Returns One number per bar, oldest first.

const values = ta.sma(close, 20).toArray();
const shifted = seriesOf(values.map((v) => v * 1.01));

time_close.materialize()

time_close.materialize(): Series

Computes the values now and returns a Series that stores them, without links to the series it was built from. Use it on a long chain of methods to compute it once and free the steps in between.

Returns A Series of the same values, stored.

const spread = high.sub(low).div(close).mul(100).materialize();

time_close._invalidate()

time_close._invalidate(): void

Invalidate cache (when data changes)

Note: With BarData versioning, manual invalidation is rarely needed. The cache is automatically invalidated when the underlying BarData changes. This method is kept for backward compatibility and advanced use cases.

time_close._compute()

time_close._compute(): number[]

Compute all values (alias for toArray)

Returns Array of computed values

time_close.get()

time_close.get(index: number): number

Reads the value of one bar by its position: 0 is the oldest bar, bar_index counts the same way. This is not the "bars back" of offset(): inside a bar loop, read the current bar with c.get(series) and earlier bars with c.get(series, k).

index
Bar position, 0 for the oldest bar.

Returns The value of that bar; NaN when there is no such bar.

const firstClose = close.get(0);

time_close.last()

time_close.last(): number

Reads the value of the newest bar.

Returns The value of the last bar; NaN when there are no bars.

const lastRsi = ta.rsi(close, 14).last();

time_close.length()

time_close.length(): number

Gives the number of bars of the series (a method, not a property).

Returns The number of bars.

const bars = close.length();

time_close.toTimeValuePairs()

time_close.toTimeValuePairs(): { time: any; value: number; }[]

Gives the values as { time, value } points for a chart line, oldest first, leaving out the NaN bars.

Returns The points; time is the bar time, in the unit of the bars.

const points = ta.sma(close, 20).toTimeValuePairs();

time_close.__@toPrimitive@575()

time_close.__@toPrimitive@575(hint: "string" | "number" | "default"): never

A Series holds the values of all the bars, so JavaScript operators cannot use it: without this guard close - open is NaN, close > open false and ` ${rsi} ` "[object Object]", with no error. The conversion throws instead, with the Series method or bar-loop read to use.

time_close.fullHistory

time_close.fullHistory: boolean

True for the built-in price series (open, high, low, close, volume, hl2...): their history covers every bar, so offset() may reach further than 5000 bars back.

time_close.extractortime_close.dataSourcetime_close.cachedtime_close.cachedVersion

time_close.bars

The bars this series is aligned to ({ time, open, high, low, close, volume }, oldest first).

time_close.bars.toLocaleString()

time_close.bars.toLocaleString(): string
time_close.bars.toLocaleString(locales: string | string[], options?: NumberFormatOptions & DateTimeFormatOptions): string

Returns a string representation of an array. The elements are converted to string using their toLocaleString methods.

time_close.bars.pop()

time_close.bars.pop(): Bar

Removes the last element from an array and returns it. If the array is empty, undefined is returned and the array is not modified.

time_close.bars.push()

time_close.bars.push(...items: Bar[]): number

Appends new elements to the end of an array, and returns the new length of the array.

items
New elements to add to the array.

time_close.bars.concat()

time_close.bars.concat(...items: ConcatArray<Bar>[]): Bar[]
time_close.bars.concat(...items: (Bar | ConcatArray<Bar>)[]): Bar[]

Combines two or more arrays. This method returns a new array without modifying any existing arrays.

items
Additional arrays and/or items to add to the end of the array.

time_close.bars.join()

time_close.bars.join(separator?: string): string

Adds all the elements of an array into a string, separated by the specified separator string.

separator
A string used to separate one element of the array from the next in the resulting string. If omitted, the array elements are separated with a comma.

time_close.bars.reverse()

time_close.bars.reverse(): Bar[]

Reverses the elements in an array in place. This method mutates the array and returns a reference to the same array.

time_close.bars.shift()

time_close.bars.shift(): Bar

Removes the first element from an array and returns it. If the array is empty, undefined is returned and the array is not modified.

time_close.bars.slice()

time_close.bars.slice(start?: number, end?: number): Bar[]

Returns a copy of a section of an array. For both start and end, a negative index can be used to indicate an offset from the end of the array. For example, -2 refers to the second to last element of the array.

start
The beginning index of the specified portion of the array. If start is undefined, then the slice begins at index 0.
end
The end index of the specified portion of the array. This is exclusive of the element at the index 'end'. If end is undefined, then the slice extends to the end of the array.

time_close.bars.sort()

time_close.bars.sort(compareFn?: (a: Bar, b: Bar) => number): Bar[]

Sorts an array in place. This method mutates the array and returns a reference to the same array.

compareFn
Function used to determine the order of the elements. It is expected to return a negative value if the first argument is less than the second argument, zero if they're equal, and a positive value otherwise. If omitted, the elements are sorted in ascending, ASCII character order. ``ts [11,2,22,1].sort((a, b) => a - b) ``

time_close.bars.splice()

time_close.bars.splice(start: number, deleteCount?: number): Bar[]
time_close.bars.splice(start: number, deleteCount: number, ...items: Bar[]): Bar[]

Removes elements from an array and, if necessary, inserts new elements in their place, returning the deleted elements.

start
The zero-based location in the array from which to start removing elements.
deleteCount
The number of elements to remove.

Returns An array containing the elements that were deleted.

Removes elements from an array and, if necessary, inserts new elements in their place, returning the deleted elements.

start
The zero-based location in the array from which to start removing elements.
deleteCount
The number of elements to remove.
items
Elements to insert into the array in place of the deleted elements.

Returns An array containing the elements that were deleted.

time_close.bars.unshift()

time_close.bars.unshift(...items: Bar[]): number

Inserts new elements at the start of an array, and returns the new length of the array.

items
Elements to insert at the start of the array.

time_close.bars.indexOf()

time_close.bars.indexOf(searchElement: Bar, fromIndex?: number): number

Returns the index of the first occurrence of a value in an array, or -1 if it is not present.

searchElement
The value to locate in the array.
fromIndex
The array index at which to begin the search. If fromIndex is omitted, the search starts at index 0.

time_close.bars.lastIndexOf()

time_close.bars.lastIndexOf(searchElement: Bar, fromIndex?: number): number

Returns the index of the last occurrence of a specified value in an array, or -1 if it is not present.

searchElement
The value to locate in the array.
fromIndex
The array index at which to begin searching backward. If fromIndex is omitted, the search starts at the last index in the array.

time_close.bars.every()

time_close.bars.every<S extends Bar>(predicate: (value: Bar, index: number, array: Bar[]) => value is S, thisArg?: any): this is S[]
time_close.bars.every(predicate: (value: Bar, index: number, array: Bar[]) => unknown, thisArg?: any): boolean

Determines whether all the members of an array satisfy the specified test.

predicate
A function that accepts up to three arguments. The every method calls the predicate function for each element in the array until the predicate returns a value which is coercible to the Boolean value false, or until the end of the array.
thisArg
An object to which the this keyword can refer in the predicate function. If thisArg is omitted, undefined is used as the this value.

time_close.bars.some()

time_close.bars.some(predicate: (value: Bar, index: number, array: Bar[]) => unknown, thisArg?: any): boolean

Determines whether the specified callback function returns true for any element of an array.

predicate
A function that accepts up to three arguments. The some method calls the predicate function for each element in the array until the predicate returns a value which is coercible to the Boolean value true, or until the end of the array.
thisArg
An object to which the this keyword can refer in the predicate function. If thisArg is omitted, undefined is used as the this value.

time_close.bars.forEach()

time_close.bars.forEach(callbackfn: (value: Bar, index: number, array: Bar[]) => void, thisArg?: any): void

Performs the specified action for each element in an array.

callbackfn
A function that accepts up to three arguments. forEach calls the callbackfn function one time for each element in the array.
thisArg
An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.

time_close.bars.map()

time_close.bars.map<U>(callbackfn: (value: Bar, index: number, array: Bar[]) => U, thisArg?: any): U[]

Calls a defined callback function on each element of an array, and returns an array that contains the results.

callbackfn
A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array.
thisArg
An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.

time_close.bars.filter()

time_close.bars.filter<S extends Bar>(predicate: (value: Bar, index: number, array: Bar[]) => value is S, thisArg?: any): S[]
time_close.bars.filter(predicate: (value: Bar, index: number, array: Bar[]) => unknown, thisArg?: any): Bar[]

Returns the elements of an array that meet the condition specified in a callback function.

predicate
A function that accepts up to three arguments. The filter method calls the predicate function one time for each element in the array.
thisArg
An object to which the this keyword can refer in the predicate function. If thisArg is omitted, undefined is used as the this value.

time_close.bars.reduce()

time_close.bars.reduce(callbackfn: (previousValue: Bar, currentValue: Bar, currentIndex: number, array: Bar[]) => Bar): Bar
time_close.bars.reduce(callbackfn: (previousValue: Bar, currentValue: Bar, currentIndex: number, array: Bar[]) => Bar, initialValue: Bar): Bar
time_close.bars.reduce<U>(callbackfn: (previousValue: U, currentValue: Bar, currentIndex: number, array: Bar[]) => U, initialValue: U): U

Calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function.

callbackfn
A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array.
initialValue
If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value.

Calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function.

callbackfn
A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array.
initialValue
If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value.
callbackfn
A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array.
initialValue
If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value.

time_close.bars.reduceRight()

time_close.bars.reduceRight(callbackfn: (previousValue: Bar, currentValue: Bar, currentIndex: number, array: Bar[]) => Bar): Bar
time_close.bars.reduceRight(callbackfn: (previousValue: Bar, currentValue: Bar, currentIndex: number, array: Bar[]) => Bar, initialValue: Bar): Bar
time_close.bars.reduceRight<U>(callbackfn: (previousValue: U, currentValue: Bar, currentIndex: number, array: Bar[]) => U, initialValue: U): U

Calls the specified callback function for all the elements in an array, in descending order. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function.

callbackfn
A function that accepts up to four arguments. The reduceRight method calls the callbackfn function one time for each element in the array.
initialValue
If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value.

Calls the specified callback function for all the elements in an array, in descending order. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function.

callbackfn
A function that accepts up to four arguments. The reduceRight method calls the callbackfn function one time for each element in the array.
initialValue
If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value.
callbackfn
A function that accepts up to four arguments. The reduceRight method calls the callbackfn function one time for each element in the array.
initialValue
If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value.

time_close.bars.find()

time_close.bars.find<S extends Bar>(predicate: (value: Bar, index: number, obj: Bar[]) => value is S, thisArg?: any): S
time_close.bars.find(predicate: (value: Bar, index: number, obj: Bar[]) => unknown, thisArg?: any): Bar

Returns the value of the first element in the array where predicate is true, and undefined otherwise.

predicate
find calls predicate once for each element of the array, in ascending order, until it finds one where predicate returns true. If such an element is found, find immediately returns that element value. Otherwise, find returns undefined.
thisArg
If provided, it will be used as the this value for each invocation of predicate. If it is not provided, undefined is used instead.

time_close.bars.findIndex()

time_close.bars.findIndex(predicate: (value: Bar, index: number, obj: Bar[]) => unknown, thisArg?: any): number

Returns the index of the first element in the array where predicate is true, and -1 otherwise.

predicate
find calls predicate once for each element of the array, in ascending order, until it finds one where predicate returns true. If such an element is found, findIndex immediately returns that element index. Otherwise, findIndex returns -1.
thisArg
If provided, it will be used as the this value for each invocation of predicate. If it is not provided, undefined is used instead.

time_close.bars.fill()

time_close.bars.fill(value: Bar, start?: number, end?: number): Bar[]

Changes all array elements from start to end index to a static value and returns the modified array

value
value to fill array section with
start
index to start filling the array at. If start is negative, it is treated as length+start where length is the length of the array.
end
index to stop filling the array at. If end is negative, it is treated as length+end.

time_close.bars.copyWithin()

time_close.bars.copyWithin(target: number, start: number, end?: number): Bar[]

Returns the this object after copying a section of the array identified by start and end to the same array starting at position target

target
If target is negative, it is treated as length+target where length is the length of the array.
start
If start is negative, it is treated as length+start. If end is negative, it is treated as length+end.
end
If not specified, length of the this object is used as its default value.

time_close.bars.entries()

time_close.bars.entries(): ArrayIterator<[number, Bar]>

Returns an iterable of key, value pairs for every entry in the array

time_close.bars.keys()

time_close.bars.keys(): ArrayIterator<number>

Returns an iterable of keys in the array

time_close.bars.includes()

time_close.bars.includes(searchElement: Bar, fromIndex?: number): boolean

Determines whether an array includes a certain element, returning true or false as appropriate.

searchElement
The element to search for.
fromIndex
The position in this array at which to begin searching for searchElement.

time_close.bars.flatMap()

time_close.bars.flatMap<U, This = undefined>(callback: (this: This, value: Bar, index: number, array: Bar[]) => U | readonly U[], thisArg?: This): U[]

Calls a defined callback function on each element of an array. Then, flattens the result into a new array. This is identical to a map followed by flat with depth 1.

callback
A function that accepts up to three arguments. The flatMap method calls the callback function one time for each element in the array.
thisArg
An object to which the this keyword can refer in the callback function. If thisArg is omitted, undefined is used as the this value.

time_close.bars.flat()

time_close.bars.flat<A, D extends number = 1>(this: A, depth?: D): FlatArray<A, D>[]

Returns a new array with all sub-array elements concatenated into it recursively up to the specified depth.

depth
The maximum recursion depth

time_close.bars.at()

time_close.bars.at(index: number): Bar

Returns the item located at the specified index.

index
The zero-based index of the desired code unit. A negative index will count back from the last item.

time_close.bars.findLast()

time_close.bars.findLast<S extends Bar>(predicate: (value: Bar, index: number, array: Bar[]) => value is S, thisArg?: any): S
time_close.bars.findLast(predicate: (value: Bar, index: number, array: Bar[]) => unknown, thisArg?: any): Bar

Returns the value of the last element in the array where predicate is true, and undefined otherwise.

predicate
findLast calls predicate once for each element of the array, in descending order, until it finds one where predicate returns true. If such an element is found, findLast immediately returns that element value. Otherwise, findLast returns undefined.
thisArg
If provided, it will be used as the this value for each invocation of predicate. If it is not provided, undefined is used instead.

time_close.bars.findLastIndex()

time_close.bars.findLastIndex(predicate: (value: Bar, index: number, array: Bar[]) => unknown, thisArg?: any): number

Returns the index of the last element in the array where predicate is true, and -1 otherwise.

predicate
findLastIndex calls predicate once for each element of the array, in descending order, until it finds one where predicate returns true. If such an element is found, findLastIndex immediately returns that element index. Otherwise, findLastIndex returns -1.
thisArg
If provided, it will be used as the this value for each invocation of predicate. If it is not provided, undefined is used instead.

time_close.bars.toSorted()

time_close.bars.toSorted(compareFn?: (a: Bar, b: Bar) => number): Bar[]

Returns a copy of an array with its elements sorted.

compareFn
Function used to determine the order of the elements. It is expected to return a negative value if the first argument is less than the second argument, zero if they're equal, and a positive value otherwise. If omitted, the elements are sorted in ascending, ASCII character order. ``ts [11, 2, 22, 1].toSorted((a, b) => a - b) // [1, 2, 11, 22] ``

time_close.bars.toSpliced()

time_close.bars.toSpliced(start: number, deleteCount: number, ...items: Bar[]): Bar[]
time_close.bars.toSpliced(start: number, deleteCount?: number): Bar[]

Copies an array and removes elements and, if necessary, inserts new elements in their place. Returns the copied array.

start
The zero-based location in the array from which to start removing elements.
deleteCount
The number of elements to remove.
items
Elements to insert into the copied array in place of the deleted elements.

Returns The copied array.

Copies an array and removes elements while returning the remaining elements.

start
The zero-based location in the array from which to start removing elements.
deleteCount
The number of elements to remove.

Returns A copy of the original array with the remaining elements.

time_close.bars.with()

time_close.bars.with(index: number, value: Bar): Bar[]

Copies an array, then overwrites the value at the provided index with the given value. If the index is negative, then it replaces from the end of the array.

index
The index of the value to overwrite. If the index is negative, then it replaces from the end of the array.
value
The value to write into the copied array.

Returns The copied array with the updated value.

time_close.bars.length

time_close.bars.length: number

Gets or sets the length of the array. This is a number one higher than the highest index in the array.

time_close.bars.__@unscopables@73

Is an object whose properties have the value 'true' when they will be absent when used in a 'with' statement.

time_close.bars.__@unscopables@73.pop

time_close.bars.__@unscopables@73.pop: boolean

Removes the last element from an array and returns it. If the array is empty, undefined is returned and the array is not modified.

time_close.bars.__@unscopables@73.push

time_close.bars.__@unscopables@73.push: boolean

Appends new elements to the end of an array, and returns the new length of the array.

items
New elements to add to the array.

time_close.bars.__@unscopables@73.concat

time_close.bars.__@unscopables@73.concat: boolean

Combines two or more arrays. This method returns a new array without modifying any existing arrays.

items
Additional arrays and/or items to add to the end of the array.
items
Additional arrays and/or items to add to the end of the array.

time_close.bars.__@unscopables@73.join

time_close.bars.__@unscopables@73.join: boolean

Adds all the elements of an array into a string, separated by the specified separator string.

separator
A string used to separate one element of the array from the next in the resulting string. If omitted, the array elements are separated with a comma.

time_close.bars.__@unscopables@73.reverse

time_close.bars.__@unscopables@73.reverse: boolean

Reverses the elements in an array in place. This method mutates the array and returns a reference to the same array.

time_close.bars.__@unscopables@73.shift

time_close.bars.__@unscopables@73.shift: boolean

Removes the first element from an array and returns it. If the array is empty, undefined is returned and the array is not modified.

time_close.bars.__@unscopables@73.slice

time_close.bars.__@unscopables@73.slice: boolean

Returns a copy of a section of an array. For both start and end, a negative index can be used to indicate an offset from the end of the array. For example, -2 refers to the second to last element of the array.

start
The beginning index of the specified portion of the array. If start is undefined, then the slice begins at index 0.
end
The end index of the specified portion of the array. This is exclusive of the element at the index 'end'. If end is undefined, then the slice extends to the end of the array.

time_close.bars.__@unscopables@73.sort

time_close.bars.__@unscopables@73.sort: boolean

Sorts an array in place. This method mutates the array and returns a reference to the same array.

compareFn
Function used to determine the order of the elements. It is expected to return a negative value if the first argument is less than the second argument, zero if they're equal, and a positive value otherwise. If omitted, the elements are sorted in ascending, ASCII character order. ``ts [11,2,22,1].sort((a, b) => a - b) ``

time_close.bars.__@unscopables@73.splice

time_close.bars.__@unscopables@73.splice: boolean

Removes elements from an array and, if necessary, inserts new elements in their place, returning the deleted elements.

start
The zero-based location in the array from which to start removing elements.
deleteCount
The number of elements to remove.
start
The zero-based location in the array from which to start removing elements.
deleteCount
The number of elements to remove.
items
Elements to insert into the array in place of the deleted elements.

Returns An array containing the elements that were deleted.

time_close.bars.__@unscopables@73.unshift

time_close.bars.__@unscopables@73.unshift: boolean

Inserts new elements at the start of an array, and returns the new length of the array.

items
Elements to insert at the start of the array.

time_close.bars.__@unscopables@73.indexOf

time_close.bars.__@unscopables@73.indexOf: boolean

Returns the index of the first occurrence of a value in an array, or -1 if it is not present.

searchElement
The value to locate in the array.
fromIndex
The array index at which to begin the search. If fromIndex is omitted, the search starts at index 0.

time_close.bars.__@unscopables@73.lastIndexOf

time_close.bars.__@unscopables@73.lastIndexOf: boolean

Returns the index of the last occurrence of a specified value in an array, or -1 if it is not present.

searchElement
The value to locate in the array.
fromIndex
The array index at which to begin searching backward. If fromIndex is omitted, the search starts at the last index in the array.

time_close.bars.__@unscopables@73.every

time_close.bars.__@unscopables@73.every: boolean

Determines whether all the members of an array satisfy the specified test.

predicate
A function that accepts up to three arguments. The every method calls the predicate function for each element in the array until the predicate returns a value which is coercible to the Boolean value false, or until the end of the array.
thisArg
An object to which the this keyword can refer in the predicate function. If thisArg is omitted, undefined is used as the this value.
predicate
A function that accepts up to three arguments. The every method calls the predicate function for each element in the array until the predicate returns a value which is coercible to the Boolean value false, or until the end of the array.
thisArg
An object to which the this keyword can refer in the predicate function. If thisArg is omitted, undefined is used as the this value.

time_close.bars.__@unscopables@73.some

time_close.bars.__@unscopables@73.some: boolean

Determines whether the specified callback function returns true for any element of an array.

predicate
A function that accepts up to three arguments. The some method calls the predicate function for each element in the array until the predicate returns a value which is coercible to the Boolean value true, or until the end of the array.
thisArg
An object to which the this keyword can refer in the predicate function. If thisArg is omitted, undefined is used as the this value.

time_close.bars.__@unscopables@73.forEach

time_close.bars.__@unscopables@73.forEach: boolean

Performs the specified action for each element in an array.

callbackfn
A function that accepts up to three arguments. forEach calls the callbackfn function one time for each element in the array.
thisArg
An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.

time_close.bars.__@unscopables@73.map

time_close.bars.__@unscopables@73.map: boolean

Calls a defined callback function on each element of an array, and returns an array that contains the results.

callbackfn
A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array.
thisArg
An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.

time_close.bars.__@unscopables@73.filter

time_close.bars.__@unscopables@73.filter: boolean

Returns the elements of an array that meet the condition specified in a callback function.

predicate
A function that accepts up to three arguments. The filter method calls the predicate function one time for each element in the array.
thisArg
An object to which the this keyword can refer in the predicate function. If thisArg is omitted, undefined is used as the this value.
predicate
A function that accepts up to three arguments. The filter method calls the predicate function one time for each element in the array.
thisArg
An object to which the this keyword can refer in the predicate function. If thisArg is omitted, undefined is used as the this value.

time_close.bars.__@unscopables@73.reduce

time_close.bars.__@unscopables@73.reduce: boolean

Calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function.

callbackfn
A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array.
initialValue
If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value.
callbackfn
A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array.
initialValue
If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value.

time_close.bars.__@unscopables@73.reduceRight

time_close.bars.__@unscopables@73.reduceRight: boolean

Calls the specified callback function for all the elements in an array, in descending order. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function.

callbackfn
A function that accepts up to four arguments. The reduceRight method calls the callbackfn function one time for each element in the array.
initialValue
If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value.
callbackfn
A function that accepts up to four arguments. The reduceRight method calls the callbackfn function one time for each element in the array.
initialValue
If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value.

time_close.bars.__@unscopables@73.find

time_close.bars.__@unscopables@73.find: boolean

Returns the value of the first element in the array where predicate is true, and undefined otherwise.

predicate
find calls predicate once for each element of the array, in ascending order, until it finds one where predicate returns true. If such an element is found, find immediately returns that element value. Otherwise, find returns undefined.
thisArg
If provided, it will be used as the this value for each invocation of predicate. If it is not provided, undefined is used instead.

time_close.bars.__@unscopables@73.findIndex

time_close.bars.__@unscopables@73.findIndex: boolean

Returns the index of the first element in the array where predicate is true, and -1 otherwise.

predicate
find calls predicate once for each element of the array, in ascending order, until it finds one where predicate returns true. If such an element is found, findIndex immediately returns that element index. Otherwise, findIndex returns -1.
thisArg
If provided, it will be used as the this value for each invocation of predicate. If it is not provided, undefined is used instead.

time_close.bars.__@unscopables@73.fill

time_close.bars.__@unscopables@73.fill: boolean

Changes all array elements from start to end index to a static value and returns the modified array

value
value to fill array section with
start
index to start filling the array at. If start is negative, it is treated as length+start where length is the length of the array.
end
index to stop filling the array at. If end is negative, it is treated as length+end.

time_close.bars.__@unscopables@73.copyWithin

time_close.bars.__@unscopables@73.copyWithin: boolean

Returns the this object after copying a section of the array identified by start and end to the same array starting at position target

target
If target is negative, it is treated as length+target where length is the length of the array.
start
If start is negative, it is treated as length+start. If end is negative, it is treated as length+end.
end
If not specified, length of the this object is used as its default value.

time_close.bars.__@unscopables@73.includes

time_close.bars.__@unscopables@73.includes: boolean

Determines whether an array includes a certain element, returning true or false as appropriate.

searchElement
The element to search for.
fromIndex
The position in this array at which to begin searching for searchElement.

time_close.bars.__@unscopables@73.flatMap

time_close.bars.__@unscopables@73.flatMap: boolean

Calls a defined callback function on each element of an array. Then, flattens the result into a new array. This is identical to a map followed by flat with depth 1.

callback
A function that accepts up to three arguments. The flatMap method calls the callback function one time for each element in the array.
thisArg
An object to which the this keyword can refer in the callback function. If thisArg is omitted, undefined is used as the this value.

time_close.bars.__@unscopables@73.flat

time_close.bars.__@unscopables@73.flat: boolean

Returns a new array with all sub-array elements concatenated into it recursively up to the specified depth.

depth
The maximum recursion depth

time_close.bars.__@unscopables@73.at

time_close.bars.__@unscopables@73.at: boolean

Returns the item located at the specified index.

index
The zero-based index of the desired code unit. A negative index will count back from the last item.

time_close.bars.__@unscopables@73.findLast

time_close.bars.__@unscopables@73.findLast: boolean

Returns the value of the last element in the array where predicate is true, and undefined otherwise.

predicate
findLast calls predicate once for each element of the array, in descending order, until it finds one where predicate returns true. If such an element is found, findLast immediately returns that element value. Otherwise, findLast returns undefined.
thisArg
If provided, it will be used as the this value for each invocation of predicate. If it is not provided, undefined is used instead.

time_close.bars.__@unscopables@73.findLastIndex

time_close.bars.__@unscopables@73.findLastIndex: boolean

Returns the index of the last element in the array where predicate is true, and -1 otherwise.

predicate
findLastIndex calls predicate once for each element of the array, in descending order, until it finds one where predicate returns true. If such an element is found, findLastIndex immediately returns that element index. Otherwise, findLastIndex returns -1.
thisArg
If provided, it will be used as the this value for each invocation of predicate. If it is not provided, undefined is used instead.

time_close.bars.__@unscopables@73.toSorted

time_close.bars.__@unscopables@73.toSorted: boolean

Returns a copy of an array with its elements sorted.

compareFn
Function used to determine the order of the elements. It is expected to return a negative value if the first argument is less than the second argument, zero if they're equal, and a positive value otherwise. If omitted, the elements are sorted in ascending, ASCII character order. ``ts [11, 2, 22, 1].toSorted((a, b) => a - b) // [1, 2, 11, 22] ``

time_close.bars.__@unscopables@73.toSpliced

time_close.bars.__@unscopables@73.toSpliced: boolean

Copies an array and removes elements and, if necessary, inserts new elements in their place. Returns the copied array. Copies an array and removes elements while returning the remaining elements.

start
The zero-based location in the array from which to start removing elements.
deleteCount
The number of elements to remove.
items
Elements to insert into the copied array in place of the deleted elements.
start
The zero-based location in the array from which to start removing elements.
deleteCount
The number of elements to remove.

Returns A copy of the original array with the remaining elements.

time_close.bars.__@unscopables@73.with

time_close.bars.__@unscopables@73.with: boolean

Copies an array, then overwrites the value at the provided index with the given value. If the index is negative, then it replaces from the end of the array.

index
The index of the value to overwrite. If the index is negative, then it replaces from the end of the array.
value
The value to write into the copied array.

Returns The copied array with the updated value.

time_close.barData

The BarData holding the bars this series is aligned to.

time_close.barData.pop()

time_close.barData.pop(): Bar

Remove and return the last bar

Returns The removed bar, or undefined if empty

time_close.barData.set()

time_close.barData.set(index: number, bar: Bar): void

Replace a bar at a specific index

index
Index to update
bar
New bar data

time_close.barData.updateLast()

time_close.barData.updateLast(bar: Bar): void

Update the last bar (useful for real-time/streaming updates)

bar
New bar data

time_close.barData.invalidate()

time_close.barData.invalidate(): void

Manually increment version (for advanced use cases) Call this after direct mutations to the bars array

time_close.barData.at()

time_close.barData.at(index: number): Bar

Get a bar at a specific index

index
Bar index

Returns Bar at that index, or undefined

time_close.barData.version

time_close.barData.version: number

Get the current version number Version increments whenever data is mutated

time_close.barData._barstime_close.barData._version

time_close.barData.bars

Get the underlying bar array Note: Direct mutations to this array will NOT increment version Use the provided mutation methods instead

time_close.barData.bars.toLocaleString()

time_close.barData.bars.toLocaleString(): string
time_close.barData.bars.toLocaleString(locales: string | string[], options?: NumberFormatOptions & DateTimeFormatOptions): string

Returns a string representation of an array. The elements are converted to string using their toLocaleString methods.

time_close.barData.bars.pop()

time_close.barData.bars.pop(): Bar

Removes the last element from an array and returns it. If the array is empty, undefined is returned and the array is not modified.

time_close.barData.bars.push()

time_close.barData.bars.push(...items: Bar[]): number

Appends new elements to the end of an array, and returns the new length of the array.

items
New elements to add to the array.

time_close.barData.bars.concat()

time_close.barData.bars.concat(...items: ConcatArray<Bar>[]): Bar[]
time_close.barData.bars.concat(...items: (Bar | ConcatArray<Bar>)[]): Bar[]

Combines two or more arrays. This method returns a new array without modifying any existing arrays.

items
Additional arrays and/or items to add to the end of the array.

time_close.barData.bars.join()

time_close.barData.bars.join(separator?: string): string

Adds all the elements of an array into a string, separated by the specified separator string.

separator
A string used to separate one element of the array from the next in the resulting string. If omitted, the array elements are separated with a comma.

time_close.barData.bars.reverse()

time_close.barData.bars.reverse(): Bar[]

Reverses the elements in an array in place. This method mutates the array and returns a reference to the same array.

time_close.barData.bars.shift()

time_close.barData.bars.shift(): Bar

Removes the first element from an array and returns it. If the array is empty, undefined is returned and the array is not modified.

time_close.barData.bars.slice()

time_close.barData.bars.slice(start?: number, end?: number): Bar[]

Returns a copy of a section of an array. For both start and end, a negative index can be used to indicate an offset from the end of the array. For example, -2 refers to the second to last element of the array.

start
The beginning index of the specified portion of the array. If start is undefined, then the slice begins at index 0.
end
The end index of the specified portion of the array. This is exclusive of the element at the index 'end'. If end is undefined, then the slice extends to the end of the array.

time_close.barData.bars.sort()

time_close.barData.bars.sort(compareFn?: (a: Bar, b: Bar) => number): Bar[]

Sorts an array in place. This method mutates the array and returns a reference to the same array.

compareFn
Function used to determine the order of the elements. It is expected to return a negative value if the first argument is less than the second argument, zero if they're equal, and a positive value otherwise. If omitted, the elements are sorted in ascending, ASCII character order. ``ts [11,2,22,1].sort((a, b) => a - b) ``

time_close.barData.bars.splice()

time_close.barData.bars.splice(start: number, deleteCount?: number): Bar[]
time_close.barData.bars.splice(start: number, deleteCount: number, ...items: Bar[]): Bar[]

Removes elements from an array and, if necessary, inserts new elements in their place, returning the deleted elements.

start
The zero-based location in the array from which to start removing elements.
deleteCount
The number of elements to remove.

Returns An array containing the elements that were deleted.

Removes elements from an array and, if necessary, inserts new elements in their place, returning the deleted elements.

start
The zero-based location in the array from which to start removing elements.
deleteCount
The number of elements to remove.
items
Elements to insert into the array in place of the deleted elements.

Returns An array containing the elements that were deleted.

time_close.barData.bars.unshift()

time_close.barData.bars.unshift(...items: Bar[]): number

Inserts new elements at the start of an array, and returns the new length of the array.

items
Elements to insert at the start of the array.

time_close.barData.bars.indexOf()

time_close.barData.bars.indexOf(searchElement: Bar, fromIndex?: number): number

Returns the index of the first occurrence of a value in an array, or -1 if it is not present.

searchElement
The value to locate in the array.
fromIndex
The array index at which to begin the search. If fromIndex is omitted, the search starts at index 0.

time_close.barData.bars.lastIndexOf()

time_close.barData.bars.lastIndexOf(searchElement: Bar, fromIndex?: number): number

Returns the index of the last occurrence of a specified value in an array, or -1 if it is not present.

searchElement
The value to locate in the array.
fromIndex
The array index at which to begin searching backward. If fromIndex is omitted, the search starts at the last index in the array.

time_close.barData.bars.every()

time_close.barData.bars.every<S extends Bar>(predicate: (value: Bar, index: number, array: Bar[]) => value is S, thisArg?: any): this is S[]
time_close.barData.bars.every(predicate: (value: Bar, index: number, array: Bar[]) => unknown, thisArg?: any): boolean

Determines whether all the members of an array satisfy the specified test.

predicate
A function that accepts up to three arguments. The every method calls the predicate function for each element in the array until the predicate returns a value which is coercible to the Boolean value false, or until the end of the array.
thisArg
An object to which the this keyword can refer in the predicate function. If thisArg is omitted, undefined is used as the this value.

time_close.barData.bars.some()

time_close.barData.bars.some(predicate: (value: Bar, index: number, array: Bar[]) => unknown, thisArg?: any): boolean

Determines whether the specified callback function returns true for any element of an array.

predicate
A function that accepts up to three arguments. The some method calls the predicate function for each element in the array until the predicate returns a value which is coercible to the Boolean value true, or until the end of the array.
thisArg
An object to which the this keyword can refer in the predicate function. If thisArg is omitted, undefined is used as the this value.

time_close.barData.bars.forEach()

time_close.barData.bars.forEach(callbackfn: (value: Bar, index: number, array: Bar[]) => void, thisArg?: any): void

Performs the specified action for each element in an array.

callbackfn
A function that accepts up to three arguments. forEach calls the callbackfn function one time for each element in the array.
thisArg
An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.

time_close.barData.bars.map()

time_close.barData.bars.map<U>(callbackfn: (value: Bar, index: number, array: Bar[]) => U, thisArg?: any): U[]

Calls a defined callback function on each element of an array, and returns an array that contains the results.

callbackfn
A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array.
thisArg
An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.

time_close.barData.bars.filter()

time_close.barData.bars.filter<S extends Bar>(predicate: (value: Bar, index: number, array: Bar[]) => value is S, thisArg?: any): S[]
time_close.barData.bars.filter(predicate: (value: Bar, index: number, array: Bar[]) => unknown, thisArg?: any): Bar[]

Returns the elements of an array that meet the condition specified in a callback function.

predicate
A function that accepts up to three arguments. The filter method calls the predicate function one time for each element in the array.
thisArg
An object to which the this keyword can refer in the predicate function. If thisArg is omitted, undefined is used as the this value.

time_close.barData.bars.reduce()

time_close.barData.bars.reduce(callbackfn: (previousValue: Bar, currentValue: Bar, currentIndex: number, array: Bar[]) => Bar): Bar
time_close.barData.bars.reduce(callbackfn: (previousValue: Bar, currentValue: Bar, currentIndex: number, array: Bar[]) => Bar, initialValue: Bar): Bar
time_close.barData.bars.reduce<U>(callbackfn: (previousValue: U, currentValue: Bar, currentIndex: number, array: Bar[]) => U, initialValue: U): U

Calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function.

callbackfn
A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array.
initialValue
If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value.

Calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function.

callbackfn
A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array.
initialValue
If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value.
callbackfn
A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array.
initialValue
If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value.

time_close.barData.bars.reduceRight()

time_close.barData.bars.reduceRight(callbackfn: (previousValue: Bar, currentValue: Bar, currentIndex: number, array: Bar[]) => Bar): Bar
time_close.barData.bars.reduceRight(callbackfn: (previousValue: Bar, currentValue: Bar, currentIndex: number, array: Bar[]) => Bar, initialValue: Bar): Bar
time_close.barData.bars.reduceRight<U>(callbackfn: (previousValue: U, currentValue: Bar, currentIndex: number, array: Bar[]) => U, initialValue: U): U

Calls the specified callback function for all the elements in an array, in descending order. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function.

callbackfn
A function that accepts up to four arguments. The reduceRight method calls the callbackfn function one time for each element in the array.
initialValue
If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value.

Calls the specified callback function for all the elements in an array, in descending order. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function.

callbackfn
A function that accepts up to four arguments. The reduceRight method calls the callbackfn function one time for each element in the array.
initialValue
If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value.
callbackfn
A function that accepts up to four arguments. The reduceRight method calls the callbackfn function one time for each element in the array.
initialValue
If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value.

time_close.barData.bars.find()

time_close.barData.bars.find<S extends Bar>(predicate: (value: Bar, index: number, obj: Bar[]) => value is S, thisArg?: any): S
time_close.barData.bars.find(predicate: (value: Bar, index: number, obj: Bar[]) => unknown, thisArg?: any): Bar

Returns the value of the first element in the array where predicate is true, and undefined otherwise.

predicate
find calls predicate once for each element of the array, in ascending order, until it finds one where predicate returns true. If such an element is found, find immediately returns that element value. Otherwise, find returns undefined.
thisArg
If provided, it will be used as the this value for each invocation of predicate. If it is not provided, undefined is used instead.

time_close.barData.bars.findIndex()

time_close.barData.bars.findIndex(predicate: (value: Bar, index: number, obj: Bar[]) => unknown, thisArg?: any): number

Returns the index of the first element in the array where predicate is true, and -1 otherwise.

predicate
find calls predicate once for each element of the array, in ascending order, until it finds one where predicate returns true. If such an element is found, findIndex immediately returns that element index. Otherwise, findIndex returns -1.
thisArg
If provided, it will be used as the this value for each invocation of predicate. If it is not provided, undefined is used instead.

time_close.barData.bars.fill()

time_close.barData.bars.fill(value: Bar, start?: number, end?: number): Bar[]

Changes all array elements from start to end index to a static value and returns the modified array

value
value to fill array section with
start
index to start filling the array at. If start is negative, it is treated as length+start where length is the length of the array.
end
index to stop filling the array at. If end is negative, it is treated as length+end.

time_close.barData.bars.copyWithin()

time_close.barData.bars.copyWithin(target: number, start: number, end?: number): Bar[]

Returns the this object after copying a section of the array identified by start and end to the same array starting at position target

target
If target is negative, it is treated as length+target where length is the length of the array.
start
If start is negative, it is treated as length+start. If end is negative, it is treated as length+end.
end
If not specified, length of the this object is used as its default value.

time_close.barData.bars.entries()

time_close.barData.bars.entries(): ArrayIterator<[number, Bar]>

Returns an iterable of key, value pairs for every entry in the array

time_close.barData.bars.includes()

time_close.barData.bars.includes(searchElement: Bar, fromIndex?: number): boolean

Determines whether an array includes a certain element, returning true or false as appropriate.

searchElement
The element to search for.
fromIndex
The position in this array at which to begin searching for searchElement.

time_close.barData.bars.flatMap()

time_close.barData.bars.flatMap<U, This = undefined>(callback: (this: This, value: Bar, index: number, array: Bar[]) => U | readonly U[], thisArg?: This): U[]

Calls a defined callback function on each element of an array. Then, flattens the result into a new array. This is identical to a map followed by flat with depth 1.

callback
A function that accepts up to three arguments. The flatMap method calls the callback function one time for each element in the array.
thisArg
An object to which the this keyword can refer in the callback function. If thisArg is omitted, undefined is used as the this value.

time_close.barData.bars.flat()

time_close.barData.bars.flat<A, D extends number = 1>(this: A, depth?: D): FlatArray<A, D>[]

Returns a new array with all sub-array elements concatenated into it recursively up to the specified depth.

depth
The maximum recursion depth

time_close.barData.bars.at()

time_close.barData.bars.at(index: number): Bar

Returns the item located at the specified index.

index
The zero-based index of the desired code unit. A negative index will count back from the last item.

time_close.barData.bars.findLast()

time_close.barData.bars.findLast<S extends Bar>(predicate: (value: Bar, index: number, array: Bar[]) => value is S, thisArg?: any): S
time_close.barData.bars.findLast(predicate: (value: Bar, index: number, array: Bar[]) => unknown, thisArg?: any): Bar

Returns the value of the last element in the array where predicate is true, and undefined otherwise.

predicate
findLast calls predicate once for each element of the array, in descending order, until it finds one where predicate returns true. If such an element is found, findLast immediately returns that element value. Otherwise, findLast returns undefined.
thisArg
If provided, it will be used as the this value for each invocation of predicate. If it is not provided, undefined is used instead.

time_close.barData.bars.findLastIndex()

time_close.barData.bars.findLastIndex(predicate: (value: Bar, index: number, array: Bar[]) => unknown, thisArg?: any): number

Returns the index of the last element in the array where predicate is true, and -1 otherwise.

predicate
findLastIndex calls predicate once for each element of the array, in descending order, until it finds one where predicate returns true. If such an element is found, findLastIndex immediately returns that element index. Otherwise, findLastIndex returns -1.
thisArg
If provided, it will be used as the this value for each invocation of predicate. If it is not provided, undefined is used instead.

time_close.barData.bars.toSorted()

time_close.barData.bars.toSorted(compareFn?: (a: Bar, b: Bar) => number): Bar[]

Returns a copy of an array with its elements sorted.

compareFn
Function used to determine the order of the elements. It is expected to return a negative value if the first argument is less than the second argument, zero if they're equal, and a positive value otherwise. If omitted, the elements are sorted in ascending, ASCII character order. ``ts [11, 2, 22, 1].toSorted((a, b) => a - b) // [1, 2, 11, 22] ``

time_close.barData.bars.toSpliced()

time_close.barData.bars.toSpliced(start: number, deleteCount: number, ...items: Bar[]): Bar[]
time_close.barData.bars.toSpliced(start: number, deleteCount?: number): Bar[]

Copies an array and removes elements and, if necessary, inserts new elements in their place. Returns the copied array.

start
The zero-based location in the array from which to start removing elements.
deleteCount
The number of elements to remove.
items
Elements to insert into the copied array in place of the deleted elements.

Returns The copied array.

Copies an array and removes elements while returning the remaining elements.

start
The zero-based location in the array from which to start removing elements.
deleteCount
The number of elements to remove.

Returns A copy of the original array with the remaining elements.

time_close.barData.bars.with()

time_close.barData.bars.with(index: number, value: Bar): Bar[]

Copies an array, then overwrites the value at the provided index with the given value. If the index is negative, then it replaces from the end of the array.

index
The index of the value to overwrite. If the index is negative, then it replaces from the end of the array.
value
The value to write into the copied array.

Returns The copied array with the updated value.

time_close.barData.bars.length

time_close.barData.bars.length: number

Gets or sets the length of the array. This is a number one higher than the highest index in the array.

time_close.barData.bars.__@unscopables@73

Is an object whose properties have the value 'true' when they will be absent when used in a 'with' statement.

time_close.barData.bars.__@unscopables@73.pop

time_close.barData.bars.__@unscopables@73.pop: boolean

Removes the last element from an array and returns it. If the array is empty, undefined is returned and the array is not modified.

time_close.barData.bars.__@unscopables@73.concat

time_close.barData.bars.__@unscopables@73.concat: boolean

Combines two or more arrays. This method returns a new array without modifying any existing arrays.

items
Additional arrays and/or items to add to the end of the array.
items
Additional arrays and/or items to add to the end of the array.

time_close.barData.bars.__@unscopables@73.join

time_close.barData.bars.__@unscopables@73.join: boolean

Adds all the elements of an array into a string, separated by the specified separator string.

separator
A string used to separate one element of the array from the next in the resulting string. If omitted, the array elements are separated with a comma.

time_close.barData.bars.__@unscopables@73.shift

time_close.barData.bars.__@unscopables@73.shift: boolean

Removes the first element from an array and returns it. If the array is empty, undefined is returned and the array is not modified.

time_close.barData.bars.__@unscopables@73.slice

time_close.barData.bars.__@unscopables@73.slice: boolean

Returns a copy of a section of an array. For both start and end, a negative index can be used to indicate an offset from the end of the array. For example, -2 refers to the second to last element of the array.

start
The beginning index of the specified portion of the array. If start is undefined, then the slice begins at index 0.
end
The end index of the specified portion of the array. This is exclusive of the element at the index 'end'. If end is undefined, then the slice extends to the end of the array.

time_close.barData.bars.__@unscopables@73.sort

time_close.barData.bars.__@unscopables@73.sort: boolean

Sorts an array in place. This method mutates the array and returns a reference to the same array.

compareFn
Function used to determine the order of the elements. It is expected to return a negative value if the first argument is less than the second argument, zero if they're equal, and a positive value otherwise. If omitted, the elements are sorted in ascending, ASCII character order. ``ts [11,2,22,1].sort((a, b) => a - b) ``

time_close.barData.bars.__@unscopables@73.splice

time_close.barData.bars.__@unscopables@73.splice: boolean

Removes elements from an array and, if necessary, inserts new elements in their place, returning the deleted elements.

start
The zero-based location in the array from which to start removing elements.
deleteCount
The number of elements to remove.
start
The zero-based location in the array from which to start removing elements.
deleteCount
The number of elements to remove.
items
Elements to insert into the array in place of the deleted elements.

Returns An array containing the elements that were deleted.

time_close.barData.bars.__@unscopables@73.unshift

time_close.barData.bars.__@unscopables@73.unshift: boolean

Inserts new elements at the start of an array, and returns the new length of the array.

items
Elements to insert at the start of the array.

time_close.barData.bars.__@unscopables@73.indexOf

time_close.barData.bars.__@unscopables@73.indexOf: boolean

Returns the index of the first occurrence of a value in an array, or -1 if it is not present.

searchElement
The value to locate in the array.
fromIndex
The array index at which to begin the search. If fromIndex is omitted, the search starts at index 0.

time_close.barData.bars.__@unscopables@73.lastIndexOf

time_close.barData.bars.__@unscopables@73.lastIndexOf: boolean

Returns the index of the last occurrence of a specified value in an array, or -1 if it is not present.

searchElement
The value to locate in the array.
fromIndex
The array index at which to begin searching backward. If fromIndex is omitted, the search starts at the last index in the array.

time_close.barData.bars.__@unscopables@73.every

time_close.barData.bars.__@unscopables@73.every: boolean

Determines whether all the members of an array satisfy the specified test.

predicate
A function that accepts up to three arguments. The every method calls the predicate function for each element in the array until the predicate returns a value which is coercible to the Boolean value false, or until the end of the array.
thisArg
An object to which the this keyword can refer in the predicate function. If thisArg is omitted, undefined is used as the this value.
predicate
A function that accepts up to three arguments. The every method calls the predicate function for each element in the array until the predicate returns a value which is coercible to the Boolean value false, or until the end of the array.
thisArg
An object to which the this keyword can refer in the predicate function. If thisArg is omitted, undefined is used as the this value.

time_close.barData.bars.__@unscopables@73.some

time_close.barData.bars.__@unscopables@73.some: boolean

Determines whether the specified callback function returns true for any element of an array.

predicate
A function that accepts up to three arguments. The some method calls the predicate function for each element in the array until the predicate returns a value which is coercible to the Boolean value true, or until the end of the array.
thisArg
An object to which the this keyword can refer in the predicate function. If thisArg is omitted, undefined is used as the this value.

time_close.barData.bars.__@unscopables@73.forEach

time_close.barData.bars.__@unscopables@73.forEach: boolean

Performs the specified action for each element in an array.

callbackfn
A function that accepts up to three arguments. forEach calls the callbackfn function one time for each element in the array.
thisArg
An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.

time_close.barData.bars.__@unscopables@73.map

time_close.barData.bars.__@unscopables@73.map: boolean

Calls a defined callback function on each element of an array, and returns an array that contains the results.

callbackfn
A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array.
thisArg
An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.

time_close.barData.bars.__@unscopables@73.filter

time_close.barData.bars.__@unscopables@73.filter: boolean

Returns the elements of an array that meet the condition specified in a callback function.

predicate
A function that accepts up to three arguments. The filter method calls the predicate function one time for each element in the array.
thisArg
An object to which the this keyword can refer in the predicate function. If thisArg is omitted, undefined is used as the this value.
predicate
A function that accepts up to three arguments. The filter method calls the predicate function one time for each element in the array.
thisArg
An object to which the this keyword can refer in the predicate function. If thisArg is omitted, undefined is used as the this value.

time_close.barData.bars.__@unscopables@73.reduce

time_close.barData.bars.__@unscopables@73.reduce: boolean

Calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function.

callbackfn
A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array.
initialValue
If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value.
callbackfn
A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array.
initialValue
If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value.

time_close.barData.bars.__@unscopables@73.reduceRight

time_close.barData.bars.__@unscopables@73.reduceRight: boolean

Calls the specified callback function for all the elements in an array, in descending order. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function.

callbackfn
A function that accepts up to four arguments. The reduceRight method calls the callbackfn function one time for each element in the array.
initialValue
If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value.
callbackfn
A function that accepts up to four arguments. The reduceRight method calls the callbackfn function one time for each element in the array.
initialValue
If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value.

time_close.barData.bars.__@unscopables@73.find

time_close.barData.bars.__@unscopables@73.find: boolean

Returns the value of the first element in the array where predicate is true, and undefined otherwise.

predicate
find calls predicate once for each element of the array, in ascending order, until it finds one where predicate returns true. If such an element is found, find immediately returns that element value. Otherwise, find returns undefined.
thisArg
If provided, it will be used as the this value for each invocation of predicate. If it is not provided, undefined is used instead.

time_close.barData.bars.__@unscopables@73.findIndex

time_close.barData.bars.__@unscopables@73.findIndex: boolean

Returns the index of the first element in the array where predicate is true, and -1 otherwise.

predicate
find calls predicate once for each element of the array, in ascending order, until it finds one where predicate returns true. If such an element is found, findIndex immediately returns that element index. Otherwise, findIndex returns -1.
thisArg
If provided, it will be used as the this value for each invocation of predicate. If it is not provided, undefined is used instead.

time_close.barData.bars.__@unscopables@73.fill

time_close.barData.bars.__@unscopables@73.fill: boolean

Changes all array elements from start to end index to a static value and returns the modified array

value
value to fill array section with
start
index to start filling the array at. If start is negative, it is treated as length+start where length is the length of the array.
end
index to stop filling the array at. If end is negative, it is treated as length+end.

time_close.barData.bars.__@unscopables@73.copyWithin

time_close.barData.bars.__@unscopables@73.copyWithin: boolean

Returns the this object after copying a section of the array identified by start and end to the same array starting at position target

target
If target is negative, it is treated as length+target where length is the length of the array.
start
If start is negative, it is treated as length+start. If end is negative, it is treated as length+end.
end
If not specified, length of the this object is used as its default value.

time_close.barData.bars.__@unscopables@73.includes

time_close.barData.bars.__@unscopables@73.includes: boolean

Determines whether an array includes a certain element, returning true or false as appropriate.

searchElement
The element to search for.
fromIndex
The position in this array at which to begin searching for searchElement.

time_close.barData.bars.__@unscopables@73.flatMap

time_close.barData.bars.__@unscopables@73.flatMap: boolean

Calls a defined callback function on each element of an array. Then, flattens the result into a new array. This is identical to a map followed by flat with depth 1.

callback
A function that accepts up to three arguments. The flatMap method calls the callback function one time for each element in the array.
thisArg
An object to which the this keyword can refer in the callback function. If thisArg is omitted, undefined is used as the this value.

time_close.barData.bars.__@unscopables@73.flat

time_close.barData.bars.__@unscopables@73.flat: boolean

Returns a new array with all sub-array elements concatenated into it recursively up to the specified depth.

depth
The maximum recursion depth

time_close.barData.bars.__@unscopables@73.at

time_close.barData.bars.__@unscopables@73.at: boolean

Returns the item located at the specified index.

index
The zero-based index of the desired code unit. A negative index will count back from the last item.

time_close.barData.bars.__@unscopables@73.findLast

time_close.barData.bars.__@unscopables@73.findLast: boolean

Returns the value of the last element in the array where predicate is true, and undefined otherwise.

predicate
findLast calls predicate once for each element of the array, in descending order, until it finds one where predicate returns true. If such an element is found, findLast immediately returns that element value. Otherwise, findLast returns undefined.
thisArg
If provided, it will be used as the this value for each invocation of predicate. If it is not provided, undefined is used instead.

time_close.barData.bars.__@unscopables@73.findLastIndex

time_close.barData.bars.__@unscopables@73.findLastIndex: boolean

Returns the index of the last element in the array where predicate is true, and -1 otherwise.

predicate
findLastIndex calls predicate once for each element of the array, in descending order, until it finds one where predicate returns true. If such an element is found, findLastIndex immediately returns that element index. Otherwise, findLastIndex returns -1.
thisArg
If provided, it will be used as the this value for each invocation of predicate. If it is not provided, undefined is used instead.

time_close.barData.bars.__@unscopables@73.toSorted

time_close.barData.bars.__@unscopables@73.toSorted: boolean

Returns a copy of an array with its elements sorted.

compareFn
Function used to determine the order of the elements. It is expected to return a negative value if the first argument is less than the second argument, zero if they're equal, and a positive value otherwise. If omitted, the elements are sorted in ascending, ASCII character order. ``ts [11, 2, 22, 1].toSorted((a, b) => a - b) // [1, 2, 11, 22] ``

time_close.barData.bars.__@unscopables@73.toSpliced

time_close.barData.bars.__@unscopables@73.toSpliced: boolean

Copies an array and removes elements and, if necessary, inserts new elements in their place. Returns the copied array. Copies an array and removes elements while returning the remaining elements.

start
The zero-based location in the array from which to start removing elements.
deleteCount
The number of elements to remove.
items
Elements to insert into the copied array in place of the deleted elements.
start
The zero-based location in the array from which to start removing elements.
deleteCount
The number of elements to remove.

Returns A copy of the original array with the remaining elements.

time_close.barData.bars.__@unscopables@73.with

time_close.barData.bars.__@unscopables@73.with: boolean

Copies an array, then overwrites the value at the provided index with the given value. If the index is negative, then it replaces from the end of the array.

index
The index of the value to overwrite. If the index is negative, then it replaces from the end of the array.
value
The value to write into the copied array.

Returns The copied array with the updated value.

timeframe

The chart timeframe: its period and kind (timeframe.period, timeframe.isintraday...), from the chart context, and in_seconds(timeframe?), from_seconds(seconds), info(timeframe) to work with timeframe strings.

timeframe.in_seconds()

timeframe.in_seconds(tf?: string): number

Number of seconds in a timeframe. A month counts 2,628,003 seconds (365 / 12 days); a tick timeframe gives NaN. Without an argument, or with "", the chart timeframe.

tf
Timeframe string, e.g. "60", "1D", "W", "30S". Default: the chart timeframe.

Returns The number of seconds. Throws for a string that is not a timeframe ("1H").

const barMinutes = timeframe.in_seconds() / 60;
const dayLength = Math.max(1, Math.round(1440 / barMinutes));
plot(ta.sma(close, dayLength), "One-day average");

timeframe.from_seconds()

timeframe.from_seconds(seconds: number): string

The timeframe string of a number of seconds. When no timeframe lasts exactly that long, the next longer one is returned (45 gives "1"); when several do, the larger unit wins (604800 gives "1W"). From 365 days the result is "12M".

seconds
Duration in seconds.

Returns A timeframe string such as "60", "1D" or "1W".

const higher = timeframe.from_seconds(timeframe.in_seconds() * 4);
const higherClose = request.security("", higher, () => close);
plot(higherClose, "Close x4");

timeframe.info()

timeframe.info(timeframe: string): TimeframeInfo

Describes any timeframe string with the same fields as the chart values (period, multiplier, isintraday, isdaily...). Use it to test a timeframe chosen in the inputs.

timeframe
Timeframe string, e.g. "5", "60", "D", "1W", "30S".

Returns An object with period (always with its multiplier: "D" becomes "1D"), multiplier and the is* flags. Throws for a string that is not a timeframe.

const tf = input.timeframe("D", "Higher timeframe");
const isDayOrMore = timeframe.info(tf).isdwm;
plot(request.security("", tf, () => close), isDayOrMore ? "Daily+ close" : "Intraday close");

timeframe.change()

timeframe.change(tf: string): Series

Marks the bars that open a new period of another timeframe, e.g. the first bar of each day on an intraday chart. The first bar of the chart is 0. Follows the session and the holidays of the symbol.

tf
Timeframe of the periods, e.g. "D", "W", "240"; "" is the chart timeframe.

Returns Series of 1 on the first bar of each new period and 0 elsewhere.

const newDay = timeframe.change("D");
plotshape(newDay, "New day", { location: location.bottom, color: color.blue });

timeframe.period

timeframe.period: string

Chart timeframe with its multiplier: "1", "60", "1D", "1W", "30S". Throws when the app did not give it.

timeframe.main_period

timeframe.main_period: string

Timeframe of the chart the script runs on, e.g. "60" or "1D", also inside a request.security expression (where timeframe.period is the requested timeframe).

timeframe.multiplier

timeframe.multiplier: number

Number before the unit of the chart timeframe: 60 for "60", 1 for "1D", 4 for "4W".

timeframe.isdaily

timeframe.isdaily: boolean

True on a chart of days ("1D", "2D"...).

timeframe.isminutes

timeframe.isminutes: boolean

True on a chart of minutes (and hours: "60", "240").

timeframe.isdwm

timeframe.isdwm: boolean

True on a chart of days, weeks or months.

xloc

What the x coordinates of a drawing (label, line, box, polyline) are (xloc option).

xloc.bar_index

xloc.bar_index: "bar_index"

Bar indexes: 0 is the first bar, bar_index the current one (the default).

xloc.bar_time

xloc.bar_time: "bar_time"

UNIX times in milliseconds, such as time or time_close.

xloc.pane

xloc.pane: "pane"

Percents of the pane's width (0 left edge, 100 right edge): the drawing stays in place while the user scrolls and zooms.

yloc

Vertical placement of a label (label.new(..., { yloc })).

yloc.price

yloc.price: "price"

At the y value given to the label (the default).

yloc.abovebar

yloc.abovebar: "abovebar"

Above the high of the bar at the label's x; the y value is not used.

yloc.belowbar

yloc.belowbar: "belowbar"

Below the low of the bar at the label's x; the y value is not used.