Documentation

The SahiScript language and every built-in it supports.

The basics

SahiScript is compatible with Pine v6 syntax, so an indicator written for another charting platform generally runs with little or no modification. A script is evaluated once per bar, from the oldest bar to the most recent, and again on each tick of the bar still forming.

Every script needs exactly one indicator() declaration, and normally plots something:

//@version=6
indicator("My average", overlay = true)

length = input.int(20, "Length", minval = 1)
average = ta.sma(close, length)

plot(average, "SMA", color = color.blue)

The //@version=6 line is accepted so that scripts copied from elsewhere work unchanged, but it is optional.

Values and series

Most values are series: one value per bar. Writing close gives the current bar's close, and close[1] the previous bar's. Offsets must be zero or positive, since a negative offset would look into the future.

A missing value is na. Any comparison involving na is false, including !=, so test for it with na(x) rather than x == na.

Variables and types

= declares a variable and := reassigns one. A plain variable is recalculated on every bar; var keeps its value across bars, and varip also keeps it across the ticks of the bar still forming.

The basic types are int, float, bool, string and color, plus the drawing types line, label, box, table, linefill and polyline, and the collections array, map and matrix. You can declare your own with type and enum, and attach methods with method.

Control flow

if / else and switch branch; for, for…in and while loop, with break and continue. A function is declared with => and may return a tuple:

bands(source, length, mult) =>
    basis = ta.sma(source, length)
    dev = mult * ta.stdev(source, length)
    [basis, basis + dev, basis - dev]

[mid, upper, lower] = bands(close, 20, 2)

What is not supported yet

Strategies, libraries and alerts are recognised by the language but are not available yet — see the release notes. Everything documented below is supported.

Declaration

Every script begins with exactly one indicator() call, which names the script and controls how it is placed on the chart.

indicator

Declares the script as a chart indicator and sets how it is presented: the title, which cannot be empty, the short name shown on the chart, whether its visuals sit on the price pane or in a separate pane, and the number format, decimal precision and price-scale side used for its values. It also fixes the script's drawing budget, where max_lines_count, max_labels_count and max_boxes_count default to 100 and are capped at 500, max_polylines_count is capped at 100, and max_bars_back is held between 0 and 10000. Passing timeframe makes the script calculate on that timeframe rather than the chart's, and timeframe_gaps decides whether values repeat on the bars between higher-timeframe updates.

indicator(title, shorttitle?, overlay = false, format?, precision?, scale?, max_bars_back?, timeframe?, timeframe_gaps = true, explicit_plot_zorder = false, max_lines_count = 100, max_labels_count = 100, max_boxes_count = 100, calc_bars_count = 0, max_polylines_count = 50)
  • title string Display title
  • shorttitle string optional Short title
  • overlay bool optional Overlay on main chart
  • format string optional Number format
  • precision int optional Decimal precision
  • scale scale optional
  • max_bars_back int optional Max historical bars
  • timeframe string optional Timeframe string
  • timeframe_gaps bool optional
  • explicit_plot_zorder bool optional
  • max_lines_count int optional
  • max_labels_count int optional
  • max_boxes_count int optional
  • calc_bars_count int optional
  • max_polylines_count int optional

Nothing

indicator("Range width")

width = high - low
plot(width, "Bar range")

Built-in variables

Values the chart provides for the bar being calculated.

close

Closing price of the bar being processed, expressed in the instrument's quote currency. On the bar that is still forming it holds the most recent traded price and changes with every incoming tick; once the bar closes the value is final.

close : float

open

Price at which the bar opened, in the instrument's quote currency. It is set when the bar starts and does not change for the rest of that bar.

open : float

high

Highest price traded during the bar so far. On the bar that is still forming it can move up as new ticks arrive; on completed bars it is final.

high : float

low

Lowest price traded during the bar so far. On the bar that is still forming it can move down as new ticks arrive; on completed bars it is final.

low : float

volume

Number of units traded during the bar, as a whole number. It accumulates while the bar is still forming and becomes final when the bar closes.

volume : float

openinterest

Open interest recorded for the bar, that is the number of derivative contracts outstanding, as a whole number. It is meaningful for futures and options; when the data feed supplies no open interest for the instrument the value reads as zero.

openinterest : float

hl2

Midpoint of the bar, computed as high plus low divided by two. It is recalculated per bar and follows the live bar as its high and low move.

hl2 : float

hlc3

Typical price of the bar, computed as the average of high, low and close. It is recalculated per bar and follows the live bar as its values move.

hlc3 : float

ohlc4

Average price of the bar, computed as the average of open, high, low and close. It is recalculated per bar and follows the live bar as its values move.

ohlc4 : float

hlcc4

Close-weighted average price of the bar, computed as high plus low plus twice the close, divided by four. It is recalculated per bar and follows the live bar as its values move.

hlcc4 : float

ask

Price of the best offer to sell on the current tick. Charts here are built from bars rather than ticks, so it is always na; scripts that read it still run.

ask : float

bid

Price of the best offer to buy on the current tick. Charts here are built from bars rather than ticks, so it is always na; scripts that read it still run.

bid : float

bar_index

Position of the bar currently being processed within the loaded data, counted from zero. The oldest loaded bar is 0 and the number increases by one for each later bar.

bar_index : int

last_bar_index

Index of the newest bar currently loaded, as a whole number. It is the same value on every bar of a single run and increases when a new bar arrives from the feed.

last_bar_index : int

last_bar_time

Opening timestamp of the newest loaded bar, as a UNIX time in milliseconds. It is the same value on every bar of a single run and moves forward when a new bar arrives.

last_bar_time : int

timenow

Current wall-clock time as a UNIX time in milliseconds. It is sampled once per execution pass, so every bar evaluated in that pass sees the same value, and it does not depend on the timestamps of the bars.

timenow : int

time_tradingday

Start of the trading day the bar belongs to, as a UNIX time in milliseconds at midnight in exchange time. All bars of the same trading day share one value, and for a session that runs past midnight the bars are attributed to the day on which that session ends.

time_tradingday : int

syminfo.*

syminfo.basecurrency

Base currency of the instrument, which on this platform is always INR, matching syminfo.currency. It is a constant for the symbol and does not change from bar to bar.

syminfo.basecurrency : string

syminfo.country

Country of the exchange the symbol trades on, as a three-letter code. This platform serves Indian markets, so it is always IND.

syminfo.country : string

syminfo.currency

Currency in which the symbol's prices are quoted. On this platform it is always INR.

syminfo.currency : string

syminfo.description

Human-readable name of the instrument as supplied by the chart, for example the company or index name. It is an empty string when the chart provides no description. Constant for the symbol.

syminfo.description : string

syminfo.exchange

Exchange code on which the symbol trades, for example NSE or BSE. Constant for the symbol, and inside a request for another symbol it reflects that requested symbol's exchange.

syminfo.exchange : string

syminfo.expiration_date

Intended to hold the expiry date of a derivative contract. This runtime does not populate it, so it always reads as na; use contract metadata from the symbol name or your own inputs instead.

syminfo.expiration_date : string

syminfo.industry

Intended to hold the industry classification of the instrument. This runtime does not populate it, so it always reads as na.

syminfo.industry : string

syminfo.isin

Intended to hold the ISIN code of the instrument. This runtime does not populate it, so it always reads as an empty string.

syminfo.isin : string

syminfo.main_tickerid

Full identifier of the symbol the script is attached to, including the exchange prefix, for example NSE:INFY. Unlike syminfo.tickerid it keeps pointing at the chart's own symbol while the script is evaluating a request for a different symbol.

syminfo.main_tickerid : string

syminfo.mintick

Smallest price increment the instrument can move by, expressed as a price, for example 0.05. Constant for the symbol, and useful for rounding levels to valid prices.

syminfo.mintick : float

syminfo.pointvalue

Value of a one point price move in the instrument. The contract multiplier is not supplied to scripts on this platform, so this reads as na; guard it with na before using it in position sizing rather than assuming a value of one.

syminfo.pointvalue : float

syminfo.prefix

Exchange prefix used at the front of the symbol's identifier, for example NSE. On this platform it carries the same value as syminfo.exchange.

syminfo.prefix : string

syminfo.session

Session type the symbol's bars are built from. This platform serves regular-session data only, so the value is always the string regular.

syminfo.session : string

syminfo.symbol

Name of the symbol without any exchange prefix, for example INFY. Constant for the symbol, and inside a request for another symbol it reflects that requested symbol.

syminfo.symbol : string

syminfo.ticker

Name of the symbol without the exchange prefix. On this platform it returns the same value as syminfo.symbol.

syminfo.ticker : string

syminfo.tickerid

Full symbol identifier including the exchange prefix, for example NSE:INFY. While the script is evaluating a request for a different symbol it reports that requested symbol rather than the chart's.

syminfo.tickerid : string

syminfo.timeframe

Timeframe of the data the script is currently computing on, written as a short string such as 15 for fifteen minutes or 1D for daily. While the script is evaluating a request at another timeframe it reports that requested timeframe.

syminfo.timeframe : string

syminfo.timezone

Time zone of the exchange, given as a fixed offset from UTC such as UTC+5:30 for Indian exchanges. It describes the exchange, not the device's local zone, and all calendar and session values are derived in it.

syminfo.timezone : string

syminfo.type

Category of the instrument, taken from the platform's security master rather than guessed from the symbol name. Values include stock, fund, index, futures, option and commodity. While the script is evaluating a request for a different symbol it reports that symbol's category.

syminfo.type : string

barstate.*

barstate.isconfirmed

True when the values of the bar being processed can no longer change. It is true on every completed bar, becomes true on the newest bar once that bar closes, and is true on all bars, including the newest, while the market is closed.

barstate.isconfirmed : bool

barstate.isfirst

True only on the oldest bar of the loaded data, the one whose bar_index is zero. It is false on every other bar and is handy for one-time setup work.

barstate.isfirst : bool

barstate.ishistory

True on bars that are no longer receiving live updates. While the market is open it is true on every bar except the newest one; while the market is closed it is true on all loaded bars, including the newest.

barstate.ishistory : bool

barstate.islast

True on the newest bar currently loaded, whether or not the market is open, and false on every earlier bar. It marks the right-hand edge of the data and is commonly used to draw labels or tables once per run.

barstate.islast : bool

barstate.islastconfirmedhistory

True on the newest bar whose values are already final. While the market is open that is the bar immediately before the live one; while the market is closed it is the newest loaded bar.

barstate.islastconfirmedhistory : bool

barstate.isnew

True the first time the script evaluates a given bar, and false on the later updates that arrive within that same bar. While the market is closed every bar is evaluated as new.

barstate.isnew : bool

barstate.isrealtime

True only on the newest bar while the market is open, that is the bar currently being updated by live ticks. It is false on all earlier bars and false on every bar while the market is closed.

barstate.isrealtime : bool

chart.*

chart.bg_color

Background color the chart is drawn on, following the app's current theme. It falls back to white when the chart supplies no background, and stays the same for the duration of a run.

chart.bg_color : color

chart.fg_color

Foreground color the chart uses for text and axes, following the app's current theme. It falls back to black when the chart supplies no foreground, and stays the same for the duration of a run.

chart.fg_color : color

chart.is_heikinashi

True when the chart is displaying Heikin Ashi candles, so the script is being fed smoothed bar values rather than raw ones. Constant for the duration of a run.

chart.is_heikinashi : bool

chart.is_kagi

Would be true on a Kagi chart. This platform does not offer Kagi charts, so the value is always false.

chart.is_kagi : bool

chart.is_linebreak

Would be true on a Line Break chart. This platform does not offer Line Break charts, so the value is always false.

chart.is_linebreak : bool

chart.is_range

Would be true on a Range chart. This platform does not offer Range charts, so the value is always false.

chart.is_range : bool

chart.is_renko

True when the chart is displaying Renko bricks, so the script is being fed brick values rather than time-based bars. Constant for the duration of a run.

chart.is_renko : bool

chart.is_standard

True when the chart is displaying ordinary time-based candles rather than a derived bar type such as Heikin Ashi or Renko. Constant for the duration of a run.

chart.is_standard : bool

chart.left_visible_bar_time

Opening timestamp of the leftmost bar currently visible on screen, as a UNIX time in milliseconds. It changes as the chart is scrolled or zoomed, and reads as zero when the visible range is not known.

chart.left_visible_bar_time : int

chart.right_visible_bar_time

Opening timestamp of the rightmost bar currently visible on screen, as a UNIX time in milliseconds. It changes as the chart is scrolled or zoomed, and reads as zero when the visible range is not known.

chart.right_visible_bar_time : int

timeframe.*

timeframe.isdaily

True when the chart timeframe is measured in days, such as 1D or 3D. Constant for the duration of a run.

timeframe.isdaily : bool

timeframe.isdwm

True when the chart timeframe is measured in days, weeks or months, that is any timeframe of one day or longer. It is the opposite of timeframe.isintraday for the timeframes this platform offers.

timeframe.isdwm : bool

timeframe.isintraday

True when the chart timeframe is shorter than a day, that is measured in minutes or seconds. Constant for the duration of a run and often used to guard session-based logic.

timeframe.isintraday : bool

timeframe.isminutes

True when the chart timeframe is measured in minutes. Minute timeframes are written as a plain number, so 15 means fifteen minutes and 60 means one hour.

timeframe.isminutes : bool

timeframe.ismonthly

True when the chart timeframe is measured in months, such as 1M or 3M. Constant for the duration of a run.

timeframe.ismonthly : bool

timeframe.isseconds

True when the chart timeframe is measured in seconds, written with an S suffix such as 30S. Constant for the duration of a run.

timeframe.isseconds : bool

timeframe.isweekly

True when the chart timeframe is measured in weeks, such as 1W. Constant for the duration of a run.

timeframe.isweekly : bool

timeframe.multiplier

Numeric part of the chart timeframe, as a whole number: 15 for a fifteen-minute chart, 3 for a three-day chart, and 1 when the timeframe carries no explicit number. Pair it with the timeframe.is... flags to work out the actual unit.

timeframe.multiplier : int

timeframe.period

Chart timeframe written as a short string: a plain number for minutes, an S suffix for seconds, and a D, W or M suffix for days, weeks and months, for example 15, 30S or 1D. Constant for the duration of a run.

timeframe.period : string

session.*

session.extended

Constant string naming the extended-hours session. It is meant as an argument when building or altering a symbol identifier with ticker.new or ticker.modify, not as a description of the current bar.

session.extended : string

session.isfirstbar

True when the bar's opening time matches the start of one of the symbol's trading session periods, that is on the opening bar of a session. It is evaluated for every bar, historical and live alike.

session.isfirstbar : bool

session.isfirstbar_regular

True on the opening bar of the regular trading session. This platform models the regular session only, so it reports the same result as session.isfirstbar.

session.isfirstbar_regular : bool

session.islastbar

True when the bar's closing time matches the end of one of the symbol's trading session periods, that is on the closing bar of a session. It is evaluated for every bar, historical and live alike.

session.islastbar : bool

session.islastbar_regular

True on the closing bar of the regular trading session. This platform models the regular session only, so it reports the same result as session.islastbar.

session.islastbar_regular : bool

session.ismarket

True when the bar's opening timestamp falls inside the symbol's trading session, measured in exchange time. It is computed per bar from the session definition, so it also answers for historical bars.

session.ismarket : bool

session.regular

Constant string naming the regular trading session. It is meant as an argument when building or altering a symbol identifier with ticker.new or ticker.modify, not as a description of the current bar.

session.regular : string

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.

input.bool(defval, title?, tooltip?, inline?, group?, confirm = false, display?, active = true) → bool
  • 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

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.

input.color(defval, title?, tooltip?, inline?, group?, confirm = false, display?, active = true) → color
  • 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

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.

input.enum(defval, title?, options?, tooltip?, inline?, group?, confirm = false, display?, active = true) → enum
  • 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

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.

input.expiry(defval, title?, tooltip?, inline?, group?, display?, active = true) → string
  • 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

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.

input.float(defval, title?, minval?, maxval?, step = 1.0, tooltip?, inline?, group?, confirm = false, display?, active = true) → float
  • 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

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.

input.int(defval, title?, minval?, maxval?, step = 1, tooltip?, inline?, group?, confirm = false, display?, active = true) → int
  • 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

int

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.

input.price(defval, title?, tooltip?, inline?, group?, confirm = false, display?, active = true) → float
  • 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

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.

input.session(defval, title?, options?, tooltip?, inline?, group?, confirm = false, display?, active = true) → string
  • 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

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.

input.source(defval, title?, tooltip?, inline?, group?, display?, active = true, confirm = false) → float
  • 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

float

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.

input.string(defval, title?, options?, tooltip?, inline?, group?, confirm = false, display?, active = true) → string
  • 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

string

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.

input.symbol(defval, title?, tooltip?, inline?, group?, confirm = false, display?, active = true) → string
  • 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

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.

input.text_area(defval, title?, tooltip?, group?, confirm = false, display?, active = true) → string
  • 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

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.

input.time(defval, title?, tooltip?, inline?, group?, confirm = false, display?, active = true) → int
  • 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

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.

input.timeframe(defval, title?, options?, tooltip?, inline?, group?, confirm = false, display?, active = true) → string
  • 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

string

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.

barcolor(color?, offset = 0, editable = true, show_last?, title?, display = display.all)
  • 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

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.

bgcolor(color?, offset = 0, editable = true, show_last?, display = display.all, force_overlay = false)
  • 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

Nothing

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.

fill(plot1?, plot2?, color?, title?, editable = true, show_last?, fill_gaps = false, top_value?, bottom_value?, top_color?, bottom_color?)
  • 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

Nothing

It consumes the string ids that plot and hline return, but hands back none of its own.

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.

hline(price = 0.0, title?, color?, linestyle = hline.style_dashed, linewidth = 1, editable = true, display = display.all) → hline
  • 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

hline

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.

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
  • 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

plot

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.

plotarrow(series, title?, colorup?, colordown?, offset = 0, minheight = 5, maxheight = 100, editable = true, show_last?, display = display.all)
  • 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

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.

plotbar(open, high, low, close, title?, color?, editable = true, show_last?, display = display.all)
  • 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

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.

plotcandle(open, high, low, close, title?, color?, wickcolor?, editable = true, show_last?, bordercolor?, display = display.all)
  • 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

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.

plotchar(series, title?, char?, location = location.abovebar, color?, offset = 0, text?, textcolor?, editable = true, size = size.auto)
  • 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

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.

plotshape(series, title?, style = shape.xcross, location = location.abovebar, color?, offset = 0, text?, textcolor?, editable = true, size = size.auto, show_last?, display = display.all)
  • 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

string, an id identifying this call site

The id is not usable with fill, which accepts only the ids that plot and hline return.

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)

Conversions and other globals

Remaining global functions, including type conversions.

dayofmonth

Gives the day of the month, from 1 to 31, of the current bar's opening time in the exchange time zone. Called with a UNIX timestamp in milliseconds it returns the same field for that moment instead, read in the exchange time zone unless a timezone string is passed.

dayofmonth(time?, timezone?) → int
  • time int optional UNIX time in milliseconds.
  • timezone string optional Timezone in UTC/GMT notation or IANA name. Default: syminfo.timezone.

int

dayofweek

Gives the day of the week, of the current bar's opening time in the exchange time zone. Days are numbered 1 for Sunday through 7 for Saturday, which the dayofweek.monday style constants also name. Called with a UNIX timestamp in milliseconds it returns the same field for that moment instead, read in the exchange time zone unless a timezone string is passed.

dayofweek(time?, timezone?) → int
  • time int optional UNIX time in milliseconds.
  • timezone string optional Timezone in UTC/GMT notation or IANA name. Default: syminfo.timezone.

int

fixnan

Returns the source value on every bar where it is available, and on bars where it is na returns the most recent earlier value that was not na, turning an occasionally updated series into a continuous one. The result stays na until the first usable value appears. It works with numbers and with colours.

fixnan(source) → float | int | color
  • source Source used for the calculation

float | int | color

hour

Gives the hour, from 0 to 23, of the current bar's opening time in the exchange time zone. Called with a UNIX timestamp in milliseconds it returns the same field for that moment instead, read in the exchange time zone unless a timezone string is passed.

hour(time?, timezone?) → int
  • time int optional UNIX time in milliseconds.
  • timezone string optional Timezone in UTC/GMT notation or IANA name. Default: syminfo.timezone.

int

max_bars_back

States how many historical bars of a variable a script needs to keep available. It is accepted for compatibility with Pine scripts; this engine sizes history buffers on its own, so the call does not change how a script runs.

max_bars_back(var, num)
  • var
  • num int

Nothing

The call itself does nothing at run time; num is read from the code beforehand to size the shared history buffer.

minute

Gives the minute, from 0 to 59, of the current bar's opening time in the exchange time zone. Called with a UNIX timestamp in milliseconds it returns the same field for that moment instead, read in the exchange time zone unless a timezone string is passed.

minute(time?, timezone?) → int
  • time int optional UNIX time in milliseconds.
  • timezone string optional Timezone in UTC/GMT notation or IANA name. Default: syminfo.timezone.

int

month

Gives the month, from 1 to 12, of the current bar's opening time in the exchange time zone. Called with a UNIX timestamp in milliseconds it returns the same field for that moment instead, read in the exchange time zone unless a timezone string is passed.

month(time?, timezone?) → int
  • time int optional UNIX time in milliseconds.
  • timezone string optional Timezone in UTC/GMT notation or IANA name. Default: syminfo.timezone.

int

na

Reports whether a value is missing, returning true when it is. A value counts as missing when it was never set, when it is a number that is not finite, when it is an empty string, or when it is a line, label, box, polyline, linefill or table that has been deleted.

na(value) → bool
  • value Value to use

bool

nz

Returns the source value unchanged unless it is na, in which case it returns the replacement. With no replacement given it substitutes a value that suits the type: 0 for an integer, 0.0 for a float, an empty string, false for a boolean and a fully transparent colour.

nz(source, replacement = 0) → float
  • source Input data series
  • replacement optional Replacement text

float

second

Gives the second, from 0 to 59, of the current bar's opening time in the exchange time zone. Called with a UNIX timestamp in milliseconds it returns the same field for that moment instead, read in the exchange time zone unless a timezone string is passed.

second(time?, timezone?) → int
  • time int optional UNIX time in milliseconds.
  • timezone string optional Timezone in UTC/GMT notation or IANA name. Default: syminfo.timezone.

int

time

Opening timestamp of the bar, as a UNIX time in milliseconds. Called with a timeframe it gives the opening time of that timeframe's bar holding the current one, such as the start of the day or week. bars_back counts chart bars and timeframe_bars_back counts bars of that timeframe, from 5000 back to 500 ahead, so a script can find where the next session or period begins before it opens. Times ahead follow the session's trading hours and weekdays but not exchange holidays. With a session string, that timeframe's bars follow the session, and a chart bar that falls between them gives na.

time(timeframe, session?, timezone?, bars_back = 0, timeframe_bars_back = 0) → int
  • timeframe string Timeframe of the bar. An empty string means the chart timeframe.
  • session string optional Session to filter by: na when the bar opens outside it. Default: the symbol's session.
  • timezone string optional Timezone of the session in UTC/GMT notation or IANA name. Default: syminfo.timezone. When it is left out, bars_back is the third argument.
  • bars_back int optional Chart bars back from the current bar, up to 5000. Negative values look up to 500 bars ahead.
  • timeframe_bars_back int optional Bars of the timeframe back from the one holding that chart bar, up to 5000. Negative values look up to 500 bars ahead.

int

time_close

Closing timestamp of the bar, as a UNIX time in milliseconds. It is the bar's opening time plus the length of the chart timeframe, trimmed back to the end of the trading session when the bar would otherwise extend past the session close. Called with the same arguments as time() it gives the closing time of that bar instead: a day closes at the end of its session, and a week or month requested from a shorter timeframe closes when the next one opens. On a weekly or monthly chart, a bar closes at the end of its last trading day.

time_close(timeframe, session?, timezone?, bars_back = 0, timeframe_bars_back = 0) → int
  • timeframe string Timeframe of the bar. An empty string means the chart timeframe.
  • session string optional Session to filter by: na when the bar opens outside it. Default: the symbol's session.
  • timezone string optional Timezone of the session in UTC/GMT notation or IANA name. Default: syminfo.timezone. When it is left out, bars_back is the third argument.
  • bars_back int optional Chart bars back from the current bar, up to 5000. Negative values look up to 500 bars ahead.
  • timeframe_bars_back int optional Bars of the timeframe back from the one holding that chart bar, up to 5000. Negative values look up to 500 bars ahead.

int

timestamp

Builds a UNIX timestamp in milliseconds from a date and time. It accepts either a single date string, or year, month, day, hour and minute with an optional second, preceded optionally by a timezone string; without a timezone the parts are read in the exchange time zone.

timestamp() → int

int

weekofyear

Gives the ISO week number, of the current bar's opening time in the exchange time zone. Week 1 is the week that contains the first Thursday of the year. Called with a UNIX timestamp in milliseconds it returns the same field for that moment instead, read in the exchange time zone unless a timezone string is passed.

weekofyear(time?, timezone?) → int
  • time int optional UNIX time in milliseconds.
  • timezone string optional Timezone in UTC/GMT notation or IANA name. Default: syminfo.timezone.

int

year

Gives the four-digit year of the current bar's opening time in the exchange time zone. Called with a UNIX timestamp in milliseconds it returns the same field for that moment instead, read in the exchange time zone unless a timezone string is passed.

year(time?, timezone?) → int
  • time int optional UNIX time in milliseconds.
  • timezone string optional Timezone in UTC/GMT notation or IANA name. Default: syminfo.timezone.

int

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.

ta.accdist() → float

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.

ta.alma(source, length, offset, sigma) → float
  • source float Input data series
  • length int Window size
  • offset float Gaussian offset (0-1)
  • sigma float Gaussian sigma

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.

ta.atr(length) → float
  • length int Number of bars

float

indicator("Average true range")

plot(ta.atr(14), "ATR")

ta.barssince

Counts how many bars have passed since condition was last true, returning 0 on the bar where it is true. The result is na until the condition has been true at least once.

ta.barssince(condition) → int
  • condition bool Condition to check

int

indicator("Bars since the last new high")

newHigh = high == ta.highest(high, 50)
plot(ta.barssince(newHigh), "Bars")

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.

ta.bb(source, length, mult) → [float, float, float]
  • source float Input data series
  • length int Number of bars
  • mult float Standard deviation multiplier

[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.

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.

ta.bbw(source, length, mult) → float
  • source float Input data series
  • length int Number of bars
  • mult float Standard deviation multiplier

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.

ta.cci(source, length) → float
  • source float Input data series
  • length int Number of bars

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.

ta.change(source, length = 1) → float
  • source Input data series
  • length int optional Number of bars

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.

ta.cmo(source, length) → float
  • source float Input data series
  • length int Number of bars

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.

ta.cog(source, length) → float
  • source float Input data series
  • length int Number of bars

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.

ta.correlation(source1, source2, length) → float
  • source1 float First source series
  • source2 float Second source series
  • length int Number of bars

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.

ta.cross(source1, source2) → bool
  • source1 float First source series
  • source2 float Second source series

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.

ta.crossover(source1, source2) → bool
  • source1 float First source series
  • source2 float Second source series

bool

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.

ta.crossunder(source1, source2) → bool
  • source1 float First source series
  • source2 float Second source series

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.

ta.cum(source) → float
  • source float Input data series

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.

ta.dev(source, length) → float
  • source float Input data series
  • length int Number of bars

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.

ta.dmi(dilength, adxsmoothing) → [float, float, float]
  • dilength int DI length
  • adxsmoothing int ADX smoothing length

[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.

ta.ema(source, length) → float
  • source float Input data series
  • length int Number of bars

float

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.

ta.falling(source, length) → bool
  • source float Input data series
  • length int Number of bars

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.

ta.highest(source?, length) → float
  • source float optional Input data series
  • length int Number of bars

float

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.

ta.highestbars(source?, length) → int
  • source float optional Input data series
  • length int Number of bars

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.

ta.hma(source, length) → float
  • source float Input data series
  • length int Number of bars

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.

ta.ichimoku_cloud(conversion_periods = 9, base_periods = 26, lagging_span2_periods = 52) → [float, float, float, float, float]
  • conversion_periods int optional Conversion line periods
  • base_periods int optional Base line periods
  • lagging_span2_periods int optional Lagging span 2 periods

[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.

ta.iii() → float

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.

ta.kc(source, length, mult, usetruerange = true) → [float, float, float]
  • source float Input data series
  • length int Number of bars
  • mult float ATR multiplier
  • usetruerange bool optional Use true range

[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.

ta.kcw(source, length, mult, usetruerange = true) → float
  • source float Input data series
  • length int Number of bars
  • mult float ATR multiplier
  • usetruerange bool optional Use true range

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.

ta.linreg(source, length, offset) → float
  • source float Input data series
  • length int Number of bars
  • offset int Offset from current bar

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.

ta.lowest(source?, length) → float
  • source float optional Input data series
  • length int Number of bars

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.

ta.lowestbars(source?, length) → int
  • source float optional Input data series
  • length int Number of bars

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.

ta.macd(source, fastlen, slowlen, siglen) → [float, float, float]
  • source float Input data series
  • fastlen int Fast EMA length
  • slowlen int Slow EMA length
  • siglen int Signal EMA length

[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.

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.

ta.max(source) → float
  • source float Input data series

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.

ta.median(source, length?) → float
  • source float Input data series
  • length int optional Number of bars

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.

ta.mfi(source, length) → float
  • source float Input data series
  • length int Number of bars

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.

ta.min(source) → float
  • source float Input data series

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.

ta.mode(source, length) → float
  • source float Input data series
  • length int Number of bars

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.

ta.mom(source, length) → float
  • source float Input data series
  • length int Number of bars

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.

ta.normalize(source, range_upper, range_lower, length) → float
  • source float Source series
  • range_upper float Upper range bound
  • range_lower float Lower range bound
  • length int Number of bars

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.

ta.nvi() → float

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.

ta.obv() → float

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.

ta.percentile_linear_interpolation(source, length, percentage) → float
  • source float Input data series
  • length int Number of bars
  • percentage float Percentile (0-100)

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.

ta.percentile_nearest_rank(source, length, percentage) → float
  • source float Input data series
  • length int Number of bars
  • percentage float Percentile (0-100)

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.

ta.percentrank(source, length) → float
  • source float Input data series
  • length int Number of bars

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.

ta.pivot_point_levels(type, anchor, developing = false) → [float x 11]
  • 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

[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.

ta.pivothigh(source?, leftbars, rightbars) → float
  • source float optional Input data series
  • leftbars int Left lookback bars
  • rightbars int Right lookback bars

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.

ta.pivotlow(source?, leftbars, rightbars) → float
  • source float optional Input data series
  • leftbars int Left lookback bars
  • rightbars int Right lookback bars

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.

ta.pvi() → float

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.

ta.pvt() → float

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.

ta.range(source, length) → float
  • source float Input data series
  • length int Number of bars

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.

ta.rci(source, length) → float
  • source float Input data series
  • length int Number of bars

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.

ta.rising(source, length) → bool
  • source float Input data series
  • length int Number of bars

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.

ta.rma(source, length) → float
  • source float Input data series
  • length int Number of bars

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.

ta.roc(source, length) → float
  • source float Input data series
  • length int Number of bars

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.

ta.rsi(source, length) → float
  • source float Input data series
  • length int Number of bars

float

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.

ta.sar(start, inc, max) → float
  • start float Start acceleration factor
  • inc float Acceleration increment
  • max float Maximum acceleration factor

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.

ta.sma(source, length) → float
  • source float Input data series
  • length int Number of bars

float

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.

ta.stdev(source, length) → float
  • source float Input data series
  • length int Number of bars

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.

ta.stoch(source, high, low, length) → float
  • source float Source series
  • high float High series
  • low float Low series
  • length int Number of bars

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.

ta.supertrend(factor, atrperiod) → [float, float]
  • factor float ATR multiplier factor
  • atrperiod int ATR period

[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.

ta.swma(source) → float
  • source float Input data series

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.

ta.tr(handle_na = false) → float
  • handle_na bool optional Handle NA values

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.

ta.tsi(source, short_length, long_length) → float
  • source float Input data series
  • short_length int Short smoothing length
  • long_length int Long smoothing length

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.

ta.valuewhen(condition, source, occurrence) → float
  • condition bool Condition to check
  • source float Input data series
  • occurrence int Nth occurrence (0-based)

float

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.

ta.variance(source, length, biased = true) → float
  • source float Input data series
  • length int Number of bars
  • biased bool optional Use biased calculation

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.

ta.vwap(source?, anchor?, stdev_mult?) → float
  • source float optional Source series
  • anchor bool optional Anchor condition for reset
  • stdev_mult float optional Standard deviation multiplier for bands

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.

ta.vwma(source, length) → float
  • source float Input data series
  • length int Number of bars

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.

ta.wad() → float

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.

ta.wma(source, length) → float
  • source float Input data series
  • length int Number of bars

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.

ta.wpr(length) → float
  • length int Number of bars

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.

ta.wvad() → float

float

math.* — Mathematics

math.abs

Returns the magnitude of value with any negative sign removed, so -2.5 becomes 2.5. A na input, or a result that is not a finite number, gives na.

math.abs(value) → float
  • value float Value to use

float

math.acos

Returns the angle in radians whose cosine is value, in the range 0 to pi. The argument must lie between -1 and 1; anything outside that range, or na, returns na.

math.acos(value) → float
  • value float Value to use

float

math.asin

Returns the angle in radians whose sine is value, in the range -pi/2 to pi/2. The argument must lie between -1 and 1; anything outside that range, or na, returns na.

math.asin(value) → float
  • value float Value to use

float

math.atan

Returns the angle in radians whose tangent is value, always between -pi/2 and pi/2. Any finite number is accepted; a na input returns na.

math.atan(value) → float
  • value float Value to use

float

math.atan2

Returns the angle in radians between the positive x axis and the point given by x and y, in the range -pi to pi, using the signs of both arguments to pick the correct quadrant. It is the usual way to turn a rise and a run into a slope angle. If either argument is na the result is na.

math.atan2(y, x) → float
  • y float Y coordinate
  • x float X coordinate

float

math.avg

Returns the arithmetic mean of the values passed to it. This is a plain average of the arguments in one call, not a running average across bars, and if any argument is na the result is na.

math.avg() → float

float

math.ceil

Rounds value up to the nearest whole number and returns an integer, so 2.1 becomes 3 and -2.1 becomes -2. A na or non-finite input returns na.

math.ceil(value) → int
  • value float Value to use

int

math.cos

Returns the cosine of an angle expressed in radians, always between -1 and 1. Convert from degrees with math.toradians first. A na input returns na.

math.cos(angle) → float
  • angle float

float

math.exp

Returns e raised to the power of value, the inverse of math.log. Inputs large enough to overflow the numeric range return na, as does a na input.

math.exp(value) → float
  • value float Value to use

float

math.floor

Rounds value down to the nearest whole number and returns an integer, so 2.9 becomes 2 and -2.1 becomes -3. A na or non-finite input returns na.

math.floor(value) → int
  • value float Value to use

int

math.log

Returns the natural logarithm, to base e, of value. Only strictly positive numbers have a result; zero, negative numbers and na all return na.

math.log(value) → float
  • value float Value to use

float

math.log10

Returns the base-10 logarithm of value, which is convenient for working with orders of magnitude. Only strictly positive numbers have a result; zero, negative numbers and na all return na.

math.log10(value) → float
  • value float Value to use

float

math.max

Returns the largest of its arguments, and accepts more than two values in a single call. If any argument is na the result is na, so guard inputs that a series may not have supplied yet.

math.max(a, b) → float
  • a float
  • b float Blue component (0-255)

float

indicator("Widest recent range")

plot(math.max(high - low, ta.atr(14)), "Range")

math.min

Returns the smallest of its arguments, and accepts more than two values in a single call. If any argument is na the result is na, so guard inputs that a series may not have supplied yet.

math.min(a, b) → float
  • a float
  • b float Blue component (0-255)

float

math.pow

Returns base raised to the power of exponent. Combinations with no finite real result, such as a negative base with a fractional exponent or a value that overflows the numeric range, return na, as does a na argument.

math.pow(base, exponent) → float
  • base float Base value
  • exponent float Exponent value

float

math.random

Returns a number that is at least min and below max, taken from a seeded generator; min defaults to 0 and max to 1 when they are not supplied. The generator is rebuilt from the seed on every call, so a given seed always produces the same number, and leaving seed out uses a fixed built-in one.

math.random(min, max, seed?) → float
  • min float Minimum value
  • max float Maximum value
  • seed int optional Random seed

float

math.round

Rounds number to the given number of decimal places, so a precision of 2 turns 1.2345 into 1.23. With precision left out or set to 0 it returns the nearest whole number, with halves going away from zero. A na or non-finite input returns na.

math.round(number, precision?) → float
  • number float The value to be rounded
  • precision int optional Decimal places to round to (0 = nearest integer)

float

indicator("Rounded close")

plot(math.round(close, 2), "Close")

math.round_to_mintick

Rounds number to the nearest multiple of the current symbol's minimum price increment, so the result is a price the instrument can actually trade at. Returns na for a na or non-finite input, or when the symbol reports no usable tick size.

math.round_to_mintick(number) → float
  • number float The value to be rounded to the nearest mintick

float

math.sign

Returns 1 when value is positive, -1 when it is negative and 0 when it is zero. Unlike most math functions it does not pass na through: a na or non-finite input also returns 0.

math.sign(value) → int
  • value float Value to use

int

math.sin

Returns the sine of an angle expressed in radians, always between -1 and 1. Use math.toradians first when the angle is in degrees. A na input returns na.

math.sin(angle) → float
  • angle float

float

math.sqrt

Returns the non-negative square root of value. Negative numbers have no real root and return na, as does a na input.

math.sqrt(value) → float
  • value float Value to use

float

math.sum

Returns the total of the last length values of source, advancing one bar at a time. Bars where source is na are skipped rather than counted, so such a bar carries the total of the values before it, and the result is na until length values have been collected. length must be a whole number of at least 1.

math.sum() → float

float

math.tan

Returns the tangent of an angle expressed in radians. Angles close to a quarter turn produce very large results, and a na input returns na.

math.tan(angle) → float
  • angle float

float

math.todegrees

Converts an angle from radians to degrees, so pi becomes 180. A na input returns na.

math.todegrees(radians) → float
  • radians float Angle in radians

float

math.toradians

Converts an angle from degrees to radians, so 180 becomes pi. Trigonometric functions such as math.sin expect radians, making this the usual first step when an angle is stated in degrees. A na input returns na.

math.toradians(degrees) → float
  • degrees float Angle in degrees

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.

str.contains(value, substring) → bool
  • value string Value to use
  • substring string Substring to find

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.

str.endswith(value, suffix) → bool
  • value string Value to use
  • suffix string

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.

str.format(format_string) → string
  • format_string string Format template

string

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.

str.format_time(time, format, timezone = "UTC") → string
  • time int UNIX timestamp in milliseconds
  • format string Date/time format string
  • timezone string optional Timezone (IANA name or UTC offset)

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.

str.length(value) → int
  • value string Value to use

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.

str.lower(value) → string
  • value string Value to use

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.

str.match(source, regex) → string
  • source string Source string
  • regex string Regular expression pattern

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.

str.pos(value, substring) → int
  • value string Value to use
  • substring string Substring to find

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.

str.repeat(value, count) → string
  • value string Value to repeat
  • count int Number of repetitions

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.

str.replace(value, from, to) → string
  • value string Value to use
  • from string From value
  • to string To value

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.

str.replace_all(value, from, to) → string
  • value string Value to use
  • from string From value
  • to string To value

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.

str.split(value, pattern) → array<string>
  • value string Value to use
  • pattern string Search pattern

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.

str.startswith(value, prefix) → bool
  • value string Value to use
  • prefix string

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.

str.substring(value, start, end?) → string
  • value string Value to use
  • start int Start position
  • end int optional End position

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.

str.tonumber(value) → float
  • value string Value to use

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.

str.tostring(value, format?) → string
  • value Value to use
  • format string optional Number format

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.

str.trim(value) → string
  • value string Value to use

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.

str.upper(value) → string
  • value string Value to use

string

color.* — Colours

color.b

Returns the blue channel of a colour as a whole number from 0 to 255. A na colour returns na.

color.b(color) → int
  • color color Color value

int

color.from_gradient

Returns a colour blended between bottom_color and top_color according to where value falls between bottom and top, interpolating the red, green, blue and transparency channels in a straight line. Values at or below bottom give bottom_color and values at or above top give top_color, and when bottom and top are equal bottom_color is returned. Arguments left out or set to na fall back to 0 for value, 0 and 100 for the bounds, and green and red for the two colours.

color.from_gradient(value, bottom, top, bottom_color, top_color) → color
  • value float Value to use
  • bottom float Bottom edge y
  • top float Top edge y
  • bottom_color color Bottom gradient color
  • top_color color Top gradient color

color

color.g

Returns the green channel of a colour as a whole number from 0 to 255. A na colour returns na.

color.g(color) → int
  • color color Color value

int

color.new

Returns the given colour with its transparency replaced, where transp runs from 0 for fully opaque to 100 for fully transparent. Values outside that range are clamped into it, an omitted or na transparency counts as 0, and a na colour returns na.

color.new(color, transp = 0) → color
  • color color Color value
  • transp int optional

color

indicator("Faded background", overlay = true)

bgcolor(color.new(color.teal, 90))

color.r

Returns the red channel of a colour as a whole number from 0 to 255. A na colour returns na.

color.r(color) → int
  • color color Color value

int

color.rgb

Builds a colour from red, green and blue channel values, each rounded to a whole number and clamped into the 0 to 255 range, with transp setting transparency from 0 for fully opaque to 100 for fully transparent. Channel arguments that are na count as 0, and the transparency is clamped into the 0 to 100 range.

color.rgb(red, green, blue, transp = 0) → color
  • red int
  • green int
  • blue int
  • transp int optional

color

color.t

Returns the transparency of a colour as a whole number from 0 to 100, where 0 means fully opaque and 100 fully transparent. The figure is derived from the colour's alpha channel and rounded to the nearest whole number. A na colour returns na.

color.t(color) → int
  • color color Color value

int

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.

array.abs(id) → array
  • id array Object reference

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.

array.avg(id) → float
  • id array Object reference

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.

array.binary_search(id, value) → int
  • id array Object reference
  • value Value to search for

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.

array.binary_search_leftmost(id, value) → int
  • id array Object reference
  • value Value to search for

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.

array.binary_search_rightmost(id, value) → int
  • id array Object reference
  • value Value to use

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.

array.clear(id)
  • id array Object reference

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.

array.concat(id1, id2) → array
  • id1 array First object reference
  • id2 array Second object reference

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.

array.copy(id) → array
  • id array Object reference

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.

array.covariance(id1, id2, biased = true) → float
  • id1 array First array
  • id2 array Second array
  • biased bool optional Use biased calculation

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.

array.every(id) → bool
  • id array Object reference

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.

array.fill(id, value, index_from?, index_to?)
  • id array Object reference
  • value Value to use
  • index_from int optional
  • index_to int optional

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.

array.first(id)
  • id array Object reference

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.

array.from() → array

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.

array.get(id, index)
  • id array Object reference
  • index int Element index

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.

array.includes(id, value) → bool
  • id array Object reference
  • value Value to use

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.

array.indexof(id, value) → int
  • id array Object reference
  • value Value to use

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.

array.insert(id, index, value)
  • id array Object reference
  • index int Element index
  • value Value to use

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.

array.join(id, separator = ",") → string
  • id array Object reference
  • separator string optional Separator string

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.

array.last(id)
  • id array Object reference

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.

array.lastindexof(id, value) → int
  • id array Object reference
  • value Value to search for

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.

array.max(id) → float
  • id array Object reference

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.

array.median(id) → float
  • id array Object reference

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.

array.min(id) → float
  • id array Object reference

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.

array.mode(id)
  • id array Object reference

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.

array.new() → array

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.

array.new_point(size = 0, initial_value?) → array<chart.point>
  • size int optional Initial size
  • initial_value chart.point optional Default value

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.

array.percentile_linear_interpolation(id, percentage) → float
  • id array Object reference
  • percentage float Percentile (0-100)

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.

array.percentile_nearest_rank(id, percentage)
  • id array Object reference
  • percentage float Percentile (0-100)

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.

array.percentrank(id, index) → float
  • id array Object reference
  • index int Element index

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.

array.pop(id)
  • id array Object reference

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.

array.push(id, value)
  • id array Object reference
  • value Value to use

Nothing

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.

array.range(id) → float
  • id array Object reference

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.

array.remove(id, index)
  • id array Object reference
  • index int Element index

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.

array.reverse(id)
  • id array Object reference

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.

array.set(id, index, value)
  • id array Object reference
  • index int Element index
  • value Value to use

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.

array.shift(id)
  • id array Object reference

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.

array.size(id) → int
  • id array Object reference

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.

array.slice(id, index_from, index_to) → array
  • id array Object reference
  • index_from int
  • index_to int

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.

array.some(id) → bool
  • id array Object reference

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.

array.sort(id, order = order.ascending, sort_field = 0)
  • id array Object reference
  • order order optional
  • sort_field int|string optional UDT field index or name used for sorting

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.

array.sort_indices(id, order = order.ascending, sort_field = 0) → array<int>
  • id array Object reference
  • order order optional Sort order
  • sort_field int|string optional UDT field index or name used for sorting

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.

array.standardize(id) → array<float>
  • id array Object reference

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.

array.stdev(id, biased = true) → float
  • id array Object reference
  • biased bool optional Use biased calculation

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.

array.sum(id) → float
  • id array Object reference

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.

array.unshift(id, value)
  • id array Object reference
  • value Value to use

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.

array.variance(id, biased = true) → float
  • id array Object reference
  • biased bool optional Use biased calculation

float

map.* — Maps

map.clear

Removes every key-value pair from the map in place, leaving it empty. The key and value types stay as declared, so the map can be refilled.

map.clear(id)
  • id map Object reference

Nothing

map.contains

Returns true when the map holds an entry under the given key. The key is converted to the map's key type first, so a whole number matches a float key; a na key raises an error.

map.contains(id, key) → bool
  • id map Object reference
  • key Map key

bool

map.copy

Returns a new map holding the same entries in the same insertion order, leaving the original untouched. The copy is shallow, so for maps of objects both maps go on referring to the same underlying objects.

map.copy(id) → map
  • id map Object reference

map

map.get

Returns the value stored under the given key, or na when the map holds no such key. The key is converted to the map's key type first, and a na key raises an error.

map.get(id, key)
  • id map Object reference
  • key Map key

the value stored under that key, or na when the key is absent

map.keys

Returns a new array holding every key in the order the keys were first added. The array is independent of the map, so changing it does not alter the map.

map.keys(id) → array
  • id map Object reference

array

map.new

Creates a new empty map for the key and value types given in the type parameters. The key type must be a value type such as a primitive or an enum; a missing, unknown or reference key type raises an error.

map.new() → map

map

map.put

Stores the value under the given key, replacing any value already held there and otherwise adding a new entry at the end of the insertion order. Updating an existing key keeps its original position. A na key, a key or value that does not match the map's declared types, or going past the 50000-entry limit raises an error.

map.put(id, key, value)
  • id map Object reference
  • key Map key
  • value Value to use

Nothing

Any value the key already held is overwritten without being handed back.

indicator("Counts by direction")

counts = map.new<string, int>()
map.put(counts, "up", close > open ? 1 : 0)
plot(map.get(counts, "up"), "Up bar")

map.put_all

Copies every entry of the second map into the first, in the second map's insertion order, overwriting values whose keys are already present. Only the first map is changed; a non-map argument, mismatched key or value types, or going past the 50000-entry limit raises an error.

map.put_all(id, id2)
  • id map Object reference
  • id2 map Second object reference

Nothing

map.remove

Removes the entry stored under the given key and returns the value it held. Returns na and leaves the map unchanged when the key is not present; a na key raises an error.

map.remove(id, key)
  • id map Object reference
  • key Map key

the value that was removed, or na when the key was absent

The value it removes is handed back, so discarding the result loses it.

map.size

Returns the current number of key-value pairs held by the map. An empty map returns zero.

map.size(id) → int
  • id map Object reference

int

map.values

Returns a new array holding every value in the order the keys were first added. The array is independent of the map, so changing it does not alter the map.

map.values(id) → array
  • id map Object reference

array

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.

matrix.add_col(id, column, values?)
  • id matrix Object reference
  • column int Column index
  • values array optional Column values

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.

matrix.add_row(id, row, values?)
  • id matrix Object reference
  • row int Row index
  • values array optional Row values

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.

matrix.avg(id) → float
  • id matrix Object reference

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.

matrix.col(id, column) → array
  • id matrix Object reference
  • column int Column index

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.

matrix.columns(id) → int
  • id matrix Object reference

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.

matrix.concat(id, id2, rows = true) → matrix
  • id matrix Object reference
  • id2 matrix Matrix to append
  • rows bool optional Append below (true) or to the right (false)

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.

matrix.copy(id) → matrix
  • id matrix Object reference

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.

matrix.det(id) → float
  • id matrix Object reference

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.

matrix.diff(id, id2) → matrix
  • id matrix Object reference
  • id2 matrix|float Matrix or number to subtract

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.

matrix.eigenvalues(id) → array<float>
  • id matrix Object reference

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.

matrix.eigenvectors(id) → matrix
  • id matrix Object reference

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.

matrix.elements_count(id) → int
  • id matrix Object reference

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.

matrix.fill(id, value, from_row?, to_row?, from_column?, to_column?)
  • 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

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.

matrix.from_columns(id, rows, columns) → matrix
  • id array Flat array of values
  • rows int Number of rows
  • columns int Number of columns

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.

matrix.from_rows(id, rows, columns) → matrix
  • id array Flat array of values
  • rows int Number of rows
  • columns int Number of columns

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.

matrix.get(id, row, column)
  • id matrix Object reference
  • row int Row index
  • column int Column index

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.

matrix.inv(id) → matrix
  • id matrix Object reference

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.

matrix.is_antidiagonal(id) → bool
  • id matrix Object reference

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.

matrix.is_antisymmetric(id) → bool
  • id matrix Object reference

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.

matrix.is_binary(id) → bool
  • id matrix Object reference

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.

matrix.is_diagonal(id) → bool
  • id matrix Object reference

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.

matrix.is_identity(id) → bool
  • id matrix Object reference

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.

matrix.is_square(id) → bool
  • id matrix Object reference

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.

matrix.is_stochastic(id) → bool
  • id matrix Object reference

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.

matrix.is_symmetric(id) → bool
  • id matrix Object reference

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.

matrix.is_triangular(id) → bool
  • id matrix Object reference

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.

matrix.is_zero(id) → bool
  • id matrix Object reference

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.

matrix.kron(id, id2) → matrix
  • id matrix Object reference
  • id2 matrix Second matrix

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.

matrix.max(id) → float
  • id matrix Object reference

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.

matrix.median(id) → float
  • id matrix Object reference

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.

matrix.min(id) → float
  • id matrix Object reference

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.

matrix.mode(id) → float
  • id matrix Object reference

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.

matrix.mult(id, id2) → matrix
  • id matrix Object reference
  • id2 matrix Second matrix

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.

matrix.new(rows, columns, initial_value?) → matrix
  • rows int Number of rows
  • columns int Number of columns
  • initial_value optional

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.

matrix.pinv(id) → matrix
  • id matrix Object reference

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.

matrix.pow(id, exponent) → matrix
  • id matrix Object reference
  • exponent int Integer exponent

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.

matrix.rank(id) → int
  • id matrix Object reference

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.

matrix.remove_col(id, column)
  • id matrix Object reference
  • column int Column index

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.

matrix.remove_row(id, row)
  • id matrix Object reference
  • row int Row index

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.

matrix.reshape(id, rows, columns)
  • id matrix Object reference
  • rows int New row count
  • columns int New column count

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.

matrix.reverse(id)
  • id matrix Object reference

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.

matrix.row(id, row) → array
  • id matrix Object reference
  • row int Row index

array

matrix.rows

Returns the number of rows currently held by the matrix. An empty matrix returns zero.

matrix.rows(id) → int
  • id matrix Object reference

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.

matrix.set(id, row, column, value)
  • id matrix Object reference
  • row int Row index
  • column int Column index
  • value Value to use

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.

matrix.sort(id, column, order = order.ascending, sort_field = 0)
  • 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

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.

matrix.stdev(id, biased = true) → float
  • id matrix Object reference
  • biased bool optional Use biased calculation

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.

matrix.submatrix(id, from_row, to_row, from_column, to_column) → matrix
  • id matrix Object reference
  • from_row int Start row
  • to_row int End row
  • from_column int Start column
  • to_column int End column

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.

matrix.sum(id, id2) → matrix
  • id matrix Object reference
  • id2 matrix|float Matrix or number to add

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.

matrix.swap_columns(id, column1, column2)
  • id matrix Object reference
  • column1 int First column index
  • column2 int Second column index

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.

matrix.swap_rows(id, row1, row2)
  • id matrix Object reference
  • row1 int First row index
  • row2 int Second row index

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.

matrix.trace(id) → float
  • id matrix Object reference

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.

matrix.transpose(id) → matrix
  • id matrix Object reference

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.

matrix.variance(id, biased = true) → float
  • id matrix Object reference
  • biased bool optional Use biased calculation

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.

line.copy(id) → line
  • id line Object reference

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.

line.delete(id)
  • id line Object reference

Nothing

line.get_color

Returns the colour the line is currently drawn with. The result is na if the line has been deleted.

line.get_color(id) → color
  • id line Object reference

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.

line.get_style(id) → line_style
  • id line Object reference

line_style

line.get_width

Returns the line's stroke width in pixels.

line.get_width(id) → int
  • id line Object reference

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.

line.get_x1(id) → int
  • id line Object reference

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.

line.get_x2(id) → int
  • id line Object reference

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.

line.get_xloc(id) → xloc
  • id line Object reference

xloc

line.get_y1

Returns the price at the line's first point, or na if that coordinate is unset.

line.get_y1(id) → float
  • id line Object reference

float

line.get_y2

Returns the price at the line's second point, or na if that coordinate is unset.

line.get_y2(id) → float
  • id line Object reference

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.

line.new(x1, y1, x2, y2, xloc = xloc.bar_index, extend = extend.none, color?, style = line.style_solid, width = 1) → line
  • 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

line

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.

line.set_color(id, color)
  • id line Object reference
  • color color Color value

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.

line.set_extend(id, extend)
  • id line Object reference
  • extend extend Line extend mode

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.

line.set_first_point(id, point)
  • id line Object reference
  • point chart.point Chart point

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.

line.set_second_point(id, point)
  • id line Object reference
  • point chart.point Chart point

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.

line.set_style(id, style)
  • id line Object reference
  • style line_style Visual style

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.

line.set_width(id, width)
  • id line Object reference
  • width int Width value

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.

line.set_x1(id, x)
  • id line Object reference
  • x int X coordinate

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.

line.set_x2(id, x)
  • id line Object reference
  • x int X coordinate

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.

line.set_xloc(id, xloc)
  • id line Object reference
  • xloc xloc X-location mode

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.

line.set_xy1(id, x, y)
  • id line Object reference
  • x int X coordinate
  • y float Y coordinate

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.

line.set_xy2(id, x, y)
  • id line Object reference
  • x int X coordinate
  • y float Y coordinate

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.

line.set_y1(id, y)
  • id line Object reference
  • y float Y coordinate

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.

line.set_y2(id, y)
  • id line Object reference
  • y float Y coordinate

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.

label.copy(id) → label
  • id label Object reference

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.

label.delete(id)
  • id label Object reference

Nothing

label.get_color

Returns the label's background colour, or na if the label has none or has been deleted.

label.get_color(id) → color
  • id label Object reference

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.

label.get_style(id) → label_style
  • id label Object reference

label_style

label.get_text

Returns the text the label currently shows, which is an empty string if no text was given.

label.get_text(id) → string
  • id label Object reference

string

label.get_textcolor

Returns the colour used to draw the label's text, or na if none was set.

label.get_textcolor(id) → color
  • id label Object reference

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.

label.get_x(id) → int
  • id label Object reference

int

label.get_xloc

Returns the label's x coordinate mode, xloc.bar_index or xloc.bar_time.

label.get_xloc(id) → xloc
  • id label Object reference

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.

label.get_y(id) → float
  • id label Object reference

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.

label.get_yloc(id) → yloc
  • id label Object reference

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.

label.new(x, y, text?, xloc = xloc.bar_index, yloc = yloc.price, color?, style = label.style_label_down, textcolor?, size = size.normal, tooltip?) → label
  • 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

label

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.

label.set_color(id, color)
  • id label Object reference
  • color color Color value

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.

label.set_point(id, point)
  • id label Object reference
  • point chart.point Chart point

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.

label.set_size(id, size)
  • id label Object reference
  • size size Shape/text size

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.

label.set_style(id, style)
  • id label Object reference
  • style label_style Visual style

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.

label.set_text(id, text)
  • id label Object reference
  • text string Text content

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.

label.set_text_font_family(id, font_family)
  • id label Object reference
  • font_family string Font family

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.

label.set_textalign(id, textalign)
  • id label Object reference
  • textalign string Text alignment

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.

label.set_textcolor(id, color)
  • id label Object reference
  • color color Color value

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.

label.set_tooltip(id, tooltip)
  • id label Object reference
  • tooltip string Tooltip text

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.

label.set_x(id, x)
  • id label Object reference
  • x int X coordinate

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.

label.set_xloc(id, xloc)
  • id label Object reference
  • xloc xloc X-location mode

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.

label.set_xy(id, x, y)
  • id label Object reference
  • x int X coordinate
  • y float Y coordinate

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.

label.set_y(id, y)
  • id label Object reference
  • y float Y coordinate

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).

label.set_yloc(id, yloc)
  • id label Object reference
  • yloc yloc Y-location mode

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.

box.copy(id) → box
  • id box Object reference

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.

box.delete(id)
  • id box Object reference

Nothing

box.get_bgcolor

Returns the box's fill colour, or na if it has none.

box.get_bgcolor(id) → color
  • id box Object reference

color

box.get_border_color

Returns the colour of the box's border, or na if no border colour was set.

box.get_border_color(id) → color
  • id box Object reference

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.

box.get_border_style(id) → line_style
  • id box Object reference

line_style

box.get_border_width

Returns the width of the box's border in pixels.

box.get_border_width(id) → int
  • id box Object reference

int

box.get_bottom

Returns the price of the box's lower edge, or na if it is unset.

box.get_bottom(id) → float
  • id box Object reference

float

box.get_extend

Returns how the box is stretched horizontally beyond its edges: extend.none, extend.left, extend.right or extend.both.

box.get_extend(id) → extend
  • id box Object reference

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.

box.get_left(id) → int
  • id box Object reference

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.

box.get_right(id) → int
  • id box Object reference

int

box.get_text

Returns the text drawn inside the box, or na if the box carries none.

box.get_text(id) → string
  • id box Object reference

string

box.get_text_color

Returns the colour used for the text inside the box, or na if none was set.

box.get_text_color(id) → color
  • id box Object reference

color

box.get_text_font_family

Returns the font family of the box's text, font.family_default or font.family_monospace.

box.get_text_font_family(id) → string
  • id box Object reference

string

box.get_text_halign

Returns the horizontal alignment of the box's text: text.align_left, text.align_center or text.align_right.

box.get_text_halign(id) → string
  • id box Object reference

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.

box.get_text_size(id) → size
  • id box Object reference

size

box.get_text_valign

Returns the vertical alignment of the box's text: text.align_top, text.align_center or text.align_bottom.

box.get_text_valign(id) → string
  • id box Object reference

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.

box.get_text_wrap(id) → string
  • id box Object reference

string

box.get_top

Returns the price of the box's upper edge, or na if it is unset.

box.get_top(id) → float
  • id box Object reference

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.

box.get_xloc(id) → xloc
  • id box Object reference

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.

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
  • 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

box

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.

box.set_bgcolor(id, color)
  • id box Object reference
  • color color Color value

Nothing

box.set_border_color

Sets the colour of an existing box's border. A na colour removes the explicit border colour.

box.set_border_color(id, color)
  • id box Object reference
  • color color Color value

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.

box.set_border_style(id, style)
  • id box Object reference
  • style line_style Visual style

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.

box.set_border_width(id, width)
  • id box Object reference
  • width int Width value

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.

box.set_bottom(id, bottom)
  • id box Object reference
  • bottom float Bottom edge y

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.

box.set_bottom_right_point(id, point)
  • id box Object reference
  • point chart.point Chart point

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.

box.set_extend(id, extend)
  • id box Object reference
  • extend extend Line extend mode

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.

box.set_left(id, left)
  • id box Object reference
  • left int Left edge x

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.

box.set_lefttop(id, left, top)
  • id box Object reference
  • left int Left edge x
  • top float Top edge y

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.

box.set_right(id, right)
  • id box Object reference
  • right int Right edge x

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.

box.set_rightbottom(id, right, bottom)
  • id box Object reference
  • right int Right edge x
  • bottom float Bottom edge y

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.

box.set_text(id, text)
  • id box Object reference
  • text string Text content

Nothing

box.set_text_color

Sets the colour of the text inside an existing box; na clears the explicit colour.

box.set_text_color(id, text_color)
  • id box Object reference
  • text_color color Text color

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.

box.set_text_font_family(id, font_family)
  • id box Object reference
  • font_family string Font family

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.

box.set_text_halign(id, text_halign)
  • id box Object reference
  • text_halign string Horizontal text alignment

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.

box.set_text_size(id, text_size)
  • id box Object reference
  • text_size size Text size

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.

box.set_text_valign(id, text_valign)
  • id box Object reference
  • text_valign string Vertical text alignment

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).

box.set_text_wrap(id, text_wrap)
  • id box Object reference
  • text_wrap string Text wrapping mode

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.

box.set_top(id, top)
  • id box Object reference
  • top float Top edge y

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.

box.set_top_left_point(id, point)
  • id box Object reference
  • point chart.point Chart point

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.

box.set_xloc(id, xloc)
  • id box Object reference
  • xloc xloc X-location mode

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.

table.cell(id, column, row, text?, width?, height?, text_color?, text_halign?, text_valign?, text_size?, bgcolor?, tooltip?, text_font_family?)
  • 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

Nothing

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.

table.cell_set_bgcolor(id, column, row, bgcolor)
  • id table Object reference
  • column int Column index
  • row int Row index
  • bgcolor color Background color

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.

table.cell_set_height(id, column, row, height)
  • id table Object reference
  • column int Column index
  • row int Row index
  • height float Height value

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.

table.cell_set_text(id, column, row, text)
  • id table Object reference
  • column int Column index
  • row int Row index
  • text string Text content

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.

table.cell_set_text_color(id, column, row, text_color)
  • id table Object reference
  • column int Column index
  • row int Row index
  • text_color color Text color

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.

table.cell_set_text_font_family(id, column, row, text_font_family)
  • id table Object reference
  • column int Column index
  • row int Row index
  • text_font_family string Font family

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.

table.cell_set_text_halign(id, column, row, text_halign)
  • id table Object reference
  • column int Column index
  • row int Row index
  • text_halign string Horizontal text alignment

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.

table.cell_set_text_size(id, column, row, text_size)
  • id table Object reference
  • column int Column index
  • row int Row index
  • text_size size Text size

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.

table.cell_set_text_valign(id, column, row, text_valign)
  • id table Object reference
  • column int Column index
  • row int Row index
  • text_valign string Vertical text alignment

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.

table.cell_set_width(id, column, row, width)
  • id table Object reference
  • column int Column index
  • row int Row index
  • width float Width value

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.

table.clear(id, start_column, start_row, end_column, end_row)
  • id table Object reference
  • start_column int
  • start_row int
  • end_column int
  • end_row int

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.

table.delete(id)
  • id table Object reference

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.

table.merge_cells(id, start_column, start_row, end_column, end_row)
  • id table Object reference
  • start_column int
  • start_row int
  • end_column int
  • end_row int

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.

table.new(position, columns, rows, bgcolor?, frame_color?, frame_width = 0, border_color?, border_width = 0) → table
  • 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

table

table.set_bgcolor

Sets the background colour drawn behind an existing table's cells. Passing na removes the background.

table.set_bgcolor(id, bgcolor)
  • id table Object reference
  • bgcolor color Background color

Nothing

table.set_border_color

Sets the colour of the borders drawn between an existing table's cells; na clears it.

table.set_border_color(id, border_color)
  • id table Object reference
  • border_color color Border color

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.

table.set_border_width(id, border_width)
  • id table Object reference
  • border_width int Border width

Nothing

table.set_frame_color

Sets the colour of the frame around the outside of an existing table; na clears it.

table.set_frame_color(id, frame_color)
  • id table Object reference
  • frame_color color Frame color

Nothing

table.set_frame_width

Sets the width, in pixels, of the frame around an existing table. The default of zero draws no frame.

table.set_frame_width(id, frame_width)
  • id table Object reference
  • frame_width int Frame width

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.

table.set_position(id, position)
  • id table Object reference
  • position position Table position

Nothing

linefill.* — Line fills

linefill.delete

Removes the shaded area between the two lines. The lines themselves stay on the chart, nothing is returned, and repeated calls have no further effect.

linefill.delete(id)
  • id linefill Object reference

Nothing

linefill.get_line1

Returns the first of the two lines the fill spans, as a line reference, or na if that line no longer exists.

linefill.get_line1(id) → line
  • id linefill Object reference

line

linefill.get_line2

Returns the second of the two lines the fill spans, as a line reference, or na if that line no longer exists.

linefill.get_line2(id) → line
  • id linefill Object reference

line

linefill.new

Shades the area between two existing lines and returns a linefill reference. The shaded region follows both lines as their coordinates change, and if no colour is given the fill is fully transparent. It lasts until deleted, disappears automatically when either of its lines is removed, and a script may hold 500 line fills before the oldest are evicted.

linefill.new(line1, line2, color?) → linefill
  • line1 line First line reference
  • line2 line Second line reference
  • color color optional Color value

linefill

linefill.set_color

Changes the colour of an existing fill in place. A na colour leaves the current colour untouched, and nothing is returned.

linefill.set_color(id, color)
  • id linefill Object reference
  • color color Color value

Nothing

polyline.* — Polylines

polyline.delete

Removes the polyline from the chart and frees its slot against the script's polyline cap. Nothing is returned, and repeated calls through the same reference do nothing.

polyline.delete(id)
  • id polyline

Nothing

polyline.new

Draws one connected path through an array of chart.point values and returns a polyline reference. xloc decides whether each point is placed by its bar index or by its UNIX time in milliseconds; curved smooths the joins, closed links the last point back to the first, and fill_color shades the enclosed area. A polyline may carry up to 10000 points, and a script keeps 50 polylines by default, or up to 100 if its declaration asks for more, with the oldest removed beyond that.

polyline.new(points, curved = false, closed = false, xloc = xloc.bar_index, line_color?, fill_color?, line_style = line.style_solid, line_width = 1, force_overlay = false) → polyline
  • points array<chart.point>
  • curved bool optional
  • closed bool optional
  • xloc xloc optional
  • line_color color optional
  • fill_color color optional
  • line_style line_style optional
  • line_width int optional
  • force_overlay bool optional

polyline

request.* — Market data

request.extraData

Returns the extra values the chart publishes for the current instrument as a map keyed by name, covering option-chain figures such as open-interest support and resistance, max pain, the week's high and low, and the current expected-move band together with its expiry. Only the keys the chart has actually published are present, and the map is empty until the first update arrives. The call takes no arguments.

request.extraData()

map of string to value, empty until live chart indicator data arrives

Only string, bool, int and finite float fields are kept, and a field that has not arrived yet is absent from the map rather than na.

request.instrument

Specific to this platform: fetches data for another instrument, evaluating the given expression on that instrument at the requested timeframe and mapping each result onto the chart's bars. The result is na until the first value for the requested context exists, so early bars need guarding, and a tuple expression yields na in each of its targets there. By default the latest confirmed value is carried forward between updates; barmerge.gaps_on returns na on bars that bring no fresh value, and barmerge.lookahead_on allows the value of a requested bar that has not closed yet.

request.instrument(symbol, timeframe, expression, gaps?, lookahead?, ignore_invalid_symbol?, currency?)
  • symbol string Symbol/ticker
  • timeframe string Timeframe string
  • expression Expression to evaluate
  • gaps barmerge_gaps optional Gap handling mode
  • lookahead barmerge_lookahead optional Lookahead mode
  • ignore_invalid_symbol bool optional Ignore invalid symbols
  • currency string optional Currency code

the expression's own shape: one value, or a tuple of the same size

This is the same implementation as request.security, so the result shape and the na behaviour are identical.

request.instrument_lower_tf

Specific to this platform: evaluates the expression on another instrument at a timeframe lower than the chart's and returns an array holding one entry for each lower-timeframe bar that falls inside the current chart bar, in chronological order. The array is empty on bars for which no lower-timeframe data exists yet.

request.instrument_lower_tf(symbol, timeframe, expression)
  • symbol string Symbol/ticker
  • timeframe string Timeframe string
  • expression Expression to evaluate

array of the expression's values, one element per intrabar, oldest first

This is the same implementation as request.security_lower_tf, including the empty array when a chart bar has no intrabar data.

request.oi_change_pcr

Specific to this platform: returns the live put-to-call ratio of the change in open interest across the option chain of the given underlying, or of the chart's own instrument when symbol is omitted. The value is na until the first live update for that instrument arrives.

request.oi_change_pcr(symbol?)
  • symbol string optional Optional symbol/ticker

float, or na until the live put-call open-interest change ratio arrives

The ratio is a live last-bar value with no history, so an update recomputes only the latest bar and earlier bars keep na.

request.pcr

Specific to this platform: returns the live put-to-call ratio of open interest across the option chain of the given underlying, or of the chart's own instrument when symbol is omitted. The value is na until the first live update for that instrument arrives.

request.pcr(symbol?)
  • symbol string optional Optional symbol/ticker

float, or na until the live put-call open-interest ratio arrives

The ratio is a live last-bar value with no history, so an update recomputes only the latest bar and earlier bars keep na.

request.security

Evaluates the given expression on another symbol or timeframe and maps each result onto the chart's bars, returning either a single value or a tuple. The result is na until the first value for the requested context exists, so early bars need guarding, and a tuple expression yields na in each of its targets there. By default the latest confirmed value is carried forward between updates; barmerge.gaps_on returns na on bars that bring no fresh value, and barmerge.lookahead_on allows the value of a requested bar that has not closed yet.

request.security(symbol, timeframe, expression, gaps?, lookahead?, ignore_invalid_symbol?, currency?)
  • symbol string Symbol/ticker
  • timeframe string Timeframe string
  • expression Expression to evaluate
  • gaps barmerge_gaps optional Gap handling mode
  • lookahead barmerge_lookahead optional Lookahead mode
  • ignore_invalid_symbol bool optional Ignore invalid symbols
  • currency string optional Currency code

the expression's own shape: one value, or a tuple of the same size

A tuple expression has to be destructured with square brackets, and every element is na on bars where the requested timeframe has no value yet.

indicator("Daily close on any chart", overlay = true)

daily = request.security(syminfo.tickerid, "D", close)
plot(daily, "Daily close", color = color.orange)

request.security_lower_tf

Evaluates the expression at a timeframe lower than the chart's and returns an array holding one entry for each lower-timeframe bar that falls inside the current chart bar, in chronological order. The array is empty on bars for which no lower-timeframe data exists yet.

request.security_lower_tf(symbol, timeframe, expression)
  • symbol string Symbol/ticker
  • timeframe string Timeframe string
  • expression Expression to evaluate

array of the expression's values, one element per intrabar, oldest first

The array is empty rather than na on chart bars with no intrabar data, so check its size before reading elements.

request.volume_pcr

Specific to this platform: returns the live put-to-call ratio of traded volume across the option chain of the given underlying, or of the chart's own instrument when symbol is omitted. The value is na until the first live update for that instrument arrives.

request.volume_pcr(symbol?)
  • symbol string optional Optional symbol/ticker

float, or na until the live put-call volume ratio arrives

The ratio is a live last-bar value with no history, so an update recomputes only the latest bar and earlier bars keep na.

ticker.* — Tickers

ticker.heikinashi

Builds a symbol identifier that asks for the same instrument with Heikin Ashi candle values. Pass the result to a data request when you want smoothed bars for a calculation without changing the chart itself.

ticker.heikinashi(symbol) → string
  • symbol string Source symbol

string

ticker.inherit

Builds a symbol identifier for the second symbol while carrying over the session, price-adjustment and candle-type settings attached to the first identifier. Any such settings already on the second symbol are replaced by the inherited ones.

ticker.inherit(from_tickerid, symbol) → string
  • from_tickerid string Ticker ID whose modifiers are inherited
  • symbol string Target symbol

string

ticker.modify

Returns a copy of an existing symbol identifier with its session or price-adjustment settings changed. Arguments you leave out keep whatever the original identifier had; the session accepts the session.regular and session.extended values, and the adjustment accepts none, splits or dividends.

ticker.modify(tickerid, session?, adjustment?) → string
  • tickerid string Ticker ID to modify
  • session string optional Session type
  • adjustment string optional Adjustment type

string

ticker.new

Builds a symbol identifier from an exchange prefix and a symbol name, optionally attaching a session and a price-adjustment setting. The result looks like NSE:INFY, or carries the extra settings as a suffix, and is meant to be passed to a data request.

ticker.new(prefix, ticker, session?, adjustment?) → string
  • prefix string Exchange prefix
  • ticker string Ticker symbol
  • session string optional Session type
  • adjustment string optional Adjustment type

string

ticker.standard

Returns the plain form of a symbol identifier, such as NSE:INFY, with any session, price-adjustment or candle-type settings removed. Use it for readable labels or to compare two identifiers by instrument alone; called without an argument it works on the current symbol.

ticker.standard(symbol = syminfo.tickerid) → string
  • symbol string optional Ticker ID to convert to its plain form

string

timeframe.* — Timeframe functions

timeframe.change

Returns true on the first bar of each new period of the timeframe given as a string, for example timeframe.change("1D") is true on the first bar of every trading day. It also returns true on the first bar of the loaded data, and periods are aligned using the symbol's session and exchange time zone.

timeframe.change(timeframe) → bool
  • timeframe string Timeframe string

bool

indicator("New day marker", overlay = true)

plotshape(timeframe.change("D"), "New day", shape.circle, location.bottom)

timeframe.from_seconds

Converts a duration in seconds into the shortest standard timeframe string that is not shorter than that duration, for example 604800 returns 1W. When two notations cover the same duration the larger unit is chosen.

timeframe.from_seconds(seconds) → string
  • seconds int Number of seconds

string

timeframe.in_seconds

Returns the length of a timeframe in seconds. Called without an argument it measures the chart's own timeframe; pass a timeframe string to measure that one instead. Weeks are counted as seven days and months as thirty days.

timeframe.in_seconds() → int

int

chart.point.* — Chart points

chart.point.copy

Returns a new chart point holding the same time, index and price as the one given, leaving the original untouched. Passing na instead of a point raises an error.

chart.point.copy(id) → chart.point
  • id chart.point Object reference

chart.point

chart.point.from_index

Builds a chart point positioned by bar index, for drawings that use xloc.bar_index. The index defaults to the current bar and the price to the current close, and the point carries no time value.

chart.point.from_index(index, price?) → chart.point
  • index int Element index
  • price float optional Price level

chart.point

chart.point.from_time

Builds a chart point positioned by a UNIX timestamp in milliseconds, for drawings that use xloc.bar_time. The time defaults to the current bar's time and the price to the current close, and the point carries no bar index.

chart.point.from_time(time, price?) → chart.point
  • time int Time value
  • price float optional Price level

chart.point

chart.point.new

Builds a chart point from an explicit time, bar index and price and returns it. time is a UNIX timestamp in milliseconds and index is a bar index, and a drawing later uses whichever of the two suits its xloc; if price is omitted the current bar's close is used. A point is a plain value rather than a drawing, so nothing appears on the chart until it is handed to something that draws.

chart.point.new(time?, index?, price?) → chart.point
  • time int optional Time value
  • index int optional Element index
  • price float optional Price level

chart.point

chart.point.now

Builds a chart point anchored to the bar currently being processed, carrying both that bar's index and its time in milliseconds so it can be used under either xloc mode. If price is omitted the bar's close is used, and the point is returned rather than drawn.

chart.point.now(price?) → chart.point
  • price float optional Price level

chart.point

log.* — Logging

log.error

Writes a message to the console output of the application running the script, tagged by you as an error condition. The text may contain numbered placeholders such as {0} and {1} that are filled from the arguments after it. There is no in-app log panel, so the message is visible only in the developer console, and the chosen level does not change what is printed.

log.error(message)
  • message string Message text

Nothing

log.info

Writes an informational message to the console output of the application running the script. The text may contain numbered placeholders such as {0} and {1} that are filled from the arguments after it. There is no in-app log panel, so the message is visible only in the developer console, and the chosen level does not change what is printed.

log.info(message)
  • message string Message text

Nothing

indicator("Log the last close")

if barstate.islast
    log.info("Close is " + str.tostring(close))

log.warning

Writes a message to the console output of the application running the script, tagged by you as a warning. The text may contain numbered placeholders such as {0} and {1} that are filled from the arguments after it. There is no in-app log panel, so the message is visible only in the developer console, and the chosen level does not change what is printed.

log.warning(message)
  • message string Message text

Nothing

runtime.* — Runtime

runtime.error

Stops the script immediately with the message you supply. The indicator stops producing output and the message is shown as that indicator's own error rather than being reported as an internal fault, so it is the right way to refuse an unsupported symbol, timeframe or missing data series.

runtime.error(message)
  • message string Message text

Nothing

The call never returns; it halts the script with the given message.

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).

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.

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).

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

order.ascending

order.descending

Sorts from largest to smallest. Accepted by the order argument of array.sort, array.sort_indices and matrix.sort.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

position.bottom_left

position.bottom_center

Anchors a table to the bottom of the pane, horizontally centred and ten pixels above the bottom edge.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

label.style_circle

label.style_square

Draws a filled square behind the label text, centred on the anchor point and sized to cover it.

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.

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.

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.

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.

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.

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.

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.

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.

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.

label.style_label_upper_right

label.style_triangleup

Draws a filled triangle pointing up, sized from the label text, with no bubble around it.

label.style_triangleup

label.style_triangledown

Draws a filled triangle pointing down, sized from the label text and centred on the anchor.

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.

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.

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.

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.

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.

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.

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.

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.

label.style_xcross