Skip to the content

Help / Indicators and scripts

Scripting reference

Everything a script can use, as the editor knows it: autocomplete and the notes on hover come from the same list. Concepts first, then each function and namespace, then Pine constructs and what they become.

How scripts run#

Whole series, not bar by bar

A script runs once over all the bars. close is a Series: every bar’s close, oldest first. Maths is by method (close.sub(open), close.gt(open)) because JavaScript can’t overload + or >, and a series used as an if condition is always true: the editor marks it. Use select(cond, a, b) for a value per bar, and series((i, previous) => …) for a value that builds on its own past.

indicator('Range', { overlay: false });
const range = high.sub(low);
const wide = range.gt(ta.sma(range, 20).mul(1.5));
plot(range, { color: colors(wide, '#d65d5d', '#7f8ea3') });

Strategies

strategy.entry, close and exit take a series of conditions; orders fill at the next bar’s open. For decisions that need the open position, use strategy.onBar((bar, position, broker) => …): it’s called at each close in the backtest, and broker places orders with quantities, limits, stops and OCA groups.

Repainting and look-ahead

  • Higher timeframes (request.security) are read from their own closed bars, so a daily value changes only when the day closes, as it will live.
  • shift(-n) is refused and values[i + 1] is marked: both read a later bar. Strategies are run again on fewer bars to find any look-ahead, which the tester names.
  • Reading the last bar (barstate.islast, last_bar_index, .last()) changes history as bars come: it’s called a repaint.

Versions

A script states its API version (indicator('X', { api: 2 })). Saved scripts, alerts and publications keep theirs, and the editor’s Upgrade shows what a newer version would change before a script moves.

Note:Libraries come in with use('my:name') or use('@handle/name@1'); see Sharing.

Index#

Globals · str · matrix · strategy · input · table · label · line · box · polyline · linefill · ticker · syminfo · timeframe · barstate · console · log · ta · request · Series · Types

Globals#

Functions and values every script can use by name.

indicator(title: string, options?: IndicatorOptions): void
Declares an indicator. Call once, first.
library(name: string, options?: { api?: number }): void
Declares a library: what it exports (export function f…), scripts read with use('my:name') or use('@handle/name@1'). It draws, alerts and trades nothing itself. Call once, first.
use<K extends keyof ScriptLibraries>(name: K): ScriptLibraries[K]
A library's exports: use('my:name') for one of your own saved scripts, use('@handle/name@1') for a published release.
use(name: string): any
plot(values: SeriesLike, options?: { title?: string; color?: string | ColorSeries; style?: 'line' | 'stepline' | 'histogram' | 'columns' | 'dots' | 'circles' | 'cross' | 'area'; areaBase?: number; forceOverlay?: boolean; lineStyle?: 'solid' | 'dashed' | 'dotted'; lineWidth?: number; offset?: number; display?: 'all' | 'none' | 'dataWindow'; colorBySign?: { positive: string; negative: string }; }): PlotRef
Draws a series. Returns a reference for fill().
colors(cond: Series, a: string, b: string): ColorSeries
a on bars where cond holds, else b: a colour per bar for plot().
palette(colours: string[], index: SeriesLike): ColorSeries
palette[index] on each bar: a colour per bar for plot().
plotcandle(open: SeriesLike, high: SeriesLike, low: SeriesLike, close: SeriesLike, options?: { title?: string; colorUp?: string; colorDown?: string }): PlotRef
Candles of your own values (Pine's plotcandle), rising in colorUp and falling in colorDown.
plotshape(when: Series, options?: MarkerOptions & { shape?: ShapeKind; text?: string }): PlotRef
Draws a marker on bars where when is true.
hline(price: number): { readonly hline: number }
A horizontal reference line; fill() can shade between two.
alertcondition(when: Series, options?: { title?: string; message?: string }): void
Offers a condition for alerts: then create an alert on this script and pick it. It fires on bars where when is true; message is the alert's default text.
alert(when: Series, message: string | ((bar: number) => string), options?: { title?: string }): void
An alert with a message built from values (Pine's alert()): text, or a function of the bar index giving the text there, worked out only on bars where when holds, e.g. alert(rsi.gt(70), (i) => 'RSI ' + rsi.values[i].toFixed(1) + ' on {{ticker}}'). An alert on it sends that as {{message}}; {{close}}, {{plot("RSI")}} and the like are filled in too.
bgcolor(when: Series, color: string, options?: { title?: string }): PlotRef
Shades the background of bars where when is true, e.g. bgcolor(close.gt(open), 'rgba(76, 171, 52, 0.15)').
barcolor(when: Series, color: string, options?: { title?: string }): PlotRef
Paints the bars where when is true in color (on the price chart).
plotchar(when: Series, options?: MarkerOptions & { char?: string }): PlotRef
A character (default ★) above or below bars where when is true.
plotarrow(values: SeriesLike, options?: { title?: string; colorUp?: string; colorDown?: string }): PlotRef
Arrows: up under bars where values > 0, down over bars where values < 0.
fill(a: PlotRef | { readonly hline: number }, b: PlotRef | { readonly hline: number }, options?: { color?: string; topValue?: SeriesLike; bottomValue?: SeriesLike; topColor?: string; bottomColor?: string }): void
Shades between two plots, or two hlines: in one colour, or as a gradient from topColor at topValue to bottomColor at bottomValue (numbers or series).
series(fn: (index: number, previous: Float64Array) => number): Series
A series computed bar by bar; previous holds the values computed so far (for recursive formulas).
select(cond: Series, a: SeriesLike, b: SeriesLike): Series
cond ? a : b, per bar.
na(value: number): boolean
Whether a number is missing (NaN).
nz(value: number, replacement?: number): number
Replace a missing number.
open: Series
high: Series
low: Series
close: Series
volume: Series
time: Series
Bar open times, epoch milliseconds.
hl2: Series
hlc3: Series
ohlc4: Series
barCount: number
Number of bars.
bar_index: Series
Each bar's index, 0 for the oldest (Pine's bar_index).
last_bar_index: number
The newest bar's index.
time_close: Series
When each bar closes, epoch milliseconds (Pine's time_close).
taStep(kind: 'sma' | 'ema' | 'rma' | 'highest' | 'lowest' | 'stdev' | 'change' | 'crossover' | 'crossunder' | 'cross' | 'rising' | 'falling' | 'wma' | 'vwma' | 'hma' | 'tr' | 'atr' | 'rsi' | 'macd' | 'stoch' | 'cci' | 'mom' | 'roc' | 'pivothigh' | 'pivotlow' | 'highestbars' | 'lowestbars' | 'valuewhen' | 'barssince' | 'cum' | 'linreg' | 'percentrank' | 'correlation', ...params: number[]): { next(...inputs: number[]): number; nextAll(...inputs: number[]): number[] }
ta.* one bar at a time, for code that runs bar by bar (series((i) => …)): one per place it's used, fed each bar's value with next(x) (crosses: next(a, b)).
taStepSeries(kind: 'sma' | 'stdev' | 'highest' | 'lowest' | 'change' | 'mom' | 'roc' | 'rising' | 'falling' | 'wma' | 'vwma' | 'cci' | 'linreg' | 'percentrank' | 'correlation' | 'highestbars' | 'lowestbars' | 'stoch' | 'valuewhen'): { next(params: number[], ...inputs: number[]): number }
taStep with lengths that change bar by bar (Pine's series int): next([length], x).
timenow: number
The clock when the script runs, epoch ms (Pine's timenow).
last_bar_time: number
When the newest bar opened, epoch ms (Pine's last_bar_time).
hour(zone?: string): Series
The hour (0-23) each bar opens, in zone (default: the exchange's; UTC for crypto).
minute(zone?: string): Series
second(zone?: string): Series
dayofweek(zone?: string): Series
1 Sunday, 2 Monday … 7 Saturday, as Pine numbers them.
dayofmonth(zone?: string): Series
month(zone?: string): Series
1 January … 12 December.
year(zone?: string): Series
weekofyear(zone?: string): Series
The ISO week of the year (1-53) each bar opens in, in zone (Pine's weekofyear).
inMarketHours(): Series
1 on bars inside the market's regular hours, 0 before and after (Pine's session.ismarket).
inSession(session: string, zone?: string): Series
1 on bars opening inside a session such as '0930-1600' ('2200-0200' passes midnight; '0930-1600:23456' for Monday to Friday), in zone.
timestamp(year: number, month: number, day: number, hour?: number, minute?: number, second?: number, zone?: string): number
Epoch ms of a wall-clock time in zone (default: the exchange's). Months count from 1.
round(value: number, decimals?: number): number
Rounded to decimals places (Pine's math.round(x, precision)).
round(value: Series, decimals?: number): Series
roundToTick(value: number): number
Rounded to the symbol's tick size (Pine's math.round_to_mintick); as it is when the tick size isn't known.
roundToTick(value: Series): Series

str#

Pine's text functions. Numbers take a Pine format: "#.##", "0.00", 'mintick', 'percent', 'volume', 'integer'.

str.tostring(value: unknown, format?: string): string
str.format(pattern: string, ...values: unknown[]): string
"{0} at {1,number,#.##}" filled from the values.
str.tonumber(text: string): number
str.length(text: string): number
str.contains(text: string, part: string): boolean
str.startswith(text: string, part: string): boolean
str.endswith(text: string, part: string): boolean
str.pos(text: string, part: string): number
Where part first is, or NaN.
str.substring(text: string, begin: number, end?: number): string
str.replace(text: string, target: string, replacement: string, occurrence?: number): string
Replaces the occurrence-th (from 0) appearance.
str.replace_all(text: string, target: string, replacement: string): string
str.lower(text: string): string
str.upper(text: string): string
str.trim(text: string): string
str.split(text: string, separator: string): string[]
str.repeat(text: string, count: number, separator?: string): string
str.match(text: string, pattern: string): string
The first match of a regular expression, or ''.

matrix#

matrix.new(rows?: number, columns?: number, initial?: number): Matrix

strategy#

strategy(title: string, options?: StrategyOptions): void
strategy.long: 'long'
strategy.short: 'short'
strategy.entry(id: string, direction: 'long' | 'short', when: Series | ((position: StrategyPosition) => Series), options?: { alertMessage?: string }): void
Opens a position on bars where when is true, filled at the next bar's open. Reverses an opposite position.
strategy.close(target: 'long' | 'short' | 'all', when: Series | ((position: StrategyPosition) => Series), options?: { qtyPercent?: number; from?: string }): void
Closes the position (all, or only long/short) on bars where when is true, at the next open; with qtyPercent, only that percent of it.
strategy.exit(options: { direction?: 'long' | 'short'; from?: string; stopLossPercent?: number; takeProfitPercent?: number; trailingPercent?: number; stop?: SeriesLike; limit?: SeriesLike; qtyPercent?: number }): void
Protective exits: percentages from the entry price, or stop and limit prices. For every position, or one side (direction: strategy.long) or the position holding one entry (from: 'Long').
strategy.onBar(fn: (bar: BrokerBar, position: BrokerPosition, broker: Broker) => void): void
Decides bar by bar with the position in view: called at each close of the tested bars; place orders with broker. Not mixed with entry/close/exit. Read series with .values[bar.index].

input#

Inputs the user can change in the script's settings. Numbers are kept inside min and max (and whole for int), however they were set.

input.int(title: string, value: number, options?: { min?: number; max?: number; step?: number } & InputLayout): number
input.float(title: string, value: number, options?: { min?: number; max?: number; step?: number } & InputLayout): number
input.bool(title: string, value: boolean, options?: InputLayout): boolean
input.source(title: string, value?: SourceName, options?: InputLayout): Series
A price source the user can change (close, hl2, …).
input.select<T extends string>(title: string, value: T, options: T[], opts?: InputLayout): T
input.timeframe(title: string, value?: string, opts?: InputLayout): string
A timeframe for request.security: 'chart' (the chart's own), '1h', '4h', '1D', '1W'…
input.string(title: string, value?: string, options?: { options?: string[] } & InputLayout): string
Text; with options, one of them.
input.text_area(title: string, value?: string, options?: InputLayout): string
Text over several lines.
input.color(title: string, value: string, options?: InputLayout): string
A colour the user picks.
input.symbol(title: string, value?: string, options?: InputLayout): string
Another symbol ('binance:ETHUSDT'): pass it to request.security's { symbol } and its bars are loaded.
input.session(title: string, value?: string, options?: InputLayout): string
A session such as '0930-1600' (Pine's days after a colon: '0930-1600:23456'), for inSession().
input.time(title: string, value: number, options?: InputLayout): number
A moment, epoch ms (picked in the settings or on the chart).
input.price(title: string, value: number, options?: InputLayout): number

table#

Tables of text over the chart (a dashboard), showing the last bar's values.

table.new(position: TablePosition, columns: number, rows: number, options?: { background?: string; frameColor?: string; frameWidth?: number; borderColor?: string; borderWidth?: number }): { id: number }
table.cell(table: { id: number }, column: number, row: number, text: string | number | Series, options?: { background?: string; color?: string; size?: LabelSize | number; halign?: 'left' | 'center' | 'right'; valign?: 'top' | 'middle' | 'bottom'; tooltip?: string; }): void
text may be a string, a number, or a series (its last value); tooltip shows on hover.
table.mergeCells(table: { id: number }, startColumn: number, startRow: number, endColumn: number, endRow: number): void
Joins the cells from one corner to the other into one (Pine's table.merge_cells).
table.clear(table: { id: number }, startColumn?: number, startRow?: number, endColumn?: number, endRow?: number): void
Empties every cell, or those from one corner to the other.

label#

Labels at a bar index (0 = first bar, barCount - 1 = last; a time with xloc: 'time') and a price. At most 500 of each kind.

label.new(bar: number, price: number, text: string | number | Series, options?: DrawingLook): DrawingHandle
A series shows its newest value.
label.set_xy(label: DrawingHandle, bar: number, price: number): void
label.set_x(label: DrawingHandle, bar: number): void
label.set_y(label: DrawingHandle, price: number): void
label.set_text(label: DrawingHandle, text: string | number | Series): void
label.set_color(label: DrawingHandle, color: string): void
label.set_textcolor(label: DrawingHandle, color: string): void
label.set_size(label: DrawingHandle, size: LabelSize): void
label.set_style(label: DrawingHandle, style: 'callout' | 'text'): void
label.set_tooltip(label: DrawingHandle, tooltip: string): void
label.get_x(label: DrawingHandle): number
label.get_y(label: DrawingHandle): number
label.get_text(label: DrawingHandle): string
label.delete(label: DrawingHandle | undefined): void

line#

Lines between two points (bar index, price).

line.new(bar1: number, price1: number, bar2: number, price2: number, options?: DrawingLook): DrawingHandle
line.set_xy1(line: DrawingHandle, bar: number, price: number): void
line.set_xy2(line: DrawingHandle, bar: number, price: number): void
line.set_x1(line: DrawingHandle, bar: number): void
line.set_y1(line: DrawingHandle, price: number): void
line.set_x2(line: DrawingHandle, bar: number): void
line.set_y2(line: DrawingHandle, price: number): void
line.set_color(line: DrawingHandle, color: string): void
line.set_width(line: DrawingHandle, width: number): void
line.set_style(line: DrawingHandle, style: 'solid' | 'dashed' | 'dotted'): void
line.set_extend(line: DrawingHandle, extend: 'none' | 'left' | 'right' | 'both'): void
line.get_x1(line: DrawingHandle): number
line.get_y1(line: DrawingHandle): number
line.get_x2(line: DrawingHandle): number
line.get_y2(line: DrawingHandle): number
line.get_price(line: DrawingHandle, bar: number): number
The line's price at a bar.
line.delete(line: DrawingHandle | undefined): void

box#

Boxes from bar left to bar right, between top and bottom: a fill, a border and words.

box.new(left: number, top: number, right: number, bottom: number, options?: DrawingLook): DrawingHandle
box.set_lefttop(box: DrawingHandle, bar: number, price: number): void
box.set_rightbottom(box: DrawingHandle, bar: number, price: number): void
box.set_left(box: DrawingHandle, bar: number): void
box.set_top(box: DrawingHandle, price: number): void
box.set_right(box: DrawingHandle, bar: number): void
box.set_bottom(box: DrawingHandle, price: number): void
box.set_bgcolor(box: DrawingHandle, color: string): void
box.set_border_color(box: DrawingHandle, color: string): void
box.set_text(box: DrawingHandle, text: string): void
box.set_text_color(box: DrawingHandle, color: string): void
box.set_color(box: DrawingHandle, color: string): void
box.get_left(box: DrawingHandle): number
box.get_top(box: DrawingHandle): number
box.get_right(box: DrawingHandle): number
box.get_bottom(box: DrawingHandle): number
box.delete(box: DrawingHandle | undefined): void

polyline#

A line through points, each [bar, price]; closed: true joins the ends and fills it with fill.

polyline.new(points: [number, number][], options?: DrawingLook & { closed?: boolean }): DrawingHandle
polyline.delete(polyline: DrawingHandle | undefined): void

linefill#

Shades between two lines (Pine's linefill.new).

linefill.new(line1: DrawingHandle, line2: DrawingHandle, color: string): DrawingHandle

ticker#

ticker.new(prefix: string, ticker: string): string
ticker.heikinashi(symbol: string): string
ticker.standard(symbol: string): string
ticker.modify(symbol: string): string

syminfo#

syminfo.tickerid: string
'binance:BTCUSDT'
syminfo.ticker: string
'BTCUSDT'
syminfo.prefix: string
The venue, 'binance'.
syminfo.mintick: number
The smallest price step.
syminfo.currency: string
syminfo.type: string
'crypto', 'stock', 'forex', …
syminfo.timezone: string
The exchange's IANA time zone.
syminfo.session: string
'utc' (round the clock), 'us-equity' or 'forex'.
syminfo.pointvalue: number
What one unit of price movement is worth per contract (1 for spot).
syminfo.basecurrency: string
The base of a pair ('BTC'), or ''.
syminfo.description: string
A readable name, or the ticker.

timeframe#

The chart's timeframe (Pine's timeframe.*). period is written as we write timeframes: '1h', '1D'.

timeframe.period: string
timeframe.ms: number
Its length in ms (a month as 30 days).
timeframe.multiplier: number
Pine's multiplier: minutes for intraday (60 for 1h), else the count.
timeframe.isseconds: boolean
timeframe.isminutes: boolean
timeframe.isintraday: boolean
timeframe.isdaily: boolean
timeframe.isweekly: boolean
timeframe.ismonthly: boolean
timeframe.isdwm: boolean
timeframe.in_seconds(tf?: string): number
Seconds in tf ('1h', or Pine's '60', 'D'), or in the chart's timeframe when left out.

barstate#

Each bar's state, as series of 1 and 0 (Pine's barstate.*).

barstate.isfirst: Series
barstate.islast: Series
barstate.isconfirmed: Series
1 on closed bars, 0 on the forming one whose values may still change: use it to avoid signals that repaint.
barstate.isrealtime: Series
1 on the forming bar only.
barstate.ishistory: Series
barstate.isnew: Series
1 on each closed bar; 0 on the forming bar's updates.
barstate.islastconfirmedhistory: Series
1 on the newest closed bar only: the standard 'draw once' guard.

console#

The script's console, under the editor. A series shows its length and newest value.

console.log(...values: unknown[]): void
console.info(...values: unknown[]): void
console.warn(...values: unknown[]): void
console.error(...values: unknown[]): void

log#

Lines about one bar (Pine's log.*), e.g. inside series((i) => …): log.at(i, 'rsi', r.values[i]). Clicking one scrolls the chart there.

log.at(bar: number, ...values: unknown[]): void
log.warn(bar: number, ...values: unknown[]): void
log.error(bar: number, ...values: unknown[]): void

ta#

ta.sma(src: SeriesLike, length: SeriesLike): Series
length may be a series: a window of its own on each bar.
ta.ema(src: SeriesLike, length: number): Series
ta.rma(src: SeriesLike, length: number): Series
Wilder's moving average.
ta.wma(src: SeriesLike, length: SeriesLike): Series
length may be a series: a window of its own on each bar.
ta.hma(src: SeriesLike, length: number): Series
ta.vwma(src: SeriesLike, length: number): Series
ta.stdev(src: SeriesLike, length: SeriesLike): Series
length may be a series: a window of its own on each bar.
ta.highest(src: SeriesLike, length: SeriesLike): Series
length may be a series: a window of its own on each bar.
ta.lowest(src: SeriesLike, length: SeriesLike): Series
length may be a series: a window of its own on each bar.
ta.change(src: SeriesLike, bars?: number): Series
ta.mom(src: SeriesLike, length: number): Series
ta.roc(src: SeriesLike, length: number): Series
ta.sum(src: SeriesLike, length: SeriesLike): Series
length may be a series: a window of its own on each bar.
ta.cum(src: SeriesLike): Series
ta.rsi(src: SeriesLike, length: number): Series
ta.macd(src: SeriesLike, fast?: number, slow?: number, signal?: number): { macd: Series; signal: Series; histogram: Series }
ta.bb(src: SeriesLike, length?: number, mult?: number): { basis: Series; upper: Series; lower: Series }
ta.tr(): Series
ta.atr(length?: number): Series
ta.stoch(length?: number, smoothK?: number, smoothD?: number): { k: Series; d: Series }
Stochastic %K (smoothed) and %D of the close in the high-low range.
ta.stoch(src: Series, high: SeriesLike, low: SeriesLike, length: number): Series
Raw %K of any source in a high/low range, as in Pine: ta.stoch(rsi, rsi, rsi, 14) is Stochastic RSI.
ta.cci(src: SeriesLike, length?: number): Series
ta.mfi(length?: number): Series
Money Flow Index of the typical price (hlc3).
ta.mfi(src: Series, length?: number): Series
Money Flow Index of any source.
ta.obv(): Series
ta.vwap(src?: SeriesLike, anchor?: Series | 'day' | 'week' | 'month'): Series
VWAP of src (hlc3 by default), restarting each UTC day, week (from Monday) or month, or on bars where an anchor series is true.
ta.supertrend(factor?: number, atrLength?: number): { line: Series; direction: Series }
ta.crossover(a: SeriesLike, b: SeriesLike): Series
1 on bars where a crosses above b.
ta.crossunder(a: SeriesLike, b: SeriesLike): Series
1 on bars where a crosses below b.
ta.cross(a: SeriesLike, b: SeriesLike): Series
ta.barssince(condition: Series): Series
ta.valuewhen(condition: Series, src: SeriesLike, occurrence?: number): Series
ta.rising(src: SeriesLike, length: number): Series
1 where src is above each of its previous len values.
ta.falling(src: SeriesLike, length: number): Series
1 where src is below each of its previous len values.
ta.pivothigh(src: SeriesLike, left: number, right: number): Series
A pivot high's price on the bar right bars after it (when it's confirmed), else NaN.
ta.pivotlow(src: SeriesLike, left: number, right: number): Series
A pivot low's price on the bar right bars after it, else NaN.
ta.linreg(src: SeriesLike, length: number, offset?: number): Series
The least-squares line over the last length values, offset bars back from its end.
ta.highestbars(src: SeriesLike, length: SeriesLike): Series
Bars back to the highest of the last length values, as a negative number.
ta.lowestbars(src: SeriesLike, length: SeriesLike): Series
ta.percentrank(src: SeriesLike, length: number): Series
Percent of the previous length values at or below this one.
ta.correlation(a: SeriesLike, b: SeriesLike, length: number): Series
Pearson correlation over length bars, -1 to 1.
ta.median(src: SeriesLike, length: number): Series
ta.dev(src: SeriesLike, length: number): Series
Mean absolute deviation.
ta.variance(src: SeriesLike, length: number): Series
ta.cmo(src: SeriesLike, length: number): Series
Chande momentum oscillator, -100 to 100.
ta.wpr(length?: number): Series
Williams %R, -100 to 0.
ta.alma(src: SeriesLike, length: number, offset?: number, sigma?: number): Series
Arnaud Legoux moving average.
ta.swma(src: SeriesLike): Series
Symmetric weighted moving average of 4 bars.
ta.tsi(src: SeriesLike, short?: number, long?: number): Series
True strength index, -1 to 1.
ta.dmi(diLength?: number, adxSmoothing?: number): { plus: Series; minus: Series; adx: Series }
Directional movement: +DI, -DI and ADX.
ta.kc(src: SeriesLike, length?: number, mult?: number, useTrueRange?: boolean): { basis: Series; upper: Series; lower: Series }
Keltner channels.
ta.sar(start?: number, increment?: number, maximum?: number): Series
Parabolic SAR.
ta.bbw(src: SeriesLike, length?: number, mult?: number): Series
Bollinger Bands width: (upper - lower) / basis.
ta.kcw(src: SeriesLike, length?: number, mult?: number, useTrueRange?: boolean): Series
Keltner Channels width: (upper - lower) / basis.
ta.range(src: SeriesLike, length: number): Series
Highest minus lowest of the last length values.
ta.mode(src: SeriesLike, length: number): Series
The most frequent of the last length values.
ta.percentile_linear_interpolation(src: SeriesLike, length: number, percentage: number): Series
ta.percentile_nearest_rank(src: SeriesLike, length: number, percentage: number): Series
ta.rci(src: SeriesLike, length: number): Series
Rank Correlation Index, -100 to 100.
ta.cog(src: SeriesLike, length: number): Series
Centre of gravity.
ta.max(src: SeriesLike): Series
The highest value so far.
ta.min(src: SeriesLike): Series
The lowest value so far.
ta.accdist(): Series
Accumulation/distribution.
ta.pvt(): Series
Price-volume trend.
ta.nvi(): Series
Negative and positive volume indexes, from 1.
ta.pvi(): Series
ta.wad(): Series
Williams accumulation/distribution, and its variable form.
ta.wvad(): Series
ta.iii(): Series
Intraday intensity index.
ta.fixnan(src: SeriesLike): Series
The last value that wasn't NaN, carried forward.

request#

request.security(timeframe: string, fn: (bars: TimeframeBars) => SeriesLike, options?: { gaps?: boolean; symbol?: string; barsBack?: number; }): Series
fn computed on a higher timeframe ('1h', '4h', '1D', '1W', '1M'), mapped back to the chart's bars. Each bar sees the newest higher-timeframe bar that had closed by then, so backtests don't see the future. Compute from fn's argument: request.security('1D', (d) => d.ta.sma(d.close, 20)). With { gaps: true } the value shows only on the bars where one closes.
request.periodOpen(timeframe: string): Series
The open of the higher-timeframe period each chart bar is in ('1D': today's open on an intraday chart), known from the period's first bar, so it doesn't look ahead.
request.periodStart(timeframe: string): Series
When the timeframe's period each bar is in opens ('1D': the day's start; Pine's time("D")).
request.periodEnd(timeframe: string): Series
When that period closes (Pine's time_close("D")): a stock's day at its close.
request.currencyRate(from: string, to: string): Series
The rate turning one currency into another on each bar ('EUR', 'USD'), from a forex pair; 1 for the same money.
request.lowerTf(timeframe: string, fn: (bars: TimeframeBars) => SeriesLike, options?: { symbol?: string }): Intrabar
A lower timeframe's values inside each chart bar (Pine's request.security_lower_tf): fn is worked out on that timeframe's bars ('1m' on a 1h chart), e.g. request.lowerTf('1m', (d) => d.close.sub(d.open).mul(d.volume)).sum(). Chart bars older than its history have none.
request.financial(field: 'revenue' | 'grossProfit' | 'operatingIncome' | 'netIncome' | 'eps' | 'operatingCashFlow', options?: { period?: 'FQ' | 'FY'; symbol?: string; gaps?: boolean }): Series
A stock's reported results by quarter (FQ, the default) or year (FY), on each bar from the day after its filing; NaN without filings.
request.earnings(options?: { field?: 'actual' | 'estimate' | 'surprise'; symbol?: string; gaps?: boolean }): Series
Reported EPS (actual, the default), the estimate, or the surprise, from the day after each report (your own Finnhub key).
request.dividends(options?: { symbol?: string; gaps?: boolean }): Series
The newest dividend per share, from its ex-date.
request.splits(options?: { symbol?: string; gaps?: boolean }): Series
The newest split as new shares per old (4 for 4:1), from its ex-date.
request.economic(field: 'gdp' | 'cpi' | 'unemployment' | 'fedFunds' | 'pce' | 'retailSales' | 'claims', options?: { country?: 'US'; gaps?: boolean }): Series
A US economic figure from FRED, as first published, from the day after its release (your own FRED key).

Series#

A value per bar, oldest first. Math is by method because JavaScript has no operator overloading.

Series.values: Float64Array
Series.length: number
Series.from(length: number, fn: (index: number) => number): Series
A series computed per bar.
Series.at(index: number): number
Value at a bar; negative indices count back from the last bar (-1 = last).
Series.last(): number
The newest value.
Series.add(other: SeriesLike): Series
Series.sub(other: SeriesLike): Series
Series.mul(other: SeriesLike): Series
Series.div(other: SeriesLike): Series
Series.pow(other: SeriesLike): Series
Series.neg(): Series
Series.abs(): Series
Series.max(other: SeriesLike): Series
Element-wise maximum.
Series.min(other: SeriesLike): Series
Element-wise minimum.
Series.gt(other: SeriesLike): Series
1 where this > other, else 0.
Series.gte(other: SeriesLike): Series
Series.lt(other: SeriesLike): Series
Series.lte(other: SeriesLike): Series
Series.eq(other: SeriesLike): Series
Series.neq(other: SeriesLike): Series
Series.and(other: SeriesLike): Series
Series.or(other: SeriesLike): Series
Series.not(): Series
Series.shift(n?: number): Series
The value n bars ago (Pine's src[n]). n must be 0 or more: a negative n would read future bars, so it throws (use plot's offset to draw shifted).
Series.nz(value?: number): Series
Replace missing values (Pine's nz).
Series.map(fn: (value: number, index: number) => number): Series
Series.toArray(): number[]

Types#

Options and results the functions above take and give back.

type SeriesLike = Series | number
type SourceName = 'open' | 'high' | 'low' | 'close' | 'hl2' | 'hlc3' | 'ohlc4'
type ShapeKind = 'triangleUp' | 'triangleDown' | 'circle' | 'cross' | 'diamond' | 'none'
type ShapeLocation = 'above' | 'below' | 'top' | 'bottom' | 'absolute'
above/below the bar (in a pane of its own: the pane's top/bottom edge), top/bottom of the pane, or absolute: at the value given as at.
interface MarkerOptions { title?: string; location?: ShapeLocation; at?: SeriesLike; offset?: number; color?: string; forceOverlay?: boolean; }
interface IndicatorOptions { overlay?: boolean; shortTitle?: string; levels?: number[]; range?: [number, number]; format?: 'price' | 'percent' | 'volume'; precision?: number; }
type OrderSize = | { type: 'percent'; value: number } | { type: 'quantity'; value: number } | { type: 'cash'; value: number }
Percent of equity (× leverage), units, or cash: the order's value, whatever the leverage.
interface StrategyOptions extends IndicatorOptions { initialCapital?: number; commissionPercent?: number; slippagePercent?: number; slippageTicks?: number; orderSize?: OrderSize; pyramiding?: number; barMagnifier?: boolean; intrabar?: 'conservative' | 'ohlc'; commissionPerOrder?: number; commissionPerUnit?: number; leverageLong?: number; leverageShort?: number; maintenanceMarginPercent?: number; financingPercentYear?: number; fillOnClose?: boolean; calcOnEveryTick?: boolean; tradeDirection?: 'both' | 'long' | 'short'; maxDrawdownPercent?: number; dailyLossPercent?: number; maxTradesPerDay?: number; maxConsecutiveLossDays?: number; maxPositionSize?: number; riskFreePercent?: number; accountCurrency?: string; }
interface PlotRef { readonly id: string }
interface Matrix { rows(): number; columns(): number; elements_count(): number; get(row: number, column: number): number; set(row: number, column: number, value: number): void; row(row: number): number[]; col(column: number): number[]; fill(value: number): void; add_row(index?: number, values?: number[]): void; add_col(index?: number, values?: number[]): void; remove_row(index?: number): number[]; remove_col(index?: number): number[]; swap_rows(a: number, b: number): void; swap_columns(a: number, b: number): void; reshape(rows: number, columns: number): void; copy(): Matrix; transpose(): Matrix; avg(): number; max(): number; min(): number; median(): number; sum(other: Matrix | number): Matrix; diff(other: Matrix | number): Matrix; mult(other: Matrix | number): Matrix; }
A matrix of numbers, rows by columns.
interface ScriptLibraries {}
The libraries the editor knows the exports of, by the name they're used by.
interface StrategyPosition { readonly long: Series; readonly short: Series; readonly flat: Series; readonly direction: Series; }
The open position, in an order's condition: each is 1 when it holds and 0 when not.
interface BrokerBar { readonly index: number; readonly time: number; readonly open: number; readonly high: number; readonly low: number; readonly close: number; readonly volume: number }
A bar as strategy.onBar sees it.
interface BrokerTrade { readonly id: string; readonly direction: 'long' | 'short'; readonly entryPrice: number; readonly entryTime: number; readonly entryBar: number; readonly quantity: number; readonly profit: number }
An open entry of the position. profit is marked at this close.
interface BrokerClosedTrade { readonly id: string; readonly direction: 'long' | 'short'; readonly entryPrice: number; readonly entryTime: number; readonly exitPrice: number; readonly exitTime: number; readonly quantity: number; readonly profit: number; readonly exitReason: string }
A closed trade (profit net of commission).
interface BrokerPosition { readonly size: number; readonly direction: 'flat' | 'long' | 'short'; readonly avgPrice: number; readonly quantity: number; readonly openTrades: number; readonly trades: readonly BrokerTrade[]; readonly closedTrades: number; readonly lastClosed: BrokerClosedTrade | undefined; readonly closed: readonly BrokerClosedTrade[]; readonly equity: number; readonly netProfit: number; readonly openProfit: number; readonly grossProfit: number; readonly grossLoss: number; readonly wins: number; readonly losses: number; readonly initialCapital: number; readonly maxDrawdown: number; readonly pending: readonly { readonly id: string; readonly kind: string }[]; }
The position and account at this close (Pine's strategy.position_size, position_avg_price, opentrades, closedtrades, equity, netprofit…).
interface BrokerOrderOptions { qty?: number; limit?: number; stop?: number; oca?: { name: string; type?: 'cancel' | 'reduce' | 'none' } }
qty in units (the strategy's order size when left out); limit and stop prices (both: stop-limit); oca: one-cancels-all group.
interface Broker { entry(id: string, direction: 'long' | 'short', options?: BrokerOrderOptions): void; order(id: string, direction: 'long' | 'short', options?: BrokerOrderOptions): void; exit(id: string, options: { from?: string; qty?: number; qtyPercent?: number; limit?: number; stop?: number; trailPercent?: number; profitDistance?: number; lossDistance?: number; profitPercent?: number; lossPercent?: number; side?: 'long' | 'short' }): void; close(id: string, options?: { qty?: number; qtyPercent?: number; immediately?: boolean }): void; closeAll(options?: { qtyPercent?: number; immediately?: boolean }): void; cancel(id: string): void; cancelAll(): void; record(name: string, value: number): void; }
Places orders from strategy.onBar; they work from the next bar.
interface InputLayout { group?: string; inline?: string; tooltip?: string; id?: string }
Where an input sits in the settings: under a group heading, on a row with others of the same inline name, with a tooltip.
interface ColorSeries { readonly kind: 'colors'; readonly palette: readonly string[]; readonly index: Float64Array }
A colour per bar, from colors() or palette().
type TablePosition = | 'top_left' | 'top_center' | 'top_right' | 'middle_left' | 'middle_center' | 'middle_right' | 'bottom_left' | 'bottom_center' | 'bottom_right'
type LabelSize = 'tiny' | 'small' | 'normal' | 'large' | 'huge'
interface DrawingLook { color?: string; xloc?: 'index' | 'time'; width?: number; style?: 'solid' | 'dashed' | 'dotted'; extend?: 'none' | 'left' | 'right' | 'both'; text?: string; textColor?: string; size?: LabelSize; labelStyle?: 'callout' | 'text'; tooltip?: string; fill?: string; borderColor?: string; }
interface DrawingHandle { readonly id: number; readonly kind: 'label' | 'line' | 'box' | 'polyline'; set(patch: DrawingLook & { x?: number; y?: number; x2?: number; y2?: number; points?: [number, number][] }): void; get(): { points: ({ index: number; price: number } | { time: number; price: number })[]; text?: string; color: string } | undefined; delete(): void; }
A drawing the script keeps: change it, read it back, or remove it.
interface TimeframeBars { open: Series; high: Series; low: Series; close: Series; volume: Series; time: Series; hl2: Series; hlc3: Series; ohlc4: Series; barCount: number; bar_index: Series; ta: Ta; hour(zone?: string): Series; minute(zone?: string): Series; dayofweek(zone?: string): Series; dayofmonth(zone?: string): Series; month(zone?: string): Series; year(zone?: string): Series; weekofyear(zone?: string): Series; inMarketHours(): Series; inSession(session: string, zone?: string): Series; series(fn: (index: number, previous: Float64Array) => number): Series; select(cond: Series, a: SeriesLike, b: SeriesLike): Series; na(value: number): boolean; nz(value: number, replacement?: number): number; }
A higher timeframe's bars, built from the chart's, as request.security's function gets them.
interface Intrabar { readonly length: number; at(index: number): Float64Array; map(fn: (values: Float64Array, index: number) => number): Series; count(): Series; sum(): Series; mean(): Series; max(): Series; min(): Series; first(): Series; last(): Series; }
Lower-timeframe values inside each chart bar (request.lowerTf).

From Pine#

Pine on the left; on the right, what the converter writes for it, worked out as this page is shown. Where it can’t convert something it leaves a // TODO(pine) comment, and the editor counts them.

A moving average

plot(ta.ema(close, 20))
plot(ta.ema(close, 20));

Comparisons are per bar

up = close > open
const up = close.gt(open);

A value per bar from a condition

mid = close > open ? high : low
const mid = select(close.gt(open), high, low);

The value n bars ago

prev = close[1]
const prev = close.shift(1);

A value built on its own past

var float s = na
s := na(s[1]) ? close : s[1] * 0.9 + close * 0.1
plot(s)
const sStart = series(() => NaN);
let s = sStart;
const loopInput1 = close.mul(0.1);
const sByBar = new Float64Array(barCount);
for (let bar = 0; bar < barCount; bar++) {
  let s_ = bar > 0 ? sByBar[bar - 1] : sStart.values[0];
  s_ = (na((bar - 1 >= 0 ? sByBar[bar - 1] : NaN)) ? close.values[bar] : (((bar - 1 >= 0 ? sByBar[bar - 1] : NaN) * 0.9) + loopInput1.values[bar]));
  sByBar[bar] = s_;
}
s = series((i) => sByBar[i]);
plot(s);

An input

len = input.int(14, "Length")
const len = input.int('Length', 14);

A higher timeframe

h = request.security(syminfo.tickerid, "D", high)
const h = request.security('D', ({ open, high, low, close, volume, time, hl2, hlc3, ohlc4, ta, series, select, na, nz, barCount }) => high);

A marker

plotshape(ta.crossover(close, open), style=shape.triangleup, location=location.belowbar)
plotshape(ta.crossover(close, open), { shape: 'triangleUp', location: 'below' });

A background colour

bgcolor(close > open ? color.new(color.green, 80) : na)
bgcolor(close.gt(open), 'rgba(76, 175, 80, 0.2)');

An alert condition

alertcondition(ta.crossover(close, open), "Cross", "Crossed")
alertcondition(ta.crossover(close, open), { title: 'Cross', message: 'Crossed' });

A strategy entry

if ta.crossover(close, ta.sma(close, 20))
    strategy.entry("L", strategy.long)
strategy.entry('L', strategy.long, ta.crossover(close, ta.sma(close, 20)));

A stop and target

if close > open
    strategy.entry("L", strategy.long)
strategy.exit("X", "L", stop=low, limit=high * 1.02)
strategy.entry('L', strategy.long, close.gt(open));
strategy.exit({ from: 'L', stop: low, limit: high.mul(1.02) });

TradingView and Pine Script are trademarks of TradingView, Inc. OpenTapefolio is not affiliated with or endorsed by TradingView.