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 });
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.
Series of the chart's bars: one value per bar. Combine them with the Series methods and pass them to the functions.
bar_indexbar_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 });
closeclose: 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");
highhigh: 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");
hl2hl2: Series
Median price of each bar, (high + low) / 2, as a Series.
plot(ta.sma(hl2, 10), "Median SMA");
hlc3hlc3: Series
Typical price of each bar, (high + low + close) / 3, as a Series.
plot(ta.sma(hlc3, 20), "Typical SMA");
hlcc4hlcc4: Series
Weighted close of each bar, (high + low + close + close) / 4, as a Series.
plot(ta.ema(hlcc4, 20), "Weighted close EMA");
last_bar_indexlast_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" });
lowlow: 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");
ohlc4ohlc4: Series
Average price of each bar, (open + high + low + close) / 4, as a Series.
plot(ohlc4, "OHLC average");
openopen: 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_tradingdaytime_tradingday: Series
00:00 UTC of the trading day of each bar, in ms.
timenowtimenow: Series
The current time in ms, the same on every bar of a run (ChartContext.now).
volumevolume: 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 });
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.
otherReturns 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.
otherReturns 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.
otherReturns 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.
otherReturns 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).
indexReturns 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.
otherReturns 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.
otherReturns 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.
trueValuefalseValueReturns 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.
otherReturns 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.
otherReturns 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.
otherReturns 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.
otherReturns 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.
otherReturns 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.
offsetclose, 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.
otherReturns 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.
exponentReturns 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.
otherReturns 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();
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.
conditiontitlemessageconst 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.
colorscolor.when() (usual colour on an na entry).optionstitle (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.
colorscolor.when() (no colour on an na entry).optionsoffset (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): numberdayofmonth(time: Series, timezone?: string): Series
The calendar field (year, month, day, hour...) of a time.
timetimezoneReturns 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).
timetime.timezoneReturns 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{ 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).
fnReturns 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").
textvariables{}.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): voidfill(a: PlotHandle, b: PlotHandle, color: ScriptFillColor, title?: string, ...rest: unknown[]): voidfill(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.
aplot() / hline() returned).ba.optionscolor.when()), title, editable. Default: {}.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).
aplot() / hline() returned).ba.colorcolor.when(); na (null) leaves a bar unfilled.titleresteditable (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.
aplot() returned).btop_valuebottom_valuetop_colorbottom_colortitleresteditable (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): Seriesfixnan(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.
sourceReturns 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.
sourcecolor.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.
textsma(close, 20) or rsi(close, length) > 70.variables{}.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.
objReturns 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): numberhour(time: Series, timezone?: string): Series
The calendar field (year, month, day, hour...) of a time.
timetimezoneReturns 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).
timetime.timezoneReturns 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.
titleoptions{} (own pane).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).
timec.time in eachBar().sessiontimezoneReturns 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): numberminute(time: Series, timezone?: string): Series
The calendar field (year, month, day, hour...) of a time.
timetimezoneReturns 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).
timetime.timezoneReturns Series of the calendar field of each time.
plot(minute(time), "Minute");month()month(time: number, timezone?: string): numbermonth(time: Series, timezone?: string): Series
The calendar field (year, month, day, hour...) of a time.
timetimezoneReturns 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).
timetime.timezoneReturns 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): Seriesna(x: unknown): boolean
Tells, bar by bar, whether a Series is na (NaN or +/-Infinity): a Series of 1 where it is, 0 elsewhere.
xReturns 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.
xReturns 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): Seriesnz<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.
sourcereplacementReturns 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.
sourcereplacementsource 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.
initialReturns 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).
seriestitleoptions{} (green up, red down).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.
openhighlowclosetitleoptions{}.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.
openhighlowclosetitleoptions{}.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.
conditionlocation.absolute,
its value is the price of the character.titleoptionschar), place (location.*), colour, text, size (size.*), offset... Default: {}
(a star above the bar).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.
conditionlocation.absolute, its
value is the price of the shape.titleoptionsshape.*), place (location.*), colour, text, size (size.*), offset... Default: {}
(a cross above the bar).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.
objnull / 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): numbersecond(time: Series, timezone?: string): Series
The calendar field (year, month, day, hour...) of a time.
timetimezoneReturns 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).
timetime.timezoneReturns 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().
valuesReturns Series of the values.
const ranges = [];
eachBar((c) => { ranges.push(c.high - c.low); });
plot(seriesOf(ranges), "Range");
timestamp()timestamp(dateString: string): numbertimestamp(timezone: string, year: number, month: number, day: number, hour?: number, minute?: number, second?: number): numbertimestamp(year: number, month: number, day: number, hour?: number, minute?: number, second?: number): number
The UNIX time (milliseconds) of a date written as text.
dateStringReturns 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.
timezoneyearmonthdayhourminutesecondReturns 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.
yearmonthdayhourminutesecondReturns 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.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.
initialReturns 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): numberweekofyear(time: Series, timezone?: string): Series
The calendar field (year, month, day, hour...) of a time.
timetimezoneReturns 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).
timetime.timezoneReturns Series of the calendar field of each time.
plot(weekofyear(time), "Week");year()year(time: number, timezone?: string): numberyear(time: Series, timezone?: string): Series
The calendar field (year, month, day, hour...) of a time.
timetimezoneReturns 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).
timetime.timezoneReturns 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)));boxbox: 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_FUNCTIONSFORMULA_FUNCTIONS: Record<string, FormulaFunction>
The functions a formula can call (lowercase names; a formula may write them in any case).
labellabel: 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.
lineline: 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.
linefilllinefill: 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_ENTRIESMAX_LOG_ENTRIES: 10000
The most messages a run keeps: the newest ones.
polylinepolyline: 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.
adjustmentPrice adjustment of a ticker. Kept for compatibility: no function of the library reads it yet.
adjustment.noneadjustment.none: "none"
Prices not adjusted.
adjustment.splitsadjustment.splits: "splits"
Prices adjusted for splits.
adjustment.dividendsadjustment.dividends: "dividends"
Prices adjusted for dividends.
alertalert()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.
messageundefined makes no call.freqalert.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_allalert.freq_all: "all"
Frequency for alert(): the alert fires on every call, several times per bar if need be.
alert.freq_once_per_baralert.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_closealert.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.
barmergeOptions of request.security: gaps (barmerge.gaps_on / gaps_off) and lookahead (barmerge.lookahead_on / lookahead_off).
barmerge.gaps_onbarmerge.gaps_on: "gaps_on"
A value shows only on the bar where it appears; the bars between are na.
barmerge.gaps_offbarmerge.gaps_off: "gaps_off"
A value stays on every bar until the next one (the default).
barmerge.lookahead_onbarmerge.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_offbarmerge.lookahead_off: "lookahead_off"
A period's value shows from the chart bar that completes the period (the default, no future values).
barstateThe 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.isfirstbarstate.isfirst: Series
1 on the first bar of the data.
barstate.islastbarstate.islast: Series
1 on the last bar of the chart.
barstate.isconfirmedbarstate.isconfirmed: Series
1 on closed bars: every bar but the last, and the last bar once the app says it has closed.
barstate.isrealtimebarstate.isrealtime: Series
1 on the last bar when it receives live updates.
barstate.ishistorybarstate.ishistory: Series
1 on every bar but a live last bar.
barstate.isnewbarstate.isnew: Series
1 on every history bar, and on a live last bar at its first update.
barstate.islastconfirmedhistorybarstate.islastconfirmedhistory: Series
1 on the last closed history bar: the last bar when it is closed and not live, else the bar before it.
calcPlain-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.
sourceclose, or a number.lengthkindta.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.
abReturns 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.
abReturns 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.
abReturns 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.
abReturns 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.
abReturns 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.
valuelowLimithighLimitReturns 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.
sourcebarsReturns 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.
sourcebarsReturns 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.
sourcebarsReturns 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.
sourcehigh, or a number.lengthReturns 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.
sourcelow, or a number.lengthReturns 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).
sourcebarsReturns 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).
sourcebarsReturns 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.
sourcelengthReturns 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.
conditionwhenTruewhenFalseReturns 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.
conditionsReturns 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.
conditionsReturns 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));
chartThe 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_colorchart.fg_color: string
Foreground (text) colour of the chart, e.g. "#DBDBDB" on a dark chart.
chart.bg_colorchart.bg_color: string
Background colour of the chart, e.g. "#0F0F0F" on a dark chart.
chart.left_visible_bar_timechart.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_timechart.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_standardchart.is_standard: boolean
True when the chart shows standard bars or candles (none of the types below).
chart.is_heikinashichart.is_heikinashi: boolean
True on a Heikin Ashi chart.
chart.is_renkochart.is_renko: boolean
True on a Renko chart.
chart.is_kagichart.is_kagi: boolean
True on a Kagi chart.
chart.is_linebreakchart.is_linebreak: boolean
True on a Line break chart.
chart.is_pnfchart.is_pnf: boolean
True on a Point and figure chart.
chart.is_rangechart.is_range: boolean
True on a Range chart.
chart.pointChart 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.
timeindexpriceReturns 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).
timeindexpriceReturns 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.
timepriceReturns 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.
indexpriceReturns 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.
pointReturns 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.
priceReturns 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)]);
});
colorColours: 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.
redgreenbluetranspNaN 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.
hextranspReturns 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.
baseColorcolor.red, a "#RRGGBB" or "rgb(...)" text.transpNaN 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.
baseColortranspReturns 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).
camountReturns 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().
condclose.gt(open).colorTruecolorFalseReturns 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.
condclose.gt(open).colorTruecolorFalseundefined).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): stringcolor.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.
valuebottom_valuebottom_color.top_valuetop_color.bottom_colorundefined) counts as fully transparent.top_colorundefined) 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.
valuebottom_valuebottom_color: a Series or a number.top_valuetop_color: a Series or a number.bottom_colortop_colorReturns 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.
clrcolor.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.
clrcolor.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.
clrcolor.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.
clrReturns The transparency, 0-100.
const lighter = color.new(color.blue, Math.min(color.t(color.blue) + 50, 100));
color.aquacolor.aqua: "#00BCD4"
Aqua, "#00BCD4".
color.blackcolor.black: "#363A45"
Black (a dark grey-blue), "#363A45".
color.bluecolor.blue: "#2962FF"
Blue, "#2962FF": the default colour of plot().
color.fuchsiacolor.fuchsia: "#E040FB"
Fuchsia, "#E040FB".
color.graycolor.gray: "#787B86"
Gray, "#787B86".
color.greencolor.green: "#4CAF50"
Green, "#4CAF50".
color.limecolor.lime: "#00E676"
Lime (a bright green), "#00E676".
color.marooncolor.maroon: "#880E4F"
Maroon, "#880E4F".
color.navycolor.navy: "#311B92"
Navy, "#311B92".
color.olivecolor.olive: "#808000"
Olive, "#808000".
color.orangecolor.orange: "#FF9800"
Orange, "#FF9800".
color.purplecolor.purple: "#9C27B0"
Purple, "#9C27B0".
color.redcolor.red: "#F23645"
Red, "#F23645".
color.silvercolor.silver: "#B2B5BE"
Silver (a light grey), "#B2B5BE".
color.tealcolor.teal: "#089981"
Teal, "#089981".
color.whitecolor.white: "#FFFFFF"
White, "#FFFFFF".
color.yellowcolor.yellow: "#FDD835"
Yellow, "#FDD835".
compareComparisons 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).
abReturns 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 !==.
abReturns 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).
abReturns 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).
abReturns 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).
abReturns 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).
abReturns True when b - a <= 1e-10.
const notBelow = eachBar((c) => (compare.ge(c.close, c.open) ? 1 : 0));
compare.EPSILONcompare.EPSILON: 1e-10
Tolerance of the comparisons: two numbers closer than 1e-10 are equal.
currencyCurrency 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.AEDcurrency.AED: "AED"
United Arab Emirates dirham.
currency.ARScurrency.ARS: "ARS"
Argentine peso.
currency.AUDcurrency.AUD: "AUD"
Australian dollar.
currency.BDTcurrency.BDT: "BDT"
Bangladeshi taka.
currency.BHDcurrency.BHD: "BHD"
Bahraini dinar.
currency.BRLcurrency.BRL: "BRL"
Brazilian real.
currency.BTCcurrency.BTC: "BTC"
Bitcoin.
currency.CADcurrency.CAD: "CAD"
Canadian dollar.
currency.CHFcurrency.CHF: "CHF"
Swiss franc.
currency.CLPcurrency.CLP: "CLP"
Chilean peso.
currency.CNYcurrency.CNY: "CNY"
Chinese yuan.
currency.COPcurrency.COP: "COP"
Colombian peso.
currency.CZKcurrency.CZK: "CZK"
Czech koruna.
currency.DKKcurrency.DKK: "DKK"
Danish krone.
currency.EGPcurrency.EGP: "EGP"
Egyptian pound.
currency.ETHcurrency.ETH: "ETH"
Ether.
currency.EURcurrency.EUR: "EUR"
Euro.
currency.GBPcurrency.GBP: "GBP"
Pound sterling.
currency.GELcurrency.GEL: "GEL"
Georgian lari.
currency.HKDcurrency.HKD: "HKD"
Hong Kong dollar.
currency.HUFcurrency.HUF: "HUF"
Hungarian forint.
currency.IDRcurrency.IDR: "IDR"
Indonesian rupiah.
currency.ILScurrency.ILS: "ILS"
Israeli new shekel.
currency.INRcurrency.INR: "INR"
Indian rupee.
currency.ISKcurrency.ISK: "ISK"
Icelandic krona.
currency.JPYcurrency.JPY: "JPY"
Japanese yen.
currency.KEScurrency.KES: "KES"
Kenyan shilling.
currency.KRWcurrency.KRW: "KRW"
South Korean won.
currency.KWDcurrency.KWD: "KWD"
Kuwaiti dinar.
currency.LKRcurrency.LKR: "LKR"
Sri Lankan rupee.
currency.MADcurrency.MAD: "MAD"
Moroccan dirham.
currency.MXNcurrency.MXN: "MXN"
Mexican peso.
currency.MYRcurrency.MYR: "MYR"
Malaysian ringgit.
currency.NGNcurrency.NGN: "NGN"
Nigerian naira.
currency.NOKcurrency.NOK: "NOK"
Norwegian krone.
currency.NZDcurrency.NZD: "NZD"
New Zealand dollar.
currency.PENcurrency.PEN: "PEN"
Peruvian sol.
currency.PHPcurrency.PHP: "PHP"
Philippine peso.
currency.PKRcurrency.PKR: "PKR"
Pakistani rupee.
currency.PLNcurrency.PLN: "PLN"
Polish zloty.
currency.QARcurrency.QAR: "QAR"
Qatari riyal.
currency.RONcurrency.RON: "RON"
Romanian leu.
currency.RSDcurrency.RSD: "RSD"
Serbian dinar.
currency.RUBcurrency.RUB: "RUB"
Russian ruble.
currency.SARcurrency.SAR: "SAR"
Saudi riyal.
currency.SEKcurrency.SEK: "SEK"
Swedish krona.
currency.SGDcurrency.SGD: "SGD"
Singapore dollar.
currency.THBcurrency.THB: "THB"
Thai baht.
currency.TNDcurrency.TND: "TND"
Tunisian dinar.
currency.TRYcurrency.TRY: "TRY"
Turkish lira.
currency.TWDcurrency.TWD: "TWD"
New Taiwan dollar.
currency.USDcurrency.USD: "USD"
United States dollar.
currency.USDTcurrency.USDT: "USDT"
Tether (USDT).
currency.VEScurrency.VES: "VES"
Venezuelan bolivar.
currency.VNDcurrency.VND: "VND"
Vietnamese dong.
currency.ZARcurrency.ZAR: "ZAR"
South African rand.
currency.NONEcurrency.NONE: "NONE"
No currency (na).
dayofweekdayofweek()dayofweek(time: number, timezone?: string): numberdayofweek(time: Series, timezone?: string): Series
The calendar field (year, month, day, hour...) of a time.
timetimezoneReturns 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).
timetime.timezoneReturns Series of the calendar field of each time.
const monday = dayofweek(time).eq(dayofweek.monday);
bgcolor(color.when(monday, color.new(color.gray, 90)));dayofweek.sundaydayofweek.sunday: 1
Sunday (1).
dayofweek.mondaydayofweek.monday: 2
Monday (2).
dayofweek.tuesdaydayofweek.tuesday: 3
Tuesday (3).
dayofweek.wednesdaydayofweek.wednesday: 4
Wednesday (4).
dayofweek.thursdaydayofweek.thursday: 5
Thursday (5).
dayofweek.fridaydayofweek.friday: 6
Friday (6).
dayofweek.saturdaydayofweek.saturday: 7
Saturday (7).
DEFAULT_CANDLE_COLORSColours 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_CANDLE_COLORS.colorDEFAULT_CANDLE_COLORS.color: "#2962FF"
Body colour (and the colour of plotbar() bars).
DEFAULT_CANDLE_COLORS.wickColorDEFAULT_CANDLE_COLORS.wickColor: "#737375"
Wick colour.
DEFAULT_CANDLE_COLORS.borderColorDEFAULT_CANDLE_COLORS.borderColor: "#000000"
Border colour.
DEFAULT_OUTPUT_TITLESThe 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_OUTPUT_TITLES.plotDEFAULT_OUTPUT_TITLES.plot: "Plot"
Title of a plot() without one.
DEFAULT_OUTPUT_TITLES.hlineDEFAULT_OUTPUT_TITLES.hline: "Level"
Title of an hline() without one.
DEFAULT_OUTPUT_TITLES.plotFillDEFAULT_OUTPUT_TITLES.plotFill: "Plots Background"
Title of a fill() between two plots without one.
DEFAULT_OUTPUT_TITLES.hlineFillDEFAULT_OUTPUT_TITLES.hlineFill: "Hlines Background"
Title of a fill() between two hlines without one.
DEFAULT_OUTPUT_TITLES.shapeDEFAULT_OUTPUT_TITLES.shape: "Shapes"
Title of a plotshape() without one.
DEFAULT_OUTPUT_TITLES.charDEFAULT_OUTPUT_TITLES.char: "Chars"
Title of a plotchar() without one.
DEFAULT_OUTPUT_TITLES.arrowDEFAULT_OUTPUT_TITLES.arrow: "Arrows"
Title of a plotarrow() without one.
DEFAULT_OUTPUT_TITLES.bgcolorDEFAULT_OUTPUT_TITLES.bgcolor: "Background Color"
Title of a bgcolor() without one.
DEFAULT_OUTPUT_TITLES.barcolorDEFAULT_OUTPUT_TITLES.barcolor: "Bar Color"
Title of a barcolor() without one.
DEFAULT_OUTPUT_TITLES.candleDEFAULT_OUTPUT_TITLES.candle: "PlotCandle"
Title of a plotcandle() without one.
DEFAULT_OUTPUT_TITLES.barDEFAULT_OUTPUT_TITLES.bar: "PlotBar"
Title of a plotbar() without one.
DEFAULT_PALETTEThe colours given in turn to plots without a colour when ScriptOptions.palette is true.
DEFAULT_PALETTE.toString()DEFAULT_PALETTE.toString(): string
Returns a string representation of an array.
DEFAULT_PALETTE.toLocaleString()DEFAULT_PALETTE.toLocaleString(): stringDEFAULT_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.
itemsDEFAULT_PALETTE.join()DEFAULT_PALETTE.join(separator?: string): string
Adds all the elements of an array separated by the specified separator string.
separatorDEFAULT_PALETTE.slice()DEFAULT_PALETTE.slice(start?: number, end?: number): string[]
Returns a section of an array.
startendDEFAULT_PALETTE.indexOf()DEFAULT_PALETTE.indexOf(searchElement: string, fromIndex?: number): number
Returns the index of the first occurrence of a value in an array.
searchElementfromIndexDEFAULT_PALETTE.lastIndexOf()DEFAULT_PALETTE.lastIndexOf(searchElement: string, fromIndex?: number): number
Returns the index of the last occurrence of a specified value in an array.
searchElementfromIndexDEFAULT_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.
predicatethisArgDEFAULT_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.
predicatethisArgDEFAULT_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.
callbackfnthisArgDEFAULT_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.
callbackfnthisArgDEFAULT_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.
predicatethisArgDEFAULT_PALETTE.reduce()DEFAULT_PALETTE.reduce(callbackfn: (previousValue: string, currentValue: string, currentIndex: number, array: readonly string[]) => string): stringDEFAULT_PALETTE.reduce(callbackfn: (previousValue: string, currentValue: string, currentIndex: number, array: readonly string[]) => string, initialValue: string): stringDEFAULT_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.
callbackfninitialValueCalls 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.
callbackfninitialValuecallbackfninitialValueDEFAULT_PALETTE.reduceRight()DEFAULT_PALETTE.reduceRight(callbackfn: (previousValue: string, currentValue: string, currentIndex: number, array: readonly string[]) => string): stringDEFAULT_PALETTE.reduceRight(callbackfn: (previousValue: string, currentValue: string, currentIndex: number, array: readonly string[]) => string, initialValue: string): stringDEFAULT_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.
callbackfninitialValueCalls 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.
callbackfninitialValuecallbackfninitialValueDEFAULT_PALETTE.find()DEFAULT_PALETTE.find<S extends string>(predicate: (value: string, index: number, obj: readonly string[]) => value is S, thisArg?: any): SDEFAULT_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.
predicatethisArgDEFAULT_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.
predicatethisArgDEFAULT_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.values()DEFAULT_PALETTE.values(): ArrayIterator<string>
Returns an iterable of values 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.
searchElementfromIndexDEFAULT_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.
callbackthisArgDEFAULT_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.
depthDEFAULT_PALETTE.at()DEFAULT_PALETTE.at(index: number): string
Returns the item located at the specified index.
indexDEFAULT_PALETTE.findLast()DEFAULT_PALETTE.findLast<S extends string>(predicate: (value: string, index: number, array: readonly string[]) => value is S, thisArg?: any): SDEFAULT_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.
predicatethisArgDEFAULT_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.
predicatethisArgDEFAULT_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.
compareFnts
[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.
startdeleteCountitemsReturns A copy of the original array with the remaining elements.
Copies an array and removes elements while returning the remaining elements.
startdeleteCountReturns 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
indexvalueReturns A copy of the original array with the inserted value.
DEFAULT_PALETTE.__@iterator@71()DEFAULT_PALETTE.__@iterator@71(): ArrayIterator<string>
Iterator of values in the array.
DEFAULT_PALETTE.lengthDEFAULT_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@73Is an object whose properties have the value 'true' when they will be absent when used in a 'with' statement.
DEFAULT_PALETTE.__@unscopables@73.lengthDEFAULT_PALETTE.__@unscopables@73.length: boolean
Gets the length of the array. This is a number one higher than the highest element defined in an array.
DEFAULT_PALETTE.__@unscopables@73.toStringDEFAULT_PALETTE.__@unscopables@73.toString: boolean
Returns a string representation of an array.
DEFAULT_PALETTE.__@unscopables@73.toLocaleStringDEFAULT_PALETTE.__@unscopables@73.toLocaleString: boolean
Returns a string representation of an array. The elements are converted to string using their toLocaleString methods.
DEFAULT_PALETTE.__@unscopables@73.concatDEFAULT_PALETTE.__@unscopables@73.concat: boolean
Combines two or more arrays.
itemsitemsDEFAULT_PALETTE.__@unscopables@73.joinDEFAULT_PALETTE.__@unscopables@73.join: boolean
Adds all the elements of an array separated by the specified separator string.
separatorDEFAULT_PALETTE.__@unscopables@73.sliceDEFAULT_PALETTE.__@unscopables@73.slice: boolean
Returns a section of an array.
startendDEFAULT_PALETTE.__@unscopables@73.indexOfDEFAULT_PALETTE.__@unscopables@73.indexOf: boolean
Returns the index of the first occurrence of a value in an array.
searchElementfromIndexDEFAULT_PALETTE.__@unscopables@73.lastIndexOfDEFAULT_PALETTE.__@unscopables@73.lastIndexOf: boolean
Returns the index of the last occurrence of a specified value in an array.
searchElementfromIndexDEFAULT_PALETTE.__@unscopables@73.everyDEFAULT_PALETTE.__@unscopables@73.every: boolean
Determines whether all the members of an array satisfy the specified test.
predicatethisArgpredicatethisArgDEFAULT_PALETTE.__@unscopables@73.someDEFAULT_PALETTE.__@unscopables@73.some: boolean
Determines whether the specified callback function returns true for any element of an array.
predicatethisArgDEFAULT_PALETTE.__@unscopables@73.forEachDEFAULT_PALETTE.__@unscopables@73.forEach: boolean
Performs the specified action for each element in an array.
callbackfnthisArgDEFAULT_PALETTE.__@unscopables@73.mapDEFAULT_PALETTE.__@unscopables@73.map: boolean
Calls a defined callback function on each element of an array, and returns an array that contains the results.
callbackfnthisArgDEFAULT_PALETTE.__@unscopables@73.filterDEFAULT_PALETTE.__@unscopables@73.filter: boolean
Returns the elements of an array that meet the condition specified in a callback function.
predicatethisArgpredicatethisArgDEFAULT_PALETTE.__@unscopables@73.reduceDEFAULT_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.
callbackfninitialValuecallbackfninitialValueDEFAULT_PALETTE.__@unscopables@73.reduceRightDEFAULT_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.
callbackfninitialValuecallbackfninitialValueDEFAULT_PALETTE.__@unscopables@73.findDEFAULT_PALETTE.__@unscopables@73.find: boolean
Returns the value of the first element in the array where predicate is true, and undefined otherwise.
predicatethisArgDEFAULT_PALETTE.__@unscopables@73.findIndexDEFAULT_PALETTE.__@unscopables@73.findIndex: boolean
Returns the index of the first element in the array where predicate is true, and -1 otherwise.
predicatethisArgDEFAULT_PALETTE.__@unscopables@73.entriesDEFAULT_PALETTE.__@unscopables@73.entries: boolean
Returns an iterable of key, value pairs for every entry in the array
DEFAULT_PALETTE.__@unscopables@73.keysDEFAULT_PALETTE.__@unscopables@73.keys: boolean
Returns an iterable of keys in the array
DEFAULT_PALETTE.__@unscopables@73.valuesDEFAULT_PALETTE.__@unscopables@73.values: boolean
Returns an iterable of values in the array
DEFAULT_PALETTE.__@unscopables@73.includesDEFAULT_PALETTE.__@unscopables@73.includes: boolean
Determines whether an array includes a certain element, returning true or false as appropriate.
searchElementfromIndexDEFAULT_PALETTE.__@unscopables@73.flatMapDEFAULT_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.
callbackthisArgDEFAULT_PALETTE.__@unscopables@73.flatDEFAULT_PALETTE.__@unscopables@73.flat: boolean
Returns a new array with all sub-array elements concatenated into it recursively up to the specified depth.
depthDEFAULT_PALETTE.__@unscopables@73.atDEFAULT_PALETTE.__@unscopables@73.at: boolean
Returns the item located at the specified index.
indexDEFAULT_PALETTE.__@unscopables@73.findLastDEFAULT_PALETTE.__@unscopables@73.findLast: boolean
Returns the value of the last element in the array where predicate is true, and undefined otherwise.
predicatethisArgDEFAULT_PALETTE.__@unscopables@73.findLastIndexDEFAULT_PALETTE.__@unscopables@73.findLastIndex: boolean
Returns the index of the last element in the array where predicate is true, and -1 otherwise.
predicatethisArgDEFAULT_PALETTE.__@unscopables@73.toReversedDEFAULT_PALETTE.__@unscopables@73.toReversed: boolean
Copies the array and returns the copied array with all of its elements reversed.
DEFAULT_PALETTE.__@unscopables@73.toSortedDEFAULT_PALETTE.__@unscopables@73.toSorted: boolean
Copies and sorts the array.
compareFnts
[11, 2, 22, 1].toSorted((a, b) => a - b) // [1, 2, 11, 22]
``DEFAULT_PALETTE.__@unscopables@73.toSplicedDEFAULT_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.
startdeleteCountitemsstartdeleteCountReturns A copy of the original array with the remaining elements.
DEFAULT_PALETTE.__@unscopables@73.withDEFAULT_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
indexvalueReturns A copy of the original array with the inserted value.
DEFAULT_PALETTE.__@unscopables@73.__@iterator@71DEFAULT_PALETTE.__@unscopables@73.__@iterator@71: boolean
Iterator of values in the array.
DEFAULT_PALETTE.__@unscopables@73.__@unscopables@73DEFAULT_PALETTE.__@unscopables@73.__@unscopables@73: boolean
Is an object whose properties have the value 'true' when they will be absent when used in a 'with' statement.
displayWhere a plot or an input value is shown (display option).
display.nonedisplay.none: "none"
Not shown anywhere; the values still exist for alerts and other scripts.
display.alldisplay.all: "all"
Shown everywhere: on the pane, in the status line and in the data window.
display.data_windowdisplay.data_window: "data_window"
Shown only in the data window.
display.status_linedisplay.status_line: "status_line"
Shown only in the status line of the script.
display.panedisplay.pane: "pane"
Drawn only on the pane, not in the status line or the data window.
dividendsDividends: the fields of request.dividends (dividends.gross, dividends.net) and the next announced dividend of the chart symbol.
dividends.netdividends.net: "net"
The dividend after taxes (the default field of request.dividends).
dividends.grossdividends.gross: "gross"
The dividend before taxes.
dividends.future_amountdividends.future_amount: number
Amount of the next announced dividend (net); na when none is announced.
dividends.future_ex_datedividends.future_ex_date: number
Ex-date of the next announced dividend (UNIX time in ms); na when none is announced.
dividends.future_pay_datedividends.future_pay_date: number
Payment date of the next announced dividend (UNIX time in ms); na when none is announced.
earningsEarnings: the fields of request.earnings (earnings.actual, earnings.estimate...) and the next earnings release of the chart symbol.
earnings.actualearnings.actual: "actual"
The reported earnings per share (the default field of request.earnings).
earnings.estimateearnings.estimate: "estimate"
The analysts' estimate of the earnings per share.
earnings.standardizedearnings.standardized: "standardized"
The standardized earnings per share.
earnings.future_epsearnings.future_eps: number
Estimated earnings per share of the next release; na when none is announced.
earnings.future_revenueearnings.future_revenue: number
Estimated revenue of the next release; na when none is announced.
earnings.future_timeearnings.future_time: number
Time of the next release (UNIX time in ms); na when none is announced.
earnings.future_period_end_timeearnings.future_period_end_time: number
End of the fiscal period of the next release (UNIX time in ms); na when none is announced.
extendHow far a line (or a box's top and bottom) is drawn past its two points (extend option).
extend.noneextend.none: "none"
Not extended: drawn between its two points only (the default).
extend.leftextend.left: "left"
Extended to the left edge of the chart, past the first point.
extend.rightextend.right: "right"
Extended to the right edge of the chart, past the second point.
extend.bothextend.both: "both"
Extended in both directions.
fontFont families of labels, boxes and table cells (text_font_family option).
font.family_defaultfont.family_default: "default"
The default font of the chart.
font.family_monospacefont.family_monospace: "monospace"
A monospace font: every character has the same width.
formatNumber formats: the format option of indicator() and the format of str.tostring().
format.inheritformat.inherit: "inherit"
The same format as the chart symbol.
format.priceformat.price: "price"
A price, with the precision of the script or of the symbol.
format.volumeformat.volume: "volume"
A volume, shortened with K, M, B, T (12345 shows as "12.345K").
format.percentformat.percent: "percent"
A percentage: two decimals and a "%" sign; the value is not multiplied by 100.
format.mintickformat.mintick: "mintick"
Rounded to the tick size of the symbol (syminfo.mintick).
hlinehline()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).
pricetitleoptions{} (a dashed line).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));
hline.style_solidhline.style_solid: "solid"
Line style: solid.
hline.style_dottedhline.style_dotted: "dotted"
Line style: dotted.
hline.style_dashedhline.style_dashed: "dashed"
Line style: dashed (the default).
inputScript 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{ defval, title, minval... }).titletitle in them. Default: none (id input_int).optsminval, maxval, step, options (a choice list) and the common input options.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{ defval, title, minval... }).titletitle in them. Default: none (id input_float).optsminval, maxval, step, options (a choice list) and the common input options.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{ defval, title... }).titletitle in them. Default: none (id input_bool).optsgroup, inline, tooltip, confirm, display, active, id).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.
defvaloptions when they are given), or every argument by name.titletitle in them. Default: none (id input_string).optsoptions (a choice list) and the common input options.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.
defvaltitletitle in them. Default: none (id input_text_area).optsReturns 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.
defvalcolor.blue, "#2962FF", color.new(...)), or every argument by name.titletitle in them. Default: none (id input_color).optsReturns 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"close") or as the built-in Series (close), or every argument by
name. Default: "close".titletitle in them. Default: none (id input_source).optsReturns 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"60" (60 minutes), "D", "W", "M"...; "" is the chart's timeframe.
Or every argument by name.titletitle in them. Default: none (id input_timeframe).optsoptions (a choice list of timeframes) and the common input options.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"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.titletitle in them. Default: none (id input_session).optsoptions (a choice list of sessions) and the common input options.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"EXCHANGE:TICKER" ("NASDAQ:MSFT"), or every argument by name.titletitle in them. Default: none (id input_symbol).optsoptions (a choice list of symbols) and the common input options.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.
defvaltitletitle in them. Default: none (id input_float).optsReturns 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.
defvalMaType.sma), or every argument by name. It must be one of options.titletitle in them. Default: none (id input_enum).optsoptions (only these fields of the enum) and the common input options.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.
defvaltimestamp(), or every argument by name.titletitle in them. Default: none (id input_time).optsReturns 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)));
locationWhere plotshape() and plotchar() draw their marker (location option).
location.abovebarlocation.abovebar: "abovebar"
Above the high of the bar (the default of plotshape() and plotchar()).
location.belowbarlocation.belowbar: "belowbar"
Below the low of the bar.
location.toplocation.top: "top"
At the top edge of the pane.
location.bottomlocation.bottom: "bottom"
At the bottom edge of the pane.
location.absolutelocation.absolute: "absolute"
At the value of the series itself, read as a price (bars where it is na or 0 get no marker).
logMessages 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{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.argseachBar((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{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.argseachBar((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{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.argseachBar((c) => {
if (c.high < c.low) log.error("High below low on bar {0}", c.i);
});
mathMath 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): Seriesmath.abs(value: number): number
Returns the absolute value of a number.
valueReturns 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): Seriesmath.ceil(value: number): number
Returns the smallest integer greater than or equal to a given number (rounds up).
valueReturns 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): Seriesmath.floor(value: number): number
Returns the largest integer less than or equal to a given number (rounds down).
valueReturns 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): Seriesmath.round(value: number, precision?: number): number
Returns the value rounded to the nearest integer or to a specified precision.
valueprecisionReturns 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.
value1 / 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.
valuesReturns 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.
valuesReturns 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.
valuesReturns 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>): Seriesmath.sum(source: series_float, length: number | Series | ArrayLike<number>): series_float
Returns the sum of values over a sliding window.
sourcelengthReturns 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): Seriesmath.sqrt(value: number): number
Returns the square root of a number.
valueReturns 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): Seriesmath.pow(base: number, exponent: Series): Seriesmath.pow(base: Series, exponent: Series): Seriesmath.pow(base: number, exponent: number): number
Returns base raised to the power of exponent.
baseexponentReturns 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): Seriesmath.exp(value: number): number
Returns e (Euler's number) raised to the power of value.
valueReturns 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): Seriesmath.log(value: number): number
Returns the natural logarithm (base e) of a number.
valueReturns 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): Seriesmath.log10(value: number): number
Returns the base-10 logarithm of a number.
valueReturns 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): Seriesmath.sin(value: number): number
Returns the sine of an angle in radians.
valueReturns 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): Seriesmath.cos(value: number): number
Returns the cosine of an angle in radians.
valueReturns 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): Seriesmath.tan(value: number): number
Returns the tangent of an angle in radians.
valueReturns 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): Seriesmath.asin(value: number): number
Returns the arcsine (inverse sine) of a number.
valueReturns 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): Seriesmath.acos(value: number): number
Returns the arccosine (inverse cosine) of a number.
valueReturns 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): Seriesmath.atan(value: number): number
Returns the arctangent (inverse tangent) of a number.
valueReturns 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): Seriesmath.toradians(degrees: number): number
Converts an angle from degrees to radians.
degreesReturns 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): Seriesmath.todegrees(radians: number): number
Converts an angle from radians to degrees.
radiansReturns 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).
seedReturns 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.
minmaxseedjava.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): Seriesmath.sign(value: number): number
Returns the sign of a number.
valueReturns 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): Seriesmath.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).
numberminticksyminfo.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.pimath.pi: number
Pi, the ratio of a circle's circumference to its diameter: 3.141592653589793.
math.emath.e: number
Euler's number e, the base of natural logarithms (math.log): 2.718281828459045.
math.phimath.phi: 1.618033988749895
The golden ratio: 1.618033988749895.
math.rphimath.rphi: 0.6180339887498948
The reciprocal of the golden ratio (1 / phi): 0.6180339887498948.
orderSort order of array.sort(), array.sort_indices() and matrix.sort().
order.ascendingorder.ascending: "ascending"
Smallest value first (the default).
order.descendingorder.descending: "descending"
Largest value first.
plotplot()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.
sourcetitleoptions{} (a blue line).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_lineplot.style_line: "line"
Style: a line through every value; na values are bridged.
plot.style_linebrplot.style_linebr: "linebr"
Style: a line with a gap where the value is na.
plot.style_steplineplot.style_stepline: "stepline"
Style: steps (horizontal then vertical moves); na values are bridged.
plot.style_steplinebrplot.style_steplinebr: "steplinebr"
Style: steps with a gap where the value is na.
plot.style_stepline_diamondplot.style_stepline_diamond: "stepline_diamond"
Style: steps with a diamond on each change.
plot.style_histogramplot.style_histogram: "histogram"
Style: a thin bar from the base line (histbase, default 0) to each value.
plot.style_columnsplot.style_columns: "columns"
Style: a wide column from the base line to each value.
plot.style_areaplot.style_area: "area"
Style: a line with the area down to the base line filled.
plot.style_areabrplot.style_areabr: "areabr"
Style: a filled area with a gap where the value is na.
plot.style_circlesplot.style_circles: "circles"
Style: a dot on each value.
plot.style_crossplot.style_cross: "cross"
Style: a cross on each value.
plot.linestyle_solidplot.linestyle_solid: "solid"
Line style: solid.
plot.linestyle_dottedplot.linestyle_dotted: "dotted"
Line style: dotted.
plot.linestyle_dashedplot.linestyle_dashed: "dashed"
Line style: dashed.
positionWhere a table sits in the pane: the first argument of table.new() and of table.set_position() (table.new(position.top_right, 2, 3)).
position.top_leftposition.top_left: "top_left"
The top-left corner of the pane.
position.top_centerposition.top_center: "top_center"
The middle of the top edge.
position.top_rightposition.top_right: "top_right"
The top-right corner of the pane.
position.middle_leftposition.middle_left: "middle_left"
The middle of the left edge.
position.middle_centerposition.middle_center: "middle_center"
The centre of the pane.
position.middle_rightposition.middle_right: "middle_right"
The middle of the right edge.
position.bottom_leftposition.bottom_left: "bottom_left"
The bottom-left corner of the pane.
position.bottom_centerposition.bottom_center: "bottom_center"
The middle of the bottom edge.
position.bottom_rightposition.bottom_right: "bottom_right"
The bottom-right corner of the pane.
requestData 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[] : Seriesrequest.security<T extends SecurityValue>(symbol: string, timeframe: string, expression: () => T, args: SecurityArgs<T>): T extends unknown[] ? Series[] : Seriesrequest.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"" or syminfo.tickerid for the chart symbol, "NASDAQ:AAPL" for another one,
ticker.heikinashi(...) for Heikin Ashi bars.timeframe"D", "W", "60"; "" is the chart timeframe.expressiongapsbarmerge.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.lookaheadbarmerge.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_symbolReturns 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"" is the chart symbol.timeframe"" is the chart timeframe.expressionargsgaps, 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.
argssymbol, 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"" or syminfo.tickerid is the chart symbol.timeframe"1", "15", "1T".expressionignore_invalid_symbolReturns 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"" is the chart symbol.timeframeexpressionargsignore_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.
argssymbol, 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[] : Seriesrequest.seed<T extends SecurityValue>(source: string, symbol: string, expression: () => T, args: SeedArgs<T>): T extends unknown[] ? Series[] : Seriesrequest.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).
sourcesymbolexpressionignore_invalid_symbolReturns 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.
sourcesymbolexpressionargsignore_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.
argssource, 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): Seriesrequest.dividends(ticker: string, field: string, args: EventRequestArgs): Seriesrequest.dividends(ticker: string, args: EventRequestArgs): Seriesrequest.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"" or syminfo.tickerid is the chart symbol.fielddividends.net or dividends.gross. Default: dividends.net.gapsbarmerge.gaps_on shows the value only on the bar where it appears. Default: barmerge.gaps_off.lookaheadbarmerge.lookahead_on shows it from the first bar of its period. Default:
barmerge.lookahead_off.ignore_invalid_symbolcurrency"" 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"" is the chart symbol.fielddividends.net or dividends.gross.argsgaps, 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"" is the chart symbol.argsfield, 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.
argsticker (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): Seriesrequest.splits(ticker: string, field: string, args: SplitsRequestArgs): Seriesrequest.splits(ticker: string, args: SplitsRequestArgs): Seriesrequest.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"" or syminfo.tickerid is the chart symbol.fieldsplits.numerator or splits.denominator (required).gapsbarmerge.gaps_on shows the value only on the bar where it appears. Default: barmerge.gaps_off.lookaheadbarmerge.lookahead_on shows it from the first bar of its period. Default:
barmerge.lookahead_off.ignore_invalid_symbolReturns 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"" is the chart symbol.fieldsplits.numerator or splits.denominator.argsgaps, 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"" is the chart symbol.argsfield (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.
argsticker 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): Seriesrequest.earnings(ticker: string, field: string, args: EventRequestArgs): Seriesrequest.earnings(ticker: string, args: EventRequestArgs): Seriesrequest.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"" or syminfo.tickerid is the chart symbol.fieldearnings.actual, earnings.estimate or earnings.standardized. Default: earnings.actual.gapsbarmerge.gaps_on shows the value only on the bar where it appears. Default: barmerge.gaps_off.lookaheadbarmerge.lookahead_on shows it from the first bar of its period. Default:
barmerge.lookahead_off.ignore_invalid_symbolcurrency"" 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"" is the chart symbol.fieldearnings.actual, earnings.estimate or earnings.standardized.argsgaps, 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"" is the chart symbol.argsfield, 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.
argsticker (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");scalePrice scale a script is attached to (indicator(..., { scale })).
scale.rightscale.right: "right"
The right price scale.
scale.leftscale.left: "left"
The left price scale.
scale.nonescale.none: "none"
No price scale of its own (for overlay scripts).
sessionTrading 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.regularsession.regular: "regular"
Session type of regular trading hours (compare with syminfo.session).
session.extendedsession.extended: "extended"
Session type with the pre and post market hours (compare with syminfo.session).
session.isfirstbarsession.isfirstbar: Series
1 on the first bar of each session period (including pre market when the bars have it).
session.islastbarsession.islastbar: Series
1 on the last bar of each session period.
session.ismarketsession.ismarket: Series
1 on bars inside the regular trading hours.
session.ispremarketsession.ispremarket: Series
1 on bars before the regular hours open (pre market).
session.ispostmarketsession.ispostmarket: Series
1 on bars after the regular hours close (post market).
session.isfirstbar_regularsession.isfirstbar_regular: Series
1 on the first bar of the regular trading hours of each day.
session.islastbar_regularsession.islastbar_regular: Series
1 on the last bar of the regular trading hours of each day.
shapeShapes of plotshape() (style option): plotshape(cond, "Buy", { style: shape.triangleup }).
shape.xcrossshape.xcross: "xcross"
A diagonal cross (x).
shape.crossshape.cross: "cross"
An upright cross (+).
shape.triangleupshape.triangleup: "triangleup"
A triangle pointing up.
shape.triangledownshape.triangledown: "triangledown"
A triangle pointing down.
shape.flagshape.flag: "flag"
A small flag.
shape.circleshape.circle: "circle"
A filled circle.
shape.arrowupshape.arrowup: "arrowup"
An arrow pointing up.
shape.arrowdownshape.arrowdown: "arrowdown"
An arrow pointing down.
shape.labelupshape.labelup: "labelup"
A label box pointing up (its tip at the value): put it below the bar.
shape.labeldownshape.labeldown: "labeldown"
A label box pointing down (its tip at the value): put it above the bar.
shape.squareshape.square: "square"
A filled square.
shape.diamondshape.diamond: "diamond"
A filled diamond.
sizeSizes of shapes, characters, labels and table texts (size / text_size options).
size.autosize.auto: "auto"
Size chosen by the chart to fit the space.
size.tinysize.tiny: "tiny"
The smallest size.
size.smallsize.small: "small"
Small size.
size.normalsize.normal: "normal"
Normal size.
size.largesize.large: "large"
Large size.
size.hugesize.huge: "huge"
The largest size.
splitsStock splits: the fields of request.splits (splits.numerator, splits.denominator).
splits.numeratorsplits.numerator: "numerator"
The number of shares after the split (2 for a 2-for-1 split).
splits.denominatorsplits.denominator: "denominator"
The number of shares before the split (1 for a 2-for-1 split).
strText 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.
strReturns 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.
valueformatformat.percent ("percent"), format.volume ("volume"), format.mintick ("mintick"),
format.price / format.inheritmintickformat.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_mintickpricescaleformat.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).
strReturns 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.
strbeginendReturns 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.
strReturns 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.
strReturns 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.
sourcestrReturns 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.
sourcestrReturns 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.
sourcetargetreplacementoccurrenceReturns 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.
sourcetargetreplacementReturns 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.
strseparatorReturns 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.
stringsReturns 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{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 quoteargsReturns 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.
sourcestrReturns 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.
sourcestrReturns 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.
strposReturns 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.
strReturns 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.
strReturns 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.
strReturns 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.
sourceregexReturns 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.
sourcecountseparatorReturns 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.
timetime on a bar or timenowformatyyyy 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"timezoneReturns 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"));
});
strategystrategy()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().
titleoptionsoverlay (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.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().
fnc (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.
idfrom_entry.directionstrategy.long or strategy.short.optionsqty (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: {}.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.
iddirectionstrategy.long (buy) or strategy.short (sell).optionsqty (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: {}.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).
idoptionsfrom_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: {}.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).
idoptionsqty / qty_percent (default: the whole position of the entry), comment, alert_message,
immediately (default false), disable_alert. Default: {}.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).
optionscomment, alert_message, immediately (default false), disable_alert. Default: {}.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.
idReturns 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.
indexstrategy.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.
indexstrategy.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_priceReturns 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.longstrategy.long: "long"
Direction of a long order: buys (strategy.entry("L", strategy.long)).
strategy.shortstrategy.short: "short"
Direction of a short order: sells (strategy.entry("S", strategy.short)).
strategy.fixedstrategy.fixed: "fixed"
Order size type: default_qty_value is a number of contracts (shares, units).
strategy.cashstrategy.cash: "cash"
Order size type: default_qty_value is an amount of money; also the money type of the risk rules.
strategy.percent_of_equitystrategy.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_sizestrategy.position_size: number
Size of the current position: positive when long, negative when short, 0 when flat.
strategy.position_avg_pricestrategy.position_avg_price: number
Average entry price of the current position; NaN when flat.
strategy.equitystrategy.equity: number
Current equity: initial capital + net profit + open profit, in the account currency.
strategy.initial_capitalstrategy.initial_capital: number
Starting capital of the backtest (the initial_capital property); readable anywhere after strategy().
strategy.netprofitstrategy.netprofit: number
Profit of all closed trades, after commission, in the account currency.
strategy.netprofit_percentstrategy.netprofit_percent: number
strategy.netprofit in percent of the initial capital.
strategy.openprofitstrategy.openprofit: number
Profit or loss of the open trades not yet realized, in the account currency.
strategy.openprofit_percentstrategy.openprofit_percent: number
strategy.openprofit in percent.
strategy.grossprofitstrategy.grossprofit: number
Sum of the profits of the winning closed trades, in the account currency.
strategy.grossprofit_percentstrategy.grossprofit_percent: number
strategy.grossprofit in percent of the initial capital.
strategy.grosslossstrategy.grossloss: number
Sum of the losses of the losing closed trades, as a positive amount in the account currency.
strategy.grossloss_percentstrategy.grossloss_percent: number
strategy.grossloss in percent of the initial capital.
strategy.opentradesstrategy.opentrades: number
Number of open trades (a number, not a function: read a trade with strategy.opentrade(i)).
strategy.closedtradesstrategy.closedtrades: number
Number of closed trades (a number, not a function: read a trade with strategy.closedtrade(i)).
strategy.wintradesstrategy.wintrades: number
Number of closed trades with a profit.
strategy.losstradesstrategy.losstrades: number
Number of closed trades with a loss.
strategy.eventradesstrategy.eventrades: number
Number of closed trades that broke even (profit 0).
strategy.avg_tradestrategy.avg_trade: number
Average profit per closed trade, in the account currency; NaN before the first closed trade.
strategy.avg_trade_percentstrategy.avg_trade_percent: number
Average profit per closed trade, in percent; NaN before the first closed trade.
strategy.avg_winning_tradestrategy.avg_winning_trade: number
Average profit of the winning trades, in the account currency; NaN before the first one.
strategy.avg_winning_trade_percentstrategy.avg_winning_trade_percent: number
Average profit of the winning trades, in percent; NaN before the first one.
strategy.avg_losing_tradestrategy.avg_losing_trade: number
Average loss of the losing trades, as a positive amount in the account currency; NaN before the first one.
strategy.avg_losing_trade_percentstrategy.avg_losing_trade_percent: number
Average loss of the losing trades, as a positive percent; NaN before the first one.
strategy.max_drawdownstrategy.max_drawdown: number
Largest drop of the equity from a peak so far, in the account currency.
strategy.max_drawdown_percentstrategy.max_drawdown_percent: number
strategy.max_drawdown in percent.
strategy.max_runupstrategy.max_runup: number
Largest rise of the equity from a low so far, in the account currency.
strategy.max_runup_percentstrategy.max_runup_percent: number
strategy.max_runup in percent.
strategy.max_contracts_held_allstrategy.max_contracts_held_all: number
Largest position held so far, long or short, in contracts (shares, units).
strategy.max_contracts_held_longstrategy.max_contracts_held_long: number
Largest long position held so far, in contracts (shares, units).
strategy.max_contracts_held_shortstrategy.max_contracts_held_short: number
Largest short position held so far, in contracts (shares, units).
strategy.margin_liquidation_pricestrategy.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_namestrategy.position_entry_name: string
Id of the entry that opened the current position (its oldest open trade); empty when flat.
strategy.account_currencystrategy.account_currency: string
Currency of the account the results are counted in (e.g. "USD"); readable anywhere after strategy().
strategy.commissionCommission types for the commission_type property of strategy().
strategy.commission.percentstrategy.commission.percent: "percent"
Commission in percent of the order value (commission_value: 0.1 is 0.1 %).
strategy.commission.cash_per_contractstrategy.commission.cash_per_contract: "cash_per_contract"
Commission in money for each contract (or share) traded.
strategy.commission.cash_per_orderstrategy.commission.cash_per_order: "cash_per_order"
Commission in money for each filled order, whatever its size.
strategy.directionDirections for strategy.risk.allow_entry_in().
strategy.direction.allstrategy.direction.all: "all"
Long and short entries are both allowed.
strategy.direction.longstrategy.direction.long: "long"
Only long entries open a position.
strategy.direction.shortstrategy.direction.short: "short"
Only short entries open a position.
strategy.ocaOne-cancels-all group types for the oca_type option of strategy.entry() / strategy.order().
strategy.oca.nonestrategy.oca.none: "none"
No group: the order does not act on other orders.
strategy.oca.cancelstrategy.oca.cancel: "cancel"
When one order of the group fills, the other orders of the group are cancelled.
strategy.oca.reducestrategy.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.riskRisk 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.
directionstrategy.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.
countalert_messageReturns 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.
valuetype).type"percent_of_equity" or "cash" (strategy.percent_of_equity, strategy.cash).alert_messageReturns 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.
countalert_messageReturns 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.
valuetype).type"percent_of_equity" or "cash" (strategy.percent_of_equity, strategy.cash).alert_messageReturns 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.
contractsReturns Nothing.
strategy("Capped", { overlay: true });
strategy.risk.max_position_size(100);
STRATEGY_DEFAULTSDefault values of the strategy() options, used for every option a strategy leaves out.
STRATEGY_DEFAULTS.pyramidingSTRATEGY_DEFAULTS.pyramiding: number
Most entries in the same direction (0 and 1 allow one).
STRATEGY_DEFAULTS.calc_on_order_fillsSTRATEGY_DEFAULTS.calc_on_order_fills: boolean
Runs the bar again after a fill inside it.
STRATEGY_DEFAULTS.calc_on_every_tickSTRATEGY_DEFAULTS.calc_on_every_tick: boolean
Runs on every price update of the live bar.
STRATEGY_DEFAULTS.calc_on_every_history_tickSTRATEGY_DEFAULTS.calc_on_every_history_tick: boolean
Runs on each price step of the history bars.
STRATEGY_DEFAULTS.backtest_fill_limits_assumptionSTRATEGY_DEFAULTS.backtest_fill_limits_assumption: number
Ticks the price must pass a limit price by before it fills.
STRATEGY_DEFAULTS.default_qty_typeSTRATEGY_DEFAULTS.default_qty_type: StrategyQtyType
Unit of default_qty_value.
STRATEGY_DEFAULTS.default_qty_valueSTRATEGY_DEFAULTS.default_qty_value: number
Size of an order that gives no qty.
STRATEGY_DEFAULTS.initial_capitalSTRATEGY_DEFAULTS.initial_capital: number
Money the account starts with.
STRATEGY_DEFAULTS.currencySTRATEGY_DEFAULTS.currency: string
undefined: the symbol currency.
STRATEGY_DEFAULTS.slippageSTRATEGY_DEFAULTS.slippage: number
Ticks added against you to market and stop fills.
STRATEGY_DEFAULTS.commission_typeSTRATEGY_DEFAULTS.commission_type: StrategyCommissionType
How commission_value is read.
STRATEGY_DEFAULTS.commission_valueSTRATEGY_DEFAULTS.commission_value: number
Commission per order.
STRATEGY_DEFAULTS.process_orders_on_closeSTRATEGY_DEFAULTS.process_orders_on_close: boolean
Orders fill at the close of the bar that sent them.
STRATEGY_DEFAULTS.close_entries_ruleSTRATEGY_DEFAULTS.close_entries_rule: "FIFO" | "ANY"
"FIFO": exits close the oldest entry first; "ANY": the entry they name.
STRATEGY_DEFAULTS.margin_longSTRATEGY_DEFAULTS.margin_long: number
Margin of long positions, in percent of their value.
STRATEGY_DEFAULTS.margin_shortSTRATEGY_DEFAULTS.margin_short: number
Margin of short positions, in percent of their value.
STRATEGY_DEFAULTS.calc_bars_countSTRATEGY_DEFAULTS.calc_bars_count: number
Runs on the last this many bars; 0: all.
STRATEGY_DEFAULTS.risk_free_rateSTRATEGY_DEFAULTS.risk_free_rate: number
Yearly risk-free rate in percent (Sharpe, Sortino).
STRATEGY_DEFAULTS.use_bar_magnifierSTRATEGY_DEFAULTS.use_bar_magnifier: boolean
Fills orders with lower-timeframe bars.
STRATEGY_DEFAULTS.fill_orders_on_standard_ohlcSTRATEGY_DEFAULTS.fill_orders_on_standard_ohlc: boolean
Fills at real prices on synthetic charts.
syminfoThe 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.minticksyminfo.mintick: number
Smallest price step of the symbol, e.g. 0.01. Equals minmove / pricescale.
syminfo.minmovesyminfo.minmove: number
Number of price-scale units in one price step: mintick = minmove / pricescale (1 for most symbols).
syminfo.pricescalesyminfo.pricescale: number
Price scale of the symbol: 100 for prices with 2 decimals, 32 for prices in 1/32.
syminfo.pointvaluesyminfo.pointvalue: number
Money value of a one-point price move for one contract (1 for stocks).
syminfo.mincontractsyminfo.mincontract: number
Smallest quantity that can be traded (1 for whole shares).
syminfo.timezonesyminfo.timezone: string
Time zone of the exchange, e.g. "America/New_York". The default time zone of the date and time functions.
syminfo.tickeridsyminfo.tickerid: string
Full symbol id with its exchange prefix, e.g. "NASDAQ:AAPL". Pass it to request.security for the chart symbol.
syminfo.main_tickeridsyminfo.main_tickerid: string
Symbol id of the chart itself, also inside a request.security expression on another symbol.
syminfo.tickersyminfo.ticker: string
Symbol name without the exchange prefix, e.g. "AAPL".
syminfo.prefixsyminfo.prefix: string
Exchange prefix of the symbol id, e.g. "NASDAQ"; "" without one.
syminfo.sessionsyminfo.session: string
Session type of the bars: "regular" (regular hours) or "extended" (with pre and post market).
syminfo.typesyminfo.type: string
Type of the symbol: "stock", "fund", "index", "futures", "forex", "crypto"...
syminfo.currencysyminfo.currency: string
Currency the prices are in, e.g. "USD".
syminfo.basecurrencysyminfo.basecurrency: string
Base currency of a pair: "BTC" for a BTC/USD symbol, "EUR" for EUR/USD; "" for a stock or an index.
syminfo.rootsyminfo.root: string
Root of the symbol: "ES" for a continuous future "ES1!" or a contract "ESZ2026"; the ticker otherwise.
syminfo.descriptionsyminfo.description: string
Full name of the symbol, e.g. "Apple Inc.".
syminfo.countrysyminfo.country: string
Two-letter code of the country the symbol trades in, e.g. "US".
syminfo.current_contractsyminfo.current_contract: string
Contract a continuous future stands for, e.g. "ESZ2026"; "" for other symbols.
syminfo.expiration_datesyminfo.expiration_date: number
Last trading day of a futures contract (UNIX time in ms); na for other symbols.
syminfo.sectorsyminfo.sector: string
Sector of the company, e.g. "Electronic Technology"; "" when it has none.
syminfo.industrysyminfo.industry: string
Industry of the company; "" when it has none.
syminfo.isinsyminfo.isin: string
International Securities Identification Number of the symbol, e.g. "US0378331005".
syminfo.volumetypesyminfo.volumetype: string
Unit of the volume: "base" (units of the base currency), "quote", "tick" or "n/a".
syminfo.employeessyminfo.employees: number
Number of employees of the company.
syminfo.shareholderssyminfo.shareholders: number
Number of shareholders of the company.
syminfo.shares_outstanding_totalsyminfo.shares_outstanding_total: number
Total number of shares the company has issued.
syminfo.shares_outstanding_floatsyminfo.shares_outstanding_float: number
Number of shares free to trade (without the shares held by insiders and large holders).
syminfo.recommendations_buysyminfo.recommendations_buy: number
Number of analysts who rate the symbol "buy".
syminfo.recommendations_buy_strongsyminfo.recommendations_buy_strong: number
Number of analysts who rate the symbol "strong buy".
syminfo.recommendations_holdsyminfo.recommendations_hold: number
Number of analysts who rate the symbol "hold".
syminfo.recommendations_sellsyminfo.recommendations_sell: number
Number of analysts who rate the symbol "sell".
syminfo.recommendations_sell_strongsyminfo.recommendations_sell_strong: number
Number of analysts who rate the symbol "strong sell".
syminfo.recommendations_totalsyminfo.recommendations_total: number
Total number of analysts' ratings.
syminfo.recommendations_datesyminfo.recommendations_date: number
Date of the analysts' ratings (UNIX time in ms).
syminfo.target_price_averagesyminfo.target_price_average: number
Average of the analysts' price targets.
syminfo.target_price_highsyminfo.target_price_high: number
Highest analyst price target.
syminfo.target_price_lowsyminfo.target_price_low: number
Lowest analyst price target.
syminfo.target_price_mediansyminfo.target_price_median: number
Median of the analysts' price targets.
syminfo.target_price_estimatessyminfo.target_price_estimates: number
Number of analysts' price targets.
syminfo.target_price_datesyminfo.target_price_date: number
Date of the analysts' price targets (UNIX time in ms).
taTechnical 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.
sourceclose.lengthReturns 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.
sourcelengthReturns 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.
sourcelengthReturns 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.
sourcelengthReturns 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.
sourcelengthReturns 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.
sourcelengthoffsetsigmaflooroffset * (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.
sourceReturns 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.
sourcelengthvolvolume.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): Seriesta.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).
sourcehlc3.anchortimeframe.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.
sourcehlc3.anchorundefined for a new trading
day.stdev_multReturns 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.
sourcevolumeanchorundefined for no restart.stdev_multReturns 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): Seriesta.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.
sourceclose.lengthReturns 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.
updownReturns 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).
sourceclose.fastLengthslowLengthsignalLengthReturns 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.
sourceclose.highSourcehigh.lowSourcelow.lengthReturns 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.
sourcehlc3.lengthReturns 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.
sourcehlc3.lengthReturns 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.
lengthReturns 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.
sourceclose.shortLengthlongLengthReturns 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.
sourceclose.lengthReturns 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.
sourceclose.lengthReturns 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.
sourceclose.lengthReturns 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.
sourcelengthReturns 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.
sourcelengthReturns 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.
sourcelengthReturns 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.
handleNahigh - 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.
lengthReturns 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.
sourceclose.lengthmultReturns 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.
sourceclose.lengthmultReturns 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.
sourceclose.lengthmultuseTrueRangehigh - 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.
sourceclose.lengthmultuseTrueRangehigh - 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.
sourcelengthbiasedlength (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.
sourcelengthbiasedlength (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.
sourcelengthReturns 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.
startincmaxReturns 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.
factoratrLengthReturns 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.
diLengthadxSmoothingReturns 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).
conversionPeriodsbasePeriodslaggingSpan2PeriodsdisplacementReturns 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.
abReturns 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.
abReturns 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.
abReturns 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.
sourcelengthReturns 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.
sourcelengthReturns 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.
conditionReturns 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.
conditionsourceoccurrenceReturns 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): Seriesta.highest(source: Series, length: number | Series): Series
Highest value of the last length bars of the chart high.
lengthReturns 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.
sourcelengthReturns 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): Seriesta.lowest(source: Series, length: number | Series): Series
Lowest value of the last length bars of the chart low.
lengthReturns 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.
sourcelengthReturns Series of the lowest values.
const bottom = ta.lowest(close, 20);
plot(bottom, "20-bar low of close");ta.highestbars()ta.highestbars(length: number): Seriesta.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).
lengthReturns 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).
sourcelengthReturns 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): Seriesta.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).
lengthReturns 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).
sourcelengthReturns 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.
sourcelengthReturns 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.
sourceReturns 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.
sourceReturns 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.
sourcelengthReturns 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.
sourcelengthReturns 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.
sourcelengthpercentageReturns 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.
sourcelengthpercentageReturns 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.
sourcelengthReturns 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).
ablengthReturns 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.
sourcelengthoffsetReturns 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.
sourceReturns Series of running totals.
const totalVolume = ta.cum(volume);
plot(totalVolume, "Cumulative volume");
ta.pivothigh()ta.pivothigh(leftbars: number, rightbars: number | Series): Seriesta.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.
leftbarsrightbarsReturns 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.
sourceleftbarsrightbarsReturns 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): Seriesta.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.
leftbarsrightbarsReturns 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.
sourceleftbarsrightbarsReturns 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.
deviationdepthbackstepReturns 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.obvta.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.pvtta.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.accdistta.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.nvita.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.pvita.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.iiita.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.wadta.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.wvadta.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 });
tableTables 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): Tabletable.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): Tabletable.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.
positionposition.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.columnsrowsbgcolorframe_colorframe_widthborder_colorborder_widthforce_overlayReturns 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).
positionposition.top_right, position.bottom_left...).columnsrowsargsbgcolor, 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).
argsposition, 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).
positionposition.top_right, position.bottom_left...).columnsrowsbgcolorframe_colorframe_widthborder_colorborder_widthforce_overlayReturns 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): voidtable.cell(table_id: Table, column: Numeric, row: Numeric, args: TableCellArgs): voidtable.cell(table_id: Table, column: Numeric, row: Numeric, text: string, args: TableCellArgs): voidtable.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_idtable.new()).columnrowtext\n starts a new line. Default: "".widthheighttext_colortext_haligntext.align_left, text.align_center or text.align_right. Default: text.align_center.text_valigntext.align_top, text.align_center or text.align_bottom. Default: text.align_center.text_sizesize.tiny, size.small, size.normal, size.large, size.huge, size.auto, or a size in
points. Default: size.auto.bgcolortooltiptext_font_familyfont.family_default or font.family_monospace. Default: font.family_default.text_formattingtext.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_idcolumnrowargstext, 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_idcolumnrowtext\n starts a new line.argswidth, 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).
argstable_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_idcolumnrowvalue\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_idcolumnrowvalueReturns 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_idcolumnrowvalueReturns 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_idcolumnrowvalueReturns 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_idcolumnrowvaluetext.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_idcolumnrowvaluetext.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_idcolumnrowvaluesize.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_idcolumnrowvalueReturns 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_idcolumnrowvalueReturns 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_idcolumnrowvaluefont.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_idcolumnrowvaluetext.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_idstart_columnstart_rowend_columnstart_column).end_rowstart_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_idstart_columnstart_rowend_columnstart_column.end_rowstart_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_idpositionposition.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_idvalueReturns 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_idvalueReturns 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_idvalueReturns 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_idvalueReturns 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_idvalueReturns 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_idReturns 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_idReturns Nothing.
const t = table.new(position.top_right, 1, 1);
table.delete_table(t);
table.allThe tables still on the pane, oldest first (a new array on each read).
table.all.toString()table.all.toString(): string
Returns a string representation of an array.
table.all.toLocaleString()table.all.toLocaleString(): stringtable.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.
itemstable.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.
itemstable.all.join()table.all.join(separator?: string): string
Adds all the elements of an array into a string, separated by the specified separator string.
separatortable.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.
startendtable.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.
compareFnts
[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.
startdeleteCountReturns 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.
startdeleteCountitemsReturns 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.
itemstable.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.
searchElementfromIndextable.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.
searchElementfromIndextable.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.
predicatethisArgtable.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.
predicatethisArgtable.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.
callbackfnthisArgtable.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.
callbackfnthisArgtable.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.
predicatethisArgtable.all.reduce()table.all.reduce(callbackfn: (previousValue: Table, currentValue: Table, currentIndex: number, array: Table[]) => Table): Tabletable.all.reduce(callbackfn: (previousValue: Table, currentValue: Table, currentIndex: number, array: Table[]) => Table, initialValue: Table): Tabletable.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.
callbackfninitialValueCalls 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.
callbackfninitialValuecallbackfninitialValuetable.all.reduceRight()table.all.reduceRight(callbackfn: (previousValue: Table, currentValue: Table, currentIndex: number, array: Table[]) => Table): Tabletable.all.reduceRight(callbackfn: (previousValue: Table, currentValue: Table, currentIndex: number, array: Table[]) => Table, initialValue: Table): Tabletable.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.
callbackfninitialValueCalls 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.
callbackfninitialValuecallbackfninitialValuetable.all.find()table.all.find<S extends Table>(predicate: (value: Table, index: number, obj: Table[]) => value is S, thisArg?: any): Stable.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.
predicatethisArgtable.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.
predicatethisArgtable.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
valuestartendtable.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
targetstartendtable.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.
searchElementfromIndextable.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.
callbackthisArgtable.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.
depthtable.all.at()table.all.at(index: number): Table
Returns the item located at the specified index.
indextable.all.findLast()table.all.findLast<S extends Table>(predicate: (value: Table, index: number, array: Table[]) => value is S, thisArg?: any): Stable.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.
predicatethisArgtable.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.
predicatethisArgtable.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.
compareFnts
[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.
startdeleteCountitemsReturns The copied array.
Copies an array and removes elements while returning the remaining elements.
startdeleteCountReturns 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.
indexvalueReturns The copied array with the updated value.
table.all.__@iterator@71()table.all.__@iterator@71(): ArrayIterator<Table>
Iterator
table.all.lengthtable.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@73Is an object whose properties have the value 'true' when they will be absent when used in a 'with' statement.
table.all.__@unscopables@73.lengthtable.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.toStringtable.all.__@unscopables@73.toString: boolean
Returns a string representation of an array.
table.all.__@unscopables@73.toLocaleStringtable.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.poptable.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.pushtable.all.__@unscopables@73.push: boolean
Appends new elements to the end of an array, and returns the new length of the array.
itemstable.all.__@unscopables@73.concattable.all.__@unscopables@73.concat: boolean
Combines two or more arrays. This method returns a new array without modifying any existing arrays.
itemsitemstable.all.__@unscopables@73.jointable.all.__@unscopables@73.join: boolean
Adds all the elements of an array into a string, separated by the specified separator string.
separatortable.all.__@unscopables@73.reversetable.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.shifttable.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.slicetable.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.
startendtable.all.__@unscopables@73.sorttable.all.__@unscopables@73.sort: boolean
Sorts an array in place. This method mutates the array and returns a reference to the same array.
compareFnts
[11,2,22,1].sort((a, b) => a - b)
``table.all.__@unscopables@73.splicetable.all.__@unscopables@73.splice: boolean
Removes elements from an array and, if necessary, inserts new elements in their place, returning the deleted elements.
startdeleteCountstartdeleteCountitemsReturns An array containing the elements that were deleted.
table.all.__@unscopables@73.unshifttable.all.__@unscopables@73.unshift: boolean
Inserts new elements at the start of an array, and returns the new length of the array.
itemstable.all.__@unscopables@73.indexOftable.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.
searchElementfromIndextable.all.__@unscopables@73.lastIndexOftable.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.
searchElementfromIndextable.all.__@unscopables@73.everytable.all.__@unscopables@73.every: boolean
Determines whether all the members of an array satisfy the specified test.
predicatethisArgpredicatethisArgtable.all.__@unscopables@73.sometable.all.__@unscopables@73.some: boolean
Determines whether the specified callback function returns true for any element of an array.
predicatethisArgtable.all.__@unscopables@73.forEachtable.all.__@unscopables@73.forEach: boolean
Performs the specified action for each element in an array.
callbackfnthisArgtable.all.__@unscopables@73.maptable.all.__@unscopables@73.map: boolean
Calls a defined callback function on each element of an array, and returns an array that contains the results.
callbackfnthisArgtable.all.__@unscopables@73.filtertable.all.__@unscopables@73.filter: boolean
Returns the elements of an array that meet the condition specified in a callback function.
predicatethisArgpredicatethisArgtable.all.__@unscopables@73.reducetable.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.
callbackfninitialValuecallbackfninitialValuetable.all.__@unscopables@73.reduceRighttable.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.
callbackfninitialValuecallbackfninitialValuetable.all.__@unscopables@73.findtable.all.__@unscopables@73.find: boolean
Returns the value of the first element in the array where predicate is true, and undefined otherwise.
predicatethisArgtable.all.__@unscopables@73.findIndextable.all.__@unscopables@73.findIndex: boolean
Returns the index of the first element in the array where predicate is true, and -1 otherwise.
predicatethisArgtable.all.__@unscopables@73.filltable.all.__@unscopables@73.fill: boolean
Changes all array elements from start to end index to a static value and returns the modified array
valuestartendtable.all.__@unscopables@73.copyWithintable.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
targetstartendtable.all.__@unscopables@73.entriestable.all.__@unscopables@73.entries: boolean
Returns an iterable of key, value pairs for every entry in the array
table.all.__@unscopables@73.keystable.all.__@unscopables@73.keys: boolean
Returns an iterable of keys in the array
table.all.__@unscopables@73.valuestable.all.__@unscopables@73.values: boolean
Returns an iterable of values in the array
table.all.__@unscopables@73.includestable.all.__@unscopables@73.includes: boolean
Determines whether an array includes a certain element, returning true or false as appropriate.
searchElementfromIndextable.all.__@unscopables@73.flatMaptable.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.
callbackthisArgtable.all.__@unscopables@73.flattable.all.__@unscopables@73.flat: boolean
Returns a new array with all sub-array elements concatenated into it recursively up to the specified depth.
depthtable.all.__@unscopables@73.attable.all.__@unscopables@73.at: boolean
Returns the item located at the specified index.
indextable.all.__@unscopables@73.findLasttable.all.__@unscopables@73.findLast: boolean
Returns the value of the last element in the array where predicate is true, and undefined otherwise.
predicatethisArgtable.all.__@unscopables@73.findLastIndextable.all.__@unscopables@73.findLastIndex: boolean
Returns the index of the last element in the array where predicate is true, and -1 otherwise.
predicatethisArgtable.all.__@unscopables@73.toReversedtable.all.__@unscopables@73.toReversed: boolean
Returns a copy of an array with its elements reversed.
table.all.__@unscopables@73.toSortedtable.all.__@unscopables@73.toSorted: boolean
Returns a copy of an array with its elements sorted.
compareFnts
[11, 2, 22, 1].toSorted((a, b) => a - b) // [1, 2, 11, 22]
``table.all.__@unscopables@73.toSplicedtable.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.
startdeleteCountitemsstartdeleteCountReturns A copy of the original array with the remaining elements.
table.all.__@unscopables@73.withtable.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.
indexvalueReturns The copied array with the updated value.
table.all.__@unscopables@73.__@iterator@71table.all.__@unscopables@73.__@iterator@71: boolean
Iterator
table.all.__@unscopables@73.__@unscopables@73table.all.__@unscopables@73.__@unscopables@73: boolean
Is an object whose properties have the value 'true' when they will be absent when used in a 'with' statement.
textText constants: text.format_* (bold, italic), text.align_* (alignment) and text.wrap_* (wrapping).
text.format_nonetext.format_none: 0
Plain text: neither bold nor italic (the default).
text.format_boldtext.format_bold: 1
Bold text; add text.format_italic for bold italic.
text.format_italictext.format_italic: 2
Italic text; add text.format_bold for bold italic.
text.align_lefttext.align_left: "left"
Text aligned to the left (text_halign of table.cell() and box.new(), textalign of label.new()).
text.align_centertext.align_center: "center"
Text centred, horizontally or vertically.
text.align_righttext.align_right: "right"
Text aligned to the right.
text.align_toptext.align_top: "top"
Text aligned to the top (text_valign of table.cell() and box.new()).
text.align_bottomtext.align_bottom: "bottom"
Text aligned to the bottom (text_valign).
text.wrap_autotext.wrap_auto: "auto"
Text wrapped onto several lines to fit the width of the box (text_wrap of box.new()).
text.wrap_nonetext.wrap_none: "none"
Text not wrapped: each line of the text stays on one line.
tickerSymbol 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.
symbolsyminfo.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.
symbolsyminfo.tickerid.Returns The symbol id of the standard bars.
const realClose = request.security(ticker.standard(syminfo.tickerid), "", () => close);
plot(realClose, "Close");
timetime()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.
tfsessiontimezoneReturns 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.
otherReturns 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.
otherReturns 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.
otherReturns 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.
exponentReturns 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.
otherReturns 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.
otherReturns 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.
otherReturns 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.
otherReturns 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.
otherReturns 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.
otherReturns 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.
otherReturns 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.
otherReturns 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.
otherReturns 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.
otherReturns 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.
trueValuefalseValueReturns 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.
offsetclose, 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).
indexReturns 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.fullHistorytime.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.cachedVersiontime.barsThe bars this series is aligned to ({ time, open, high, low, close, volume }, oldest first).
time.bars.toString()time.bars.toString(): string
Returns a string representation of an array.
time.bars.toLocaleString()time.bars.toLocaleString(): stringtime.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.
itemstime.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.
itemstime.bars.join()time.bars.join(separator?: string): string
Adds all the elements of an array into a string, separated by the specified separator string.
separatortime.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.
startendtime.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.
compareFnts
[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.
startdeleteCountReturns 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.
startdeleteCountitemsReturns 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.
itemstime.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.
searchElementfromIndextime.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.
searchElementfromIndextime.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.
predicatethisArgtime.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.
predicatethisArgtime.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.
callbackfnthisArgtime.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.
callbackfnthisArgtime.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.
predicatethisArgtime.bars.reduce()time.bars.reduce(callbackfn: (previousValue: Bar, currentValue: Bar, currentIndex: number, array: Bar[]) => Bar): Bartime.bars.reduce(callbackfn: (previousValue: Bar, currentValue: Bar, currentIndex: number, array: Bar[]) => Bar, initialValue: Bar): Bartime.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.
callbackfninitialValueCalls 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.
callbackfninitialValuecallbackfninitialValuetime.bars.reduceRight()time.bars.reduceRight(callbackfn: (previousValue: Bar, currentValue: Bar, currentIndex: number, array: Bar[]) => Bar): Bartime.bars.reduceRight(callbackfn: (previousValue: Bar, currentValue: Bar, currentIndex: number, array: Bar[]) => Bar, initialValue: Bar): Bartime.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.
callbackfninitialValueCalls 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.
callbackfninitialValuecallbackfninitialValuetime.bars.find()time.bars.find<S extends Bar>(predicate: (value: Bar, index: number, obj: Bar[]) => value is S, thisArg?: any): Stime.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.
predicatethisArgtime.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.
predicatethisArgtime.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
valuestartendtime.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
targetstartendtime.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.
searchElementfromIndextime.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.
callbackthisArgtime.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.
depthtime.bars.at()time.bars.at(index: number): Bar
Returns the item located at the specified index.
indextime.bars.findLast()time.bars.findLast<S extends Bar>(predicate: (value: Bar, index: number, array: Bar[]) => value is S, thisArg?: any): Stime.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.
predicatethisArgtime.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.
predicatethisArgtime.bars.toReversed()time.bars.toReversed(): Bar[]
Returns a copy of an array with its elements reversed.
time.bars.toSorted()time.bars.toSorted(compareFn?: (a: Bar, b: Bar) => number): Bar[]
Returns a copy of an array with its elements sorted.
compareFnts
[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.
startdeleteCountitemsReturns The copied array.
Copies an array and removes elements while returning the remaining elements.
startdeleteCountReturns 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.
indexvalueReturns The copied array with the updated value.
time.bars.__@iterator@71()time.bars.__@iterator@71(): ArrayIterator<Bar>
Iterator
time.bars.lengthtime.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@73Is an object whose properties have the value 'true' when they will be absent when used in a 'with' statement.
time.bars.__@unscopables@73.lengthtime.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.toStringtime.bars.__@unscopables@73.toString: boolean
Returns a string representation of an array.
time.bars.__@unscopables@73.toLocaleStringtime.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.poptime.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.pushtime.bars.__@unscopables@73.push: boolean
Appends new elements to the end of an array, and returns the new length of the array.
itemstime.bars.__@unscopables@73.concattime.bars.__@unscopables@73.concat: boolean
Combines two or more arrays. This method returns a new array without modifying any existing arrays.
itemsitemstime.bars.__@unscopables@73.jointime.bars.__@unscopables@73.join: boolean
Adds all the elements of an array into a string, separated by the specified separator string.
separatortime.bars.__@unscopables@73.reversetime.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.shifttime.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.slicetime.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.
startendtime.bars.__@unscopables@73.sorttime.bars.__@unscopables@73.sort: boolean
Sorts an array in place. This method mutates the array and returns a reference to the same array.
compareFnts
[11,2,22,1].sort((a, b) => a - b)
``time.bars.__@unscopables@73.splicetime.bars.__@unscopables@73.splice: boolean
Removes elements from an array and, if necessary, inserts new elements in their place, returning the deleted elements.
startdeleteCountstartdeleteCountitemsReturns An array containing the elements that were deleted.
time.bars.__@unscopables@73.unshifttime.bars.__@unscopables@73.unshift: boolean
Inserts new elements at the start of an array, and returns the new length of the array.
itemstime.bars.__@unscopables@73.indexOftime.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.
searchElementfromIndextime.bars.__@unscopables@73.lastIndexOftime.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.
searchElementfromIndextime.bars.__@unscopables@73.everytime.bars.__@unscopables@73.every: boolean
Determines whether all the members of an array satisfy the specified test.
predicatethisArgpredicatethisArgtime.bars.__@unscopables@73.sometime.bars.__@unscopables@73.some: boolean
Determines whether the specified callback function returns true for any element of an array.
predicatethisArgtime.bars.__@unscopables@73.forEachtime.bars.__@unscopables@73.forEach: boolean
Performs the specified action for each element in an array.
callbackfnthisArgtime.bars.__@unscopables@73.maptime.bars.__@unscopables@73.map: boolean
Calls a defined callback function on each element of an array, and returns an array that contains the results.
callbackfnthisArgtime.bars.__@unscopables@73.filtertime.bars.__@unscopables@73.filter: boolean
Returns the elements of an array that meet the condition specified in a callback function.
predicatethisArgpredicatethisArgtime.bars.__@unscopables@73.reducetime.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.
callbackfninitialValuecallbackfninitialValuetime.bars.__@unscopables@73.reduceRighttime.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.
callbackfninitialValuecallbackfninitialValuetime.bars.__@unscopables@73.findtime.bars.__@unscopables@73.find: boolean
Returns the value of the first element in the array where predicate is true, and undefined otherwise.
predicatethisArgtime.bars.__@unscopables@73.findIndextime.bars.__@unscopables@73.findIndex: boolean
Returns the index of the first element in the array where predicate is true, and -1 otherwise.
predicatethisArgtime.bars.__@unscopables@73.filltime.bars.__@unscopables@73.fill: boolean
Changes all array elements from start to end index to a static value and returns the modified array
valuestartendtime.bars.__@unscopables@73.copyWithintime.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
targetstartendtime.bars.__@unscopables@73.entriestime.bars.__@unscopables@73.entries: boolean
Returns an iterable of key, value pairs for every entry in the array
time.bars.__@unscopables@73.keystime.bars.__@unscopables@73.keys: boolean
Returns an iterable of keys in the array
time.bars.__@unscopables@73.valuestime.bars.__@unscopables@73.values: boolean
Returns an iterable of values in the array
time.bars.__@unscopables@73.includestime.bars.__@unscopables@73.includes: boolean
Determines whether an array includes a certain element, returning true or false as appropriate.
searchElementfromIndextime.bars.__@unscopables@73.flatMaptime.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.
callbackthisArgtime.bars.__@unscopables@73.flattime.bars.__@unscopables@73.flat: boolean
Returns a new array with all sub-array elements concatenated into it recursively up to the specified depth.
depthtime.bars.__@unscopables@73.attime.bars.__@unscopables@73.at: boolean
Returns the item located at the specified index.
indextime.bars.__@unscopables@73.findLasttime.bars.__@unscopables@73.findLast: boolean
Returns the value of the last element in the array where predicate is true, and undefined otherwise.
predicatethisArgtime.bars.__@unscopables@73.findLastIndextime.bars.__@unscopables@73.findLastIndex: boolean
Returns the index of the last element in the array where predicate is true, and -1 otherwise.
predicatethisArgtime.bars.__@unscopables@73.toReversedtime.bars.__@unscopables@73.toReversed: boolean
Returns a copy of an array with its elements reversed.
time.bars.__@unscopables@73.toSortedtime.bars.__@unscopables@73.toSorted: boolean
Returns a copy of an array with its elements sorted.
compareFnts
[11, 2, 22, 1].toSorted((a, b) => a - b) // [1, 2, 11, 22]
``time.bars.__@unscopables@73.toSplicedtime.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.
startdeleteCountitemsstartdeleteCountReturns A copy of the original array with the remaining elements.
time.bars.__@unscopables@73.withtime.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.
indexvalueReturns The copied array with the updated value.
time.bars.__@unscopables@73.__@iterator@71time.bars.__@unscopables@73.__@iterator@71: boolean
Iterator
time.bars.__@unscopables@73.__@unscopables@73time.bars.__@unscopables@73.__@unscopables@73: boolean
Is an object whose properties have the value 'true' when they will be absent when used in a 'with' statement.
time.barDataThe BarData holding the bars this series is aligned to.
time.barData.push()time.barData.push(bar: Bar): void
Add a new bar to the end
bartime.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
indexbartime.barData.updateLast()time.barData.updateLast(bar: Bar): void
Update the last bar (useful for real-time/streaming updates)
bartime.barData.setAll()time.barData.setAll(bars: Bar[]): void
Replace all bars with new data
barstime.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
indexReturns Bar at that index, or undefined
time.barData.versiontime.barData.version: number
Get the current version number Version increments whenever data is mutated
time.barData.lengthtime.barData.length: number
Get the number of bars
time.barData._barstime.barData._versiontime.barData.barsGet the underlying bar array Note: Direct mutations to this array will NOT increment version Use the provided mutation methods instead
time.barData.bars.toString()time.barData.bars.toString(): string
Returns a string representation of an array.
time.barData.bars.toLocaleString()time.barData.bars.toLocaleString(): stringtime.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.
itemstime.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.
itemstime.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.
separatortime.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.
startendtime.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.
compareFnts
[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.
startdeleteCountReturns 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.
startdeleteCountitemsReturns 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.
itemstime.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.
searchElementfromIndextime.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.
searchElementfromIndextime.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.
predicatethisArgtime.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.
predicatethisArgtime.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.
callbackfnthisArgtime.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.
callbackfnthisArgtime.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.
predicatethisArgtime.barData.bars.reduce()time.barData.bars.reduce(callbackfn: (previousValue: Bar, currentValue: Bar, currentIndex: number, array: Bar[]) => Bar): Bartime.barData.bars.reduce(callbackfn: (previousValue: Bar, currentValue: Bar, currentIndex: number, array: Bar[]) => Bar, initialValue: Bar): Bartime.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.
callbackfninitialValueCalls 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.
callbackfninitialValuecallbackfninitialValuetime.barData.bars.reduceRight()time.barData.bars.reduceRight(callbackfn: (previousValue: Bar, currentValue: Bar, currentIndex: number, array: Bar[]) => Bar): Bartime.barData.bars.reduceRight(callbackfn: (previousValue: Bar, currentValue: Bar, currentIndex: number, array: Bar[]) => Bar, initialValue: Bar): Bartime.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.
callbackfninitialValueCalls 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.
callbackfninitialValuecallbackfninitialValuetime.barData.bars.find()time.barData.bars.find<S extends Bar>(predicate: (value: Bar, index: number, obj: Bar[]) => value is S, thisArg?: any): Stime.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.
predicatethisArgtime.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.
predicatethisArgtime.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
valuestartendtime.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
targetstartendtime.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.keys()time.barData.bars.keys(): ArrayIterator<number>
Returns an iterable of keys in the array
time.barData.bars.values()time.barData.bars.values(): ArrayIterator<Bar>
Returns an iterable of values 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.
searchElementfromIndextime.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.
callbackthisArgtime.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.
depthtime.barData.bars.at()time.barData.bars.at(index: number): Bar
Returns the item located at the specified index.
indextime.barData.bars.findLast()time.barData.bars.findLast<S extends Bar>(predicate: (value: Bar, index: number, array: Bar[]) => value is S, thisArg?: any): Stime.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.
predicatethisArgtime.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.
predicatethisArgtime.barData.bars.toReversed()time.barData.bars.toReversed(): Bar[]
Returns a copy of an array with its elements reversed.
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.
compareFnts
[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.
startdeleteCountitemsReturns The copied array.
Copies an array and removes elements while returning the remaining elements.
startdeleteCountReturns 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.
indexvalueReturns The copied array with the updated value.
time.barData.bars.__@iterator@71()time.barData.bars.__@iterator@71(): ArrayIterator<Bar>
Iterator
time.barData.bars.lengthtime.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@73Is an object whose properties have the value 'true' when they will be absent when used in a 'with' statement.
time.barData.bars.__@unscopables@73.lengthtime.barData.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.barData.bars.__@unscopables@73.toStringtime.barData.bars.__@unscopables@73.toString: boolean
Returns a string representation of an array.
time.barData.bars.__@unscopables@73.toLocaleStringtime.barData.bars.__@unscopables@73.toLocaleString: boolean
Returns a string representation of an array. The elements are converted to string using their toLocaleString methods.
time.barData.bars.__@unscopables@73.poptime.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.pushtime.barData.bars.__@unscopables@73.push: boolean
Appends new elements to the end of an array, and returns the new length of the array.
itemstime.barData.bars.__@unscopables@73.concattime.barData.bars.__@unscopables@73.concat: boolean
Combines two or more arrays. This method returns a new array without modifying any existing arrays.
itemsitemstime.barData.bars.__@unscopables@73.jointime.barData.bars.__@unscopables@73.join: boolean
Adds all the elements of an array into a string, separated by the specified separator string.
separatortime.barData.bars.__@unscopables@73.reversetime.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.shifttime.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.slicetime.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.
startendtime.barData.bars.__@unscopables@73.sorttime.barData.bars.__@unscopables@73.sort: boolean
Sorts an array in place. This method mutates the array and returns a reference to the same array.
compareFnts
[11,2,22,1].sort((a, b) => a - b)
``time.barData.bars.__@unscopables@73.splicetime.barData.bars.__@unscopables@73.splice: boolean
Removes elements from an array and, if necessary, inserts new elements in their place, returning the deleted elements.
startdeleteCountstartdeleteCountitemsReturns An array containing the elements that were deleted.
time.barData.bars.__@unscopables@73.unshifttime.barData.bars.__@unscopables@73.unshift: boolean
Inserts new elements at the start of an array, and returns the new length of the array.
itemstime.barData.bars.__@unscopables@73.indexOftime.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.
searchElementfromIndextime.barData.bars.__@unscopables@73.lastIndexOftime.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.
searchElementfromIndextime.barData.bars.__@unscopables@73.everytime.barData.bars.__@unscopables@73.every: boolean
Determines whether all the members of an array satisfy the specified test.
predicatethisArgpredicatethisArgtime.barData.bars.__@unscopables@73.sometime.barData.bars.__@unscopables@73.some: boolean
Determines whether the specified callback function returns true for any element of an array.
predicatethisArgtime.barData.bars.__@unscopables@73.forEachtime.barData.bars.__@unscopables@73.forEach: boolean
Performs the specified action for each element in an array.
callbackfnthisArgtime.barData.bars.__@unscopables@73.maptime.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.
callbackfnthisArgtime.barData.bars.__@unscopables@73.filtertime.barData.bars.__@unscopables@73.filter: boolean
Returns the elements of an array that meet the condition specified in a callback function.
predicatethisArgpredicatethisArgtime.barData.bars.__@unscopables@73.reducetime.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.
callbackfninitialValuecallbackfninitialValuetime.barData.bars.__@unscopables@73.reduceRighttime.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.
callbackfninitialValuecallbackfninitialValuetime.barData.bars.__@unscopables@73.findtime.barData.bars.__@unscopables@73.find: boolean
Returns the value of the first element in the array where predicate is true, and undefined otherwise.
predicatethisArgtime.barData.bars.__@unscopables@73.findIndextime.barData.bars.__@unscopables@73.findIndex: boolean
Returns the index of the first element in the array where predicate is true, and -1 otherwise.
predicatethisArgtime.barData.bars.__@unscopables@73.filltime.barData.bars.__@unscopables@73.fill: boolean
Changes all array elements from start to end index to a static value and returns the modified array
valuestartendtime.barData.bars.__@unscopables@73.copyWithintime.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
targetstartendtime.barData.bars.__@unscopables@73.entriestime.barData.bars.__@unscopables@73.entries: boolean
Returns an iterable of key, value pairs for every entry in the array
time.barData.bars.__@unscopables@73.keystime.barData.bars.__@unscopables@73.keys: boolean
Returns an iterable of keys in the array
time.barData.bars.__@unscopables@73.valuestime.barData.bars.__@unscopables@73.values: boolean
Returns an iterable of values in the array
time.barData.bars.__@unscopables@73.includestime.barData.bars.__@unscopables@73.includes: boolean
Determines whether an array includes a certain element, returning true or false as appropriate.
searchElementfromIndextime.barData.bars.__@unscopables@73.flatMaptime.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.
callbackthisArgtime.barData.bars.__@unscopables@73.flattime.barData.bars.__@unscopables@73.flat: boolean
Returns a new array with all sub-array elements concatenated into it recursively up to the specified depth.
depthtime.barData.bars.__@unscopables@73.attime.barData.bars.__@unscopables@73.at: boolean
Returns the item located at the specified index.
indextime.barData.bars.__@unscopables@73.findLasttime.barData.bars.__@unscopables@73.findLast: boolean
Returns the value of the last element in the array where predicate is true, and undefined otherwise.
predicatethisArgtime.barData.bars.__@unscopables@73.findLastIndextime.barData.bars.__@unscopables@73.findLastIndex: boolean
Returns the index of the last element in the array where predicate is true, and -1 otherwise.
predicatethisArgtime.barData.bars.__@unscopables@73.toReversedtime.barData.bars.__@unscopables@73.toReversed: boolean
Returns a copy of an array with its elements reversed.
time.barData.bars.__@unscopables@73.toSortedtime.barData.bars.__@unscopables@73.toSorted: boolean
Returns a copy of an array with its elements sorted.
compareFnts
[11, 2, 22, 1].toSorted((a, b) => a - b) // [1, 2, 11, 22]
``time.barData.bars.__@unscopables@73.toSplicedtime.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.
startdeleteCountitemsstartdeleteCountReturns A copy of the original array with the remaining elements.
time.barData.bars.__@unscopables@73.withtime.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.
indexvalueReturns The copied array with the updated value.
time.barData.bars.__@unscopables@73.__@iterator@71time.barData.bars.__@unscopables@73.__@iterator@71: boolean
Iterator
time.barData.bars.__@unscopables@73.__@unscopables@73time.barData.bars.__@unscopables@73.__@unscopables@73: boolean
Is an object whose properties have the value 'true' when they will be absent when used in a 'with' statement.
time_closetime_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.
tfsessiontimezoneReturns 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.
otherReturns 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.
otherReturns 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.
otherReturns 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.
exponentReturns 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.
otherReturns 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.
otherReturns 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.
otherReturns 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.
otherReturns 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.
otherReturns 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.
otherReturns 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.
otherReturns 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.
otherReturns 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.
otherReturns 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.
otherReturns 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.
trueValuefalseValueReturns 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.
offsetclose, 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).
indexReturns 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.fullHistorytime_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.cachedVersiontime_close.barsThe bars this series is aligned to ({ time, open, high, low, close, volume }, oldest first).
time_close.bars.toString()time_close.bars.toString(): string
Returns a string representation of an array.
time_close.bars.toLocaleString()time_close.bars.toLocaleString(): stringtime_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.
itemstime_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.
itemstime_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.
separatortime_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.
startendtime_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.
compareFnts
[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.
startdeleteCountReturns 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.
startdeleteCountitemsReturns 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.
itemstime_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.
searchElementfromIndextime_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.
searchElementfromIndextime_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.
predicatethisArgtime_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.
predicatethisArgtime_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.
callbackfnthisArgtime_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.
callbackfnthisArgtime_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.
predicatethisArgtime_close.bars.reduce()time_close.bars.reduce(callbackfn: (previousValue: Bar, currentValue: Bar, currentIndex: number, array: Bar[]) => Bar): Bartime_close.bars.reduce(callbackfn: (previousValue: Bar, currentValue: Bar, currentIndex: number, array: Bar[]) => Bar, initialValue: Bar): Bartime_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.
callbackfninitialValueCalls 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.
callbackfninitialValuecallbackfninitialValuetime_close.bars.reduceRight()time_close.bars.reduceRight(callbackfn: (previousValue: Bar, currentValue: Bar, currentIndex: number, array: Bar[]) => Bar): Bartime_close.bars.reduceRight(callbackfn: (previousValue: Bar, currentValue: Bar, currentIndex: number, array: Bar[]) => Bar, initialValue: Bar): Bartime_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.
callbackfninitialValueCalls 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.
callbackfninitialValuecallbackfninitialValuetime_close.bars.find()time_close.bars.find<S extends Bar>(predicate: (value: Bar, index: number, obj: Bar[]) => value is S, thisArg?: any): Stime_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.
predicatethisArgtime_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.
predicatethisArgtime_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
valuestartendtime_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
targetstartendtime_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.values()time_close.bars.values(): ArrayIterator<Bar>
Returns an iterable of values 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.
searchElementfromIndextime_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.
callbackthisArgtime_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.
depthtime_close.bars.at()time_close.bars.at(index: number): Bar
Returns the item located at the specified index.
indextime_close.bars.findLast()time_close.bars.findLast<S extends Bar>(predicate: (value: Bar, index: number, array: Bar[]) => value is S, thisArg?: any): Stime_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.
predicatethisArgtime_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.
predicatethisArgtime_close.bars.toReversed()time_close.bars.toReversed(): Bar[]
Returns a copy of an array with its elements reversed.
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.
compareFnts
[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.
startdeleteCountitemsReturns The copied array.
Copies an array and removes elements while returning the remaining elements.
startdeleteCountReturns 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.
indexvalueReturns The copied array with the updated value.
time_close.bars.__@iterator@71()time_close.bars.__@iterator@71(): ArrayIterator<Bar>
Iterator
time_close.bars.lengthtime_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@73Is an object whose properties have the value 'true' when they will be absent when used in a 'with' statement.
time_close.bars.__@unscopables@73.lengthtime_close.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_close.bars.__@unscopables@73.toStringtime_close.bars.__@unscopables@73.toString: boolean
Returns a string representation of an array.
time_close.bars.__@unscopables@73.toLocaleStringtime_close.bars.__@unscopables@73.toLocaleString: boolean
Returns a string representation of an array. The elements are converted to string using their toLocaleString methods.
time_close.bars.__@unscopables@73.poptime_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.pushtime_close.bars.__@unscopables@73.push: boolean
Appends new elements to the end of an array, and returns the new length of the array.
itemstime_close.bars.__@unscopables@73.concattime_close.bars.__@unscopables@73.concat: boolean
Combines two or more arrays. This method returns a new array without modifying any existing arrays.
itemsitemstime_close.bars.__@unscopables@73.jointime_close.bars.__@unscopables@73.join: boolean
Adds all the elements of an array into a string, separated by the specified separator string.
separatortime_close.bars.__@unscopables@73.reversetime_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.shifttime_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.slicetime_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.
startendtime_close.bars.__@unscopables@73.sorttime_close.bars.__@unscopables@73.sort: boolean
Sorts an array in place. This method mutates the array and returns a reference to the same array.
compareFnts
[11,2,22,1].sort((a, b) => a - b)
``time_close.bars.__@unscopables@73.splicetime_close.bars.__@unscopables@73.splice: boolean
Removes elements from an array and, if necessary, inserts new elements in their place, returning the deleted elements.
startdeleteCountstartdeleteCountitemsReturns An array containing the elements that were deleted.
time_close.bars.__@unscopables@73.unshifttime_close.bars.__@unscopables@73.unshift: boolean
Inserts new elements at the start of an array, and returns the new length of the array.
itemstime_close.bars.__@unscopables@73.indexOftime_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.
searchElementfromIndextime_close.bars.__@unscopables@73.lastIndexOftime_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.
searchElementfromIndextime_close.bars.__@unscopables@73.everytime_close.bars.__@unscopables@73.every: boolean
Determines whether all the members of an array satisfy the specified test.
predicatethisArgpredicatethisArgtime_close.bars.__@unscopables@73.sometime_close.bars.__@unscopables@73.some: boolean
Determines whether the specified callback function returns true for any element of an array.
predicatethisArgtime_close.bars.__@unscopables@73.forEachtime_close.bars.__@unscopables@73.forEach: boolean
Performs the specified action for each element in an array.
callbackfnthisArgtime_close.bars.__@unscopables@73.maptime_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.
callbackfnthisArgtime_close.bars.__@unscopables@73.filtertime_close.bars.__@unscopables@73.filter: boolean
Returns the elements of an array that meet the condition specified in a callback function.
predicatethisArgpredicatethisArgtime_close.bars.__@unscopables@73.reducetime_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.
callbackfninitialValuecallbackfninitialValuetime_close.bars.__@unscopables@73.reduceRighttime_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.
callbackfninitialValuecallbackfninitialValuetime_close.bars.__@unscopables@73.findtime_close.bars.__@unscopables@73.find: boolean
Returns the value of the first element in the array where predicate is true, and undefined otherwise.
predicatethisArgtime_close.bars.__@unscopables@73.findIndextime_close.bars.__@unscopables@73.findIndex: boolean
Returns the index of the first element in the array where predicate is true, and -1 otherwise.
predicatethisArgtime_close.bars.__@unscopables@73.filltime_close.bars.__@unscopables@73.fill: boolean
Changes all array elements from start to end index to a static value and returns the modified array
valuestartendtime_close.bars.__@unscopables@73.copyWithintime_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
targetstartendtime_close.bars.__@unscopables@73.entriestime_close.bars.__@unscopables@73.entries: boolean
Returns an iterable of key, value pairs for every entry in the array
time_close.bars.__@unscopables@73.keystime_close.bars.__@unscopables@73.keys: boolean
Returns an iterable of keys in the array
time_close.bars.__@unscopables@73.valuestime_close.bars.__@unscopables@73.values: boolean
Returns an iterable of values in the array
time_close.bars.__@unscopables@73.includestime_close.bars.__@unscopables@73.includes: boolean
Determines whether an array includes a certain element, returning true or false as appropriate.
searchElementfromIndextime_close.bars.__@unscopables@73.flatMaptime_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.
callbackthisArgtime_close.bars.__@unscopables@73.flattime_close.bars.__@unscopables@73.flat: boolean
Returns a new array with all sub-array elements concatenated into it recursively up to the specified depth.
depthtime_close.bars.__@unscopables@73.attime_close.bars.__@unscopables@73.at: boolean
Returns the item located at the specified index.
indextime_close.bars.__@unscopables@73.findLasttime_close.bars.__@unscopables@73.findLast: boolean
Returns the value of the last element in the array where predicate is true, and undefined otherwise.
predicatethisArgtime_close.bars.__@unscopables@73.findLastIndextime_close.bars.__@unscopables@73.findLastIndex: boolean
Returns the index of the last element in the array where predicate is true, and -1 otherwise.
predicatethisArgtime_close.bars.__@unscopables@73.toReversedtime_close.bars.__@unscopables@73.toReversed: boolean
Returns a copy of an array with its elements reversed.
time_close.bars.__@unscopables@73.toSortedtime_close.bars.__@unscopables@73.toSorted: boolean
Returns a copy of an array with its elements sorted.
compareFnts
[11, 2, 22, 1].toSorted((a, b) => a - b) // [1, 2, 11, 22]
``time_close.bars.__@unscopables@73.toSplicedtime_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.
startdeleteCountitemsstartdeleteCountReturns A copy of the original array with the remaining elements.
time_close.bars.__@unscopables@73.withtime_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.
indexvalueReturns The copied array with the updated value.
time_close.bars.__@unscopables@73.__@iterator@71time_close.bars.__@unscopables@73.__@iterator@71: boolean
Iterator
time_close.bars.__@unscopables@73.__@unscopables@73time_close.bars.__@unscopables@73.__@unscopables@73: boolean
Is an object whose properties have the value 'true' when they will be absent when used in a 'with' statement.
time_close.barDataThe BarData holding the bars this series is aligned to.
time_close.barData.push()time_close.barData.push(bar: Bar): void
Add a new bar to the end
bartime_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
indexbartime_close.barData.updateLast()time_close.barData.updateLast(bar: Bar): void
Update the last bar (useful for real-time/streaming updates)
bartime_close.barData.setAll()time_close.barData.setAll(bars: Bar[]): void
Replace all bars with new data
barstime_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
indexReturns Bar at that index, or undefined
time_close.barData.versiontime_close.barData.version: number
Get the current version number Version increments whenever data is mutated
time_close.barData.lengthtime_close.barData.length: number
Get the number of bars
time_close.barData._barstime_close.barData._versiontime_close.barData.barsGet the underlying bar array Note: Direct mutations to this array will NOT increment version Use the provided mutation methods instead
time_close.barData.bars.toString()time_close.barData.bars.toString(): string
Returns a string representation of an array.
time_close.barData.bars.toLocaleString()time_close.barData.bars.toLocaleString(): stringtime_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.
itemstime_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.
itemstime_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.
separatortime_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.
startendtime_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.
compareFnts
[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.
startdeleteCountReturns 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.
startdeleteCountitemsReturns 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.
itemstime_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.
searchElementfromIndextime_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.
searchElementfromIndextime_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.
predicatethisArgtime_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.
predicatethisArgtime_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.
callbackfnthisArgtime_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.
callbackfnthisArgtime_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.
predicatethisArgtime_close.barData.bars.reduce()time_close.barData.bars.reduce(callbackfn: (previousValue: Bar, currentValue: Bar, currentIndex: number, array: Bar[]) => Bar): Bartime_close.barData.bars.reduce(callbackfn: (previousValue: Bar, currentValue: Bar, currentIndex: number, array: Bar[]) => Bar, initialValue: Bar): Bartime_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.
callbackfninitialValueCalls 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.
callbackfninitialValuecallbackfninitialValuetime_close.barData.bars.reduceRight()time_close.barData.bars.reduceRight(callbackfn: (previousValue: Bar, currentValue: Bar, currentIndex: number, array: Bar[]) => Bar): Bartime_close.barData.bars.reduceRight(callbackfn: (previousValue: Bar, currentValue: Bar, currentIndex: number, array: Bar[]) => Bar, initialValue: Bar): Bartime_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.
callbackfninitialValueCalls 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.
callbackfninitialValuecallbackfninitialValuetime_close.barData.bars.find()time_close.barData.bars.find<S extends Bar>(predicate: (value: Bar, index: number, obj: Bar[]) => value is S, thisArg?: any): Stime_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.
predicatethisArgtime_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.
predicatethisArgtime_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
valuestartendtime_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
targetstartendtime_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.keys()time_close.barData.bars.keys(): ArrayIterator<number>
Returns an iterable of keys in the array
time_close.barData.bars.values()time_close.barData.bars.values(): ArrayIterator<Bar>
Returns an iterable of values 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.
searchElementfromIndextime_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.
callbackthisArgtime_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.
depthtime_close.barData.bars.at()time_close.barData.bars.at(index: number): Bar
Returns the item located at the specified index.
indextime_close.barData.bars.findLast()time_close.barData.bars.findLast<S extends Bar>(predicate: (value: Bar, index: number, array: Bar[]) => value is S, thisArg?: any): Stime_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.
predicatethisArgtime_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.
predicatethisArgtime_close.barData.bars.toReversed()time_close.barData.bars.toReversed(): Bar[]
Returns a copy of an array with its elements reversed.
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.
compareFnts
[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.
startdeleteCountitemsReturns The copied array.
Copies an array and removes elements while returning the remaining elements.
startdeleteCountReturns 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.
indexvalueReturns The copied array with the updated value.
time_close.barData.bars.__@iterator@71()time_close.barData.bars.__@iterator@71(): ArrayIterator<Bar>
Iterator
time_close.barData.bars.lengthtime_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@73Is 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.lengthtime_close.barData.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_close.barData.bars.__@unscopables@73.toStringtime_close.barData.bars.__@unscopables@73.toString: boolean
Returns a string representation of an array.
time_close.barData.bars.__@unscopables@73.toLocaleStringtime_close.barData.bars.__@unscopables@73.toLocaleString: boolean
Returns a string representation of an array. The elements are converted to string using their toLocaleString methods.
time_close.barData.bars.__@unscopables@73.poptime_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.pushtime_close.barData.bars.__@unscopables@73.push: boolean
Appends new elements to the end of an array, and returns the new length of the array.
itemstime_close.barData.bars.__@unscopables@73.concattime_close.barData.bars.__@unscopables@73.concat: boolean
Combines two or more arrays. This method returns a new array without modifying any existing arrays.
itemsitemstime_close.barData.bars.__@unscopables@73.jointime_close.barData.bars.__@unscopables@73.join: boolean
Adds all the elements of an array into a string, separated by the specified separator string.
separatortime_close.barData.bars.__@unscopables@73.reversetime_close.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_close.barData.bars.__@unscopables@73.shifttime_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.slicetime_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.
startendtime_close.barData.bars.__@unscopables@73.sorttime_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.
compareFnts
[11,2,22,1].sort((a, b) => a - b)
``time_close.barData.bars.__@unscopables@73.splicetime_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.
startdeleteCountstartdeleteCountitemsReturns An array containing the elements that were deleted.
time_close.barData.bars.__@unscopables@73.unshifttime_close.barData.bars.__@unscopables@73.unshift: boolean
Inserts new elements at the start of an array, and returns the new length of the array.
itemstime_close.barData.bars.__@unscopables@73.indexOftime_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.
searchElementfromIndextime_close.barData.bars.__@unscopables@73.lastIndexOftime_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.
searchElementfromIndextime_close.barData.bars.__@unscopables@73.everytime_close.barData.bars.__@unscopables@73.every: boolean
Determines whether all the members of an array satisfy the specified test.
predicatethisArgpredicatethisArgtime_close.barData.bars.__@unscopables@73.sometime_close.barData.bars.__@unscopables@73.some: boolean
Determines whether the specified callback function returns true for any element of an array.
predicatethisArgtime_close.barData.bars.__@unscopables@73.forEachtime_close.barData.bars.__@unscopables@73.forEach: boolean
Performs the specified action for each element in an array.
callbackfnthisArgtime_close.barData.bars.__@unscopables@73.maptime_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.
callbackfnthisArgtime_close.barData.bars.__@unscopables@73.filtertime_close.barData.bars.__@unscopables@73.filter: boolean
Returns the elements of an array that meet the condition specified in a callback function.
predicatethisArgpredicatethisArgtime_close.barData.bars.__@unscopables@73.reducetime_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.
callbackfninitialValuecallbackfninitialValuetime_close.barData.bars.__@unscopables@73.reduceRighttime_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.
callbackfninitialValuecallbackfninitialValuetime_close.barData.bars.__@unscopables@73.findtime_close.barData.bars.__@unscopables@73.find: boolean
Returns the value of the first element in the array where predicate is true, and undefined otherwise.
predicatethisArgtime_close.barData.bars.__@unscopables@73.findIndextime_close.barData.bars.__@unscopables@73.findIndex: boolean
Returns the index of the first element in the array where predicate is true, and -1 otherwise.
predicatethisArgtime_close.barData.bars.__@unscopables@73.filltime_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
valuestartendtime_close.barData.bars.__@unscopables@73.copyWithintime_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
targetstartendtime_close.barData.bars.__@unscopables@73.entriestime_close.barData.bars.__@unscopables@73.entries: boolean
Returns an iterable of key, value pairs for every entry in the array
time_close.barData.bars.__@unscopables@73.keystime_close.barData.bars.__@unscopables@73.keys: boolean
Returns an iterable of keys in the array
time_close.barData.bars.__@unscopables@73.valuestime_close.barData.bars.__@unscopables@73.values: boolean
Returns an iterable of values in the array
time_close.barData.bars.__@unscopables@73.includestime_close.barData.bars.__@unscopables@73.includes: boolean
Determines whether an array includes a certain element, returning true or false as appropriate.
searchElementfromIndextime_close.barData.bars.__@unscopables@73.flatMaptime_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.
callbackthisArgtime_close.barData.bars.__@unscopables@73.flattime_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.
depthtime_close.barData.bars.__@unscopables@73.attime_close.barData.bars.__@unscopables@73.at: boolean
Returns the item located at the specified index.
indextime_close.barData.bars.__@unscopables@73.findLasttime_close.barData.bars.__@unscopables@73.findLast: boolean
Returns the value of the last element in the array where predicate is true, and undefined otherwise.
predicatethisArgtime_close.barData.bars.__@unscopables@73.findLastIndextime_close.barData.bars.__@unscopables@73.findLastIndex: boolean
Returns the index of the last element in the array where predicate is true, and -1 otherwise.
predicatethisArgtime_close.barData.bars.__@unscopables@73.toReversedtime_close.barData.bars.__@unscopables@73.toReversed: boolean
Returns a copy of an array with its elements reversed.
time_close.barData.bars.__@unscopables@73.toSortedtime_close.barData.bars.__@unscopables@73.toSorted: boolean
Returns a copy of an array with its elements sorted.
compareFnts
[11, 2, 22, 1].toSorted((a, b) => a - b) // [1, 2, 11, 22]
``time_close.barData.bars.__@unscopables@73.toSplicedtime_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.
startdeleteCountitemsstartdeleteCountReturns A copy of the original array with the remaining elements.
time_close.barData.bars.__@unscopables@73.withtime_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.
indexvalueReturns The copied array with the updated value.
time_close.barData.bars.__@unscopables@73.__@iterator@71time_close.barData.bars.__@unscopables@73.__@iterator@71: boolean
Iterator
time_close.barData.bars.__@unscopables@73.__@unscopables@73time_close.barData.bars.__@unscopables@73.__@unscopables@73: boolean
Is an object whose properties have the value 'true' when they will be absent when used in a 'with' statement.
timeframeThe 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"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".
secondsReturns 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"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"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.periodtimeframe.period: string
Chart timeframe with its multiplier: "1", "60", "1D", "1W", "30S". Throws when the app did not give it.
timeframe.main_periodtimeframe.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.multipliertimeframe.multiplier: number
Number before the unit of the chart timeframe: 60 for "60", 1 for "1D", 4 for "4W".
timeframe.isintradaytimeframe.isintraday: boolean
True on a minutes, seconds or ticks chart.
timeframe.isdailytimeframe.isdaily: boolean
True on a chart of days ("1D", "2D"...).
timeframe.isweeklytimeframe.isweekly: boolean
True on a chart of weeks.
timeframe.ismonthlytimeframe.ismonthly: boolean
True on a chart of months.
timeframe.isminutestimeframe.isminutes: boolean
True on a chart of minutes (and hours: "60", "240").
timeframe.issecondstimeframe.isseconds: boolean
True on a chart of seconds.
timeframe.istickstimeframe.isticks: boolean
True on a chart of ticks.
timeframe.isdwmtimeframe.isdwm: boolean
True on a chart of days, weeks or months.
xlocWhat the x coordinates of a drawing (label, line, box, polyline) are (xloc option).
xloc.bar_indexxloc.bar_index: "bar_index"
Bar indexes: 0 is the first bar, bar_index the current one (the default).
xloc.bar_timexloc.bar_time: "bar_time"
UNIX times in milliseconds, such as time or time_close.
xloc.panexloc.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.
ylocVertical placement of a label (label.new(..., { yloc })).
yloc.priceyloc.price: "price"
At the y value given to the label (the default).
yloc.abovebaryloc.abovebar: "abovebar"
Above the high of the bar at the label's x; the y value is not used.
yloc.belowbaryloc.belowbar: "belowbar"
Below the low of the bar at the label's x; the y value is not used.
Nothing matches this search.