Inputs
Every input.* call must be assigned to a variable: the variable name identifies the setting. Inputs appear in the script's settings dialog in the order they are declared.
input.bool
Adds a checkbox to the script's settings and returns its current state as a boolean. defval sets the initial state. The call has to be assigned to a variable, and that variable name identifies the setting and becomes its label when no title is given.
Syntax
input.bool(defval, title?, tooltip?, inline?, group?, confirm = false, display?, active = true) → bool
Arguments
-
defval
bool
Default value
-
title
string
optional
Display title
-
tooltip
string
optional
Tooltip text
-
inline
string
optional
Inline group ID
-
group
string
optional
Input group name
-
confirm
bool
optional
Confirm input when adding the indicator
-
display
display
optional
Display mode
-
active
bool
optional
Whether the input can be edited
Returns
bool
input.color
Adds a colour swatch that opens a colour picker and returns the chosen colour, transparency included. defval sets the starting colour, and blue is used when none is supplied. The call has to be assigned to a variable, whose name identifies the setting and supplies its label when title is omitted.
Syntax
input.color(defval, title?, tooltip?, inline?, group?, confirm = false, display?, active = true) → color
Arguments
-
defval
color
Default value
-
title
string
optional
Display title
-
tooltip
string
optional
Tooltip text
-
inline
string
optional
Inline group ID
-
group
string
optional
Input group name
-
confirm
bool
optional
Confirm input when adding the indicator
-
display
display
optional
Display mode
-
active
bool
optional
Whether the input can be edited
Returns
color
input.enum
Adds a dropdown listing the members of an enum type and returns the member the user selects. It offers every member of the enum that defval belongs to unless an explicit options list narrows the choice, and the default remains usable even when it is outside that list. A saved selection no longer in the list falls back to the declared default. The call has to be assigned to a variable, whose name identifies the setting.
Syntax
input.enum(defval, title?, options?, tooltip?, inline?, group?, confirm = false, display?, active = true) → enum
Arguments
-
defval
enum
Default value
-
title
string
optional
Display title
-
options
array<enum>
optional
Allowed values
-
tooltip
string
optional
Tooltip text
-
inline
string
optional
Inline group ID
-
group
string
optional
Input group name
-
confirm
bool
optional
Confirm input when adding the indicator
-
display
display
optional
Display mode
-
active
bool
optional
Whether the input can be edited
Returns
the chosen enum member, of the same enum type as defval
input.expiry
Specific to this platform: adds a dropdown of the option expiry dates currently available for the chart's instrument, listed as formatted dates such as 25 Sep 2025, and returns the selected label as a string. defval provides the starting label. The call has to be assigned to a variable, whose name identifies the setting.
Syntax
input.expiry(defval, title?, tooltip?, inline?, group?, display?, active = true) → string
Arguments
-
defval
string
Default value
-
title
string
optional
Display title
-
tooltip
string
optional
Tooltip text
-
inline
string
optional
Inline group ID
-
group
string
optional
Input group name
-
display
display
optional
Display mode
-
active
bool
optional
Whether the input can be edited
Returns
string
input.float
Adds a decimal-number setting and returns its value as a float. Without an options list it is a numeric field that moves in increments of step and is kept inside minval and maxval; supplying options turns it into a dropdown limited to those numbers instead. Existing saved values outside the list are preserved for compatibility. minval must not be greater than maxval and step must be positive, and the call has to be assigned to a variable, whose name identifies the setting.
Syntax
input.float(defval, title?, minval?, maxval?, step = 1.0, tooltip?, inline?, group?, confirm = false, display?, active = true) → float
Arguments
-
defval
float
Default value
-
title
string
optional
Display title
-
minval
float
optional
Minimum allowed value
-
maxval
float
optional
Maximum allowed value
-
step
float
optional
Step increment
-
tooltip
string
optional
Tooltip text
-
inline
string
optional
Inline group ID
-
group
string
optional
Input group name
-
confirm
bool
optional
Confirm input when adding the indicator
-
display
display
optional
Display mode
-
active
bool
optional
Whether the input can be edited
Returns
float
input.int
Adds a whole-number setting and returns its value as an int. Without an options list it is a numeric field that moves in increments of step and is kept inside minval and maxval; supplying options turns it into a dropdown limited to those numbers instead. Existing saved values outside the list are preserved for compatibility. Keep minval no greater than maxval and step positive, and assign the call to a variable, whose name identifies the setting.
Syntax
input.int(defval, title?, minval?, maxval?, step = 1, tooltip?, inline?, group?, confirm = false, display?, active = true) → int
Arguments
-
defval
int
Default value
-
title
string
optional
Display title
-
minval
int
optional
Minimum allowed value
-
maxval
int
optional
Maximum allowed value
-
step
int
optional
Step increment
-
tooltip
string
optional
Tooltip text
-
inline
string
optional
Inline group ID
-
group
string
optional
Input group name
-
confirm
bool
optional
Confirm input when adding the indicator
-
display
display
optional
Display mode
-
active
bool
optional
Whether the input can be edited
Returns
int
Example
indicator("Configurable length", overlay = true)
length = input.int(14, "Length", minval = 1, maxval = 200)
plot(ta.sma(close, length), "SMA")
input.price
Adds a price setting, shown as a numeric field, and returns its value as a float. defval sets the starting price. The call has to be assigned to a variable, whose name identifies the setting.
Syntax
input.price(defval, title?, tooltip?, inline?, group?, confirm = false, display?, active = true) → float
Arguments
-
defval
float
Default value
-
title
string
optional
Display title
-
tooltip
string
optional
Tooltip text
-
inline
string
optional
Inline group ID
-
group
string
optional
Input group name
-
confirm
bool
optional
Confirm input when adding the indicator
-
display
display
optional
Display mode
-
active
bool
optional
Whether the input can be edited
Returns
float
input.session
Adds a trading-session setting and returns it as a string such as 0915-1530, which may hold several comma-separated ranges and a day list after a colon where 1 is Sunday and 7 is Saturday; the shorthand 24x7 is also accepted. A malformed session is reported as an error when the script runs, but a valid default can be outside the options list. An invalid or excluded saved selection falls back to the declared default. The call has to be assigned to a variable, whose name identifies the setting.
Syntax
input.session(defval, title?, options?, tooltip?, inline?, group?, confirm = false, display?, active = true) → string
Arguments
-
defval
string
Default value
-
title
string
optional
Display title
-
options
array<string>
optional
Allowed values
-
tooltip
string
optional
Tooltip text
-
inline
string
optional
Inline group ID
-
group
string
optional
Input group name
-
confirm
bool
optional
Confirm input when adding the indicator
-
display
display
optional
Display mode
-
active
bool
optional
Whether the input can be edited
Returns
string
input.source
Adds a dropdown for choosing which price series the calculation reads, offering open, high, low, close, hl2, hlc3, ohlc4 and hlcc4, and returns that series so it can be used anywhere close would be. defval has to be one of those series. The call has to be assigned to a variable, whose name identifies the setting.
Syntax
input.source(defval, title?, tooltip?, inline?, group?, display?, active = true, confirm = false) → float
Arguments
-
defval
float
Default value
-
title
string
optional
Display title
-
tooltip
string
optional
Tooltip text
-
inline
string
optional
Inline group ID
-
group
string
optional
Input group name
-
display
display
optional
Display mode
-
active
bool
optional
Whether the input can be edited
-
confirm
bool
optional
Confirm input when adding the indicator
Returns
float
Example
indicator("Chosen source", overlay = true)
source = input.source(close, "Source")
plot(ta.ema(source, 20), "EMA")
input.string
Adds a text setting and returns its value as a string. With an options list it is a dropdown restricted to those entries; without one it is a free-text field. A resolved default outside the options still displays in the dropdown, and existing saved string values outside the list are preserved for compatibility. If the default cannot be statically resolved, settings use a text field. The call has to be assigned to a variable, whose name identifies the setting and becomes its label when title is omitted.
Syntax
input.string(defval, title?, options?, tooltip?, inline?, group?, confirm = false, display?, active = true) → string
Arguments
-
defval
string
Default value
-
title
string
optional
Display title
-
options
array<string>
optional
Allowed values
-
tooltip
string
optional
Tooltip text
-
inline
string
optional
Inline group ID
-
group
string
optional
Input group name
-
confirm
bool
optional
Confirm input when adding the indicator
-
display
display
optional
Display mode
-
active
bool
optional
Whether the input can be edited
Returns
string
Example
indicator("Selectable average", overlay = true)
mode = input.string("EMA", "Method", options = ["EMA", "SMA"])
length = input.int(20, "Length")
value = mode == "EMA" ? ta.ema(close, length) : ta.sma(close, length)
plot(value, "Average")
input.symbol
Adds a symbol picker backed by the platform's instrument search and returns the selected symbol as a string, ready to pass to functions such as request.security. defval supplies the starting symbol. The call has to be assigned to a variable, whose name identifies the setting.
Syntax
input.symbol(defval, title?, tooltip?, inline?, group?, confirm = false, display?, active = true) → string
Arguments
-
defval
string
Default value
-
title
string
optional
Display title
-
tooltip
string
optional
Tooltip text
-
inline
string
optional
Inline group ID
-
group
string
optional
Input group name
-
confirm
bool
optional
Confirm input when adding the indicator
-
display
display
optional
Display mode
-
active
bool
optional
Whether the input can be edited
Returns
string
input.text_area
Adds a multi-line text box and returns its contents as a string, which suits longer values such as a list of price levels. defval provides the starting text. The call has to be assigned to a variable, whose name identifies the setting.
Syntax
input.text_area(defval, title?, tooltip?, group?, confirm = false, display?, active = true) → string
Arguments
-
defval
string
Default value
-
title
string
optional
Display title
-
tooltip
string
optional
Tooltip text
-
group
string
optional
Input group name
-
confirm
bool
optional
Confirm input when adding the indicator
-
display
display
optional
Display mode
-
active
bool
optional
Whether the input can be edited
Returns
string
input.time
Adds a date and time setting, edited through a date picker followed by a time picker, and returns the selected moment as a UNIX timestamp in milliseconds. defval is a timestamp in the same units, so timestamp() is a convenient way to write it. The call has to be assigned to a variable, whose name identifies the setting.
Syntax
input.time(defval, title?, tooltip?, inline?, group?, confirm = false, display?, active = true) → int
Arguments
-
defval
int
Default value
-
title
string
optional
Display title
-
tooltip
string
optional
Tooltip text
-
inline
string
optional
Inline group ID
-
group
string
optional
Input group name
-
confirm
bool
optional
Confirm input when adding the indicator
-
display
display
optional
Display mode
-
active
bool
optional
Whether the input can be edited
Returns
int
input.timeframe
Adds a timeframe selector and returns the chosen timeframe as a string. The default must use an accepted form, such as 1, 60, D, W or M; an invalid default stops the script. Invalid options are omitted from both settings and execution. Valid defaults can be outside the options, and invalid or excluded saved selections fall back to the declared default; an empty default falls back to the chart's own timeframe. The call has to be assigned to a variable, whose name identifies the setting.
Syntax
input.timeframe(defval, title?, options?, tooltip?, inline?, group?, confirm = false, display?, active = true) → string
Arguments
-
defval
string
Default value
-
title
string
optional
Display title
-
options
array<string>
optional
Allowed values
-
tooltip
string
optional
Tooltip text
-
inline
string
optional
Inline group ID
-
group
string
optional
Input group name
-
confirm
bool
optional
Confirm input when adding the indicator
-
display
display
optional
Display mode
-
active
bool
optional
Whether the input can be edited
Returns
string
Example
indicator("Higher timeframe close", overlay = true)
higher = input.timeframe("60", "Timeframe")
plot(request.security(syminfo.tickerid, higher, close), "Close")
Plotting and colouring
Functions that draw directly on the chart.
barcolor
Recolours the chart's own price bars on the current bar instead of adding a separate plot, so a condition can tint candles as they are drawn. Passing na on a bar leaves that bar in its normal colour, which is the usual way to colour only selected bars. offset shifts the colouring by a number of bars and show_last restricts it to the most recent ones.
Syntax
barcolor(color?, offset = 0, editable = true, show_last?, title?, display = display.all)
Arguments
-
color
color
optional
Color of bars
-
offset
int
optional
Bar offset
-
editable
bool
optional
Allow UI editing
-
show_last
int
optional
Show only last N bars
-
title
string
optional
Title
-
display
display
optional
Display mode
Returns
Nothing
bgcolor
Fills the background of the current bar's column with the given colour, forming vertical bands wherever it is called on consecutive bars. Passing na on a bar leaves that bar's background untouched, so a conditional colour highlights only the bars that matter. The band is drawn in the pane the script occupies, or on the price pane when the script is an overlay or force_overlay is true.
Syntax
bgcolor(color?, offset = 0, editable = true, show_last?, display = display.all, force_overlay = false)
Arguments
-
color
color
optional
Color value
-
offset
int
optional
Bar offset
-
editable
bool
optional
Allow UI editing
-
show_last
int
optional
Show only last N bars
-
display
display
optional
Display mode
-
force_overlay
bool
optional
Returns
Nothing
Example
indicator("Trend background", overlay = true)
rising = close > ta.sma(close, 50)
bgcolor(rising ? color.new(color.green, 92) : color.new(color.red, 92))
fill
Shades the region between two outputs of the same script, identified by the values that plot() and hline() return. The two arguments must be of the same kind, either two plots or two hlines; mixing a plot with an hline is rejected. A plain color argument gives a flat fill that may change from bar to bar, while supplying top_value, bottom_value, top_color and bottom_color instead paints a vertical gradient between those two levels, which is available for plot pairs only.
Syntax
fill(plot1?, plot2?, color?, title?, editable = true, show_last?, fill_gaps = false, top_value?, bottom_value?, top_color?, bottom_color?)
Arguments
-
plot1
plot
optional
First plot reference
-
plot2
plot
optional
Second plot reference
-
color
color
optional
Color value
-
title
string
optional
Display title
-
editable
bool
optional
Allow UI editing
-
show_last
int
optional
Show only last N bars
-
fill_gaps
bool
optional
Fill gaps in data
-
top_value
float
optional
Top gradient value
-
bottom_value
float
optional
Bottom gradient value
-
top_color
color
optional
Top gradient color
-
bottom_color
color
optional
Bottom gradient color
Returns
Nothing
It consumes the string ids that plot and hline return, but hands back none of its own.
Example
indicator("Band fill", overlay = true)
top = plot(ta.highest(high, 20), "Upper")
bottom = plot(ta.lowest(low, 20), "Lower")
fill(top, bottom, color.new(color.blue, 90))
hline
Draws a horizontal line at a fixed price across the full width of the chart and returns an identifier that fill() can pair with a second hline. The level has to be a constant rather than a value that changes per bar, and linestyle selects a solid, dotted or dashed line while linewidth sets its thickness. The line is drawn in the pane the script occupies.
Syntax
hline(price = 0.0, title?, color?, linestyle = hline.style_dashed, linewidth = 1, editable = true, display = display.all) → hline
Arguments
-
price
float
optional
Price level
-
title
string
optional
Display title
-
color
color
optional
Color value
-
linestyle
hline_style
optional
-
linewidth
int
optional
Line width in pixels
-
editable
bool
optional
Allow UI editing
-
display
display
optional
Display mode
Returns
hline
Example
indicator("Overbought and oversold")
plot(ta.rsi(close, 14), "RSI")
hline(70, "Overbought", color.red)
hline(30, "Oversold", color.green)
plot
Draws a numeric series as one value per bar and returns an identifier that fill() can refer to. style chooses the rendering, among line, stepline, area, histogram, columns, circles and cross, with histbase giving the baseline for the area, histogram and column styles, while offset shifts the drawing sideways by a number of bars. The colour may be a single colour or an expression evaluated on every bar, where na leaves that bar undrawn, and the plot appears in the script's pane unless the script is an overlay or force_overlay is true.
Syntax
plot(series, title?, color?, linewidth = 1, style = plot.style_line, trackprice = false, histbase = 0.0, offset = 0, join = false, editable = true, show_last?, display = display.all, format?, precision?, force_overlay = false) → plot
Arguments
-
series
float
Data series to plot
-
title
string
optional
Display title
-
color
color
optional
Color value
-
linewidth
int
optional
Line width in pixels
-
style
plot_style
optional
-
trackprice
bool
optional
-
histbase
float
optional
Histogram base level
-
offset
int
optional
Bar offset
-
join
bool
optional
Connect gaps
-
editable
bool
optional
Allow UI editing
-
show_last
int
optional
Show only last N bars
-
display
display
optional
Display mode
-
format
string
optional
Number format
-
precision
int
optional
Decimal precision
-
force_overlay
bool
optional
Returns
plot
Example
indicator("Two averages", overlay = true)
plot(ta.sma(close, 20), "Fast", color = color.aqua)
plot(ta.sma(close, 50), "Slow", color = color.orange, linewidth = 2)
plotarrow
Draws an arrow per bar from a numeric series: positive values point up, negative values point down, and na draws nothing. Arrow length follows the magnitude of the value, scaled between minheight and maxheight pixels, so relative size carries meaning. colorup and colordown set the colours used for the two directions.
Syntax
plotarrow(series, title?, colorup?, colordown?, offset = 0, minheight = 5, maxheight = 100, editable = true, show_last?, display = display.all)
Arguments
-
series
int
Data series to plot
-
title
string
optional
Display title
-
colorup
color
optional
Up candle/bar color
-
colordown
color
optional
Down candle/bar color
-
offset
int
optional
Bar offset
-
minheight
int
optional
Minimum arrow height
-
maxheight
int
optional
Maximum arrow height
-
editable
bool
optional
Allow UI editing
-
show_last
int
optional
Show only last N bars
-
display
display
optional
Display mode
Returns
string, an id identifying this call site
The id is not usable with fill, which accepts only the ids that plot and hline return.
plotbar
Draws one price bar per chart bar from four separate series, rendered in open-high-low-close bar style rather than as candles, which suits showing a derived or smoothed instrument. Bars whose values are all na are left out, so a condition can decide where bars appear. color sets the bar colour and may differ from bar to bar.
Syntax
plotbar(open, high, low, close, title?, color?, editable = true, show_last?, display = display.all)
Arguments
-
open
float
Open price
-
high
float
High price
-
low
float
Low price
-
close
float
Close price
-
title
string
optional
Display title
-
color
color
optional
Color value
-
editable
bool
optional
Allow UI editing
-
show_last
int
optional
Show only last N bars
-
display
display
optional
Display mode
Returns
string, an id identifying this call site
The id is not usable with fill, which accepts only the ids that plot and hline return.
plotcandle
Draws one candle per chart bar from four separate series, which is the usual way to show a derived or smoothed instrument alongside the chart. Candles whose values are all na are left out, so a condition can decide where they appear. color fills the body, wickcolor draws the wick and bordercolor outlines it, and each may differ from bar to bar.
Syntax
plotcandle(open, high, low, close, title?, color?, wickcolor?, editable = true, show_last?, bordercolor?, display = display.all)
Arguments
-
open
float
Open price
-
high
float
High price
-
low
float
Low price
-
close
float
Close price
-
title
string
optional
Display title
-
color
color
optional
Color value
-
wickcolor
color
optional
Candle wick color
-
editable
bool
optional
Allow UI editing
-
show_last
int
optional
Show only last N bars
-
bordercolor
color
optional
Candle border color
-
display
display
optional
Display mode
Returns
string, an id identifying this call site
The id is not usable with fill, which accepts only the ids that plot and hline return.
plotchar
Draws a single text character on the bars where the series is true or a number that is not na, which suits compact marks and symbols. char is required and only its first character is used, while location places the mark above or below the bar, at the top or bottom of the pane, or at the price carried by the series value when location.absolute is chosen. The character, its colour, its size and any accompanying text are fixed when the plot is created and apply to every bar it marks.
Syntax
plotchar(series, title?, char?, location = location.abovebar, color?, offset = 0, text?, textcolor?, editable = true, size = size.auto)
Arguments
-
series
bool
Data series to plot
-
title
string
optional
Display title
-
char
string
optional
Character to display
-
location
location
optional
-
color
color
optional
Color value
-
offset
int
optional
Bar offset
-
text
string
optional
Text content
-
textcolor
color
optional
Text color
-
editable
bool
optional
Allow UI editing
-
size
size
optional
Shape/text size
Returns
string, an id identifying this call site
The id is not usable with fill, which accepts only the ids that plot and hline return.
plotshape
Draws a small shape on the bars where the series is true or a number that is not na, choosing from the built-in shapes triangleup, triangledown, arrowup, arrowdown, labelup, labeldown, circle, cross, xcross, diamond, flag and square. location places the shape above or below the bar, at the top or bottom of the pane, or at the price carried by the series value when location.absolute is chosen, and offset shifts it sideways by a number of bars. The shape's colour, size and optional text are fixed when the plot is created and apply to every bar it marks.
Syntax
plotshape(series, title?, style = shape.xcross, location = location.abovebar, color?, offset = 0, text?, textcolor?, editable = true, size = size.auto, show_last?, display = display.all)
Arguments
-
series
bool
Data series to plot
-
title
string
optional
Display title
-
style
shape
optional
-
location
location
optional
-
color
color
optional
Color value
-
offset
int
optional
Bar offset
-
text
string
optional
Text content
-
textcolor
color
optional
Text color
-
editable
bool
optional
Allow UI editing
-
size
size
optional
Shape/text size
-
show_last
int
optional
Show only last N bars
-
display
display
optional
Display mode
Returns
string, an id identifying this call site
The id is not usable with fill, which accepts only the ids that plot and hline return.
Example
indicator("Cross markers", overlay = true)
fast = ta.sma(close, 10)
slow = ta.sma(close, 30)
plotshape(ta.crossover(fast, slow), "Up", shape.triangleup, location.belowbar)
plotshape(ta.crossunder(fast, slow), "Down", shape.triangledown, location.abovebar)
ta.* — Technical analysis
ta.accdist
Running accumulation/distribution line: each bar adds its money flow multiplier, ((close - low) - (high - close)) divided by the bar range, multiplied by volume, to a cumulative total that starts at zero. Bars whose high equals their low contribute nothing, and the result is na on any bar with missing price or volume data.
Syntax
ta.accdist() → float
Returns
float
ta.alma
Arnaud Legoux moving average of source over length bars, using Gaussian weights whose peak sits at offset (0 to 1, default 0.85) across the window and whose spread is set by sigma (default 6). A higher offset tracks recent bars more closely and a higher sigma makes the curve smoother; the result is na until length bars have been collected.
Syntax
ta.alma(source, length, offset, sigma) → float
Arguments
-
source
float
Input data series
-
length
int
Window size
-
offset
float
Gaussian offset (0-1)
-
sigma
float
Gaussian sigma
Returns
float
ta.atr
Average true range over length bars, in price units, as a measure of volatility. It is seeded with the simple average of the first length true ranges and then smoothed in Wilder's fashion, so it stays na until length bars exist; on the very first bar true range is taken as high minus low.
Syntax
ta.atr(length) → float
Arguments
-
length
int
Number of bars
Returns
float
Example
indicator("Average true range")
plot(ta.atr(14), "ATR")
ta.bb
Bollinger Bands over source: returns three values, the simple moving average basis, the upper band and the lower band, with the bands placed mult standard deviations (default 2) either side of the basis. The deviation is measured over the whole window rather than as a sample estimate. Like ta.sma, the window holds the last length values of source, skipping na bars, and all three values are na until it is full.
Syntax
ta.bb(source, length, mult) → [float, float, float]
Arguments
-
source
float
Input data series
-
length
int
Number of bars
-
mult
float
Standard deviation multiplier
Returns
[basis, upper, lower] - three floats
The middle band is the first element, not the last, and all three go na together until the average has enough bars.
Example
indicator("Bollinger bands", overlay = true)
[middle, upper, lower] = ta.bb(close, 20, 2)
plot(middle, "Basis", color = color.orange)
plot(upper, "Upper")
plot(lower, "Lower")
ta.bbw
Bollinger Band width: the distance between the upper and lower Bollinger Bands expressed as a percentage of the moving average basis, so it rises as volatility expands. Like ta.bb it skips na values of source, and it is na until length values exist, and also na if the basis is zero.
Syntax
ta.bbw(source, length, mult) → float
Arguments
-
source
float
Input data series
-
length
int
Number of bars
-
mult
float
Standard deviation multiplier
Returns
float
ta.cci
Commodity channel index over length bars: how far source sits from its simple moving average, divided by 0.015 times the mean absolute deviation of that window. It is unbounded and oscillates around zero, and reads 0 when every value in the window is the same. It is na until the window is full and whenever a bar inside it is na.
Syntax
ta.cci(source, length) → float
Arguments
-
source
float
Input data series
-
length
int
Number of bars
Returns
float
ta.change
Difference between source now and its value length bars ago, with length defaulting to 1. If source is a boolean the result is instead true when the two values differ. It returns na until length bars of history exist, and a negative length is rejected.
Syntax
ta.change(source, length = 1) → float
Arguments
-
source
Input data series
-
length
int
optional
Number of bars
Returns
float
ta.cmo
Chande momentum oscillator over length bars: the sum of upward changes minus the sum of downward changes, divided by their total and scaled to a range of -100 to +100. A completely flat window gives 0, and the result is na until length changes have accumulated.
Syntax
ta.cmo(source, length) → float
Arguments
-
source
float
Input data series
-
length
int
Number of bars
Returns
float
ta.cog
Centre of gravity of source over length bars, a weighted average of the positions of values within the window that behaves like a smooth, lagging oscillator. It is na until the window is full and whenever the values in the window sum to zero.
Syntax
ta.cog(source, length) → float
Arguments
-
source
float
Input data series
-
length
int
Number of bars
Returns
float
ta.correlation
Pearson correlation coefficient between source1 and source2 measured over length bars, running from -1 for opposite movement through 0 for no relationship to +1 for identical movement. A bar where one series is na is skipped for that series only, so afterwards the two windows can cover different bars and the result can stray outside -1 to +1. It is na until length values exist, and 0 when either series has no variation across its window.
Syntax
ta.correlation(source1, source2, length) → float
Arguments
-
source1
float
First source series
-
source2
float
Second source series
-
length
int
Number of bars
Returns
float
ta.cross
True on the bar where source1 and source2 swap sides, in either direction. It reports false rather than na on the first bar and whenever either input is missing.
Syntax
ta.cross(source1, source2) → bool
Arguments
-
source1
float
First source series
-
source2
float
Second source series
Returns
bool
ta.crossover
True only on the bar where source1 moves from at or below source2 to strictly above it. It reports false rather than na on the first bar and whenever either input is missing.
Syntax
ta.crossover(source1, source2) → bool
Arguments
-
source1
float
First source series
-
source2
float
Second source series
Returns
bool
Example
indicator("Crossover count")
fast = ta.ema(close, 9)
slow = ta.ema(close, 21)
var crosses = 0
if ta.crossover(fast, slow)
crosses := crosses + 1
plot(crosses, "Crossovers")
ta.crossunder
True only on the bar where source1 moves from at or above source2 to strictly below it. It reports false rather than na on the first bar and whenever either input is missing.
Syntax
ta.crossunder(source1, source2) → bool
Arguments
-
source1
float
First source series
-
source2
float
Second source series
Returns
bool
ta.cum
Running total of source from the first bar onwards, with no periodic reset. A bar whose source is na yields na for that bar and leaves the accumulated total untouched.
Syntax
ta.cum(source) → float
Arguments
-
source
float
Input data series
Returns
float
ta.dev
Mean absolute deviation of source from its own simple moving average over length bars, in the same units as source. Larger readings mean the series is straying further from its average. The result is na until the window is full and whenever a bar inside it is na.
Syntax
ta.dev(source, length) → float
Arguments
-
source
float
Input data series
-
length
int
Number of bars
Returns
float
ta.dmi
Directional movement index: returns three values, +DI, -DI and ADX. The two DI readings measure the strength of upward and downward movement over dilength bars on a 0 to 100 scale, while ADX smooths the gap between them over adxsmoothing bars as a trend-strength reading. All three are na through the warm-up and whenever the smoothed true range is zero.
Syntax
ta.dmi(dilength, adxsmoothing) → [float, float, float]
Arguments
-
dilength
int
DI length
-
adxsmoothing
int
ADX smoothing length
Returns
[diPlus, diMinus, adx] - three floats
ADX is the third element and remains na for the additional adxsmoothing bars after the two DI lines have values.
ta.ema
Exponential moving average of source over length bars. Warm-up matters here: no value is produced until length bars exist, the first one is the simple average of those bars, and exponential smoothing only takes over afterwards, so early values differ from an average seeded on the first bar.
Syntax
ta.ema(source, length) → float
Arguments
-
source
float
Input data series
-
length
int
Number of bars
Returns
float
Example
indicator("Exponential average", overlay = true)
plot(ta.ema(close, 21), "EMA 21")
ta.falling
True when source has fallen on each of the last length bars, every bar below the one before it. A bar equal to the one before it ends the run, and a comparison with a bar where source is na is skipped, neither adding to the run nor ending it. It returns false rather than na until such a run exists.
Syntax
ta.falling(source, length) → bool
Arguments
-
source
float
Input data series
-
length
int
Number of bars
Returns
bool
ta.highest
Highest value of source over the last length bars, falling back to the bar high when source is omitted. It is na until length bars exist. An na in source restarts the window: the result is na on that bar, and afterwards it covers only the bars since the na until length bars have passed.
Syntax
ta.highest(source?, length) → float
Arguments
-
source
float
optional
Input data series
-
length
int
Number of bars
Returns
float
Example
indicator("Twenty bar high", overlay = true)
plot(ta.highest(high, 20), "Highest high")
ta.highestbars
Offset of the bar carrying the highest value of source within the last length bars, falling back to the bar high when source is omitted. The result is zero or negative, with 0 meaning the current bar and -k meaning k bars ago, and when the highest value occurs on several bars the newest is reported. It is na until length bars exist. An na in source restarts the window, and on an na bar the offset is 0.
Syntax
ta.highestbars(source?, length) → int
Arguments
-
source
float
optional
Input data series
-
length
int
Number of bars
Returns
int
ta.hma
Hull moving average of source over length bars, which turns faster than a simple average of the same length while staying smooth. It is built from three weighted averages applied in sequence, each treating na as ta.wma does, so it returns na until enough values exist for all of them and on bars where source is na.
Syntax
ta.hma(source, length) → float
Arguments
-
source
float
Input data series
-
length
int
Number of bars
Returns
float
ta.ichimoku_cloud
Returns the five Ichimoku components in order: conversion line, base line, leading span A, leading span B and the lagging span. Every value is calculated for the current bar with no forward or backward displacement, so the lagging span is simply the current close and you must apply the usual offsets yourself when plotting. Each line other than the lagging span is na until its own period has elapsed.
Syntax
ta.ichimoku_cloud(conversion_periods = 9, base_periods = 26, lagging_span2_periods = 52) → [float, float, float, float, float]
Arguments
-
conversion_periods
int
optional
Conversion line periods
-
base_periods
int
optional
Base line periods
-
lagging_span2_periods
int
optional
Lagging span 2 periods
Returns
[conversion, base, leadingSpanA, leadingSpanB, laggingSpan] - five floats
The lagging span is simply the current close, so shift it back yourself when plotting, and leading span A is the midpoint of the conversion and base lines.
ta.iii
Intraday intensity index for the current bar: twice the close less the high and the low, divided by the bar's range times its volume. It reads off the current bar only, so there is no warm-up, and it is na on bars with zero range or zero volume.
Syntax
ta.iii() → float
Returns
float
ta.kc
Keltner Channels over source: returns the exponential moving average basis, the upper band and the lower band, offset by mult (default 1.5) times a smoothed range. That range is true range by default, or simply high minus low when usetruerange is false, and all three values are na through the moving average warm-up.
Syntax
ta.kc(source, length, mult, usetruerange = true) → [float, float, float]
Arguments
-
source
float
Input data series
-
length
int
Number of bars
-
mult
float
ATR multiplier
-
usetruerange
bool
optional
Use true range
Returns
[basis, upper, lower] - three floats
The basis comes first as with ta.bb, and all three elements are na together while the averages are still filling.
ta.kcw
Keltner Channel width: the distance between the upper and lower Keltner bands as a percentage of the exponential moving average basis. The band range uses true range unless usetruerange is false; the result is na during warm-up and when the basis is zero.
Syntax
ta.kcw(source, length, mult, usetruerange = true) → float
Arguments
-
source
float
Input data series
-
length
int
Number of bars
-
mult
float
ATR multiplier
-
usetruerange
bool
optional
Use true range
Returns
float
ta.linreg
Value of the least-squares straight line fitted to the last length bars of source, read offset bars back along that line. An offset of 0 gives the line's value on the current bar and larger offsets step backwards; the result is na until length bars are available.
Syntax
ta.linreg(source, length, offset) → float
Arguments
-
source
float
Input data series
-
length
int
Number of bars
-
offset
int
Offset from current bar
Returns
float
ta.lowest
Lowest value of source over the last length bars, falling back to the bar low when source is omitted. It is na until length bars exist. An na in source restarts the window: the result is na on that bar, and afterwards it covers only the bars since the na until length bars have passed.
Syntax
ta.lowest(source?, length) → float
Arguments
-
source
float
optional
Input data series
-
length
int
Number of bars
Returns
float
ta.lowestbars
Offset of the bar carrying the lowest value of source within the last length bars, falling back to the bar low when source is omitted. The result is zero or negative, with 0 meaning the current bar and -k meaning k bars ago, and when the lowest value occurs on several bars the newest is reported. It is na until length bars exist. An na in source restarts the window, and on an na bar the offset is 0.
Syntax
ta.lowestbars(source?, length) → int
Arguments
-
source
float
optional
Input data series
-
length
int
Number of bars
Returns
int
ta.macd
Returns the three MACD values in order: the MACD line, being the fast exponential average minus the slow one, the signal line, an exponential average of that line over siglen bars, and the histogram, the MACD line minus the signal. All are na while the underlying averages warm up, and the histogram remains na until the signal line itself has a value.
Syntax
ta.macd(source, fastlen, slowlen, siglen) → [float, float, float]
Arguments
-
source
float
Input data series
-
fastlen
int
Fast EMA length
-
slowlen
int
Slow EMA length
-
siglen
int
Signal EMA length
Returns
[macdLine, signalLine, histogram] - three floats
The histogram is the MACD line minus the signal line, so it stays na for the extra signal-length bars during which the MACD line already has a value.
Example
indicator("MACD")
[macdLine, signalLine, histogram] = ta.macd(close, 12, 26, 9)
plot(macdLine, "MACD")
plot(signalLine, "Signal", color = color.orange)
plot(histogram, "Histogram", style = plot.style_histogram)
ta.max
Highest value source has reached since the first bar, never resetting. A bar whose source is na yields na for that bar and leaves the recorded maximum unchanged.
Syntax
ta.max(source) → float
Arguments
-
source
float
Input data series
Returns
float
ta.median
Median of source over the last length bars: the middle value of the sorted window, or the average of the two middle values when length is even. It returns na until length usable values have been collected, and na inputs are skipped rather than counted towards the window.
Syntax
ta.median(source, length?) → float
Arguments
-
source
float
Input data series
-
length
int
optional
Number of bars
Returns
float
ta.mfi
Money flow index over length bars, a volume-weighted oscillator on a 0 to 100 scale comparing money flow on rising bars with money flow on falling bars. Source is the price used for money flow, typically hlc3, and volume comes from the chart. It is na through the warm-up, returns 100 when the window holds no negative flow, and 50 when there is no flow either way.
Syntax
ta.mfi(source, length) → float
Arguments
-
source
float
Input data series
-
length
int
Number of bars
Returns
float
ta.min
Lowest value source has reached since the first bar, never resetting. A bar whose source is na yields na for that bar and leaves the recorded minimum unchanged.
Syntax
ta.min(source) → float
Arguments
-
source
float
Input data series
Returns
float
ta.mode
Most frequently occurring value of source over the last length bars. When several values tie on frequency the smallest of them is returned, and the result is na until the window is full.
Syntax
ta.mode(source, length) → float
Arguments
-
source
float
Input data series
-
length
int
Number of bars
Returns
float
ta.mom
Momentum: source minus its value length bars ago, in the same units as source and positive when the series has risen over that span. It returns na until length bars of history exist.
Syntax
ta.mom(source, length) → float
Arguments
-
source
float
Input data series
-
length
int
Number of bars
Returns
float
ta.normalize
Rescales source onto the span between range_lower and range_upper using the highest and lowest values of the last length bars, so the window's low maps to range_lower and its high to range_upper. The bounds default to 0 and 1, and the result is na until length bars exist and when the window is completely flat.
Syntax
ta.normalize(source, range_upper, range_lower, length) → float
Arguments
-
source
float
Source series
-
range_upper
float
Upper range bound
-
range_lower
float
Lower range bound
-
length
int
Number of bars
Returns
float
ta.nvi
Negative volume index: a cumulative index starting at 1 that moves only on bars where volume fell against the previous bar, applying that bar's percentage price change. Bars with equal or rising volume leave it untouched, so only its trend is meaningful, not its absolute level.
Syntax
ta.nvi() → float
Returns
float
ta.obv
On-balance volume: a running total that adds the bar's volume on a higher close, subtracts it on a lower close and leaves it alone on an unchanged close. It starts at zero and never resets, so read its direction and slope rather than its level.
Syntax
ta.obv() → float
Returns
float
ta.percentile_linear_interpolation
The value below which the given percentage of the last length bars of source falls, interpolating linearly between the two neighbouring observations when the percentile lands between them. Percentage runs from 0 to 100, and the result is na until the window is full.
Syntax
ta.percentile_linear_interpolation(source, length, percentage) → float
Arguments
-
source
float
Input data series
-
length
int
Number of bars
-
percentage
float
Percentile (0-100)
Returns
float
ta.percentile_nearest_rank
The value below which the given percentage of the last length bars of source falls, returned as an actual observation from the window rather than an interpolated figure. Percentage runs from 0 to 100, with 100 giving the window maximum, and the result is na until the window is full.
Syntax
ta.percentile_nearest_rank(source, length, percentage) → float
Arguments
-
source
float
Input data series
-
length
int
Number of bars
-
percentage
float
Percentile (0-100)
Returns
float
ta.percentrank
Percentage of the previous length bars whose source is at or below the current value, on a 0 to 100 scale. The current bar is not counted, bars where source is na never count, and a bar where source itself is na reads 0. It returns na until length previous bars exist.
Syntax
ta.percentrank(source, length) → float
Arguments
-
source
float
Input data series
-
length
int
Number of bars
Returns
float
ta.pivot_point_levels
Returns up to eleven pivot levels derived from the previous completed period, ordered as the pivot itself, then R1, S1, R2, S2 and onwards; woodie also weighs the open of the period the levels are for. Type selects the formula and may be traditional, fibonacci, woodie, classic, dm or camarilla; formulas with fewer levels leave the remaining entries na. Pass anchor as true on the first bar of each period so the aggregated open, high, low and close roll over, and expect all-na results until one full period has completed. With developing set to true, the levels instead follow the current period as it forms, so they show where the next period's levels are heading; woodie levels can't develop, because they depend on the period's open.
Syntax
ta.pivot_point_levels(type, anchor, developing = false) → [float x 11]
Arguments
-
type
string
Pivot type (Traditional, Fibonacci, Woodie, Classic, DM, Camarilla)
-
anchor
bool
True on the first bar of each new period, which starts over
-
developing
bool
optional
Recalculate from the current period so far instead of the last finished one. Not for Woodie
Returns
[P, R1, S1, R2, S2, R3, S3, R4, S4, R5, S5] - eleven floats
There are always eleven elements with the resistance of each level before its support, and a type that defines fewer levels leaves the rest na: dm through S1, fibonacci through S3, woodie and classic through S4, traditional and camarilla through S5.
ta.pivothigh
Price of a confirmed swing high, taken from source or from the bar high when source is omitted. It is reported only rightbars later, and only when no bar among the leftbars before the candidate is higher and every bar among the rightbars after it is lower, so of two equal highs inside the same window the later one is the pivot. Bars beyond an na on either side are not compared, and an na candidate is never a pivot; every other bar returns na. Both leftbars and rightbars must be at least 1.
Syntax
ta.pivothigh(source?, leftbars, rightbars) → float
Arguments
-
source
float
optional
Input data series
-
leftbars
int
Left lookback bars
-
rightbars
int
Right lookback bars
Returns
float
ta.pivotlow
Price of a confirmed swing low, taken from source or from the bar low when source is omitted. It is reported only rightbars later, and only when no bar among the leftbars before the candidate is lower and every bar among the rightbars after it is higher, so of two equal lows inside the same window the later one is the pivot. Bars beyond an na on either side are not compared, and an na candidate is never a pivot; every other bar returns na. Both leftbars and rightbars must be at least 1.
Syntax
ta.pivotlow(source?, leftbars, rightbars) → float
Arguments
-
source
float
optional
Input data series
-
leftbars
int
Left lookback bars
-
rightbars
int
Right lookback bars
Returns
float
ta.pvi
Positive volume index: a cumulative index starting at 1 that moves only on bars where volume rose against the previous bar, applying that bar's percentage price change. Bars with equal or falling volume leave it untouched, so only its trend is meaningful, not its absolute level.
Syntax
ta.pvi() → float
Returns
float
ta.pvt
Price-volume trend: a running total that adds each bar's percentage change in close multiplied by its volume. It starts at zero and never resets, so read its direction and slope rather than its level.
Syntax
ta.pvt() → float
Returns
float
ta.range
Difference between the highest and lowest of the last length values of source, always zero or positive and in the same units as source. Bars where source is na are skipped rather than counted, so such a bar repeats the previous range, and the result is na until length values exist. When every value in the window is zero or below, the range is measured from zero: the range of -6, -5 and -3 is 6.
Syntax
ta.range(source, length) → float
Arguments
-
source
float
Input data series
-
length
int
Number of bars
Returns
float
ta.rci
Rank correlation index over length bars: the correlation between the order of prices and the order of time, scaled to a range of -100 to +100, where strongly positive readings mean the series has been climbing consistently. It returns na until the window is full.
Syntax
ta.rci(source, length) → float
Arguments
-
source
float
Input data series
-
length
int
Number of bars
Returns
float
ta.rising
True when source has risen on each of the last length bars, every bar above the one before it. A bar equal to the one before it ends the run, and a comparison with a bar where source is na is skipped, neither adding to the run nor ending it. It returns false rather than na until such a run exists.
Syntax
ta.rising(source, length) → bool
Arguments
-
source
float
Input data series
-
length
int
Number of bars
Returns
bool
ta.rma
Wilder's smoothed moving average of source over length bars, which reacts more slowly than an exponential average of the same length. The first value appears only once length bars exist and is the simple average of them, after which each bar is blended in with a weight of one over length.
Syntax
ta.rma(source, length) → float
Arguments
-
source
float
Input data series
-
length
int
Number of bars
Returns
float
ta.roc
Rate of change: the percentage difference between source now and its value length bars ago. It returns na until length bars of history exist, and also when the earlier value was zero.
Syntax
ta.roc(source, length) → float
Arguments
-
source
float
Input data series
-
length
int
Number of bars
Returns
float
ta.rsi
Relative strength index of source over length bars on a 0 to 100 scale, with high readings meaning gains have dominated recent changes. Average gains and losses are seeded with the simple average of the first length changes and then smoothed in Wilder's fashion, so the result is na until those bars exist. A bar where source is na is skipped, and so is the bar after it, whose change is unknown. A window with no losses returns 100, including one with no movement at all.
Syntax
ta.rsi(source, length) → float
Arguments
-
source
float
Input data series
-
length
int
Number of bars
Returns
float
Example
indicator("Relative strength")
plot(ta.rsi(close, 14), "RSI", color = color.purple)
ta.sar
Parabolic SAR trailing stop level in price units, with an acceleration factor that begins at start, grows by inc on each new extreme and is capped at max. It is na on the first bar, and the second bar seeds the calculation by assuming an uptrend, so readings before the first genuine reversal should be treated with care.
Syntax
ta.sar(start, inc, max) → float
Arguments
-
start
float
Start acceleration factor
-
inc
float
Acceleration increment
-
max
float
Maximum acceleration factor
Returns
float
ta.sma
Simple moving average: the arithmetic mean of the last length values of source. Bars where source is na are skipped rather than counted, so such a bar carries the average of the values before it, and the result is na until length values exist.
Syntax
ta.sma(source, length) → float
Arguments
-
source
float
Input data series
-
length
int
Number of bars
Returns
float
Example
indicator("Simple average", overlay = true)
length = input.int(20, "Length", minval = 1)
plot(ta.sma(close, length), "SMA")
ta.stdev
Standard deviation of the last length values of source, in the same units as source. It is computed over the window as a whole rather than as a sample estimate. Bars where source is na are skipped as in ta.sma, and the result is na until length values exist.
Syntax
ta.stdev(source, length) → float
Arguments
-
source
float
Input data series
-
length
int
Number of bars
Returns
float
ta.stoch
Position of source within the range of the supplied high and low series over length bars, scaled from 0 at the bottom of that range to 100 at the top, and na until length bars exist. On a bar where source, high or low is na, or where the range is flat and source sits on it, the previous value carries over. When the range is flat and source lies outside it, the result is na.
Syntax
ta.stoch(source, high, low, length) → float
Arguments
-
source
float
Source series
-
high
float
High series
-
low
float
Low series
-
length
int
Number of bars
Returns
float
ta.supertrend
Returns two values, the supertrend level in price units and the trend direction, where direction is -1 while the trend is up and the level trails below price, and 1 while it is down and the level trails above. Bands are placed factor times the average true range of atrperiod bars either side of the bar midpoint, and both values are na until that average true range is available.
Syntax
ta.supertrend(factor, atrperiod) → [float, float]
Arguments
-
factor
float
ATR multiplier factor
-
atrperiod
int
ATR period
Returns
[supertrend, direction] - two floats, direction being -1 or 1
Direction is -1 while the trend is up and the line tracks the lower band, and 1 while it is down and the line tracks the upper band.
ta.swma
Symmetrically weighted moving average over four bars, weighting them one sixth, two sixths, two sixths and one sixth from oldest to newest. It returns na until four bars are available.
Syntax
ta.swma(source) → float
Arguments
-
source
float
Input data series
Returns
float
ta.tr
True range of the current bar in price units: the largest of the bar's own high-low range, the distance from its high to the previous close, and the distance from its low to the previous close. On the first bar, where there is no previous close, it returns na unless handle_na is true, in which case it returns high minus low.
Syntax
ta.tr(handle_na = false) → float
Arguments
-
handle_na
bool
optional
Handle NA values
Returns
float
ta.tsi
True strength index of source: bar-to-bar change smoothed over long_length and then short_length bars, divided by the same double smoothing of the absolute change. The result is a ratio normally between -1 and 1 rather than a percentage, and it stays na through the fairly long warm-up of both smoothing stages. A bar where source is na is skipped, and so is the bar after it, whose change is unknown.
Syntax
ta.tsi(source, short_length, long_length) → float
Arguments
-
source
float
Input data series
-
short_length
int
Short smoothing length
-
long_length
int
Long smoothing length
Returns
float
ta.valuewhen
Value that source had on the bar where condition was most recently true, with occurrence 0 meaning the latest such bar, 1 the one before it, and so on. It returns na while the condition has not yet occurred that many times, and for a negative occurrence.
Syntax
ta.valuewhen(condition, source, occurrence) → float
Arguments
-
condition
bool
Condition to check
-
source
float
Input data series
-
occurrence
int
Nth occurrence (0-based)
Returns
float
Example
indicator("Close at last cross", overlay = true)
crossed = ta.crossover(close, ta.sma(close, 50))
plot(ta.valuewhen(crossed, close, 0), "Close when crossed")
ta.variance
Variance of the last length values of source, in squared source units. By default it is the biased figure, dividing by length; pass biased as false to divide by length minus 1 for the sample estimate instead. Bars where source is na are skipped as in ta.sma, and the result is na until length values exist.
Syntax
ta.variance(source, length, biased = true) → float
Arguments
-
source
float
Input data series
-
length
int
Number of bars
-
biased
bool
optional
Use biased calculation
Returns
float
ta.vwap
Volume-weighted average price in price units. Called with no arguments it accumulates hlc3 against volume from the first bar of the chart and never resets, whereas the form taking a source resets at the start of each trading day unless you pass an explicit anchor condition, in which case it resets on every bar where that condition is true. Supplying stdev_mult returns three values instead: the VWAP plus an upper and a lower band at that multiple of the volume-weighted standard deviation.
Syntax
ta.vwap(source?, anchor?, stdev_mult?) → float
Arguments
-
source
float
optional
Source series
-
anchor
bool
optional
Anchor condition for reset
-
stdev_mult
float
optional
Standard deviation multiplier for bands
Returns
float
ta.vwma
Volume-weighted moving average of source over length bars, giving busy bars more influence than quiet ones. A bar where source is na adds nothing to the weighted prices but its volume still counts, so such a bar keeps a value and the next few can differ from a plain weighted mean. It returns na until length values exist, when volume is unavailable, and when total volume is zero.
Syntax
ta.vwma(source, length) → float
Arguments
-
source
float
Input data series
-
length
int
Number of bars
Returns
float
ta.wad
Williams accumulation/distribution: a running total that on a higher close adds the close less the lower of this bar's low and the previous close, and on a lower close adds the close less the higher of this bar's high and the previous close, which drags the total down. Unchanged closes contribute nothing, and the total starts at zero and never resets.
Syntax
ta.wad() → float
Returns
float
ta.wma
Weighted moving average of source over length bars, with weights falling linearly from the newest bar back to the oldest so that recent values dominate. A bar inside the window where source is na counts as the value before it. The result is na until length values of source exist, and on bars where source is na.
Syntax
ta.wma(source, length) → float
Arguments
-
source
float
Input data series
-
length
int
Number of bars
Returns
float
ta.wpr
Williams %R over length bars: where the current close sits within the high-low range of that window, scaled from 0 at the top of the range down to -100 at the bottom. It reads the chart's own high, low and close, and returns na until length bars exist and when the range is flat.
Syntax
ta.wpr(length) → float
Arguments
-
length
int
Number of bars
Returns
float
ta.wvad
Williams variable accumulation/distribution for the current bar: the move from open to close as a fraction of the bar's high-low range, multiplied by volume. It reads off the current bar only, so there is no warm-up, and it is na on bars with zero range.
Syntax
ta.wvad() → float
Returns
float
str.* — Strings
str.contains
Returns true when substring occurs anywhere inside value. The comparison is case sensitive, an empty substring is always reported as present, and a na string argument behaves as an empty string.
Syntax
str.contains(value, substring) → bool
Arguments
-
value
string
Value to use
-
substring
string
Substring to find
Returns
bool
str.endswith
Returns true when value finishes with exactly the text given as suffix. The comparison is case sensitive and an empty suffix always matches.
Syntax
str.endswith(value, suffix) → bool
Arguments
-
value
string
Value to use
-
suffix
string
Returns
bool
str.format
Builds a string from a template, where {0} is replaced by the first value after the template, {1} by the second, and so on. A placeholder can also carry a type and pattern, as in {0,number,#.##} or {0,number,#,###.00}, along with the presets integer, currency and percent, and text wrapped in single quotes is emitted literally so braces can be printed. An unbalanced brace, an empty placeholder, or an index with no matching value stops the script with an error.
Syntax
str.format(format_string) → string
Arguments
-
format_string
string
Format template
Returns
string
Example
indicator("Labelled close", overlay = true)
if barstate.islast
label.new(bar_index, high, str.format("Close: {0}", close))
str.format_time
Turns a millisecond timestamp into readable text using the supplied pattern, in which yyyy, yy, MM, M, dd, d, HH, H, hh, h, mm, m, ss, s, S, a and Z stand for the date and time parts while every other character is copied through unchanged. The timezone argument accepts UTC or GMT, an explicit offset such as UTC+5:30, or one of a set of common zone names; anything else falls back to UTC, and the offsets used are fixed, with no daylight saving adjustment. A na timestamp is treated as zero, the start of 1970.
Syntax
str.format_time(time, format, timezone = "UTC") → string
Arguments
-
time
int
UNIX timestamp in milliseconds
-
format
string
Date/time format string
-
timezone
string
optional
Timezone (IANA name or UTC offset)
Returns
string
str.length
Returns how many characters value holds, which is 0 for an empty string. It is the usual way to check input length before slicing it with str.substring.
Syntax
str.length(value) → int
Arguments
-
value
string
Value to use
Returns
int
str.lower
Returns value with every letter converted to lower case and all other characters left untouched. It is commonly used to compare text without regard to case by lowering both sides first.
Syntax
str.lower(value) → string
Arguments
-
value
string
Value to use
Returns
string
str.match
Returns the first stretch of source that matches the regular expression regex, or an empty string when nothing matches. A regular expression that cannot be parsed also yields an empty string instead of stopping the script.
Syntax
str.match(source, regex) → string
Arguments
-
source
string
Source string
-
regex
string
Regular expression pattern
Returns
string
str.pos
Returns the zero-based position at which substring first appears in value, or -1 when it does not appear at all. Searching for an empty substring returns 0.
Syntax
str.pos(value, substring) → int
Arguments
-
value
string
Value to use
-
substring
string
Substring to find
Returns
int
str.repeat
Returns value joined end to end with itself count times, so a count of 3 applied to ab produces ababab. A count of zero or less, or a na count, returns an empty string.
Syntax
str.repeat(value, count) → string
Arguments
-
value
string
Value to repeat
-
count
int
Number of repetitions
Returns
string
str.replace
Returns value with only the first occurrence of from changed to to, leaving any later occurrences in place. When from does not occur the original string is returned unchanged.
Syntax
str.replace(value, from, to) → string
Arguments
-
value
string
Value to use
-
from
string
From value
-
to
string
To value
Returns
string
str.replace_all
Returns value with every occurrence of from changed to to. When from does not occur the original string is returned unchanged; use str.replace to change only the first match.
Syntax
str.replace_all(value, from, to) → string
Arguments
-
value
string
Value to use
-
from
string
From value
-
to
string
To value
Returns
string
str.split
Splits value everywhere pattern occurs and returns the pieces as a string array. When pattern never occurs the result is a one-element array holding the original string, and an empty pattern separates the text into individual characters.
Syntax
str.split(value, pattern) → array<string>
Arguments
-
value
string
Value to use
-
pattern
string
Search pattern
Returns
array<string>
str.startswith
Returns true when value begins with exactly the text given as prefix. The comparison is case sensitive and an empty prefix always matches.
Syntax
str.startswith(value, prefix) → bool
Arguments
-
value
string
Value to use
-
prefix
string
Returns
bool
str.substring
Returns the section of value running from the zero-based position start up to but not including end; with end left out it runs to the end of the string. Both positions must lie within the string and start must not sit past end, otherwise the call fails with an error.
Syntax
str.substring(value, start, end?) → string
Arguments
-
value
string
Value to use
-
start
int
Start position
-
end
int
optional
End position
Returns
string
str.tonumber
Parses value as a number and returns it, accepting whole numbers and decimals. An empty string, or text that is not a valid number, gives na, so the result is worth checking before it is used in arithmetic.
Syntax
str.tonumber(value) → float
Arguments
-
value
string
Value to use
Returns
float
str.tostring
Converts value to text: numbers keep up to ten decimal places with trailing zeros dropped, non-finite numbers appear as NaN, booleans become true or false, colours become a hex string, arrays are listed inside square brackets, and a na value gives an empty string. The optional second argument controls numeric formatting and takes either a format constant such as format.mintick, format.price, format.percent or format.volume, or a pattern such as #.## or #,###.00, where a trailing percent sign also multiplies the number by 100.
Syntax
str.tostring(value, format?) → string
Arguments
-
value
Value to use
-
format
string
optional
Number format
Returns
string
str.trim
Returns value with whitespace removed from both ends while spaces inside the text stay as they are. It is the usual way to tidy user input before comparing or parsing it.
Syntax
str.trim(value) → string
Arguments
-
value
string
Value to use
Returns
string
str.upper
Returns value with every letter converted to upper case and all other characters left untouched. It is often used to normalise text such as symbol or exchange names before comparison.
Syntax
str.upper(value) → string
Arguments
-
value
string
Value to use
Returns
string
array.* — Arrays
array.abs
Returns a new array in which every finite numeric element is replaced by its absolute value. Elements that are na or of a non-numeric type are carried across unchanged, and the source array is left as it was.
Syntax
array.abs(id) → array
Arguments
-
id
array
Object reference
Returns
array
array.avg
Returns the arithmetic mean of the finite numeric elements, ignoring na and any element that is not a number. Returns na when the array holds no finite numbers.
Syntax
array.avg(id) → float
Arguments
-
id
array
Object reference
Returns
float
array.binary_search
Searches an array that is already sorted in ascending order and returns the index of an element equal to the given value, or -1 when there is no match. Returns -1 if the search value is na or if a non-numeric element is met during the search; the array itself is never checked for being sorted.
Syntax
array.binary_search(id, value) → int
Arguments
-
id
array
Object reference
-
value
Value to search for
Returns
int
array.binary_search_leftmost
Searches an ascending-sorted array and returns the index of the first element that is not smaller than the value, which is also the position where the value would be inserted to keep the order. Returns 0 for an empty array or a na search value, and the array size when every element is smaller than the value.
Syntax
array.binary_search_leftmost(id, value) → int
Arguments
-
id
array
Object reference
-
value
Value to search for
Returns
int
array.binary_search_rightmost
Searches an ascending-sorted array and returns the index of the last element equal to the value, or the insertion position just past the smaller elements when no element matches. Returns 0 for an empty array or a na search value; near-equal numbers within a very small tolerance are treated as a match.
Syntax
array.binary_search_rightmost(id, value) → int
Arguments
-
id
array
Object reference
-
value
Value to use
Returns
int
array.clear
Empties the array in place, so every reference to it sees a size of zero afterwards. The declared element type is retained, so the array can be refilled with values of the same type.
Syntax
array.clear(id)
Arguments
-
id
array
Object reference
Returns
Nothing
array.concat
Adds the elements of the second array to the end of the first and returns the first array, so every reference to it sees the combined contents; the second array is left unchanged. Passing the same array twice doubles it. Int values join a float array as floats, but float values cannot join an int array. Raises an error, leaving the first array unchanged, when the second argument is not an array, when its element type cannot be held by the first array, or when the combined length would exceed the 100000-element limit.
Syntax
array.concat(id1, id2) → array
Arguments
-
id1
array
First object reference
-
id2
array
Second object reference
Returns
array
array.copy
Returns a new array with the same elements in the same order, leaving the original untouched. The copy is shallow, so for arrays of objects both arrays go on referring to the same underlying objects.
Syntax
array.copy(id) → array
Arguments
-
id
array
Object reference
Returns
array
array.covariance
Returns the covariance of the finite numeric values of the two arrays, pairing them in order and stopping at the length of the shorter one. Pass false for biased to divide by one less than the pair count. Returns na when there are no usable pairs, or when the unbiased form is asked for and only one pair exists; a non-array argument raises an error.
Syntax
array.covariance(id1, id2, biased = true) → float
Arguments
-
id1
array
First array
-
id2
array
Second array
-
biased
bool
optional
Use biased calculation
Returns
float
array.every
Returns true when every element counts as true, where na, zero and false are the only values that count as false. An empty array returns true.
Syntax
array.every(id) → bool
Arguments
-
id
array
Object reference
Returns
bool
array.fill
Overwrites elements of the array in place with the given value, covering the whole array by default or the half-open range from index_from up to but not including index_to. The value must match the array's element type, and a range that falls outside the array raises an error.
Syntax
array.fill(id, value, index_from?, index_to?)
Arguments
-
id
array
Object reference
-
value
Value to use
-
index_from
int
optional
-
index_to
int
optional
Returns
Nothing
array.first
Returns the element at the start of the array without removing it. Returns na when the array is empty, rather than raising an error.
Syntax
array.first(id)
Arguments
-
id
array
Object reference
Returns
the first element, or na when the array is empty
array.from
Builds a new array from the values passed to it, taking its element type from the first value that is not na. Raises an error when the values have incompatible types or when more than 100000 values are supplied; na values are accepted and stored as they are.
Syntax
array.from() → array
Returns
array
array.get
Returns the element stored at the given index, leaving the array unchanged. A negative index counts back from the end, and an index outside the array raises an error.
Syntax
array.get(id, index)
Arguments
-
id
array
Object reference
-
index
int
Element index
Returns
the element at that index, of the array's element type
array.includes
Returns true when the array holds an element equal to the given value. Whole numbers are compared as floats in a float array, so a match is still found when an int is passed.
Syntax
array.includes(id, value) → bool
Arguments
-
id
array
Object reference
-
value
Value to use
Returns
bool
array.indexof
Returns the index of the first element equal to the given value, or -1 when no element matches or the array is empty. The value is converted to the array's element type before comparison.
Syntax
array.indexof(id, value) → int
Arguments
-
id
array
Object reference
-
value
Value to use
Returns
int
array.insert
Inserts the value in place at the given index, shifting that element and everything after it one position later. The index may run from zero up to the current size, and a negative index counts back from the end; an index outside that span, a value of the wrong type, or exceeding the 100000-element limit raises an error.
Syntax
array.insert(id, index, value)
Arguments
-
id
array
Object reference
-
index
int
Element index
-
value
Value to use
Returns
Nothing
array.join
Returns the elements as a single string in index order, separated by the given separator or by a comma when none is supplied. The array is not modified.
Syntax
array.join(id, separator = ",") → string
Arguments
-
id
array
Object reference
-
separator
string
optional
Separator string
Returns
string
array.last
Returns the element at the end of the array without removing it. Returns na when the array is empty, rather than raising an error.
Syntax
array.last(id)
Arguments
-
id
array
Object reference
Returns
the last element, or na when the array is empty
array.lastindexof
Returns the index of the last element equal to the given value, or -1 when no element matches or the array is empty. The value is converted to the array's element type before comparison.
Syntax
array.lastindexof(id, value) → int
Arguments
-
id
array
Object reference
-
value
Value to search for
Returns
int
array.max
Returns the largest of the finite numeric elements, ignoring na and any element that is not a number. Returns na when the array holds no finite numbers.
Syntax
array.max(id) → float
Arguments
-
id
array
Object reference
Returns
float
array.median
Returns the median of the finite numeric elements, averaging the two middle values when their count is even. Elements that are na or not numeric are ignored, and the result is na when none remain. The array's own order is not changed.
Syntax
array.median(id) → float
Arguments
-
id
array
Object reference
Returns
float
array.min
Returns the smallest of the finite numeric elements, ignoring na and any element that is not a number. Returns na when the array holds no finite numbers.
Syntax
array.min(id) → float
Arguments
-
id
array
Object reference
Returns
float
array.mode
Returns the most frequently occurring finite numeric value; when several values tie for the highest count, the smallest of them is returned. Elements that are na or not numeric are ignored, and the result is na when none remain.
Syntax
array.mode(id)
Arguments
-
id
array
Object reference
Returns
the most frequent numeric element, or na when there are none
array.new
Creates a new array of the element type given in the type parameter, with the requested number of elements, or an empty array when no size is given. Each element starts as the supplied initial value, or as na when none is given or the value is not finite; an initial value of the wrong type, or a size above 100000, raises an error.
Syntax
array.new() → array
Returns
array
array.new_point
Creates a new array whose elements are chart points, with the requested number of elements or an empty array when no size is given. Each element starts as the supplied initial value, or as na when none is given; a size above 100000 raises an error.
Syntax
array.new_point(size = 0, initial_value?) → array<chart.point>
Arguments
-
size
int
optional
Initial size
-
initial_value
chart.point
optional
Default value
Returns
array<chart.point>
array.percentile_linear_interpolation
Returns the value at the requested percentage of the sorted finite numeric elements, interpolating between the two neighbouring values when the rank falls between them. Elements that are na or not numeric are ignored, the result is na when none remain, and a na percentage is treated as zero. The array's own order is not changed.
Syntax
array.percentile_linear_interpolation(id, percentage) → float
Arguments
-
id
array
Object reference
-
percentage
float
Percentile (0-100)
Returns
float
array.percentile_nearest_rank
Returns the element of the sorted finite numeric values that sits at the nearest rank for the requested percentage, without interpolating. The rank is kept within the available values, so 0 percent yields the smallest and 100 percent the largest; the result is na when the array holds no finite numbers.
Syntax
array.percentile_nearest_rank(id, percentage)
Arguments
-
id
array
Object reference
-
percentage
float
Percentile (0-100)
Returns
the numeric element at that rank, or na when there are none
array.percentrank
Returns the percentage of the finite numeric elements that are less than or equal to the element at the given index. Returns na when the index falls outside the array, when the element at that index is not a number, or when the array holds no finite numbers.
Syntax
array.percentrank(id, index) → float
Arguments
-
id
array
Object reference
-
index
int
Element index
Returns
float
array.pop
Removes the last element of the array in place and returns it. Returns na and leaves the array untouched when it is already empty.
Syntax
array.pop(id)
Arguments
-
id
array
Object reference
Returns
the removed last element, or na when the array is empty
The element it removes is handed back, so discarding the result loses it.
array.push
Appends the value to the end of the array in place, increasing its size by one. The value must match the array's element type, and pushing past the 100000-element limit raises an error.
Syntax
array.push(id, value)
Arguments
-
id
array
Object reference
-
value
Value to use
Returns
Nothing
Example
indicator("Average of recent closes")
closes = array.new<float>(0)
for offset = 0 to 9
array.push(closes, close[offset])
plot(array.avg(closes), "Average")
array.range
Returns the difference between the largest and the smallest finite numeric element, ignoring na and elements that are not numbers. Returns na when the array holds no finite numbers.
Syntax
array.range(id) → float
Arguments
-
id
array
Object reference
Returns
float
array.remove
Removes the element at the given index in place and returns it, shifting the following elements one position earlier. A negative index counts back from the end, and an index outside the array raises an error; inside a for...in loop, note that the loop re-reads the collection size before each pass, so removing while iterating changes how many passes remain.
Syntax
array.remove(id, index)
Arguments
-
id
array
Object reference
-
index
int
Element index
Returns
the element removed from that index
The element it removes is handed back, so discarding the result loses it.
array.reverse
Reverses the order of the elements in place, so the array itself is changed and nothing is returned. Every reference to the array sees the new order.
Syntax
array.reverse(id)
Arguments
-
id
array
Object reference
Returns
Nothing
array.set
Replaces the element at the given index in place with the supplied value. A negative index counts back from the end; an index outside the array, or a value that does not match the array's element type, raises an error.
Syntax
array.set(id, index, value)
Arguments
-
id
array
Object reference
-
index
int
Element index
-
value
Value to use
Returns
Nothing
array.shift
Removes the first element of the array in place and returns it, shifting the remaining elements one position earlier. Returns na and leaves the array untouched when it is already empty.
Syntax
array.shift(id)
Arguments
-
id
array
Object reference
Returns
the removed first element, or na when the array is empty
The element it removes is handed back, so discarding the result loses it.
array.size
Returns the current number of elements in the array, counting na elements. An empty array returns zero.
Syntax
array.size(id) → int
Arguments
-
id
array
Object reference
Returns
int
array.slice
Returns a new array holding the elements from index_from up to but not including index_to, leaving the source array unchanged. Negative indexes count back from the end; an index outside the array, or index_from greater than index_to, raises an error. The result is an independent array, so writing to it does not affect the original.
Syntax
array.slice(id, index_from, index_to) → array
Arguments
-
id
array
Object reference
-
index_from
int
-
index_to
int
Returns
array
array.some
Returns true when at least one element counts as true, where na, zero and false are the only values that count as false. An empty array returns false.
Syntax
array.some(id) → bool
Arguments
-
id
array
Object reference
Returns
bool
array.sort
Sorts the array in place, ascending by default, and returns nothing. Elements that are na are always placed at the end, whichever order is chosen. For arrays of user-defined objects, sort_field names or indexes the field to compare and sorting falls back to the first field when it is omitted; a field index or name that does not exist, or values that cannot be compared, raises an error.
Syntax
array.sort(id, order = order.ascending, sort_field = 0)
Arguments
-
id
array
Object reference
-
order
order
optional
-
sort_field
int|string
optional
UDT field index or name used for sorting
Returns
Nothing
array.sort_indices
Returns a new int array holding the indexes of the original array in the order the elements would take once sorted, leaving the array itself untouched. Indexes of na elements come last, whichever order is chosen, and sort_field selects the field to compare for arrays of user-defined objects.
Syntax
array.sort_indices(id, order = order.ascending, sort_field = 0) → array<int>
Arguments
-
id
array
Object reference
-
order
order
optional
Sort order
-
sort_field
int|string
optional
UDT field index or name used for sorting
Returns
array<int>
array.standardize
Returns a new float array in which each numeric element is expressed as its distance from the mean divided by the standard deviation, leaving the original untouched. An array with no finite numbers yields an empty array, and a standard deviation of zero yields an array of zeros.
Syntax
array.standardize(id) → array<float>
Arguments
-
id
array
Object reference
Returns
array<float>
array.stdev
Returns the standard deviation of the finite numeric elements, using the population form by default; pass false for biased to use the sample form that divides by one less than the count. Returns na when there are no finite numbers, or when the sample form is asked for and only one value is available.
Syntax
array.stdev(id, biased = true) → float
Arguments
-
id
array
Object reference
-
biased
bool
optional
Use biased calculation
Returns
float
array.sum
Returns the total of the finite numeric elements, ignoring na and any element that is not a number. Returns na when the array holds no finite numbers.
Syntax
array.sum(id) → float
Arguments
-
id
array
Object reference
Returns
float
array.unshift
Inserts the value at the start of the array in place, shifting every existing element one position later. The value must match the array's element type, and going past the 100000-element limit raises an error.
Syntax
array.unshift(id, value)
Arguments
-
id
array
Object reference
-
value
Value to use
Returns
Nothing
array.variance
Returns the variance of the finite numeric elements, using the population form by default; pass false for biased to use the sample form that divides by one less than the count. Returns na when there are no finite numbers, or when the sample form is asked for and only one value is available.
Syntax
array.variance(id, biased = true) → float
Arguments
-
id
array
Object reference
-
biased
bool
optional
Use biased calculation
Returns
float
matrix.* — Matrices
matrix.add_col
Inserts a column into the matrix in place at the given index, or appends one at the right when the index is omitted, and returns nothing. The values array supplies the new cells in row order and any row it does not reach receives the matrix's default value; an index outside the range from zero to the current column count, a mismatched element type, or going past the 100000-element limit raises an error. For a matrix with no rows yet, the supplied values become the first column.
Syntax
matrix.add_col(id, column, values?)
Arguments
-
id
matrix
Object reference
-
column
int
Column index
-
values
array
optional
Column values
Returns
Nothing
matrix.add_row
Inserts a row into the matrix in place at the given index, or appends one at the bottom when the index is omitted, and returns nothing. The values array must be exactly as long as the current column count, and a row added to an empty matrix sets that column count; an index outside the range from zero to the current row count, a mismatched element type, or going past the 100000-element limit raises an error. Rows added without values are filled with the matrix's default value.
Syntax
matrix.add_row(id, row, values?)
Arguments
-
id
matrix
Object reference
-
row
int
Row index
-
values
array
optional
Row values
Returns
Nothing
matrix.avg
Returns the mean of the finite numeric elements of the whole matrix, ignoring na cells. Returns na when the matrix holds no finite numbers, and raises an error when the matrix does not hold numbers.
Syntax
matrix.avg(id) → float
Arguments
-
id
matrix
Object reference
Returns
float
matrix.col
Returns a new array holding the values of the given column, top to bottom, leaving the matrix unchanged. The array is a copy, so writing to it does not affect the matrix, and a column index outside the matrix raises an error.
Syntax
matrix.col(id, column) → array
Arguments
-
id
matrix
Object reference
-
column
int
Column index
Returns
array
matrix.columns
Returns the number of columns in the matrix, taken from the length of its first row. A matrix with no rows returns zero.
Syntax
matrix.columns(id) → int
Arguments
-
id
matrix
Object reference
Returns
int
matrix.concat
Adds the rows of the second matrix below those of the first and returns the first matrix, so every reference to it sees the combined contents; the second matrix is left unchanged. Pass false for rows to add its columns to the right instead. Both matrices need the same number of columns, or the same number of rows when rows is false, unless the first is empty. The first matrix must be able to hold the second's elements, so int values can join a float matrix but not the other way round. Raises an error for a non-matrix argument, mismatched sizes or incompatible types, or when the result would exceed 100000 elements.
Syntax
matrix.concat(id, id2, rows = true) → matrix
Arguments
-
id
matrix
Object reference
-
id2
matrix
Matrix to append
-
rows
bool
optional
Append below (true) or to the right (false)
Returns
matrix
matrix.copy
Returns a new matrix with the same dimensions and the same values, leaving the original untouched. The copy is shallow, so for matrices of objects both matrices go on referring to the same underlying objects.
Syntax
matrix.copy(id) → matrix
Arguments
-
id
matrix
Object reference
Returns
matrix
matrix.det
Returns the determinant of a square numeric matrix, computed directly for the one and two element cases and by row reduction for larger ones. Returns na when the matrix is not square and zero when it is singular; na cells are treated as zero, and a matrix that does not hold numbers raises an error.
Syntax
matrix.det(id) → float
Arguments
-
id
matrix
Object reference
Returns
float
matrix.diff
Returns a new matrix holding each element of the first matrix minus the matching element of the second, or minus the number when the second argument is a number; neither source is changed. Subtracting two matrices needs equal numbers of rows and columns, and the result is an int matrix only when both are int. Subtracting a number keeps the first matrix's type, so an int matrix stays int. An na on either side gives na. Called without a second argument, or with a bool, it instead returns a float matrix of the differences between neighbouring values, taken down each column by default or across each row when the bool is false, with na cells counted as zero; this form is a SahiScript extension. Raises an error for a matrix that does not hold numbers, a second argument that is not a matrix, a number or a bool, or mismatched sizes.
Syntax
matrix.diff(id, id2) → matrix
Arguments
-
id
matrix
Object reference
-
id2
matrix|float
Matrix or number to subtract
Returns
matrix
matrix.eigenvalues
Returns a new float array of the eigenvalues of a square numeric matrix, holding the single value for a one-by-one matrix and both roots for a two-by-two one. Returns na for any larger matrix, for a non-square matrix, and for a two-by-two matrix whose eigenvalues are not real; a matrix that does not hold numbers raises an error.
Syntax
matrix.eigenvalues(id) → array<float>
Arguments
-
id
matrix
Object reference
Returns
array<float>
matrix.eigenvectors
Returns a new float matrix whose two rows are the eigenvectors of a two-by-two numeric matrix, leaving the source unchanged. Returns na for any other shape and for a matrix whose eigenvalues are not real; a matrix that does not hold numbers raises an error.
Syntax
matrix.eigenvectors(id) → matrix
Arguments
-
id
matrix
Object reference
Returns
matrix
matrix.elements_count
Returns the total number of cells in the matrix, that is its row count multiplied by its column count, counting na cells. A matrix with no rows returns zero.
Syntax
matrix.elements_count(id) → int
Arguments
-
id
matrix
Object reference
Returns
int
matrix.fill
Overwrites cells of the matrix in place with the given value, covering the whole matrix by default or the block from from_row and from_column up to but not including to_row and to_column. Nothing is returned. The value must match the matrix's element type, and bounds that fall outside the matrix raise an error.
Syntax
matrix.fill(id, value, from_row?, to_row?, from_column?, to_column?)
Arguments
-
id
matrix
Object reference
-
value
float
Fill value
-
from_row
int
optional
Start row
-
to_row
int
optional
End row
-
from_column
int
optional
Start column
-
to_column
int
optional
End column
Returns
Nothing
matrix.from_columns
Returns a new matrix of the requested shape built from a flat array, filling the first column from the start of the array before moving on to the next. The array's length must be exactly the row count multiplied by the column count, and a non-array argument or a mismatched length raises an error; the element type comes from the array.
Syntax
matrix.from_columns(id, rows, columns) → matrix
Arguments
-
id
array
Flat array of values
-
rows
int
Number of rows
-
columns
int
Number of columns
Returns
matrix
matrix.from_rows
Returns a new matrix of the requested shape built from a flat array, filling the first row from the start of the array before moving on to the next. The array's length must be exactly the row count multiplied by the column count, and a non-array argument or a mismatched length raises an error; the element type comes from the array.
Syntax
matrix.from_rows(id, rows, columns) → matrix
Arguments
-
id
array
Flat array of values
-
rows
int
Number of rows
-
columns
int
Number of columns
Returns
matrix
matrix.get
Returns the value held at the given row and column, leaving the matrix unchanged. Indexes start at zero and an index outside the matrix raises an error; negative indexes are not accepted.
Syntax
matrix.get(id, row, column)
Arguments
-
id
matrix
Object reference
-
row
int
Row index
-
column
int
Column index
Returns
the element at that row and column, of the matrix element type
matrix.inv
Returns a new float matrix that is the inverse of a square numeric matrix, so that multiplying the two gives the identity matrix; the source is unchanged. Returns na when the matrix is not square or is singular, treats na cells as zero, and raises an error when the matrix does not hold numbers.
Syntax
matrix.inv(id) → matrix
Arguments
-
id
matrix
Object reference
Returns
matrix
matrix.is_antidiagonal
Returns true when every cell outside the corner-to-corner anti-diagonal is zero. A matrix that is not square returns false, and a matrix that does not hold numbers raises an error.
Syntax
matrix.is_antidiagonal(id) → bool
Arguments
-
id
matrix
Object reference
Returns
bool
matrix.is_antisymmetric
Returns true when every cell equals the negative of its mirror across the main diagonal, which also requires the diagonal itself to be zero. A matrix that is not square returns false, na cells count as zero, and a matrix that does not hold numbers raises an error.
Syntax
matrix.is_antisymmetric(id) → bool
Arguments
-
id
matrix
Object reference
Returns
bool
matrix.is_binary
Returns true when every cell is exactly zero or one; any other value, including na, makes it false. A matrix with no cells returns true, and a matrix that does not hold numbers raises an error.
Syntax
matrix.is_binary(id) → bool
Arguments
-
id
matrix
Object reference
Returns
bool
matrix.is_diagonal
Returns true when every cell off the main diagonal is zero, whatever the diagonal itself holds. A matrix that is not square returns false, and a matrix that does not hold numbers raises an error.
Syntax
matrix.is_diagonal(id) → bool
Arguments
-
id
matrix
Object reference
Returns
bool
matrix.is_identity
Returns true when every cell on the main diagonal is one and every other cell is zero. A matrix that is not square returns false, and a matrix that does not hold numbers raises an error.
Syntax
matrix.is_identity(id) → bool
Arguments
-
id
matrix
Object reference
Returns
bool
matrix.is_square
Returns true when the matrix has the same number of rows and columns and holds at least one row. A matrix with no rows returns false.
Syntax
matrix.is_square(id) → bool
Arguments
-
id
matrix
Object reference
Returns
bool
matrix.is_stochastic
Returns true when every cell lies between zero and one and each row's values add up to one within a small tolerance. A matrix with no rows returns false, any na cell makes it false, and a matrix that does not hold numbers raises an error.
Syntax
matrix.is_stochastic(id) → bool
Arguments
-
id
matrix
Object reference
Returns
bool
matrix.is_symmetric
Returns true when every cell equals its mirror across the main diagonal. A matrix that is not square returns false, and a matrix that does not hold numbers raises an error.
Syntax
matrix.is_symmetric(id) → bool
Arguments
-
id
matrix
Object reference
Returns
bool
matrix.is_triangular
Returns true when every cell below the main diagonal is zero or every cell above it is zero, so both upper and lower triangular matrices qualify. A matrix that is not square returns false, and a matrix that does not hold numbers raises an error.
Syntax
matrix.is_triangular(id) → bool
Arguments
-
id
matrix
Object reference
Returns
bool
matrix.is_zero
Returns true when every cell of the matrix is exactly zero; any other value, including na, makes it false. A matrix with no cells returns true, and a matrix that does not hold numbers raises an error.
Syntax
matrix.is_zero(id) → bool
Arguments
-
id
matrix
Object reference
Returns
bool
matrix.kron
Returns a new float matrix that is the Kronecker product of the two matrices, in which every cell of the first is multiplied by the whole of the second; its size is the product of the two row counts by the product of the two column counts. Both source matrices are unchanged and must hold numbers, na cells count as zero, and a non-matrix argument raises an error.
Syntax
matrix.kron(id, id2) → matrix
Arguments
-
id
matrix
Object reference
-
id2
matrix
Second matrix
Returns
matrix
matrix.max
Returns the largest finite numeric value anywhere in the matrix, ignoring na cells. Returns na when the matrix holds no finite numbers, and raises an error when the matrix does not hold numbers.
Syntax
matrix.max(id) → float
Arguments
-
id
matrix
Object reference
Returns
float
matrix.median
Returns the median of the finite numeric values of the whole matrix, averaging the two middle values when their count is even. Ignores na cells and returns na when none remain; a matrix that does not hold numbers raises an error.
Syntax
matrix.median(id) → float
Arguments
-
id
matrix
Object reference
Returns
float
matrix.min
Returns the smallest finite numeric value anywhere in the matrix, ignoring na cells. Returns na when the matrix holds no finite numbers, and raises an error when the matrix does not hold numbers.
Syntax
matrix.min(id) → float
Arguments
-
id
matrix
Object reference
Returns
float
matrix.mode
Returns the most frequently occurring finite numeric value in the matrix, choosing the smallest of them when several tie for the highest count. Ignores na cells and returns na when none remain; a matrix that does not hold numbers raises an error.
Syntax
matrix.mode(id) → float
Arguments
-
id
matrix
Object reference
Returns
float
matrix.mult
Returns a new float matrix that is the matrix product of the two operands, leaving both unchanged. The column count of the first must equal the row count of the second, and a mismatch, a non-matrix argument, or a matrix that does not hold numbers raises an error; na cells count as zero.
Syntax
matrix.mult(id, id2) → matrix
Arguments
-
id
matrix
Object reference
-
id2
matrix
Second matrix
Returns
matrix
matrix.new
Creates a new matrix of the element type given in the type parameter, with the requested number of rows and columns, or an empty matrix when neither dimension is given. Cells start as the initial value, or as na when none is given; supplying only one of the two dimensions, an initial value of the wrong type, or a cell count above 100000 raises an error.
Syntax
matrix.new(rows, columns, initial_value?) → matrix
Arguments
-
rows
int
Number of rows
-
columns
int
Number of columns
-
initial_value
optional
Returns
matrix
matrix.pinv
Returns a new float matrix that is the left pseudoinverse of a numeric matrix, obtained from the transpose and the inverse of the transpose times the matrix; the source is unchanged. Returns na when that intermediate product cannot be inverted, which is the case whenever the columns are not linearly independent, and raises an error when the matrix does not hold numbers.
Syntax
matrix.pinv(id) → matrix
Arguments
-
id
matrix
Object reference
Returns
matrix
matrix.pow
Returns a new matrix equal to the matrix multiplied by itself the given number of times, leaving the source unchanged; an exponent of zero gives the identity matrix of the same size. The matrix must be square and hold numbers, and a negative exponent raises an error.
Syntax
matrix.pow(id, exponent) → matrix
Arguments
-
id
matrix
Object reference
-
exponent
int
Integer exponent
Returns
matrix
matrix.rank
Returns the number of linearly independent rows of a numeric matrix, found by row reduction with a small tolerance for values near zero. A matrix with no rows or no columns returns zero, na cells count as zero, and a matrix that does not hold numbers raises an error.
Syntax
matrix.rank(id) → int
Arguments
-
id
matrix
Object reference
Returns
int
matrix.remove_col
Removes the column at the given index from the matrix in place and returns nothing. A matrix with no rows is left alone, and a column index outside the matrix raises an error.
Syntax
matrix.remove_col(id, column)
Arguments
-
id
matrix
Object reference
-
column
int
Column index
Returns
Nothing
Unlike matrix.remove_row, this one hands back nothing at all.
matrix.remove_row
Removes the row at the given index from the matrix in place and returns it as an array. Returns na when the matrix has no rows, and a row index outside the matrix raises an error.
Syntax
matrix.remove_row(id, row)
Arguments
-
id
matrix
Object reference
-
row
int
Row index
Returns
array of the removed row, or na when the matrix has no rows
The row it removes comes back as an array, whereas matrix.remove_col returns nothing.
matrix.reshape
Changes the shape of the matrix in place to the requested number of rows and columns and returns nothing, so every reference to the matrix sees the new shape. Read row by row, the values keep the order they had before. The requested row count multiplied by the column count must equal the current number of cells, and neither count may be negative; otherwise an error is raised and the matrix is left unchanged.
Syntax
matrix.reshape(id, rows, columns)
Arguments
-
id
matrix
Object reference
-
rows
int
New row count
-
columns
int
New column count
Returns
Nothing
The matrix itself takes the new shape; to keep the original as it was, reshape a copy made with matrix.copy().
matrix.reverse
Reverses the order of the rows in place, so the first row becomes the last, and returns nothing. The order of values within each row is untouched.
Syntax
matrix.reverse(id)
Arguments
-
id
matrix
Object reference
Returns
Nothing
matrix.row
Returns a new array holding the values of the given row, left to right, leaving the matrix unchanged. The array is a copy, so writing to it does not affect the matrix, and a row index outside the matrix raises an error.
Syntax
matrix.row(id, row) → array
Arguments
-
id
matrix
Object reference
-
row
int
Row index
Returns
array
matrix.rows
Returns the number of rows currently held by the matrix. An empty matrix returns zero.
Syntax
matrix.rows(id) → int
Arguments
-
id
matrix
Object reference
Returns
int
matrix.set
Replaces the value at the given row and column in place and returns nothing. An index outside the matrix, or a value that does not match the matrix's element type, raises an error.
Syntax
matrix.set(id, row, column, value)
Arguments
-
id
matrix
Object reference
-
row
int
Row index
-
column
int
Column index
-
value
Value to use
Returns
Nothing
matrix.sort
Reorders the rows of the matrix in place by the values held in the given column, ascending by default, and returns nothing. Rows whose key is na are always placed last, whichever order is chosen. Without a sort_field the matrix must hold numbers; with matrices of user-defined objects, sort_field names or indexes the field to compare and the first field is used when it is omitted. A column index outside the matrix raises an error.
Syntax
matrix.sort(id, column, order = order.ascending, sort_field = 0)
Arguments
-
id
matrix
Object reference
-
column
int
Column to sort by
-
order
optional
Sort order
-
sort_field
int|string
optional
UDT field index or name used for sorting
Returns
Nothing
matrix.stdev
Returns the standard deviation of the finite numeric values of the whole matrix, using the population form by default; pass false for biased to use the sample form that divides by one less than the count. Returns na when there are no finite values, or when the sample form is asked for and only one value is available; a matrix that does not hold numbers raises an error.
Syntax
matrix.stdev(id, biased = true) → float
Arguments
-
id
matrix
Object reference
-
biased
bool
optional
Use biased calculation
Returns
float
matrix.submatrix
Returns a new matrix holding the block from from_row and from_column up to but not including to_row and to_column, leaving the source unchanged. The result is independent of the source for primitive element types, and bounds outside the matrix raise an error.
Syntax
matrix.submatrix(id, from_row, to_row, from_column, to_column) → matrix
Arguments
-
id
matrix
Object reference
-
from_row
int
Start row
-
to_row
int
End row
-
from_column
int
Start column
-
to_column
int
End column
Returns
matrix
matrix.sum
Returns a new matrix holding each element of the first matrix plus the matching element of the second, or plus the number when the second argument is a number; neither source is changed. Adding two matrices needs equal numbers of rows and columns, and the result is an int matrix only when both are int. Adding a number keeps the first matrix's type, so an int matrix stays int. An na on either side gives na. Called without a second argument, it instead returns the total of the matrix's finite values, or na when there are none; this form is a SahiScript extension. Raises an error for a matrix that does not hold numbers, a second argument that is neither a matrix nor a number, or mismatched sizes.
Syntax
matrix.sum(id, id2) → matrix
Arguments
-
id
matrix
Object reference
-
id2
matrix|float
Matrix or number to add
Returns
matrix
matrix.swap_columns
Exchanges the two given columns in place and returns nothing, leaving the rest of the matrix as it was. Either index falling outside the matrix raises an error.
Syntax
matrix.swap_columns(id, column1, column2)
Arguments
-
id
matrix
Object reference
-
column1
int
First column index
-
column2
int
Second column index
Returns
Nothing
matrix.swap_rows
Exchanges the two given rows in place and returns nothing, leaving the rest of the matrix as it was. Either index falling outside the matrix raises an error.
Syntax
matrix.swap_rows(id, row1, row2)
Arguments
-
id
matrix
Object reference
-
row1
int
First row index
-
row2
int
Second row index
Returns
Nothing
matrix.trace
Returns the sum of the values on the main diagonal of a square numeric matrix. Returns na when the matrix is not square, treats na cells as zero, and raises an error when the matrix does not hold numbers.
Syntax
matrix.trace(id) → float
Arguments
-
id
matrix
Object reference
Returns
float
matrix.transpose
Returns a new matrix in which rows and columns are exchanged, so a matrix of m rows by n columns becomes one of n rows by m columns; the source is unchanged. Numeric matrices come back with a float element type.
Syntax
matrix.transpose(id) → matrix
Arguments
-
id
matrix
Object reference
Returns
matrix
matrix.variance
Returns the variance of the finite numeric values of the whole matrix, using the population form by default; pass false for biased to use the sample form that divides by one less than the count. Returns na when there are no finite values, or when the sample form is asked for and only one value is available; a matrix that does not hold numbers raises an error.
Syntax
matrix.variance(id, biased = true) → float
Arguments
-
id
matrix
Object reference
-
biased
bool
optional
Use biased calculation
Returns
float
line.* — Lines
line.copy
Creates an independent duplicate of a line, carrying over its coordinates, colour, style, width, xloc and extend mode, and returns the new line reference. The copy is a separate drawing that counts towards the script's line cap and can be changed or deleted without touching the original.
Syntax
line.copy(id) → line
Arguments
Returns
line
line.delete
Removes the line from the chart and frees the slot it held against the script's line cap. Nothing is returned, and further calls through the same reference have no effect.
Syntax
line.delete(id)
Arguments
Returns
Nothing
line.get_color
Returns the colour the line is currently drawn with. The result is na if the line has been deleted.
Syntax
line.get_color(id) → color
Arguments
Returns
color
line.get_style
Returns the line's stroke style as one of the line.style_* values: solid, dashed, dotted, or the arrow_left, arrow_right and arrow_both variants.
Syntax
line.get_style(id) → line_style
Arguments
Returns
line_style
line.get_width
Returns the line's stroke width in pixels.
Syntax
line.get_width(id) → int
Arguments
Returns
int
line.get_x1
Returns the x coordinate of the line's first point. It is a bar index when the line's xloc is xloc.bar_index and a UNIX time in milliseconds when it is xloc.bar_time, and na if the coordinate was never set.
Syntax
line.get_x1(id) → int
Arguments
Returns
int
line.get_x2
Returns the x coordinate of the line's second point, read as a bar index or as a UNIX time in milliseconds according to the line's xloc. The result is na if that coordinate is unset.
Syntax
line.get_x2(id) → int
Arguments
Returns
int
line.get_xloc
Returns the line's x coordinate mode, either xloc.bar_index or xloc.bar_time, which tells you how its x1 and x2 values should be read.
Syntax
line.get_xloc(id) → xloc
Arguments
Returns
xloc
line.get_y1
Returns the price at the line's first point, or na if that coordinate is unset.
Syntax
line.get_y1(id) → float
Arguments
Returns
float
line.get_y2
Returns the price at the line's second point, or na if that coordinate is unset.
Syntax
line.get_y2(id) → float
Arguments
Returns
float
line.new
Draws a straight segment between two points and returns a line reference that can be read, moved or deleted later. x1 and x2 are bar indices when xloc is xloc.bar_index and UNIX times in milliseconds when it is xloc.bar_time, while y1 and y2 are prices; the two ends may instead be supplied as a pair of chart.point values. The line stays on the chart until it is deleted, and once the script's line cap is reached (500 by default) the oldest lines are removed to make room.
Syntax
line.new(x1, y1, x2, y2, xloc = xloc.bar_index, extend = extend.none, color?, style = line.style_solid, width = 1) → line
Arguments
-
x1
int
First point x
-
y1
float
First point y
-
x2
int
Second point x
-
y2
float
Second point y
-
xloc
xloc
optional
X-location mode
-
extend
extend
optional
Line extend mode
-
color
color
optional
Color value
-
style
line_style
optional
-
width
int
optional
Width value
Returns
line
Example
indicator("Line across the range", overlay = true)
if barstate.islast
line.new(bar_index - 20, low, bar_index, high, color = color.orange, width = 2)
line.set_color
Changes the stroke colour of an existing line in place. A na colour leaves the current colour untouched, and nothing is returned.
Syntax
line.set_color(id, color)
Arguments
-
id
line
Object reference
-
color
color
Color value
Returns
Nothing
line.set_extend
Controls how far an existing line is prolonged past its two points, accepting extend.none, extend.left, extend.right or extend.both. A na value leaves the current setting in place.
Syntax
line.set_extend(id, extend)
Arguments
-
id
line
Object reference
-
extend
extend
Line extend mode
Returns
Nothing
line.set_first_point
Moves the first end of an existing line to the position carried by a chart.point, updating both coordinates at once. The point's bar index or its millisecond time is used according to the line's current xloc, and its price becomes the new y; a na point leaves the line unchanged.
Syntax
line.set_first_point(id, point)
Arguments
-
id
line
Object reference
-
point
chart.point
Chart point
Returns
Nothing
line.set_second_point
Moves the second end of an existing line to a chart.point, taking the point's bar index or millisecond time according to the line's xloc and its price as the new y. Passing na leaves the line where it is.
Syntax
line.set_second_point(id, point)
Arguments
-
id
line
Object reference
-
point
chart.point
Chart point
Returns
Nothing
line.set_style
Replaces the stroke style of an existing line, accepting the line.style_* constants for solid, dashed, dotted and the three arrow forms. Passing na keeps the current style; nothing is returned.
Syntax
line.set_style(id, style)
Arguments
-
id
line
Object reference
-
style
line_style
Visual style
Returns
Nothing
line.set_width
Sets the stroke width, in pixels, of an existing line. A na width is ignored and the line keeps its present width.
Syntax
line.set_width(id, width)
Arguments
-
id
line
Object reference
-
width
int
Width value
Returns
Nothing
line.set_x1
Moves the first point of an existing line along the x axis, in bar indices or in UNIX milliseconds according to the line's xloc. A na value clears the coordinate, and the line is not drawn until a value is supplied again.
Syntax
line.set_x1(id, x)
Arguments
-
id
line
Object reference
-
x
int
X coordinate
Returns
Nothing
line.set_x2
Moves the second point of an existing line along the x axis, using bar indices or UNIX milliseconds to match the line's xloc. Clearing it with na leaves the line undrawn until the coordinate is set again.
Syntax
line.set_x2(id, x)
Arguments
-
id
line
Object reference
-
x
int
X coordinate
Returns
Nothing
line.set_xloc
Switches how an existing line's x coordinates are interpreted, between xloc.bar_index and xloc.bar_time; na leaves the mode alone. The stored x values are not converted, so rewrite them in the matching unit, since bar indices read as millisecond timestamps place the line far outside the visible chart.
Syntax
line.set_xloc(id, xloc)
Arguments
-
id
line
Object reference
-
xloc
xloc
X-location mode
Returns
Nothing
line.set_xy1
Moves the first point of an existing line, setting its x and its price in one call. The x value follows the line's xloc, so it is a bar index or a UNIX time in milliseconds, and nothing is returned.
Syntax
line.set_xy1(id, x, y)
Arguments
-
id
line
Object reference
-
x
int
X coordinate
-
y
float
Y coordinate
Returns
Nothing
line.set_xy2
Moves the second point of an existing line, setting its x and its price together. As with the first point, x is a bar index or a UNIX time in milliseconds depending on the line's xloc.
Syntax
line.set_xy2(id, x, y)
Arguments
-
id
line
Object reference
-
x
int
X coordinate
-
y
float
Y coordinate
Returns
Nothing
line.set_y1
Sets the price of the line's first point in place. A na or otherwise non-finite value clears the coordinate, and the line is hidden until a finite price is given.
Syntax
line.set_y1(id, y)
Arguments
-
id
line
Object reference
-
y
float
Y coordinate
Returns
Nothing
line.set_y2
Sets the price of the line's second point in place. A na or non-finite value clears the coordinate and the line stops being drawn until it is restored.
Syntax
line.set_y2(id, y)
Arguments
-
id
line
Object reference
-
y
float
Y coordinate
Returns
Nothing
label.* — Labels
label.copy
Duplicates a label with its position, text, colours, style, size and tooltip, and returns the new label reference. The copy is an independent drawing and counts towards the script's label cap.
Syntax
label.copy(id) → label
Arguments
-
id
label
Object reference
Returns
label
label.delete
Removes the label from the chart and releases its slot against the script's label cap. Nothing is returned, and later calls through the same reference do nothing.
Syntax
label.delete(id)
Arguments
-
id
label
Object reference
Returns
Nothing
label.get_color
Returns the label's background colour, or na if the label has none or has been deleted.
Syntax
label.get_color(id) → color
Arguments
-
id
label
Object reference
Returns
color
label.get_style
Returns the label's marker style, one of the label.style_* values such as label.style_label_down, label.style_circle or label.style_none.
Syntax
label.get_style(id) → label_style
Arguments
-
id
label
Object reference
Returns
label_style
label.get_text
Returns the text the label currently shows, which is an empty string if no text was given.
Syntax
label.get_text(id) → string
Arguments
-
id
label
Object reference
Returns
string
label.get_textcolor
Returns the colour used to draw the label's text, or na if none was set.
Syntax
label.get_textcolor(id) → color
Arguments
-
id
label
Object reference
Returns
color
label.get_x
Returns the label's x coordinate, read as a bar index or as a UNIX time in milliseconds depending on the label's xloc. The result is na if the coordinate is unset.
Syntax
label.get_x(id) → int
Arguments
-
id
label
Object reference
Returns
int
label.get_xloc
Returns the label's x coordinate mode, xloc.bar_index or xloc.bar_time.
Syntax
label.get_xloc(id) → xloc
Arguments
-
id
label
Object reference
Returns
xloc
label.get_y
Returns the label's y coordinate as a price. It is meaningful only while the label's yloc is yloc.price, and is na when the coordinate is unset.
Syntax
label.get_y(id) → float
Arguments
-
id
label
Object reference
Returns
float
label.get_yloc
Returns how the label is placed vertically: yloc.price for an explicit price, or yloc.abovebar and yloc.belowbar for placement relative to the bar.
Syntax
label.get_yloc(id) → yloc
Arguments
-
id
label
Object reference
Returns
yloc
label.new
Draws a text label anchored to a point on the chart and returns a label reference for later changes. x is a bar index under xloc.bar_index or a UNIX time in milliseconds under xloc.bar_time; y is a price when yloc is yloc.price, while yloc.abovebar and yloc.belowbar pin the label to the bar itself. The label persists until deleted, and once the script's label cap is reached (500 by default) the oldest labels are dropped.
Syntax
label.new(x, y, text?, xloc = xloc.bar_index, yloc = yloc.price, color?, style = label.style_label_down, textcolor?, size = size.normal, tooltip?) → label
Arguments
-
x
int
X coordinate
-
y
float
Y coordinate
-
text
string
optional
Text content
-
xloc
xloc
optional
X-location mode
-
yloc
yloc
optional
Y-location mode
-
color
color
optional
Color value
-
style
label_style
optional
-
textcolor
color
optional
Text color
-
size
size
optional
Shape/text size
-
tooltip
string
optional
Tooltip text
Returns
label
Example
indicator("Label the last bar", overlay = true)
if barstate.islast
label.new(bar_index, high, "Last", color = color.blue)
label.set_color
Sets the background colour of an existing label in place. Passing na removes the background colour rather than leaving it as it was.
Syntax
label.set_color(id, color)
Arguments
-
id
label
Object reference
-
color
color
Color value
Returns
Nothing
label.set_point
Moves an existing label to the position described by a chart.point, taking the point's bar index or millisecond time according to the label's xloc and its price as the new y. A na point leaves the label untouched.
Syntax
label.set_point(id, point)
Arguments
-
id
label
Object reference
-
point
chart.point
Chart point
Returns
Nothing
label.set_size
Sets the size of an existing label's text. It accepts the size.* constants, from size.tiny through size.huge, or a positive integer for an explicit size; anything else falls back to size.normal.
Syntax
label.set_size(id, size)
Arguments
-
id
label
Object reference
-
size
size
Shape/text size
Returns
Nothing
label.set_style
Changes the marker shape of an existing label, accepting the label.style_* values, which cover the pointing label forms, plain shapes such as circle, square, triangle and diamond, and label.style_none for text with no marker.
Syntax
label.set_style(id, style)
Arguments
-
id
label
Object reference
-
style
label_style
Visual style
Returns
Nothing
label.set_text
Replaces the text shown by an existing label, with na producing empty text. Invisible formatting characters and trailing blank lines are stripped, and since labels draw through the chart's bundled fonts, plain characters and simple geometric glyphs are far more reliable than emoji or arrow symbols.
Syntax
label.set_text(id, text)
Arguments
-
id
label
Object reference
-
text
string
Text content
Returns
Nothing
label.set_text_font_family
Sets the font family used for an existing label's text, accepting font.family_default or font.family_monospace. Passing na clears the explicit choice.
Syntax
label.set_text_font_family(id, font_family)
Arguments
-
id
label
Object reference
-
font_family
string
Font family
Returns
Nothing
label.set_textalign
Sets how the lines of an existing label's text are aligned against each other, accepting text.align_left, text.align_center or text.align_right. A na value clears the explicit alignment.
Syntax
label.set_textalign(id, textalign)
Arguments
-
id
label
Object reference
-
textalign
string
Text alignment
Returns
Nothing
label.set_textcolor
Sets the colour of an existing label's text. A na colour clears the explicit setting and the renderer's default text colour is used.
Syntax
label.set_textcolor(id, color)
Arguments
-
id
label
Object reference
-
color
color
Color value
Returns
Nothing
label.set_tooltip
Sets the text shown when the pointer rests on an existing label. The value is converted to its string form, and na clears the tooltip.
Syntax
label.set_tooltip(id, tooltip)
Arguments
-
id
label
Object reference
-
tooltip
string
Tooltip text
Returns
Nothing
label.set_x
Moves an existing label along the x axis, in bar indices or in UNIX milliseconds to match its xloc. A na value clears the coordinate and the label is not drawn until one is supplied again.
Syntax
label.set_x(id, x)
Arguments
-
id
label
Object reference
-
x
int
X coordinate
Returns
Nothing
label.set_xloc
Switches how an existing label's x coordinate is read, between xloc.bar_index and xloc.bar_time. The stored value is not converted, so supply an x in the matching unit or the label will be placed far off the visible chart.
Syntax
label.set_xloc(id, xloc)
Arguments
-
id
label
Object reference
-
xloc
xloc
X-location mode
Returns
Nothing
label.set_xy
Moves an existing label to a new x and price in a single call, with x given as a bar index or as a UNIX time in milliseconds according to the label's xloc.
Syntax
label.set_xy(id, x, y)
Arguments
-
id
label
Object reference
-
x
int
X coordinate
-
y
float
Y coordinate
Returns
Nothing
label.set_y
Sets the price coordinate of an existing label, which positions it while its yloc is yloc.price. A na or non-finite value clears the coordinate and hides the label.
Syntax
label.set_y(id, y)
Arguments
-
id
label
Object reference
-
y
float
Y coordinate
Returns
Nothing
label.set_yloc
Sets whether an existing label sits at its own price (yloc.price) or is pinned above or below the bar it belongs to (yloc.abovebar, yloc.belowbar).
Syntax
label.set_yloc(id, yloc)
Arguments
-
id
label
Object reference
-
yloc
yloc
Y-location mode
Returns
Nothing
box.* — Boxes
box.copy
Duplicates a box together with its geometry, border, background and text settings, and returns the new box reference. The copy is independent of the original and counts towards the script's box cap.
Syntax
box.copy(id) → box
Arguments
Returns
box
box.delete
Removes the box from the chart and frees its slot against the script's box cap. Nothing is returned, and repeated calls through the same reference do nothing.
Syntax
box.delete(id)
Arguments
Returns
Nothing
box.get_bgcolor
Returns the box's fill colour, or na if it has none.
Syntax
box.get_bgcolor(id) → color
Arguments
Returns
color
box.get_border_color
Returns the colour of the box's border, or na if no border colour was set.
Syntax
box.get_border_color(id) → color
Arguments
Returns
color
box.get_border_style
Returns the border's stroke style as one of the line.style_* values, such as line.style_solid or line.style_dashed.
Syntax
box.get_border_style(id) → line_style
Arguments
Returns
line_style
box.get_border_width
Returns the width of the box's border in pixels.
Syntax
box.get_border_width(id) → int
Arguments
Returns
int
box.get_bottom
Returns the price of the box's lower edge, or na if it is unset.
Syntax
box.get_bottom(id) → float
Arguments
Returns
float
box.get_extend
Returns how the box is stretched horizontally beyond its edges: extend.none, extend.left, extend.right or extend.both.
Syntax
box.get_extend(id) → extend
Arguments
Returns
extend
box.get_left
Returns the x coordinate of the box's left edge, read as a bar index or as a UNIX time in milliseconds according to the box's xloc.
Syntax
box.get_left(id) → int
Arguments
Returns
int
box.get_right
Returns the x coordinate of the box's right edge, read as a bar index or as a UNIX time in milliseconds according to the box's xloc.
Syntax
box.get_right(id) → int
Arguments
Returns
int
box.get_text
Returns the text drawn inside the box, or na if the box carries none.
Syntax
box.get_text(id) → string
Arguments
Returns
string
box.get_text_color
Returns the colour used for the text inside the box, or na if none was set.
Syntax
box.get_text_color(id) → color
Arguments
Returns
color
box.get_text_font_family
Returns the font family of the box's text, font.family_default or font.family_monospace.
Syntax
box.get_text_font_family(id) → string
Arguments
Returns
string
box.get_text_halign
Returns the horizontal alignment of the box's text: text.align_left, text.align_center or text.align_right.
Syntax
box.get_text_halign(id) → string
Arguments
Returns
string
box.get_text_size
Returns the size of the box's text as one of the size.* values, or na if no explicit size was set.
Syntax
box.get_text_size(id) → size
Arguments
Returns
size
box.get_text_valign
Returns the vertical alignment of the box's text: text.align_top, text.align_center or text.align_bottom.
Syntax
box.get_text_valign(id) → string
Arguments
Returns
string
box.get_text_wrap
Returns the box's text wrapping mode, text.wrap_auto for text that folds to the box width or text.wrap_none for a single line.
Syntax
box.get_text_wrap(id) → string
Arguments
Returns
string
box.get_top
Returns the price of the box's upper edge, or na if it is unset.
Syntax
box.get_top(id) → float
Arguments
Returns
float
box.get_xloc
Returns the box's x coordinate mode, xloc.bar_index or xloc.bar_time, which tells you how its left and right values should be read.
Syntax
box.get_xloc(id) → xloc
Arguments
Returns
xloc
box.new
Draws a rectangle from a top-left to a bottom-right corner and returns a box reference for later changes. left and right are bar indices under xloc.bar_index or UNIX times in milliseconds under xloc.bar_time, while top and bottom are prices; the two corners may instead be given as a pair of chart.point values. The box remains until deleted, and once the script's box cap is reached (500 by default) the oldest boxes are removed.
Syntax
box.new(left, top, right, bottom, border_color?, border_width = 1, border_style = line.style_solid, bgcolor?, xloc = xloc.bar_index, extend = extend.none) → box
Arguments
-
left
int
Left edge x
-
top
float
Top edge y
-
right
int
Right edge x
-
bottom
float
Bottom edge y
-
border_color
color
optional
Border color
-
border_width
int
optional
Border width
-
border_style
line_style
optional
-
bgcolor
color
optional
Background color
-
xloc
xloc
optional
X-location mode
-
extend
extend
optional
Line extend mode
Returns
box
Example
indicator("Recent range box", overlay = true)
if barstate.islast
box.new(bar_index - 20, ta.highest(high, 20), bar_index, ta.lowest(low, 20))
box.set_bgcolor
Sets the fill colour of an existing box in place. Passing na leaves the box unfilled.
Syntax
box.set_bgcolor(id, color)
Arguments
-
id
box
Object reference
-
color
color
Color value
Returns
Nothing
box.set_border_color
Sets the colour of an existing box's border. A na colour removes the explicit border colour.
Syntax
box.set_border_color(id, color)
Arguments
-
id
box
Object reference
-
color
color
Color value
Returns
Nothing
box.set_border_style
Sets the stroke style of an existing box's border, accepting the line.style_* values; a na or unrecognised value falls back to line.style_solid.
Syntax
box.set_border_style(id, style)
Arguments
-
id
box
Object reference
-
style
line_style
Visual style
Returns
Nothing
box.set_border_width
Sets the width, in pixels, of an existing box's border. Values that are not finite numbers are ignored and the box keeps its current border width.
Syntax
box.set_border_width(id, width)
Arguments
-
id
box
Object reference
-
width
int
Width value
Returns
Nothing
box.set_bottom
Moves the lower edge of an existing box to a new price. Passing na or a non-finite value clears the edge, and the box stays hidden until the edge is set again.
Syntax
box.set_bottom(id, bottom)
Arguments
-
id
box
Object reference
-
bottom
float
Bottom edge y
Returns
Nothing
box.set_bottom_right_point
Moves an existing box's bottom-right corner to a chart.point, using the point's bar index or millisecond time to match the box's xloc and its price as the new bottom edge. Passing na leaves the box as it is.
Syntax
box.set_bottom_right_point(id, point)
Arguments
-
id
box
Object reference
-
point
chart.point
Chart point
Returns
Nothing
box.set_extend
Sets how far an existing box is stretched horizontally past its edges, accepting extend.none, extend.left, extend.right or extend.both; a na value resets it to extend.none.
Syntax
box.set_extend(id, extend)
Arguments
-
id
box
Object reference
-
extend
extend
Line extend mode
Returns
Nothing
box.set_left
Moves the left edge of an existing box to a bar index or a UNIX time in milliseconds, according to the box's xloc; a fractional value is truncated. Passing na clears the edge, and the box stays hidden until the edge is set again.
Syntax
box.set_left(id, left)
Arguments
-
id
box
Object reference
-
left
int
Left edge x
Returns
Nothing
box.set_lefttop
Moves the top-left corner of an existing box, setting its left x and its top price in one call. The x value follows the box's xloc, so it is a bar index or a UNIX time in milliseconds. Passing na for either value clears that edge, and the box stays hidden until it is set again.
Syntax
box.set_lefttop(id, left, top)
Arguments
-
id
box
Object reference
-
left
int
Left edge x
-
top
float
Top edge y
Returns
Nothing
box.set_right
Moves the right edge of an existing box to a bar index or a UNIX time in milliseconds, according to the box's xloc; a fractional value is truncated. Passing na clears the edge, and the box stays hidden until the edge is set again.
Syntax
box.set_right(id, right)
Arguments
-
id
box
Object reference
-
right
int
Right edge x
Returns
Nothing
box.set_rightbottom
Moves the bottom-right corner of an existing box, setting its right x and its bottom price together, with x expressed in the unit the box's xloc implies. Passing na for either value clears that edge, and the box stays hidden until it is set again.
Syntax
box.set_rightbottom(id, right, bottom)
Arguments
-
id
box
Object reference
-
right
int
Right edge x
-
bottom
float
Bottom edge y
Returns
Nothing
box.set_text
Sets the text drawn inside an existing box. Invisible characters and trailing blank lines are stripped, and a value that is not a string clears the text altogether.
Syntax
box.set_text(id, text)
Arguments
-
id
box
Object reference
-
text
string
Text content
Returns
Nothing
box.set_text_color
Sets the colour of the text inside an existing box; na clears the explicit colour.
Syntax
box.set_text_color(id, text_color)
Arguments
-
id
box
Object reference
-
text_color
color
Text color
Returns
Nothing
box.set_text_font_family
Sets the font family used for an existing box's text, accepting font.family_default or font.family_monospace.
Syntax
box.set_text_font_family(id, font_family)
Arguments
-
id
box
Object reference
-
font_family
string
Font family
Returns
Nothing
box.set_text_halign
Sets how the text inside an existing box is aligned horizontally, accepting text.align_left, text.align_center or text.align_right.
Syntax
box.set_text_halign(id, text_halign)
Arguments
-
id
box
Object reference
-
text_halign
string
Horizontal text alignment
Returns
Nothing
box.set_text_size
Sets the size of an existing box's text, accepting the size.* values from size.tiny through size.huge. A na value clears the explicit size.
Syntax
box.set_text_size(id, text_size)
Arguments
-
id
box
Object reference
-
text_size
size
Text size
Returns
Nothing
box.set_text_valign
Sets how the text inside an existing box is aligned vertically, accepting text.align_top, text.align_center or text.align_bottom.
Syntax
box.set_text_valign(id, text_valign)
Arguments
-
id
box
Object reference
-
text_valign
string
Vertical text alignment
Returns
Nothing
box.set_text_wrap
Sets whether the text inside an existing box folds to the box width (text.wrap_auto) or stays on one line (text.wrap_none).
Syntax
box.set_text_wrap(id, text_wrap)
Arguments
-
id
box
Object reference
-
text_wrap
string
Text wrapping mode
Returns
Nothing
box.set_top
Moves the upper edge of an existing box to a new price. Passing na or a non-finite value clears the edge, and the box stays hidden until the edge is set again.
Syntax
box.set_top(id, top)
Arguments
-
id
box
Object reference
-
top
float
Top edge y
Returns
Nothing
box.set_top_left_point
Moves an existing box's top-left corner to the position held by a chart.point, taking the point's bar index or millisecond time according to the box's xloc and its price as the new top. A na point leaves the box unchanged.
Syntax
box.set_top_left_point(id, point)
Arguments
-
id
box
Object reference
-
point
chart.point
Chart point
Returns
Nothing
box.set_xloc
Switches how an existing box's left and right coordinates are read, between xloc.bar_index and xloc.bar_time; na leaves the mode unchanged. The stored edges are not converted, so rewrite them in the unit the new mode expects.
Syntax
box.set_xloc(id, xloc)
Arguments
-
id
box
Object reference
-
xloc
xloc
X-location mode
Returns
Nothing
table.* — Tables
table.cell
Fills in or updates a single cell of a table, addressed by its column and row, and can set the cell's text, width and height, text colour, horizontal and vertical alignment, text size, background colour, tooltip and font family. Only the arguments actually supplied are applied, so the same call creates a cell or adjusts part of an existing one. Nothing is returned.
Syntax
table.cell(id, column, row, text?, width?, height?, text_color?, text_halign?, text_valign?, text_size?, bgcolor?, tooltip?, text_font_family?)
Arguments
-
id
table
Object reference
-
column
int
Column index
-
row
int
Row index
-
text
string
optional
Text content
-
width
float
optional
Width value
-
height
float
optional
Height value
-
text_color
color
optional
Text color
-
text_halign
string
optional
Horizontal text alignment
-
text_valign
string
optional
Vertical text alignment
-
text_size
size
optional
Text size
-
bgcolor
color
optional
Background color
-
tooltip
string
optional
Tooltip text
-
text_font_family
string
optional
Font family
Returns
Nothing
Example
indicator("Readout table", overlay = true)
var info = table.new(position.top_right, 1, 1)
if barstate.islast
table.cell(info, 0, 0, str.tostring(close))
table.cell_set_bgcolor
Sets the background colour of one cell of an existing table, addressed by column and row. The cell is created if it is not there yet, and nothing is returned.
Syntax
table.cell_set_bgcolor(id, column, row, bgcolor)
Arguments
-
id
table
Object reference
-
column
int
Column index
-
row
int
Row index
-
bgcolor
color
Background color
Returns
Nothing
table.cell_set_height
Sets the height of one cell of an existing table, addressed by column and row, creating the cell if needed.
Syntax
table.cell_set_height(id, column, row, height)
Arguments
-
id
table
Object reference
-
column
int
Column index
-
row
int
Row index
-
height
float
Height value
Returns
Nothing
table.cell_set_text
Replaces the text of one cell, addressed by column and row, creating the cell if it does not exist yet. Invisible characters and trailing blank lines are stripped, and as with labels the chart's bundled fonts render plain characters and simple geometric glyphs far more reliably than emoji.
Syntax
table.cell_set_text(id, column, row, text)
Arguments
-
id
table
Object reference
-
column
int
Column index
-
row
int
Row index
-
text
string
Text content
Returns
Nothing
table.cell_set_text_color
Sets the colour of the text in one cell, addressed by column and row, creating the cell if needed.
Syntax
table.cell_set_text_color(id, column, row, text_color)
Arguments
-
id
table
Object reference
-
column
int
Column index
-
row
int
Row index
-
text_color
color
Text color
Returns
Nothing
table.cell_set_text_font_family
Sets the font family used for one cell's text, addressed by column and row, accepting font.family_default or font.family_monospace.
Syntax
table.cell_set_text_font_family(id, column, row, text_font_family)
Arguments
-
id
table
Object reference
-
column
int
Column index
-
row
int
Row index
-
text_font_family
string
Font family
Returns
Nothing
table.cell_set_text_halign
Sets the horizontal alignment of one cell's text, addressed by column and row, accepting text.align_left, text.align_center or text.align_right.
Syntax
table.cell_set_text_halign(id, column, row, text_halign)
Arguments
-
id
table
Object reference
-
column
int
Column index
-
row
int
Row index
-
text_halign
string
Horizontal text alignment
Returns
Nothing
table.cell_set_text_size
Sets the text size of one cell, addressed by column and row, accepting the size.* values from size.tiny through size.huge.
Syntax
table.cell_set_text_size(id, column, row, text_size)
Arguments
-
id
table
Object reference
-
column
int
Column index
-
row
int
Row index
-
text_size
size
Text size
Returns
Nothing
table.cell_set_text_valign
Sets the vertical alignment of one cell's text, addressed by column and row, accepting text.align_top, text.align_center or text.align_bottom.
Syntax
table.cell_set_text_valign(id, column, row, text_valign)
Arguments
-
id
table
Object reference
-
column
int
Column index
-
row
int
Row index
-
text_valign
string
Vertical text alignment
Returns
Nothing
table.cell_set_width
Sets the width of one cell of an existing table, addressed by column and row. The cell is created if it does not exist yet, and the whole column follows the widest cell in it.
Syntax
table.cell_set_width(id, column, row, width)
Arguments
-
id
table
Object reference
-
column
int
Column index
-
row
int
Row index
-
width
float
Width value
Returns
Nothing
table.clear
Empties the table's cells, discarding their text and styling while the table itself keeps its position and its declared column and row counts. The call accepts a cell range, but every cell in the table is cleared; nothing is returned.
Syntax
table.clear(id, start_column, start_row, end_column, end_row)
Arguments
-
id
table
Object reference
-
start_column
int
-
start_row
int
-
end_column
int
-
end_row
int
Returns
Nothing
table.delete
Removes the table from the chart and frees one of the script's nine table slots. Nothing is returned, and later calls through the same reference do nothing.
Syntax
table.delete(id)
Arguments
-
id
table
Object reference
Returns
Nothing
table.merge_cells
Takes the start and end column and row of a rectangular block of cells and checks that the four bounds are valid integers. The cells are not currently joined into one, and nothing is returned.
Syntax
table.merge_cells(id, start_column, start_row, end_column, end_row)
Arguments
-
id
table
Object reference
-
start_column
int
-
start_row
int
-
end_column
int
-
end_row
int
Returns
Nothing
table.new
Creates a table of fixed size, pinned to one of nine chart anchors from position.top_left to position.bottom_right, and returns a table reference. The columns and rows counts fix the grid, while the optional background, frame and border settings style it; cells are filled in afterwards with table.cell. A script may hold nine tables at once, and creating more removes the oldest.
Syntax
table.new(position, columns, rows, bgcolor?, frame_color?, frame_width = 0, border_color?, border_width = 0) → table
Arguments
-
position
position
Table position
-
columns
int
Number of columns
-
rows
int
Number of rows
-
bgcolor
color
optional
Background color
-
frame_color
color
optional
Frame color
-
frame_width
int
optional
Frame width
-
border_color
color
optional
Border color
-
border_width
int
optional
Border width
Returns
table
table.set_bgcolor
Sets the background colour drawn behind an existing table's cells. Passing na removes the background.
Syntax
table.set_bgcolor(id, bgcolor)
Arguments
-
id
table
Object reference
-
bgcolor
color
Background color
Returns
Nothing
table.set_border_color
Sets the colour of the borders drawn between an existing table's cells; na clears it.
Syntax
table.set_border_color(id, border_color)
Arguments
-
id
table
Object reference
-
border_color
color
Border color
Returns
Nothing
table.set_border_width
Sets the width, in pixels, of the borders between an existing table's cells. The default of zero leaves the cells without separating borders.
Syntax
table.set_border_width(id, border_width)
Arguments
-
id
table
Object reference
-
border_width
int
Border width
Returns
Nothing
table.set_frame_color
Sets the colour of the frame around the outside of an existing table; na clears it.
Syntax
table.set_frame_color(id, frame_color)
Arguments
-
id
table
Object reference
-
frame_color
color
Frame color
Returns
Nothing
table.set_frame_width
Sets the width, in pixels, of the frame around an existing table. The default of zero draws no frame.
Syntax
table.set_frame_width(id, frame_width)
Arguments
-
id
table
Object reference
-
frame_width
int
Frame width
Returns
Nothing
table.set_position
Moves an existing table to another chart anchor, accepting position.top_left, position.top_center, position.top_right, position.middle_left, position.middle_center, position.middle_right, position.bottom_left, position.bottom_center or position.bottom_right. A position is required; na is rejected.
Syntax
table.set_position(id, position)
Arguments
-
id
table
Object reference
-
position
position
Table position
Returns
Nothing
Constants and enumerations
Named values accepted by the functions above.
color.red
An opaque red preset, hex F23645. Accepted anywhere a colour is expected, such as the color argument of plot, plotshape or label.new; for a translucent version pass it through color.new, as in color.new(color.red, 70).
Syntax
color.red : color
color.green
An opaque green preset, hex 4CAF50. Use it for any colour argument, for example the up-bar colour of plotcandle or the colour of a bgcolor highlight; color.new(color.green, 80) gives the same hue at 80 percent transparency.
Syntax
color.green : color
color.blue
An opaque blue preset, hex 2962FF. Accepted by every colour argument, including the color of plot, line.new and box.new; wrap it in color.new to soften it, as in color.new(color.blue, 50).
Syntax
color.blue : color
color.white
Pure white, hex FFFFFF. Accepted wherever a colour is expected and most often used for text, such as the textcolor argument of label.new or table.cell; transparency comes from color.new rather than from the constant itself.
Syntax
color.white : color
color.black
A very dark slate rather than pure black, hex 363A45. Accepted by any colour argument, for example the border_color of box.new or a table cell's text colour; use color.new for a translucent variant.
Syntax
color.black : color
color.yellow
An opaque yellow preset, hex FDD835. Accepted by any colour argument, including the color of plot, bgcolor and barcolor; color.new(color.yellow, 85) gives a faint background wash of the same hue.
Syntax
color.yellow : color
color.orange
An opaque orange preset, hex FF9800. Accepted wherever a colour is expected, such as the color of plot or the bgcolor of a highlighted region; adjust its strength with color.new.
Syntax
color.orange : color
color.purple
An opaque purple preset, hex 9C27B0. Accepted by any colour argument, for example the border_color of box.new or the color of label.new; use color.new for a transparent variant.
Syntax
color.purple : color
color.teal
A blue-green preset, hex 089981, the shade normally used for rising values. Accepted by any colour argument; pair it with color.red for falling values and vary its strength with color.new.
Syntax
color.teal : color
color.olive
A dark yellow-green preset, hex 808000. Accepted anywhere a colour is expected, such as the color of plot or line.new; color.new controls how transparent it is drawn.
Syntax
color.olive : color
color.aqua
A bright cyan preset, hex 00BCD4. Accepted by any colour argument, including plot colours and table cell backgrounds; use color.new to make it translucent.
Syntax
color.aqua : color
color.fuchsia
A vivid pink-purple preset, hex E040FB. Accepted wherever a colour is expected, and easy to pick out against candles; soften it with color.new when used as a fill.
Syntax
color.fuchsia : color
color.lime
A bright green preset, hex 00E676, stronger than color.green. Accepted by any colour argument; color.new(color.lime, 90) turns it into a light background tint.
Syntax
color.lime : color
color.navy
A deep blue-violet preset, hex 311B92. Accepted by any colour argument, such as the color of line.new or the bgcolor of a region; use color.new to reduce its weight.
Syntax
color.navy : color
color.maroon
A dark crimson preset, hex 880E4F. Accepted wherever a colour is expected, for example box borders or bearish markers; color.new gives a translucent version.
Syntax
color.maroon : color
color.gray
A neutral mid grey, hex 787B86, and the colour an hline takes when none is given. Accepted by any colour argument; use color.new to fade it further.
Syntax
color.gray : color
color.silver
A light grey preset, hex B2B5BE. Accepted by any colour argument and useful for secondary lines and grid-like levels; color.new makes it fainter still.
Syntax
color.silver : color
polyline.all
An array holding every polyline the script currently owns, in creation order and without the ones already deleted. Read it to inspect or clear drawings, for example by looping over polyline.all and calling polyline.delete on each element.
Syntax
polyline.all : array<polyline>
format.inherit
Leaves number formatting to the enclosing script, so a plot falls back to the format given to indicator; when that is also inherit the value is printed with the requested precision, or two decimals if none was set. It is the fallback used when no format argument is supplied.
Syntax
format.inherit
format.mintick
Snaps the displayed number onto the instrument's tick grid, rounding to the nearest tick with halves going up, and prints it with as many decimals as that tick size needs. It ignores any precision argument, so choose it when a displayed value must be a tradable price.
Syntax
format.mintick
format.price
Prints the number with a fixed number of decimals: the precision argument when given, otherwise the decimal count implied by the instrument's tick size. Unlike format.mintick it only controls the digits shown and leaves the value itself unrounded.
Syntax
format.price
format.volume
Abbreviates large numbers on the Indian scale, adding a K suffix from one thousand, an L suffix from one lakh and a Cr suffix from one crore, with trailing zeros trimmed; smaller numbers print unchanged. Intended for share counts and turnover rather than prices.
Syntax
format.volume
format.percent
Prints the number with the requested decimals, two by default, and appends a percent sign. The value is not multiplied by 100, so pass a figure that is already expressed in percent.
Syntax
format.percent
size.auto
Asks the chart to choose the size. It currently resolves to exactly the same dimensions as size.normal for markers, characters and text, so it behaves as a default rather than adapting to zoom or content.
Syntax
size.auto
size.tiny
The smallest preset: shape markers are drawn with a five pixel radius and text at nine pixels. Useful when markers would otherwise crowd each other on tight bars.
Syntax
size.tiny
size.small
One step below the default: markers use a seven pixel radius and text eleven pixels. Accepted by the size arguments of plotshape, plotchar and label.new and by the text_size arguments of box.new and table.cell.
Syntax
size.small
size.normal
The default preset: markers use a nine pixel radius and text thirteen pixels. Label and cell sizes also accept a plain number instead of a preset, capped at twenty-four pixels.
Syntax
size.normal
size.large
One step above the default: markers use a twelve pixel radius and text sixteen pixels. Accepted by the same size and text_size arguments as the other presets.
Syntax
size.large
size.huge
The largest preset: markers use a sixteen pixel radius, label and table text twenty-four pixels, and plotchar characters twenty pixels.
Syntax
size.huge
scale.left
Requests that the script be measured against a price scale on the left of its pane. The value is stored with the script's configuration, but this chart draws every indicator against the single scale its pane already has, so the choice is not currently acted on.
Syntax
scale.left
scale.right
Requests the price scale on the right of the pane, which is where this chart puts its axis in any case. Like the other scale values it is recorded with the script and does not change what is drawn.
Syntax
scale.right
scale.none
Requests that the script not be tied to a price scale, which suits overlay scripts that position their own drawings. It is accepted and stored, but the current renderer always scales a pane's contents against that pane's axis.
Syntax
scale.none
shape.arrowup
Selects a solid block arrow pointing up, with a head and a narrower shaft, for the style argument of plotshape. It is drawn about half again as large as the other markers at the same size setting.
Syntax
shape.arrowup
shape.arrowdown
The same solid block arrow as shape.arrowup, pointing down. Accepted by the style argument of plotshape and normally paired with it to mark opposite signals.
Syntax
shape.arrowdown
shape.circle
Draws a filled disc centred on the plotted point, with its radius taken from the size argument. Accepted by the style argument of plotshape.
Syntax
shape.circle
shape.cross
Draws a plus sign, one horizontal and one vertical stroke meeting at the plotted point. Accepted by the style argument of plotshape; shape.xcross gives the diagonal version.
Syntax
shape.cross
shape.diamond
Draws a filled four-sided diamond centred on the plotted point, slightly taller than it is wide. Accepted by the style argument of plotshape.
Syntax
shape.diamond
shape.flag
Draws a small pennant: a thin vertical pole with a filled triangle attached at its upper right. Accepted by the style argument of plotshape.
Syntax
shape.flag
shape.labelup
Draws a rounded rectangle just below the plotted point with a triangular tip pointing up at it, and sets any text argument inside that rectangle instead of above the marker. Accepted by the style argument of plotshape.
Syntax
shape.labelup
shape.labeldown
Draws a rounded rectangle just above the plotted point with a triangular tip pointing down at it, with the text argument set inside the rectangle. Accepted by the style argument of plotshape.
Syntax
shape.labeldown
shape.square
Draws a filled square centred on the plotted point, its side twice the radius implied by the size argument. Accepted by the style argument of plotshape.
Syntax
shape.square
shape.triangleup
Draws a filled triangle with its apex pointing up and its base below the plotted point. Accepted by the style argument of plotshape.
Syntax
shape.triangleup
shape.triangledown
Draws a filled triangle with its apex pointing down and its base above the plotted point. Accepted by the style argument of plotshape.
Syntax
shape.triangledown
shape.xcross
Draws two diagonal strokes crossing at the plotted point, forming an X. Accepted by the style argument of plotshape; shape.cross gives the upright version.
Syntax
shape.xcross
location.absolute
Reads the plotted series as a price and places the marker at exactly that level, so the value controls the vertical position. Bars whose value is na or non-finite get no marker.
Syntax
location.absolute
location.abovebar
Ignores the numeric value and places the marker just above the bar's high; this is the default for plotshape and plotchar. The series then acts purely as a condition, drawing a marker on bars where it is true or not na.
Syntax
location.abovebar
location.belowbar
Places the marker just below the bar's low, again treating the series as a condition rather than a price. Pair it with location.abovebar to separate bullish and bearish markers.
Syntax
location.belowbar
location.top
Pins the marker to the top edge of the pane, where it stays as prices move. Markers placed this way are left out of the pane's automatic price-range calculation, so they never stretch the scale.
Syntax
location.top
location.bottom
Pins the marker to the bottom edge of the pane, just inside the axis. Like location.top it is excluded from the pane's automatic price range.
Syntax
location.bottom
extend.none
Leaves the drawing bounded by the coordinates you gave it, so a line stops at its two endpoints and a box keeps its stated left and right edges. It is the default for both line.new and box.new.
Syntax
extend.none
extend.left
Carries the drawing leftwards: a line is projected along its own slope until it meets the left edge of the visible area, and a box's left side is pulled to that edge. Only the first point of a line moves, so the direction follows which point you named first rather than which is further left on screen.
Syntax
extend.left
extend.right
Carries the drawing rightwards to the right edge of the visible area, projecting a line along its slope and stretching a box's right side. This is the usual way to carry a level found on a past bar forward over later bars.
Syntax
extend.right
extend.both
Extends the drawing to both edges of the visible area, turning a two-point line into a trendline that spans the chart. A linefill widens with its lines only when both of them extend in the same direction.
Syntax
extend.both
yloc.price
Treats the label's y coordinate as a price and anchors the label at that level. It is the default, and a label whose y is missing or non-finite is not drawn.
Syntax
yloc.price
yloc.abovebar
Anchors the label a little above the high of the bar its x coordinate points to and ignores the y coordinate completely. The bar must already exist on the chart, so a label placed this way beyond the last bar is not drawn.
Syntax
yloc.abovebar
yloc.belowbar
Anchors the label just below the low of its bar and ignores the y coordinate. As with yloc.abovebar the target bar has to exist on the chart for the label to appear.
Syntax
yloc.belowbar
order.ascending
Sorts from smallest to largest. It is the default for the order argument of array.sort, array.sort_indices and matrix.sort.
Syntax
order.ascending
order.descending
Sorts from largest to smallest. Accepted by the order argument of array.sort, array.sort_indices and matrix.sort.
Syntax
order.descending
adjustment.none
Asks for raw, unadjusted prices. It is recorded in the ticker identifier that ticker.new and ticker.modify build, which you then pass to request.security.
Syntax
adjustment.none
adjustment.splits
Asks for prices adjusted for share splits so history stays comparable across a split. Accepted by the adjustment argument of ticker.new and ticker.modify and carried in the ticker identifier they return.
Syntax
adjustment.splits
adjustment.dividends
Asks for prices adjusted for dividends as well as splits, which shifts historical levels by the payouts made. Accepted by the adjustment argument of ticker.new and ticker.modify.
Syntax
adjustment.dividends
settlement_as_close.off
Keeps the last traded price as each session's close for a futures contract. Accepted by the settlement_as_close argument of ticker.modify and encoded in the ticker identifier it returns.
Syntax
settlement_as_close.off
settlement_as_close.on
Uses the exchange's settlement price as each session's close for a futures contract instead of the last trade. Accepted by the settlement_as_close argument of ticker.modify.
Syntax
settlement_as_close.on
display.none
Hides the output from every surface. It is the one display value every visual honours, which makes it the reliable way to keep a series available for calculation without drawing it.
Syntax
display.none
display.pane
Selects the chart pane, where output is drawn. Clearing this bit removes plot, plotcandle and plotbar output from the pane; other visuals such as plotshape, hline and fill only react to display.none, so they keep drawing.
Syntax
display.pane
display.data_window
Selects the data window surface. Nothing in this app renders a data window, so the bit is stored and carried with the script but currently changes nothing on screen.
Syntax
display.data_window
display.status_line
Selects the indicator's status line, the row of values shown above the chart for the bar under the cursor. Clearing this bit keeps a plot, candle, shape or arrow out of that row, and on an input it hides that input from the status line summary.
Syntax
display.status_line
display.price_scale
Selects the price axis. Keeping it lets a plot show its latest value as a tag on the axis and lets the output take part in the pane's automatic price range; clearing it does both in reverse, which is a convenient way to stop an outlying series from stretching the scale.
Syntax
display.price_scale
display.pine_screener
Selects the screener surface. It is accepted and takes part in the bitmask arithmetic, but nothing in this app reads it.
Syntax
display.pine_screener
display.all
Every surface at once, and the default for plot, hline, plotshape, the input functions and the other visuals. Build a narrower set by subtraction, for example display.all - display.status_line.
Syntax
display.all
plot.style_line
The default for plot: consecutive values are joined by a straight line and bars whose value is na are bridged over, so the line stays unbroken.
Syntax
plot.style_line
plot.style_linebr
A line that is cut wherever the series is na, leaving a visible gap instead of bridging it. Choose it when missing values are meaningful rather than incidental.
Syntax
plot.style_linebr
plot.linestyle_dashed
Draws the plot as a dashed line, roughly ten pixels of ink to five of gap, bridging over na values. Pass it as the style argument of plot; the separate linestyle argument of plot is recorded but not drawn.
Syntax
plot.linestyle_dashed
plot.linestyle_dotted
Draws the plot as a finely broken line, about two pixels of ink to four of gap, bridging over na values. Pass it as the style argument of plot rather than as linestyle, which the renderer does not read.
Syntax
plot.linestyle_dotted
plot.linestyle_solid
Draws a plain unbroken line, the same result as plot.style_line. Pass it as the style argument of plot; plot's separate linestyle argument is stored but has no effect on the drawing.
Syntax
plot.linestyle_solid
plot.style_area
Fills the region between the series and the histbase level with a translucent wash and draws a solid line along its edge. The fill is continuous, so na values are bridged.
Syntax
plot.style_area
plot.style_columns
Draws one vertical bar per value, rising or falling from the histbase level, with the bar width following the candle width so the columns sit under the bars like a volume histogram.
Syntax
plot.style_columns
plot.style_circles
Marks each value with a small filled disc instead of a line. The radius follows linewidth rather than the size constants, and setting join to true connects the discs.
Syntax
plot.style_circles
plot.style_cross
Marks each value with a small plus sign. As with plot.style_circles the marker size follows linewidth, and join controls whether the points are connected by a line.
Syntax
plot.style_cross
plot.style_areabr
The area fill of plot.style_area, closed off at every na value so the shape breaks into separate regions rather than spanning the gap.
Syntax
plot.style_areabr
plot.style_stepline
Holds each value flat until the next one and then steps to it, giving square corners instead of diagonals. na values are bridged over.
Syntax
plot.style_stepline
plot.style_stepline_diamond
The stepped line of plot.style_stepline with a filled diamond marking each actual data point, sized from linewidth.
Syntax
plot.style_stepline_diamond
plot.style_steplinebr
The stepped line of plot.style_stepline, broken at na values so gaps in the series leave gaps on the chart.
Syntax
plot.style_steplinebr
plot.style_histogram
Draws a vertical bar per value from the histbase level, using linewidth as the bar thickness in pixels. Unlike plot.style_columns the bars keep that fixed width however far you zoom.
Syntax
plot.style_histogram
hline.style_dashed
Draws the horizontal level as a dashed line, about ten pixels of ink to five of gap. Accepted by the linestyle argument of hline, which uses it when no style is given.
Syntax
hline.style_dashed
hline.style_dotted
Draws the level as a finely broken line, about two pixels of ink to four of gap. Accepted by the linestyle argument of hline.
Syntax
hline.style_dotted
hline.style_solid
Draws an unbroken horizontal line. Accepted by the linestyle argument of hline; such a level always spans the full width of the pane, since hline has no extend setting.
Syntax
hline.style_solid
xloc.bar_index
Reads x coordinates as bar indices counted on the chart's own bars, and is the default for lines, boxes and labels. Positions map straight onto candle slots, so calendar gaps such as weekends and holidays do not matter, and an index past the last bar lands in the empty space to its right.
Syntax
xloc.bar_index
xloc.bar_time
Reads x coordinates as UNIX timestamps in milliseconds and looks up the bar carrying that time. A timestamp later than the last bar is projected forward by dividing the difference by the chart timeframe, which assumes an uninterrupted timeline and so takes no account of session breaks or holidays.
Syntax
xloc.bar_time
text.align_center
Centres text horizontally. Accepted by the text_align argument of label.new and label.set_text_align and by the text_halign arguments of box.new and table.cell; on a label it only shows when the text spans several lines.
Syntax
text.align_center
text.align_left
Aligns text to the left of its area. Accepted by the text_align argument of labels and the text_halign arguments of boxes and table cells, where it also pushes the text block against the left of the rectangle.
Syntax
text.align_left
text.align_right
Aligns text to the right of its area and, in boxes and table cells, moves the block against the right of the rectangle. Accepted by the same text_align and text_halign arguments as the other horizontal alignments.
Syntax
text.align_right
text.align_bottom
Sits text against the bottom of its rectangle. Accepted by the text_valign arguments of box.new and table.cell; it is a vertical alignment, so it has no effect where only a horizontal text_align is taken.
Syntax
text.align_bottom
text.align_top
Sits text against the top of its rectangle and is the fallback for vertical alignment. Accepted by the text_valign arguments of box.new and table.cell.
Syntax
text.align_top
text.format_none
Draws label text in the plain weight and upright style, and is the default. Accepted by the text_formatting argument of label.new and label.set_text_formatting.
Syntax
text.format_none
text.format_bold
Draws label text in bold. Accepted by the text_formatting argument of label.new and label.set_text_formatting; only one formatting value applies at a time, so bold and italic cannot be combined.
Syntax
text.format_bold
text.format_italic
Draws label text slanted. Accepted by the text_formatting argument of label.new and label.set_text_formatting, and like the other formatting values it replaces the current one rather than adding to it.
Syntax
text.format_italic
text.wrap_auto
Asks box text to wrap onto further lines when it is wider than the box. Accepted by the text_wrap argument of box.new and box.set_text_wrap, and it matches what the renderer already does, since box text is always wrapped to the box width.
Syntax
text.wrap_auto
text.wrap_none
Asks box text to stay on a single line rather than wrap. Accepted by the text_wrap argument of box.new and box.set_text_wrap, though the renderer currently wraps box text to the box width whichever value is set.
Syntax
text.wrap_none
font.family_default
Selects the chart's standard text font. Accepted by the text_font_family arguments of label.new, box.new and table.cell.
Syntax
font.family_default
font.family_monospace
Asks for a fixed-width font so digits line up in columns. Accepted by the same text_font_family arguments as font.family_default, but the renderer does not yet substitute a monospaced face, so text still appears in the standard font.
Syntax
font.family_monospace
position.top_left
Anchors a table to the upper left of the pane, ten pixels in from the top and left edges. Accepted by the position argument of table.new and table.set_position; a table stays pinned to the pane while the chart scrolls.
Syntax
position.top_left
position.top_center
Anchors a table to the top of the pane, horizontally centred and ten pixels below the top edge. Accepted by the position argument of table.new and table.set_position.
Syntax
position.top_center
position.top_right
Anchors a table to the upper right of the pane, ten pixels in from the top and right edges. It is also the fallback used when a position value cannot be recognised.
Syntax
position.top_right
position.middle_left
Anchors a table against the left edge of the pane, vertically centred. Accepted by the position argument of table.new and table.set_position.
Syntax
position.middle_left
position.middle_center
Centres a table both horizontally and vertically in the pane, over the bars. Accepted by the position argument of table.new and table.set_position.
Syntax
position.middle_center
position.middle_right
Anchors a table against the right edge of the pane, vertically centred and ten pixels in from that edge.
Syntax
position.middle_right
position.bottom_left
Anchors a table to the lower left of the pane, ten pixels in from the bottom and left edges.
Syntax
position.bottom_left
position.bottom_center
Anchors a table to the bottom of the pane, horizontally centred and ten pixels above the bottom edge.
Syntax
position.bottom_center
position.bottom_right
Anchors a table to the lower right of the pane, ten pixels in from the bottom and right edges.
Syntax
position.bottom_right
barmerge.gaps_off
Carries the last known value of the requested series forward onto every chart bar, so the result never becomes na between updates. It is the default for the gaps argument of request.security and request.instrument.
Syntax
barmerge.gaps_off
barmerge.gaps_on
Returns a value only on the chart bars where the requested series actually produces one, and na everywhere else. That leaves visible holes in the series but makes it obvious exactly when new higher-timeframe data arrived.
Syntax
barmerge.gaps_on
barmerge.lookahead_off
Restricts each chart bar to requested-timeframe data that had already closed by that point, so historical values match what the script could have known at the time. It is the default and the safe choice for anything that drives signals.
Syntax
barmerge.lookahead_off
barmerge.lookahead_on
Lets a chart bar read the requested-timeframe bar covering it as soon as that bar opens, before it has closed. History then shows values that were not yet knowable, so results look better on past bars than the same script behaves in real time.
Syntax
barmerge.lookahead_on
line.style_solid
Draws an unbroken line and is the default for line.new. Also accepted by line.set_style and by polyline.new.
Syntax
line.style_solid
line.style_dashed
Draws the line as dashes, about ten pixels of ink to five of gap. Accepted by the style argument of line.new, line.set_style and polyline.new.
Syntax
line.style_dashed
line.style_dotted
Draws the line as short marks, about two pixels of ink to four of gap. Accepted by the same style arguments as the other line styles.
Syntax
line.style_dotted
line.style_arrow_left
Draws the line with an open chevron arrowhead at its first point, the one given by x1 and y1. A polyline accepts the value but is drawn without the arrowhead.
Syntax
line.style_arrow_left
line.style_arrow_right
Draws the line with an open chevron arrowhead at its second point, the one given by x2 and y2. As with the other arrow styles a polyline drops the head and draws a plain path.
Syntax
line.style_arrow_right
line.style_arrow_both
Draws the line with an open chevron arrowhead at each end. Accepted by the style argument of line.new and line.set_style.
Syntax
line.style_arrow_both
label.style_circle
Draws a filled circle behind the label text, centred on the anchor point. Accepted by the style argument of label.new and label.set_style.
Syntax
label.style_circle
label.style_square
Draws a filled square behind the label text, centred on the anchor point and sized to cover it.
Syntax
label.style_square
label.style_label_up
Draws a rounded speech bubble below the anchor with its pointer aimed up at that point, so the text sits under the level it marks.
Syntax
label.style_label_up
label.style_label_down
Draws a rounded speech bubble above the anchor with its pointer aimed down at that point. It is the style label.new uses when none is given.
Syntax
label.style_label_down
label.style_label_left
Draws the bubble to the right of the anchor with its pointer on the bubble's left edge, so the text reads away from the point.
Syntax
label.style_label_left
label.style_label_right
Draws the bubble to the left of the anchor with its pointer on the bubble's right edge.
Syntax
label.style_label_right
label.style_label_center
Centres a plain rounded rectangle on the anchor with no pointer, so the text sits directly over the point it marks.
Syntax
label.style_label_center
label.style_label_lower_left
Selects a bubble whose pointer sits at its lower left corner. The renderer has no corner geometry yet, so it currently draws as a plain rounded rectangle centred on the anchor.
Syntax
label.style_label_lower_left
label.style_label_lower_right
Selects a bubble whose pointer sits at its lower right corner. Like the other corner variants it currently draws as a plain rounded rectangle centred on the anchor.
Syntax
label.style_label_lower_right
label.style_label_upper_left
Selects a bubble whose pointer sits at its upper left corner. The current renderer falls back to a plain rounded rectangle centred on the anchor.
Syntax
label.style_label_upper_left
label.style_label_upper_right
Selects a bubble whose pointer sits at its upper right corner. As with the other corner variants it currently draws as a plain rounded rectangle centred on the anchor.
Syntax
label.style_label_upper_right
label.style_triangleup
Draws a filled triangle pointing up, sized from the label text, with no bubble around it.
Syntax
label.style_triangleup
label.style_triangledown
Draws a filled triangle pointing down, sized from the label text and centred on the anchor.
Syntax
label.style_triangledown
label.style_cross
Selects a cross marker as the label's background. No cross geometry is implemented, so it currently draws as a plain rounded rectangle centred on the anchor.
Syntax
label.style_cross
label.style_flag
Selects a flag marker as the label's background. It currently draws as a plain rounded rectangle centred on the anchor.
Syntax
label.style_flag
label.style_diamond
Selects a diamond marker as the label's background. It currently draws as a plain rounded rectangle centred on the anchor.
Syntax
label.style_diamond
label.style_arrowup
Selects an upward arrow as the label's background. The current renderer draws a plain rounded rectangle centred on the anchor instead.
Syntax
label.style_arrowup
label.style_arrowdown
Selects a downward arrow as the label's background. Like label.style_arrowup it currently draws as a plain rounded rectangle.
Syntax
label.style_arrowdown
label.style_text_outline
Selects text on an outlined background. The current renderer fills the rectangle rather than outlining it, so the result looks the same as a centred rounded rectangle.
Syntax
label.style_text_outline
label.style_none
Draws no background at all, leaving only the text floating at the anchor point. Use it when a bubble would hide the bars behind it.
Syntax
label.style_none
label.style_xcross
Selects an X marker as the label's background. No X geometry is implemented, so it currently draws as a plain rounded rectangle centred on the anchor.
Syntax
label.style_xcross