Pine Script® Variables and Functions Guide
Pine Script® Variables and Functions Guide
Variables
ask
The ask price at the time of the current tick, which represents the lowest price an active seller will accept for the
instrument at its current value. This information is available only on the "1T" timeframe. On other timeframes, the
variable's value is na.
TYPE
series float
REMARKS
If the bid/ask values change since the last tick but no new trades are made, these changes will not be reflected in the
value of this variable. It is only updated on new ticks.
SEE ALSO
open high low volume time() hl2 hlc3 hlcc4 ohlc4 bid
bar_index
Current bar index. Numbering is zero-based, index of the first bar is 0.
TYPE
series int
EXAMPLE
//@version=6
indicator("bar_index")
plot(bar_index)
plot(bar_index > 5000 ? close : 0)
REMARKS
Please note that using this variable/function can cause indicator repainting.
SEE ALSO
[Link]
Returns true if the script is calculating the last (closing) update of the current bar. The next script calculation will be on
the new bar data.
TYPE
series bool
REMARKS
Pine Script® code that uses this variable could calculate differently on history and real-time data.
It is NOT recommended to use [Link] in [Link]() expression. Its value requested from
[Link]() is unpredictable.
SEE ALSO
[Link]
Returns true if current bar is first bar in barset, false otherwise.
TYPE
series bool
REMARKS
Pine Script® code that uses this variable could calculate differently on history and real-time data.
Please note that using this variable/function can cause indicator repainting.
SEE ALSO
[Link]
[Link]
Returns true if current bar is a historical bar, false otherwise.
TYPE
series bool
REMARKS
Pine Script® code that uses this variable could calculate differently on history and real-time data.
Please note that using this variable/function can cause indicator repainting.
SEE ALSO
[Link]
[Link]
Returns true if current bar is the last bar in barset, false otherwise. This condition is true for all real-time bars in barset.
TYPE
series bool
REMARKS
Pine Script® code that uses this variable could calculate differently on history and real-time data.
Please note that using this variable/function can cause indicator repainting.
SEE ALSO
[Link]
[Link]
Returns true if script is executing on the dataset's last bar when market is closed, or script is executing on the bar
immediately preceding the real-time bar, if market is open. Returns false otherwise.
TYPE
series bool
REMARKS
Pine Script® code that uses this variable could calculate differently on history and real-time data.
Please note that using this variable/function can cause indicator repainting.
SEE ALSO
[Link]
Returns true if script is currently calculating on new bar, false otherwise. This variable is true when calculating on
historical bars or on first update of a newly generated real-time bar.
TYPE
series bool
REMARKS
Pine Script® code that uses this variable could calculate differently on history and real-time data.
Please note that using this variable/function can cause indicator repainting.
SEE ALSO
[Link]
[Link]
Returns true if current bar is a real-time bar, false otherwise.
TYPE
series bool
REMARKS
Pine Script® code that uses this variable could calculate differently on history and real-time data.
Please note that using this variable/function can cause indicator repainting.
SEE ALSO
[Link]
bid
The bid price at the time of the current tick, which represents the highest price an active buyer is willing to pay for the
instrument at its current value. This information is available only on the "1T" timeframe. On other timeframes, the
variable's value is na.
TYPE
series float
REMARKS
If the bid/ask values change since the last tick but no new trades are made, these changes will not be reflected in the
value of this variable. It is only updated on new ticks.
SEE ALSO
open high low volume time() hl2 hlc3 hlcc4 ohlc4 ask
[Link]
Returns an array filled with all the current boxes drawn by the script.
TYPE
array<box>
EXAMPLE
//@version=6
indicator("[Link]")
//delete all boxes
[Link](time, open, time + 60 * 60 * 24, close, xloc=xloc.bar_time, border_style=line.style_dashed)
a_allBoxes = [Link]
if [Link](a_allBoxes) > 0
for i = 0 to [Link](a_allBoxes) - 1
[Link]([Link](a_allBoxes, i))
REMARKS
The array is read-only. Index zero of the array is the ID of the oldest object on the chart.
SEE ALSO
chart.bg_color
Returns the color of the chart's background from the "Chart settings/Appearance/Background" field. When a gradient
is selected, the middle point of the gradient is returned.
TYPE
input color
SEE ALSO
chart.fg_color
chart.fg_color
Returns a color providing optimal contrast with chart.bg_color.
TYPE
input color
SEE ALSO
chart.bg_color
chart.is_heikinashi
TYPE
simple bool
RETURNS
SEE ALSO
chart.is_kagi
TYPE
simple bool
RETURNS
SEE ALSO
chart.is_linebreak
TYPE
simple bool
RETURNS
SEE ALSO
chart.is_pnf
TYPE
simple bool
RETURNS
Returns true if the chart type is Point & figure, false otherwise.
SEE ALSO
chart.is_range
TYPE
simple bool
RETURNS
SEE ALSO
chart.is_renko
TYPE
simple bool
RETURNS
SEE ALSO
chart.is_standard
TYPE
simple bool
RETURNS
Returns true if the chart type is not one of the following: Renko, Kagi, Line break, Point & figure, Range, Heikin Ashi;
false otherwise.
SEE ALSO
chart.left_visible_bar_time
The time of the leftmost bar currently visible on the chart.
TYPE
input int
REMARKS
Scripts using this variable will automatically re-execute when its value updates to reflect changes in the chart, which
can be caused by users scrolling the chart, or new real-time bars.
Alerts created on a script that includes this variable will only use the value assigned to the variable at the moment of
the alert's creation, regardless of whether the value changes afterward, which may lead to repainting.
SEE ALSO
chart.right_visible_bar_time
chart.right_visible_bar_time
The time of the rightmost bar currently visible on the chart.
TYPE
input int
REMARKS
Scripts using this variable will automatically re-execute when its value updates to reflect changes in the chart, which
can be caused by users scrolling the chart, or new real-time bars.
Alerts created on a script that includes this variable will only use the value assigned to the variable at the moment of
the alert's creation, regardless of whether the value changes afterward, which may lead to repainting.
SEE ALSO
chart.left_visible_bar_time
close
Close price of the current bar when it has closed, or last traded price of a yet incomplete, realtime bar.
TYPE
series float
REMARKS
Previous values may be accessed with square brackets operator [], e.g. close[1], close[2].
SEE ALSO
open high low volume time() hl2 hlc3 hlcc4 ohlc4 ask bid
dayofmonth
The day number of the month, in the exchange time zone, calculated from the bar's opening UNIX timestamp.
TYPE
series int
REMARKS
This variable always references the day number corresponding to the bar's opening time. Consequently, for symbols
with overnight sessions (e.g., "EURUSD", where the "Monday" session starts on Sunday at 17:00 in exchange time),
the value may represent a day from the previous week rather than the session's primary trading day.
SEE ALSO
dayofweek
The day number of the week, in the exchange time zone, calculated from the bar's opening UNIX timestamp.
TYPE
series int
REMARKS
This variable always references the day number corresponding to the bar's opening time. Consequently, for symbols
with overnight sessions (e.g., "EURUSD", where the "Monday" session starts on Sunday at 17:00 in exchange time),
the value may represent a day from the previous week rather than the session's primary trading day.
SEE ALSO
dividends.future_amount
Returns the payment amount of the upcoming dividend in the currency of the current instrument, or na if this data isn't
available.
TYPE
series float
REMARKS
This value is only fetched once during the script's initial calculation. The variable will return the same value until the
script is recalculated, even after the expected Payment date of the next dividend.
dividends.future_ex_date
Returns the Ex-dividend date (Ex-date) of the current instrument's next dividend payment, or na if this data isn't
available. Ex-dividend date signifies when investors are no longer entitled to a payout from the most recent dividend.
Only those who purchased shares before this day are entitled to the dividend payment.
TYPE
series int
RETURNS
REMARKS
This value is only fetched once during the script's initial calculation. The variable will return the same value until the
script is recalculated, even after the expected Payment date of the next dividend.
dividends.future_pay_date
Returns the Payment date (Pay date) of the current instrument's next dividend payment, or na if this data isn't
available. Payment date signifies the day when eligible investors will receive the dividend payment.
TYPE
series int
RETURNS
REMARKS
This value is only fetched once during the script's initial calculation. The variable will return the same value until the
script is recalculated, even after the expected Payment date of the next dividend.
earnings.future_eps
Returns the estimated Earnings per Share of the next earnings report in the currency of the instrument, or na if this
data isn't available.
TYPE
series float
REMARKS
This value is only fetched once during the script's initial calculation. The variable will return the same value until the
script is recalculated, even after the expected time of the next earnings report.
SEE ALSO
[Link]()
earnings.future_period_end_time
Checks the data for the next earnings report and returns the UNIX timestamp of the day when the financial period
covered by those earnings ends, or na if this data isn't available.
TYPE
series int
RETURNS
This value is only fetched once during the script's initial calculation. The variable will return the same value until the
script is recalculated, even after the expected time of the next earnings report.
SEE ALSO
[Link]()
earnings.future_revenue
Returns the estimated Revenue of the next earnings report in the currency of the instrument, or na if this data isn't
available.
TYPE
series float
REMARKS
This value is only fetched once during the script's initial calculation. The variable will return the same value until the
script is recalculated, even after the expected time of the next earnings report.
SEE ALSO
[Link]()
earnings.future_time
Returns a UNIX timestamp indicating the expected time of the next earnings report, or na if this data isn't available.
TYPE
series int
RETURNS
REMARKS
This value is only fetched once during the script's initial calculation. The variable will return the same value until the
script is recalculated, even after the expected time of the next earnings report.
SEE ALSO
[Link]()
high
Current high price.
TYPE
series float
REMARKS
Previous values may be accessed with square brackets operator [], e.g. high[1], high[2].
SEE ALSO
open low close volume time() hl2 hlc3 hlcc4 ohlc4 ask bid
hl2
Is a shortcut for (high + low)/2
TYPE
series float
SEE ALSO
open high low close volume time() hlc3 hlcc4 ohlc4 ask bid
hlc3
Is a shortcut for (high + low + close)/3
TYPE
series float
SEE ALSO
open high low close volume time() hl2 hlcc4 ohlc4 ask bid
hlcc4
Is a shortcut for (high + low + close + close)/4
TYPE
series float
SEE ALSO
open high low close volume time() hl2 hlc3 ohlc4 ask bid
hour
Current bar hour in exchange timezone.
TYPE
series int
SEE ALSO
[Link]
Returns an array filled with all the current labels drawn by the script.
TYPE
array<label>
EXAMPLE
//@version=6
indicator("[Link]")
//delete all labels
[Link](bar_index, close)
a_allLabels = [Link]
if [Link](a_allLabels) > 0
for i = 0 to [Link](a_allLabels) - 1
[Link]([Link](a_allLabels, i))
REMARKS
The array is read-only. Index zero of the array is the ID of the oldest object on the chart.
SEE ALSO
last_bar_index
Bar index of the last chart bar. Bar indices begin at zero on the first bar.
TYPE
series int
EXAMPLE
//@version=6
strategy("Mark Last X Bars For Backtesting", overlay = true, calc_on_every_tick = true)
lastBarsFilterInput = [Link](100, "Bars Count:")
// Here, we store the 'last_bar_index' value that is known from the beginning of the script's calculati
on.
// The 'last_bar_index' will change when new real-time bars appear, so we declare 'lastbar' with the 'v
ar' keyword.
var lastbar = last_bar_index
// Check if the current bar_index is 'lastBarsFilterInput' removed from the last bar on the chart, or t
he chart is traded in real-time.
allowedToTrade = (lastbar - bar_index <= lastBarsFilterInput) or [Link]
bgcolor(allowedToTrade ? [Link]([Link], 80) : na)
RETURNS
Last historical bar index for closed markets, or the real-time bar index for open markets.
REMARKS
Please note that using this variable can cause indicator repainting.
SEE ALSO
last_bar_time
Time in UNIX format of the last chart bar. It is the number of milliseconds that have elapsed since 00:00:00 UTC, 1
January 1970.
TYPE
series int
REMARKS
Please note that using this variable/function can cause indicator repainting.
Note that this variable returns the timestamp based on the time of the bar's open.
SEE ALSO
[Link]
Returns an array filled with all the current lines drawn by the script.
TYPE
array<line>
EXAMPLE
//@version=6
indicator("[Link]")
//delete all lines
[Link](bar_index - 10, close, bar_index, close)
a_allLines = [Link]
if [Link](a_allLines) > 0
for i = 0 to [Link](a_allLines) - 1
[Link]([Link](a_allLines, i))
REMARKS
The array is read-only. Index zero of the array is the ID of the oldest object on the chart.
SEE ALSO
[Link]
Returns an array filled with all the current linefill objects drawn by the script.
TYPE
array<linefill>
REMARKS
The array is read-only. Index zero of the array is the ID of the oldest object on the chart.
low
Current low price.
TYPE
series float
REMARKS
Previous values may be accessed with square brackets operator [], e.g. low[1], low[2].
SEE ALSO
open high close volume time() hl2 hlc3 hlcc4 ohlc4 ask bid
minute
Current bar minute in exchange timezone.
TYPE
series int
SEE ALSO
month
Current bar month in exchange timezone.
TYPE
series int
REMARKS
Note that this variable returns the month based on the time of the bar's open. For overnight sessions (e.g. EURUSD,
where Monday session starts on Sunday, 17:00) this value can be lower by 1 than the month of the trading day.
SEE ALSO
na
A keyword signifying "not available", indicating that a variable has no assigned value.
TYPE
simple na
EXAMPLE
//@version=6
indicator("na")
// CORRECT
// Plot no value when on bars zero to nine. Plot `close` on other bars.
plot(bar_index < 10 ? na : close)
// CORRECT ALTERNATIVE
// Initialize `a` to `na`. Reassign `close` to `a` on bars 10 and later.
float a = na
if bar_index >= 10
a := close
plot(a)
// INCORRECT
// Trying to test the preceding bar's `close` for `na`.
// The next line, if uncommented, will cause a compilation error, because direct comparison with `na` i
s not allowed.
// plot(close[1] == na ? close : close[1])
// CORRECT
// Use the `na()` function to test for `na`.
plot(na(close[1]) ? close : close[1])
// CORRECT ALTERNATIVE
// `nz()` tests `close[1]` for `na`. It returns `close[1]` if it is not `na`, and `close` if it is.
plot(nz(close[1], close))
REMARKS
Do not use this variable with comparison operators to test values for na , as it might lead to unexpected behavior.
Instead, use the na() function. Note that na can be used to initialize variables when the initialization statement also
specifies the variable's type.
SEE ALSO
ohlc4
Is a shortcut for (open + high + low + close)/4
TYPE
series float
SEE ALSO
open
Current open price.
TYPE
series float
REMARKS
Previous values may be accessed with square brackets operator [], e.g. open[1], open[2].
SEE ALSO
high low close volume time() hl2 hlc3 hlcc4 ohlc4 ask bid
[Link]
Returns an array containing all current polyline instances drawn by the script.
TYPE
array<polyline>
REMARKS
The array is read-only. Index zero of the array references the ID of the oldest polyline object on the chart.
second
Current bar second in exchange timezone.
TYPE
series int
SEE ALSO
[Link]
Returns true if the current bar is the first bar of the day's session, false otherwise. If extended session information is
used, only returns true on the first bar of the pre-market bars.
TYPE
series bool
EXAMPLE
//@version=6
strategy("`[Link]` Example", overlay = true)
longCondition = year >= 2022
// Place a long order at the `close` of the trading session's first bar.
if [Link] and longCondition
[Link]("Long", [Link])
// Close the long position at the `close` of the trading session's last bar.
if [Link] and [Link]
[Link]("Long", immediately = true)
SEE ALSO
session.isfirstbar_regular
Returns true on the first regular session bar of the day, false otherwise. The result is the same whether extended
session information is used or not.
TYPE
series bool
EXAMPLE
//@version=6
strategy("`session.isfirstbar_regular` Example", overlay = true)
longCondition = year >= 2022
// Place a long order at the `close` of the trading session's first bar.
if [Link] and longCondition
[Link]("Long", [Link])
// Close the long position at the `close` of the trading session's last bar.
if session.islastbar_regular and [Link]
[Link]("Long", immediately = true)
SEE ALSO
[Link] [Link]
[Link]
Returns true if the current bar is the last bar of the day's session, false otherwise. If extended session information is
used, only returns true on the last bar of the post-market bars.
TYPE
series bool
EXAMPLE
//@version=6
strategy("`[Link]` Example", overlay = true)
longCondition = year >= 2022
// Place a long order at the `close` of the trading session's last bar.
// The position will enter on the `open` of next session's first bar.
if [Link] and longCondition
[Link]("Long", [Link])
// Close 'Long' position at the close of the last bar of the trading session
if [Link] and [Link]
[Link]("Long", immediately = true)
REMARKS
This variable is not guaranteed to return true once in every session because the last bar of the session might not exist
if no trades occur during what should be the session's last bar.
This variable is not guaranteed to work as expected on non-standard chart types, e.g., Renko.
SEE ALSO
[Link] session.islastbar_regular
session.islastbar_regular
Returns true on the last regular session bar of the day, false otherwise. The result is the same whether extended
session information is used or not.
TYPE
series bool
EXAMPLE
//@version=6
strategy("`session.islastbar_regular` Example", overlay = true)
longCondition = year >= 2022
// Place a long order at the `close` of the trading session's first bar.
if [Link] and longCondition
[Link]("Long", [Link])
// Close the long position at the `close` of the trading session's last bar.
if session.islastbar_regular and [Link]
[Link]("Long", immediately = true)
REMARKS
This variable is not guaranteed to return true once in every session because the last bar of the session might not exist
if no trades occur during what should be the session's last bar.
This variable is not guaranteed to work as expected on non-standard chart types, e.g., Renko.
SEE ALSO
[Link]
Returns true if the current bar is a part of the regular trading hours (i.e. market hours), false otherwise.
TYPE
series bool
SEE ALSO
[Link] [Link]
[Link]
Returns true if the current bar is a part of the post-market, false otherwise. On non-intraday charts always returns fa
lse .
TYPE
series bool
SEE ALSO
[Link] [Link]
[Link]
Returns true if the current bar is a part of the pre-market, false otherwise. On non-intraday charts always returns fal
se .
TYPE
series bool
SEE ALSO
[Link] [Link]
strategy.account_currency
Returns the currency used to calculate results, which can be set in the strategy's properties.
TYPE
simple string
SEE ALSO
TYPE
series float
SEE ALSO
strategy.avg_losing_trade_percent
strategy.avg_losing_trade_percent
Returns the average percentage loss per losing trade. Calculated as the sum of loss percentages divided by the
number of losing trades.
TYPE
series float
SEE ALSO
strategy.avg_losing_trade
strategy.avg_trade
Returns the average amount of money gained or lost per trade. Calculated as the sum of all profits and losses divided
by the number of closed trades.
TYPE
series float
SEE ALSO
strategy.avg_trade_percent
strategy.avg_trade_percent
Returns the average percentage gain or loss per trade. Calculated as the sum of all profit and loss percentages divided
by the number of closed trades.
TYPE
series float
SEE ALSO
strategy.avg_trade
strategy.avg_winning_trade
Returns the average amount of money gained per winning trade. Calculated as the sum of profits divided by the
number of winning trades.
TYPE
series float
SEE ALSO
strategy.avg_winning_trade_percent
strategy.avg_winning_trade_percent
Returns the average percentage gain per winning trade. Calculated as the sum of profit percentages divided by the
number of winning trades.
TYPE
series float
SEE ALSO
strategy.avg_winning_trade
[Link]
Number of trades, which were closed for the whole trading range.
TYPE
series int
SEE ALSO
[Link].first_index
The index, or trade number, of the first (oldest) trade listed in the List of Trades. This number is usually zero. If more
trades than the allowed limit have been closed, the oldest trades are removed, and this number is the index of the
oldest remaining trade.
TYPE
series int
SEE ALSO
[Link]
Current equity (strategy.initial_capital + [Link] + [Link]).
TYPE
series float
SEE ALSO
[Link]
Number of breakeven trades for the whole trading range.
TYPE
series int
SEE ALSO
TYPE
series float
SEE ALSO
[Link] [Link]
strategy.grossloss_percent
The total value of all completed losing trades, expressed as a percentage of the initial capital.
TYPE
series float
SEE ALSO
[Link]
[Link]
Total currency value of all completed winning trades.
TYPE
series float
SEE ALSO
[Link] [Link]
strategy.grossprofit_percent
The total currency value of all completed winning trades, expressed as a percentage of the initial capital.
TYPE
series float
SEE ALSO
[Link]
strategy.initial_capital
The amount of initial capital set in the strategy properties.
TYPE
series float
SEE ALSO
strategy()
[Link]
Number of unprofitable trades for the whole trading range.
TYPE
series int
SEE ALSO
strategy.margin_liquidation_price
When margin is used in a strategy, returns the price point where a simulated margin call will occur and liquidate
enough of the position to meet the margin requirements.
TYPE
series float
EXAMPLE
//@version=6
strategy("Margin call management", overlay = true, margin_long = 25, margin_short = 25,
default_qty_type = strategy.percent_of_equity, default_qty_value = 395)
if [Link](maFast, maSlow)
[Link]("Long", [Link])
if [Link](maFast, maSlow)
[Link]("Short", [Link])
// exit when we're 10% away from a margin call, to prevent it.
if [Link](changePercent(close, strategy.margin_liquidation_price)) <= 10
[Link]("Long")
[Link]("Short")
REMARKS
The variable returns na if the strategy does not use margin, i.e., the strategy() declaration statement does not specify
an argument for the margin_long or margin_short parameter.
strategy.max_contracts_held_all
Maximum number of contracts/shares/lots/units in one trade for the whole trading range.
TYPE
series float
SEE ALSO
strategy.max_contracts_held_long
Maximum number of contracts/shares/lots/units in one long trade for the whole trading range.
TYPE
series float
SEE ALSO
TYPE
series float
SEE ALSO
strategy.max_drawdown
Maximum equity drawdown value for the whole trading range.
TYPE
series float
SEE ALSO
strategy.max_drawdown_percent
The maximum equity drawdown value for the whole trading range, expressed as a percentage and calculated by
formula: Lowest Value During Trade / (Entry Price x Quantity) * 100 .
TYPE
series float
SEE ALSO
strategy.max_drawdown
strategy.max_runup
Maximum equity run-up value for the whole trading range.
TYPE
series float
SEE ALSO
strategy.max_runup_percent
The maximum equity run-up value for the whole trading range, expressed as a percentage and calculated by formula:
Highest Value During Trade / (Entry Price x Quantity) * 100 .
TYPE
series float
SEE ALSO
strategy.max_runup
[Link]
Total currency value of all completed trades.
TYPE
series float
SEE ALSO
strategy.netprofit_percent
The total value of all completed trades, expressed as a percentage of the initial capital.
TYPE
series float
SEE ALSO
[Link]
[Link]
Current unrealized profit or loss for all open positions.
TYPE
series float
SEE ALSO
[Link] strategy.position_size
strategy.openprofit_percent
The current unrealized profit or loss for all open positions, expressed as a percentage and calculated by formula: ope
nPL / realizedEquity * 100 .
TYPE
series float
SEE ALSO
[Link]
[Link]
Number of market position entries, which were not closed and remain opened. If there is no open market position, 0 is
returned.
TYPE
series int
SEE ALSO
strategy.position_size
[Link].capital_held
Returns the capital amount currently held by open trades.
TYPE
series float
EXAMPLE
//@version=6
strategy(
"[Link].capital_held example", overlay=false, margin_long=50, margin_short=50,
default_qty_type = strategy.percent_of_equity, default_qty_value = 100
)
REMARKS
This variable returns na if the strategy does not simulate funding trades with a portion of the hypothetical account, i.e.,
if the strategy() function does not include nonzero margin_long or margin_short arguments.
strategy.position_avg_price
Average entry price of current market position. If the market position is flat, 'NaN' is returned.
TYPE
series float
SEE ALSO
strategy.position_size
strategy.position_entry_name
Name of the order that initially opened current market position.
TYPE
series string
SEE ALSO
strategy.position_size
strategy.position_size
Direction and size of the current market position. If the value is > 0, the market position is long. If the value is < 0, the
market position is short. The absolute value is the number of contracts/shares/lots/units in trade (position size).
TYPE
series float
SEE ALSO
strategy.position_avg_price
[Link]
Number of profitable trades for the whole trading range.
TYPE
series int
SEE ALSO
[Link]
Returns a string containing the code representing the symbol's base currency (i.e., the traded currency or coin) if the
instrument is a Forex or Crypto pair or a derivative based on such a pair. Otherwise, it returns an empty string. For
example, this variable returns "EUR" for "EURJPY", "BTC" for "BTCUSDT", "CAD" for "CME:6C1!", and "" for
"NASDAQ:AAPL".
TYPE
simple string
SEE ALSO
[Link] [Link]
[Link]
Returns the two-letter code of the country where the symbol is traded, in the ISO 3166-1 alpha-2 format, or na if the
exchange is not directly tied to a specific country. For example, on "NASDAQ:AAPL" it will return "US", on "LSE:AAPL"
it will return "GB", and on "BITSTAMP:BTCUSD it will return na.
TYPE
simple string
[Link]
Returns a string containing the code representing the currency of the symbol's prices. For example, this variable
returns "USD" for "NASDAQ:AAPL" and "JPY" for "EURJPY".
TYPE
simple string
SEE ALSO
syminfo.current_contract
The ticker identifier of the underlying contract, if the current symbol is a continuous futures contract; na otherwise.
TYPE
simple string
SEE ALSO
[Link] [Link]
[Link]
Description for the current symbol.
TYPE
simple string
SEE ALSO
[Link] [Link]
[Link]
The number of employees the company has.
TYPE
simple int
EXAMPLE
//@version=6
indicator("syminfo simple")
//@variable A table containing information about a company's employees, shareholders, and shares.
var result_table = [Link](position = position.top_right, columns = 2, rows = 5, border_width = 1)
if [Link]
// Add header cells
[Link](table_id = result_table, column = 0, row = 0, text = "name")
[Link](table_id = result_table, column = 1, row = 0, text = "value")
// Add employee info cells.
[Link](table_id = result_table, column = 0, row = 1, text = "employees")
[Link](table_id = result_table, column = 1, row = 1, text = [Link]([Link]))
// Add shareholder cells.
[Link](table_id = result_table, column = 0, row = 2, text = "shareholders")
[Link](table_id = result_table, column = 1, row = 2, text = [Link]([Link]))
// Add float shares outstanding cells.
[Link](table_id = result_table, column = 0, row = 3, text = "shares_outstanding_float")
[Link](table_id = result_table, column = 1, row = 3, text = [Link](syminfo.shares_outstan
ding_float))
// Add total shares outstanding cells.
[Link](table_id = result_table, column = 0, row = 4, text = "shares_outstanding_total")
[Link](table_id = result_table, column = 1, row = 4, text = [Link](syminfo.shares_outstan
ding_total))
SEE ALSO
syminfo.expiration_date
A UNIX timestamp representing the start of the last day of the current futures contract. This variable is only compatible
with non-continuous futures symbols. On other symbols, it returns na.
TYPE
simple int
[Link]
Returns the industry of the symbol, or na if the symbol has no industry. Example: "Internet Software/Services",
"Packaged software", "Integrated Oil", "Motor Vehicles", etc. These are the same values one can see in the chart's
"Symbol info" window.
TYPE
simple string
REMARKS
A sector is a broad section of the economy. An industry is a narrower classification. NASDAQ:CAT (Caterpillar, Inc.) for
example, belongs to the "Producer Manufacturing" sector and the "Trucks/Construction/Farm Machinery" industry.
[Link]
Holds a string representing a symbol's associated International Securities Identification Number (ISIN), or an empty
string if there is no ISIN information available for the symbol. An ISIN is a 12-character alphanumeric code that
uniquely identifies a security globally. Unlike ticker symbols, which can vary across exchanges, the ISIN for a security is
consistent across exchanges. As such, programmers can use the ISIN to identify an underlying financial instrument,
regardless of the exchange or the symbol name listed by an exchange.
For example, the ISIN associated with NASDAQ:AAPL and GETTEX:APC is US0378331005, because both symbols
refer to the common stock from Apple Inc. In contrast, the ISIN for TSX:AAPL is CA03785Y1007, because the symbol
refers to a different instrument: the Apple Inc. Canadian Depositary Receipt (CDR).
TYPE
simple string
SEE ALSO
[Link] [Link]
syminfo.main_tickerid
A ticker identifier representing the current chart's symbol. The value contains an exchange prefix and a symbol name,
separated by a colon (e.g., "NASDAQ:AAPL"). It can also include information about data modifications such as dividend
adjustment, non-standard chart type, currency conversion, etc. Unlike [Link], this variable's value does not
change when used in the expression argument of a request.*() function call.
TYPE
simple string
SEE ALSO
[Link]
[Link]
The smallest amount of the current symbol that can be traded. This limit is set by the exchange. For cryptocurrencies,
it is often less than 1 token. For most other types of asset, it is often 1.
TYPE
simple float
SEE ALSO
[Link] [Link]
[Link]
Returns a whole number used to calculate the smallest increment between a symbol's price movements
([Link]). It is the numerator in the [Link] formula: [Link] / [Link]
= [Link] .
TYPE
simple int
SEE ALSO
[Link]
Min tick value for the current symbol.
TYPE
simple float
SEE ALSO
[Link] [Link]
[Link]
The chart price of a security multiplied by the point value equals the actual price of the traded security.
For all types of security except futures, the point value is usually equal to 1 and can therefore be ignored. For futures,
the prices shown on the chart are either the cost of a single futures contract, in which case the point value is 1, or the
price of a single unit of the underlying commodity, in which case the point value represents the number of units
included in a single contract.
For example, the price of the "COMEX:GC1!" gold futures chart reflects the price of a single troy ounce of gold.
However, a single GC futures contract comprises 100 troy ounces, as defined by the COMEX exchange. So when the
price on the "GC1!" chart is 2000 USD, a single contract costs 2000 USD * 100 troy ounces = 200,000 USD. This
calculation is important in backtesting, because the strategy engine takes the point value into account, and does not
open a position if there is not enough capital.
The point value is also displayed in the Security Info window for a given asset.
TYPE
simple float
SEE ALSO
[Link] [Link]
[Link]
Prefix of current symbol name (i.e. for 'CME_EOD:TICKER' prefix is 'CME_EOD').
TYPE
simple string
EXAMPLE
//@version=6
indicator("[Link]")
SEE ALSO
[Link] [Link]
[Link]
Returns a whole number used to calculate the smallest increment between a symbol's price movements
([Link]). It is the denominator in the [Link] formula: [Link] / [Link]
e = [Link] .
TYPE
simple int
SEE ALSO
TYPE
series int
EXAMPLE
//@version=6
indicator("syminfo recommendations", overlay = true)
//@variable A table containing information about analyst recommendations.
var table ratings = [Link](position.top_right, 8, 2, frame_color = #000000)
if [Link]
//@variable The time value one year from the date of the last analyst recommendations.
int YTD = syminfo.target_price_date + timeframe.in_seconds("12M") * 1000
// Add header cells.
[Link](ratings, 0, 0, "Start Date", bgcolor = [Link], text_color = #000000, text_size = siz
[Link])
[Link](ratings, 1, 0, "End Date", bgcolor = [Link], text_color = #000000, text_size = size.
large)
[Link](ratings, 2, 0, "Buy", bgcolor = [Link], text_color = #000000, text_size = [Link]
e)
[Link](ratings, 3, 0, "Strong Buy", bgcolor = [Link], text_color = #000000, text_size = siz
[Link])
[Link](ratings, 4, 0, "Sell", bgcolor = [Link], text_color = #000000, text_size = [Link]
rge)
[Link](ratings, 5, 0, "Strong Sell", bgcolor = [Link], text_color = #000000, text_size = siz
[Link])
[Link](ratings, 6, 0, "Hold", bgcolor = [Link], text_color = #000000, text_size = [Link]
rge)
[Link](ratings, 7, 0, "Total", bgcolor = [Link], text_color = #000000, text_size = size.l
arge)
// Recommendation strings
string startDate = str.format_time(syminfo.recommendations_date, "yyyy-MM-dd")
string endDate = str.format_time(YTD, "yyyy-MM-dd")
string buyRatings = [Link](syminfo.recommendations_buy)
string strongBuyRatings = [Link](syminfo.recommendations_buy_strong)
string sellRatings = [Link](syminfo.recommendations_sell)
string strongSellRatings = [Link](syminfo.recommendations_sell_strong)
string holdRatings = [Link](syminfo.recommendations_hold)
string totalRatings = [Link](syminfo.recommendations_total)
// Add value cells
[Link](ratings, 0, 1, startDate, bgcolor = [Link], text_color = #000000, text_size = size.l
arge)
[Link](ratings, 1, 1, endDate, bgcolor = [Link], text_color = #000000, text_size = [Link]
ge)
[Link](ratings, 2, 1, buyRatings, bgcolor = [Link], text_color = #000000, text_size = size.
large)
[Link](ratings, 3, 1, strongBuyRatings, bgcolor = [Link], text_color = #000000, text_size
= [Link])
[Link](ratings, 4, 1, sellRatings, bgcolor = [Link], text_color = #000000, text_size = si
[Link])
SEE ALSO
syminfo.recommendations_buy_strong
The number of analysts who gave the current symbol a "Strong Buy" rating.
TYPE
series int
EXAMPLE
//@version=6
indicator("syminfo recommendations", overlay = true)
//@variable A table containing information about analyst recommendations.
var table ratings = [Link](position.top_right, 8, 2, frame_color = #000000)
if [Link]
//@variable The time value one year from the date of the last analyst recommendations.
int YTD = syminfo.target_price_date + timeframe.in_seconds("12M") * 1000
// Add header cells.
[Link](ratings, 0, 0, "Start Date", bgcolor = [Link], text_color = #000000, text_size = siz
[Link])
[Link](ratings, 1, 0, "End Date", bgcolor = [Link], text_color = #000000, text_size = size.
large)
[Link](ratings, 2, 0, "Buy", bgcolor = [Link], text_color = #000000, text_size = [Link]
e)
[Link](ratings, 3, 0, "Strong Buy", bgcolor = [Link], text_color = #000000, text_size = siz
[Link])
[Link](ratings, 4, 0, "Sell", bgcolor = [Link], text_color = #000000, text_size = [Link]
rge)
[Link](ratings, 5, 0, "Strong Sell", bgcolor = [Link], text_color = #000000, text_size = siz
[Link])
[Link](ratings, 6, 0, "Hold", bgcolor = [Link], text_color = #000000, text_size = [Link]
rge)
[Link](ratings, 7, 0, "Total", bgcolor = [Link], text_color = #000000, text_size = size.l
arge)
// Recommendation strings
string startDate = str.format_time(syminfo.recommendations_date, "yyyy-MM-dd")
string endDate = str.format_time(YTD, "yyyy-MM-dd")
string buyRatings = [Link](syminfo.recommendations_buy)
string strongBuyRatings = [Link](syminfo.recommendations_buy_strong)
string sellRatings = [Link](syminfo.recommendations_sell)
string strongSellRatings = [Link](syminfo.recommendations_sell_strong)
string holdRatings = [Link](syminfo.recommendations_hold)
string totalRatings = [Link](syminfo.recommendations_total)
// Add value cells
[Link](ratings, 0, 1, startDate, bgcolor = [Link], text_color = #000000, text_size = size.l
arge)
[Link](ratings, 1, 1, endDate, bgcolor = [Link], text_color = #000000, text_size = [Link]
ge)
[Link](ratings, 2, 1, buyRatings, bgcolor = [Link], text_color = #000000, text_size = size.
large)
[Link](ratings, 3, 1, strongBuyRatings, bgcolor = [Link], text_color = #000000, text_size
= [Link])
[Link](ratings, 4, 1, sellRatings, bgcolor = [Link], text_color = #000000, text_size = si
[Link])
SEE ALSO
syminfo.recommendations_date
The starting date of the last set of recommendations for the current symbol.
TYPE
series int
EXAMPLE
//@version=6
indicator("syminfo recommendations", overlay = true)
//@variable A table containing information about analyst recommendations.
var table ratings = [Link](position.top_right, 8, 2, frame_color = #000000)
if [Link]
//@variable The time value one year from the date of the last analyst recommendations.
int YTD = syminfo.target_price_date + timeframe.in_seconds("12M") * 1000
// Add header cells.
[Link](ratings, 0, 0, "Start Date", bgcolor = [Link], text_color = #000000, text_size = siz
[Link])
[Link](ratings, 1, 0, "End Date", bgcolor = [Link], text_color = #000000, text_size = size.
large)
[Link](ratings, 2, 0, "Buy", bgcolor = [Link], text_color = #000000, text_size = [Link]
e)
[Link](ratings, 3, 0, "Strong Buy", bgcolor = [Link], text_color = #000000, text_size = siz
[Link])
[Link](ratings, 4, 0, "Sell", bgcolor = [Link], text_color = #000000, text_size = [Link]
rge)
[Link](ratings, 5, 0, "Strong Sell", bgcolor = [Link], text_color = #000000, text_size = siz
[Link])
[Link](ratings, 6, 0, "Hold", bgcolor = [Link], text_color = #000000, text_size = [Link]
rge)
[Link](ratings, 7, 0, "Total", bgcolor = [Link], text_color = #000000, text_size = size.l
arge)
// Recommendation strings
string startDate = str.format_time(syminfo.recommendations_date, "yyyy-MM-dd")
string endDate = str.format_time(YTD, "yyyy-MM-dd")
string buyRatings = [Link](syminfo.recommendations_buy)
string strongBuyRatings = [Link](syminfo.recommendations_buy_strong)
string sellRatings = [Link](syminfo.recommendations_sell)
string strongSellRatings = [Link](syminfo.recommendations_sell_strong)
string holdRatings = [Link](syminfo.recommendations_hold)
string totalRatings = [Link](syminfo.recommendations_total)
// Add value cells
[Link](ratings, 0, 1, startDate, bgcolor = [Link], text_color = #000000, text_size = size.l
arge)
[Link](ratings, 1, 1, endDate, bgcolor = [Link], text_color = #000000, text_size = [Link]
ge)
[Link](ratings, 2, 1, buyRatings, bgcolor = [Link], text_color = #000000, text_size = size.
large)
[Link](ratings, 3, 1, strongBuyRatings, bgcolor = [Link], text_color = #000000, text_size
= [Link])
[Link](ratings, 4, 1, sellRatings, bgcolor = [Link], text_color = #000000, text_size = si
[Link])
SEE ALSO
syminfo.recommendations_hold
The number of analysts who gave the current symbol a "Hold" rating.
TYPE
series int
EXAMPLE
//@version=6
indicator("syminfo recommendations", overlay = true)
//@variable A table containing information about analyst recommendations.
var table ratings = [Link](position.top_right, 8, 2, frame_color = #000000)
if [Link]
//@variable The time value one year from the date of the last analyst recommendations.
int YTD = syminfo.target_price_date + timeframe.in_seconds("12M") * 1000
// Add header cells.
[Link](ratings, 0, 0, "Start Date", bgcolor = [Link], text_color = #000000, text_size = siz
[Link])
[Link](ratings, 1, 0, "End Date", bgcolor = [Link], text_color = #000000, text_size = size.
large)
[Link](ratings, 2, 0, "Buy", bgcolor = [Link], text_color = #000000, text_size = [Link]
e)
[Link](ratings, 3, 0, "Strong Buy", bgcolor = [Link], text_color = #000000, text_size = siz
[Link])
[Link](ratings, 4, 0, "Sell", bgcolor = [Link], text_color = #000000, text_size = [Link]
rge)
[Link](ratings, 5, 0, "Strong Sell", bgcolor = [Link], text_color = #000000, text_size = siz
[Link])
[Link](ratings, 6, 0, "Hold", bgcolor = [Link], text_color = #000000, text_size = [Link]
rge)
[Link](ratings, 7, 0, "Total", bgcolor = [Link], text_color = #000000, text_size = size.l
arge)
// Recommendation strings
string startDate = str.format_time(syminfo.recommendations_date, "yyyy-MM-dd")
string endDate = str.format_time(YTD, "yyyy-MM-dd")
string buyRatings = [Link](syminfo.recommendations_buy)
string strongBuyRatings = [Link](syminfo.recommendations_buy_strong)
string sellRatings = [Link](syminfo.recommendations_sell)
string strongSellRatings = [Link](syminfo.recommendations_sell_strong)
string holdRatings = [Link](syminfo.recommendations_hold)
string totalRatings = [Link](syminfo.recommendations_total)
// Add value cells
[Link](ratings, 0, 1, startDate, bgcolor = [Link], text_color = #000000, text_size = size.l
arge)
[Link](ratings, 1, 1, endDate, bgcolor = [Link], text_color = #000000, text_size = [Link]
ge)
[Link](ratings, 2, 1, buyRatings, bgcolor = [Link], text_color = #000000, text_size = size.
large)
[Link](ratings, 3, 1, strongBuyRatings, bgcolor = [Link], text_color = #000000, text_size
= [Link])
[Link](ratings, 4, 1, sellRatings, bgcolor = [Link], text_color = #000000, text_size = si
[Link])
SEE ALSO
syminfo.recommendations_sell
The number of analysts who gave the current symbol a "Sell" rating.
TYPE
series int
EXAMPLE
//@version=6
indicator("syminfo recommendations", overlay = true)
//@variable A table containing information about analyst recommendations.
var table ratings = [Link](position.top_right, 8, 2, frame_color = #000000)
if [Link]
//@variable The time value one year from the date of the last analyst recommendations.
int YTD = syminfo.target_price_date + timeframe.in_seconds("12M") * 1000
// Add header cells.
[Link](ratings, 0, 0, "Start Date", bgcolor = [Link], text_color = #000000, text_size = siz
[Link])
[Link](ratings, 1, 0, "End Date", bgcolor = [Link], text_color = #000000, text_size = size.
large)
[Link](ratings, 2, 0, "Buy", bgcolor = [Link], text_color = #000000, text_size = [Link]
e)
[Link](ratings, 3, 0, "Strong Buy", bgcolor = [Link], text_color = #000000, text_size = siz
[Link])
[Link](ratings, 4, 0, "Sell", bgcolor = [Link], text_color = #000000, text_size = [Link]
rge)
[Link](ratings, 5, 0, "Strong Sell", bgcolor = [Link], text_color = #000000, text_size = siz
[Link])
[Link](ratings, 6, 0, "Hold", bgcolor = [Link], text_color = #000000, text_size = [Link]
rge)
[Link](ratings, 7, 0, "Total", bgcolor = [Link], text_color = #000000, text_size = size.l
arge)
// Recommendation strings
string startDate = str.format_time(syminfo.recommendations_date, "yyyy-MM-dd")
string endDate = str.format_time(YTD, "yyyy-MM-dd")
string buyRatings = [Link](syminfo.recommendations_buy)
string strongBuyRatings = [Link](syminfo.recommendations_buy_strong)
string sellRatings = [Link](syminfo.recommendations_sell)
string strongSellRatings = [Link](syminfo.recommendations_sell_strong)
string holdRatings = [Link](syminfo.recommendations_hold)
string totalRatings = [Link](syminfo.recommendations_total)
// Add value cells
[Link](ratings, 0, 1, startDate, bgcolor = [Link], text_color = #000000, text_size = size.l
arge)
[Link](ratings, 1, 1, endDate, bgcolor = [Link], text_color = #000000, text_size = [Link]
ge)
[Link](ratings, 2, 1, buyRatings, bgcolor = [Link], text_color = #000000, text_size = size.
large)
[Link](ratings, 3, 1, strongBuyRatings, bgcolor = [Link], text_color = #000000, text_size
= [Link])
[Link](ratings, 4, 1, sellRatings, bgcolor = [Link], text_color = #000000, text_size = si
[Link])
SEE ALSO
syminfo.recommendations_sell_strong
The number of analysts who gave the current symbol a "Strong Sell" rating.
TYPE
series int
EXAMPLE
//@version=6
indicator("syminfo recommendations", overlay = true)
//@variable A table containing information about analyst recommendations.
var table ratings = [Link](position.top_right, 8, 2, frame_color = #000000)
if [Link]
//@variable The time value one year from the date of the last analyst recommendations.
int YTD = syminfo.target_price_date + timeframe.in_seconds("12M") * 1000
// Add header cells.
[Link](ratings, 0, 0, "Start Date", bgcolor = [Link], text_color = #000000, text_size = siz
[Link])
[Link](ratings, 1, 0, "End Date", bgcolor = [Link], text_color = #000000, text_size = size.
large)
[Link](ratings, 2, 0, "Buy", bgcolor = [Link], text_color = #000000, text_size = [Link]
e)
[Link](ratings, 3, 0, "Strong Buy", bgcolor = [Link], text_color = #000000, text_size = siz
[Link])
[Link](ratings, 4, 0, "Sell", bgcolor = [Link], text_color = #000000, text_size = [Link]
rge)
[Link](ratings, 5, 0, "Strong Sell", bgcolor = [Link], text_color = #000000, text_size = siz
[Link])
[Link](ratings, 6, 0, "Hold", bgcolor = [Link], text_color = #000000, text_size = [Link]
rge)
[Link](ratings, 7, 0, "Total", bgcolor = [Link], text_color = #000000, text_size = size.l
arge)
// Recommendation strings
string startDate = str.format_time(syminfo.recommendations_date, "yyyy-MM-dd")
string endDate = str.format_time(YTD, "yyyy-MM-dd")
string buyRatings = [Link](syminfo.recommendations_buy)
string strongBuyRatings = [Link](syminfo.recommendations_buy_strong)
string sellRatings = [Link](syminfo.recommendations_sell)
string strongSellRatings = [Link](syminfo.recommendations_sell_strong)
string holdRatings = [Link](syminfo.recommendations_hold)
string totalRatings = [Link](syminfo.recommendations_total)
// Add value cells
[Link](ratings, 0, 1, startDate, bgcolor = [Link], text_color = #000000, text_size = size.l
arge)
[Link](ratings, 1, 1, endDate, bgcolor = [Link], text_color = #000000, text_size = [Link]
ge)
[Link](ratings, 2, 1, buyRatings, bgcolor = [Link], text_color = #000000, text_size = size.
large)
[Link](ratings, 3, 1, strongBuyRatings, bgcolor = [Link], text_color = #000000, text_size
= [Link])
[Link](ratings, 4, 1, sellRatings, bgcolor = [Link], text_color = #000000, text_size = si
[Link])
SEE ALSO
syminfo.recommendations_buy syminfo.recommendations_buy_strong syminfo.recommendations_date
syminfo.recommendations_total
The total number of recommendations for the current symbol.
TYPE
series int
EXAMPLE
//@version=6
indicator("syminfo recommendations", overlay = true)
//@variable A table containing information about analyst recommendations.
var table ratings = [Link](position.top_right, 8, 2, frame_color = #000000)
if [Link]
//@variable The time value one year from the date of the last analyst recommendations.
int YTD = syminfo.target_price_date + timeframe.in_seconds("12M") * 1000
// Add header cells.
[Link](ratings, 0, 0, "Start Date", bgcolor = [Link], text_color = #000000, text_size = siz
[Link])
[Link](ratings, 1, 0, "End Date", bgcolor = [Link], text_color = #000000, text_size = size.
large)
[Link](ratings, 2, 0, "Buy", bgcolor = [Link], text_color = #000000, text_size = [Link]
e)
[Link](ratings, 3, 0, "Strong Buy", bgcolor = [Link], text_color = #000000, text_size = siz
[Link])
[Link](ratings, 4, 0, "Sell", bgcolor = [Link], text_color = #000000, text_size = [Link]
rge)
[Link](ratings, 5, 0, "Strong Sell", bgcolor = [Link], text_color = #000000, text_size = siz
[Link])
[Link](ratings, 6, 0, "Hold", bgcolor = [Link], text_color = #000000, text_size = [Link]
rge)
[Link](ratings, 7, 0, "Total", bgcolor = [Link], text_color = #000000, text_size = size.l
arge)
// Recommendation strings
string startDate = str.format_time(syminfo.recommendations_date, "yyyy-MM-dd")
string endDate = str.format_time(YTD, "yyyy-MM-dd")
string buyRatings = [Link](syminfo.recommendations_buy)
string strongBuyRatings = [Link](syminfo.recommendations_buy_strong)
string sellRatings = [Link](syminfo.recommendations_sell)
string strongSellRatings = [Link](syminfo.recommendations_sell_strong)
string holdRatings = [Link](syminfo.recommendations_hold)
string totalRatings = [Link](syminfo.recommendations_total)
// Add value cells
[Link](ratings, 0, 1, startDate, bgcolor = [Link], text_color = #000000, text_size = size.l
arge)
[Link](ratings, 1, 1, endDate, bgcolor = [Link], text_color = #000000, text_size = [Link]
ge)
[Link](ratings, 2, 1, buyRatings, bgcolor = [Link], text_color = #000000, text_size = size.
large)
[Link](ratings, 3, 1, strongBuyRatings, bgcolor = [Link], text_color = #000000, text_size
= [Link])
[Link](ratings, 4, 1, sellRatings, bgcolor = [Link], text_color = #000000, text_size = si
[Link])
SEE ALSO
[Link]
Root for derivatives like futures contract. For other symbols returns the same value as [Link].
TYPE
simple string
EXAMPLE
//@version=6
indicator("[Link]")
// If the current chart symbol is continuous futures ('ES1!'), it would display 'ES'.
if [Link]
[Link](bar_index, high, [Link])
SEE ALSO
[Link] [Link]
[Link]
Returns the sector of the symbol, or na if the symbol has no sector. Example: "Electronic Technology", "Technology
services", "Energy Minerals", "Consumer Durables", etc. These are the same values one can see in the chart's "Symbol
info" window.
TYPE
simple string
REMARKS
A sector is a broad section of the economy. An industry is a narrower classification. NASDAQ:CAT (Caterpillar, Inc.) for
example, belongs to the "Producer Manufacturing" sector and the "Trucks/Construction/Farm Machinery" industry.
[Link]
Session type of the chart main series. Possible values are [Link], [Link].
TYPE
simple string
SEE ALSO
[Link] [Link]
[Link]
The number of shareholders the company has.
TYPE
simple int
EXAMPLE
//@version=6
indicator("syminfo simple")
//@variable A table containing information about a company's employees, shareholders, and shares.
var result_table = [Link](position = position.top_right, columns = 2, rows = 5, border_width = 1)
if [Link]
// Add header cells
[Link](table_id = result_table, column = 0, row = 0, text = "name")
[Link](table_id = result_table, column = 1, row = 0, text = "value")
// Add employee info cells.
[Link](table_id = result_table, column = 0, row = 1, text = "employees")
[Link](table_id = result_table, column = 1, row = 1, text = [Link]([Link]))
// Add shareholder cells.
[Link](table_id = result_table, column = 0, row = 2, text = "shareholders")
[Link](table_id = result_table, column = 1, row = 2, text = [Link]([Link]))
// Add float shares outstanding cells.
[Link](table_id = result_table, column = 0, row = 3, text = "shares_outstanding_float")
[Link](table_id = result_table, column = 1, row = 3, text = [Link](syminfo.shares_outstan
ding_float))
// Add total shares outstanding cells.
[Link](table_id = result_table, column = 0, row = 4, text = "shares_outstanding_total")
[Link](table_id = result_table, column = 1, row = 4, text = [Link](syminfo.shares_outstan
ding_total))
SEE ALSO
syminfo.shares_outstanding_float
The total number of shares outstanding a company has available, excluding any of its restricted shares.
TYPE
simple float
EXAMPLE
//@version=6
indicator("syminfo simple")
//@variable A table containing information about a company's employees, shareholders, and shares.
var result_table = [Link](position = position.top_right, columns = 2, rows = 5, border_width = 1)
if [Link]
// Add header cells
[Link](table_id = result_table, column = 0, row = 0, text = "name")
[Link](table_id = result_table, column = 1, row = 0, text = "value")
// Add employee info cells.
[Link](table_id = result_table, column = 0, row = 1, text = "employees")
[Link](table_id = result_table, column = 1, row = 1, text = [Link]([Link]))
// Add shareholder cells.
[Link](table_id = result_table, column = 0, row = 2, text = "shareholders")
[Link](table_id = result_table, column = 1, row = 2, text = [Link]([Link]))
// Add float shares outstanding cells.
[Link](table_id = result_table, column = 0, row = 3, text = "shares_outstanding_float")
[Link](table_id = result_table, column = 1, row = 3, text = [Link](syminfo.shares_outstan
ding_float))
// Add total shares outstanding cells.
[Link](table_id = result_table, column = 0, row = 4, text = "shares_outstanding_total")
[Link](table_id = result_table, column = 1, row = 4, text = [Link](syminfo.shares_outstan
ding_total))
SEE ALSO
syminfo.shares_outstanding_total
The total number of shares outstanding a company has available, including restricted shares held by insiders, major
shareholders, and employees.
TYPE
simple int
EXAMPLE
//@version=6
indicator("syminfo simple")
//@variable A table containing information about a company's employees, shareholders, and shares.
var result_table = [Link](position = position.top_right, columns = 2, rows = 5, border_width = 1)
if [Link]
// Add header cells
[Link](table_id = result_table, column = 0, row = 0, text = "name")
[Link](table_id = result_table, column = 1, row = 0, text = "value")
// Add employee info cells.
[Link](table_id = result_table, column = 0, row = 1, text = "employees")
[Link](table_id = result_table, column = 1, row = 1, text = [Link]([Link]))
// Add shareholder cells.
[Link](table_id = result_table, column = 0, row = 2, text = "shareholders")
[Link](table_id = result_table, column = 1, row = 2, text = [Link]([Link]))
// Add float shares outstanding cells.
[Link](table_id = result_table, column = 0, row = 3, text = "shares_outstanding_float")
[Link](table_id = result_table, column = 1, row = 3, text = [Link](syminfo.shares_outstan
ding_float))
// Add total shares outstanding cells.
[Link](table_id = result_table, column = 0, row = 4, text = "shares_outstanding_total")
[Link](table_id = result_table, column = 1, row = 4, text = [Link](syminfo.shares_outstan
ding_total))
SEE ALSO
syminfo.target_price_average
The average of the last yearly price targets for the symbol predicted by analysts.
TYPE
series float
EXAMPLE
//@version=6
indicator("syminfo target_price")
if [Link]
//@variable The time value one year from the date of the last analyst recommendations.
int YTD = syminfo.target_price_date + timeframe.in_seconds("12M") * 1000
//@variable A line connecting the current `close` to the highest yearly price estimate.
highLine = [Link](time, close, YTD, syminfo.target_price_high, color = [Link], xloc = xloc.b
ar_time)
//@variable A line connecting the current `close` to the lowest yearly price estimate.
lowLine = [Link](time, close, YTD, syminfo.target_price_low, color = [Link], xloc = xloc.bar_t
ime)
//@variable A line connecting the current `close` to the median yearly price estimate.
medianLine = [Link](time, close, YTD, syminfo.target_price_median, color = [Link], xloc = xlo
c.bar_time)
//@variable A line connecting the current `close` to the average yearly price estimate.
averageLine = [Link](time, close, YTD, syminfo.target_price_average, color = [Link], xloc
= xloc.bar_time)
// Fill the space between targets
[Link](lowLine, medianLine, [Link]([Link], 90))
[Link](medianLine, highLine, [Link]([Link], 90))
// Create a label displaying the total number of analyst estimates.
string estimatesText = [Link]("Number of estimates: {0}", syminfo.target_price_estimates)
[Link](bar_index, close, estimatesText, textcolor = [Link], size = [Link])
REMARKS
If analysts supply the targets when the market is closed, the variable can return na until the market opens.
SEE ALSO
syminfo.target_price_median
syminfo.target_price_date
The starting date of the last price target prediction for the current symbol.
TYPE
series int
EXAMPLE
//@version=6
indicator("syminfo target_price")
if [Link]
//@variable The time value one year from the date of the last analyst recommendations.
int YTD = syminfo.target_price_date + timeframe.in_seconds("12M") * 1000
//@variable A line connecting the current `close` to the highest yearly price estimate.
highLine = [Link](time, close, YTD, syminfo.target_price_high, color = [Link], xloc = xloc.b
ar_time)
//@variable A line connecting the current `close` to the lowest yearly price estimate.
lowLine = [Link](time, close, YTD, syminfo.target_price_low, color = [Link], xloc = xloc.bar_t
ime)
//@variable A line connecting the current `close` to the median yearly price estimate.
medianLine = [Link](time, close, YTD, syminfo.target_price_median, color = [Link], xloc = xlo
c.bar_time)
//@variable A line connecting the current `close` to the average yearly price estimate.
averageLine = [Link](time, close, YTD, syminfo.target_price_average, color = [Link], xloc
= xloc.bar_time)
// Fill the space between targets
[Link](lowLine, medianLine, [Link]([Link], 90))
[Link](medianLine, highLine, [Link]([Link], 90))
// Create a label displaying the total number of analyst estimates.
string estimatesText = [Link]("Number of estimates: {0}", syminfo.target_price_estimates)
[Link](bar_index, close, estimatesText, textcolor = [Link], size = [Link])
REMARKS
If analysts supply the targets when the market is closed, the variable can return na until the market opens.
SEE ALSO
syminfo.target_price_median
syminfo.target_price_estimates
The latest total number of price target predictions for the current symbol.
TYPE
series float
EXAMPLE
//@version=6
indicator("syminfo target_price")
if [Link]
//@variable The time value one year from the date of the last analyst recommendations.
int YTD = syminfo.target_price_date + timeframe.in_seconds("12M") * 1000
//@variable A line connecting the current `close` to the highest yearly price estimate.
highLine = [Link](time, close, YTD, syminfo.target_price_high, color = [Link], xloc = xloc.b
ar_time)
//@variable A line connecting the current `close` to the lowest yearly price estimate.
lowLine = [Link](time, close, YTD, syminfo.target_price_low, color = [Link], xloc = xloc.bar_t
ime)
//@variable A line connecting the current `close` to the median yearly price estimate.
medianLine = [Link](time, close, YTD, syminfo.target_price_median, color = [Link], xloc = xlo
c.bar_time)
//@variable A line connecting the current `close` to the average yearly price estimate.
averageLine = [Link](time, close, YTD, syminfo.target_price_average, color = [Link], xloc
= xloc.bar_time)
// Fill the space between targets
[Link](lowLine, medianLine, [Link]([Link], 90))
[Link](medianLine, highLine, [Link]([Link], 90))
// Create a label displaying the total number of analyst estimates.
string estimatesText = [Link]("Number of estimates: {0}", syminfo.target_price_estimates)
[Link](bar_index, close, estimatesText, textcolor = [Link], size = [Link])
REMARKS
If analysts supply the targets when the market is closed, the variable can return na until the market opens.
SEE ALSO
syminfo.target_price_median
syminfo.target_price_high
The last highest yearly price target for the symbol predicted by analysts.
TYPE
series float
EXAMPLE
//@version=6
indicator("syminfo target_price")
if [Link]
//@variable The time value one year from the date of the last analyst recommendations.
int YTD = syminfo.target_price_date + timeframe.in_seconds("12M") * 1000
//@variable A line connecting the current `close` to the highest yearly price estimate.
highLine = [Link](time, close, YTD, syminfo.target_price_high, color = [Link], xloc = xloc.b
ar_time)
//@variable A line connecting the current `close` to the lowest yearly price estimate.
lowLine = [Link](time, close, YTD, syminfo.target_price_low, color = [Link], xloc = xloc.bar_t
ime)
//@variable A line connecting the current `close` to the median yearly price estimate.
medianLine = [Link](time, close, YTD, syminfo.target_price_median, color = [Link], xloc = xlo
c.bar_time)
//@variable A line connecting the current `close` to the average yearly price estimate.
averageLine = [Link](time, close, YTD, syminfo.target_price_average, color = [Link], xloc
= xloc.bar_time)
// Fill the space between targets
[Link](lowLine, medianLine, [Link]([Link], 90))
[Link](medianLine, highLine, [Link]([Link], 90))
// Create a label displaying the total number of analyst estimates.
string estimatesText = [Link]("Number of estimates: {0}", syminfo.target_price_estimates)
[Link](bar_index, close, estimatesText, textcolor = [Link], size = [Link])
REMARKS
If analysts supply the targets when the market is closed, the variable can return na until the market opens.
SEE ALSO
syminfo.target_price_median
syminfo.target_price_low
The last lowest yearly price target for the symbol predicted by analysts.
TYPE
series float
EXAMPLE
//@version=6
indicator("syminfo target_price")
if [Link]
//@variable The time value one year from the date of the last analyst recommendations.
int YTD = syminfo.target_price_date + timeframe.in_seconds("12M") * 1000
//@variable A line connecting the current `close` to the highest yearly price estimate.
highLine = [Link](time, close, YTD, syminfo.target_price_high, color = [Link], xloc = xloc.b
ar_time)
//@variable A line connecting the current `close` to the lowest yearly price estimate.
lowLine = [Link](time, close, YTD, syminfo.target_price_low, color = [Link], xloc = xloc.bar_t
ime)
//@variable A line connecting the current `close` to the median yearly price estimate.
medianLine = [Link](time, close, YTD, syminfo.target_price_median, color = [Link], xloc = xlo
c.bar_time)
//@variable A line connecting the current `close` to the average yearly price estimate.
averageLine = [Link](time, close, YTD, syminfo.target_price_average, color = [Link], xloc
= xloc.bar_time)
// Fill the space between targets
[Link](lowLine, medianLine, [Link]([Link], 90))
[Link](medianLine, highLine, [Link]([Link], 90))
// Create a label displaying the total number of analyst estimates.
string estimatesText = [Link]("Number of estimates: {0}", syminfo.target_price_estimates)
[Link](bar_index, close, estimatesText, textcolor = [Link], size = [Link])
REMARKS
If analysts supply the targets when the market is closed, the variable can return na until the market opens.
SEE ALSO
syminfo.target_price_median
syminfo.target_price_median
The median of the last yearly price targets for the symbol predicted by analysts.
TYPE
series float
EXAMPLE
//@version=6
indicator("syminfo target_price")
if [Link]
//@variable The time value one year from the date of the last analyst recommendations.
int YTD = syminfo.target_price_date + timeframe.in_seconds("12M") * 1000
//@variable A line connecting the current `close` to the highest yearly price estimate.
highLine = [Link](time, close, YTD, syminfo.target_price_high, color = [Link], xloc = xloc.b
ar_time)
//@variable A line connecting the current `close` to the lowest yearly price estimate.
lowLine = [Link](time, close, YTD, syminfo.target_price_low, color = [Link], xloc = xloc.bar_t
ime)
//@variable A line connecting the current `close` to the median yearly price estimate.
medianLine = [Link](time, close, YTD, syminfo.target_price_median, color = [Link], xloc = xlo
c.bar_time)
//@variable A line connecting the current `close` to the average yearly price estimate.
averageLine = [Link](time, close, YTD, syminfo.target_price_average, color = [Link], xloc
= xloc.bar_time)
// Fill the space between targets
[Link](lowLine, medianLine, [Link]([Link], 90))
[Link](medianLine, highLine, [Link]([Link], 90))
// Create a label displaying the total number of analyst estimates.
string estimatesText = [Link]("Number of estimates: {0}", syminfo.target_price_estimates)
[Link](bar_index, close, estimatesText, textcolor = [Link], size = [Link])
REMARKS
If analysts supply the targets when the market is closed, the variable can return na until the market opens.
SEE ALSO
syminfo.target_price_low
[Link]
Symbol name without exchange prefix, e.g. 'MSFT'.
TYPE
simple string
SEE ALSO
[Link]
A ticker identifier representing the chart's symbol or a requested symbol, depending on how the script uses it. The
variable's value represents a requested dataset's ticker ID when used in the expression argument of a reques
t.*() function call. Otherwise, it represents the chart's ticker ID. The value contains an exchange prefix and a
symbol name, separated by a colon (e.g., "NASDAQ:AAPL"). It can also include information about data modifications
such as dividend adjustment, non-standard chart type, currency conversion, etc.
TYPE
simple string
REMARKS
Because the value of this variable does not always use a simple "prefix:ticker" format, it is a poor candidate for use in
boolean comparisons or string manipulation functions. In those contexts, run the variable's result through
[Link]() to purify it. This will remove any extraneous information and return a ticker ID consistently formatted
using the "prefix:ticker" structure.
To always access the script's main ticker ID, even within another context, use the syminfo.main_tickerid variable.
SEE ALSO
[Link]
[Link]
Timezone of the exchange of the chart main series. Possible values see in timestamp().
TYPE
simple string
SEE ALSO
timestamp()
[Link]
The type of market the symbol belongs to. The values are "stock", "fund", "dr", "right", "bond", "warrant", "structured",
"index", "forex", "futures", "spread", "economic", "fundamental", "crypto", "spot", "swap", "option", "commodity".
TYPE
simple string
SEE ALSO
[Link]
[Link]
Volume type of the current symbol. Possible values are: "base" for base currency, "quote" for quote currency, "tick"
for the number of transactions, and "n/a" when there is no volume or its type is not specified.
TYPE
simple string
REMARKS
Only some data feed suppliers provide information qualifying volume. As a result, the variable will return a value on
some symbols only, mostly in the crypto sector.
SEE ALSO
[Link]
[Link]
Accumulation/distribution index.
TYPE
series float
[Link]
Intraday Intensity Index.
TYPE
series float
EXAMPLE
//@version=6
indicator("Intraday Intensity Index")
plot([Link], color=[Link])
plot(f_iii())
[Link]
Negative Volume Index.
TYPE
series float
EXAMPLE
//@version=6
indicator("Negative Volume Index")
plot([Link], color=[Link])
plot(f_nvi())
[Link]
On Balance Volume.
TYPE
series float
EXAMPLE
//@version=6
indicator("On Balance Volume")
plot([Link], color=[Link])
plot(f_obv())
[Link]
Positive Volume Index.
TYPE
series float
EXAMPLE
//@version=6
indicator("Positive Volume Index")
plot([Link], color=[Link])
plot(f_pvi())
[Link]
Price-Volume Trend.
TYPE
series float
EXAMPLE
//@version=6
indicator("Price-Volume Trend")
plot([Link], color=[Link])
plot(f_pvt())
[Link]
True range, equivalent to [Link](handle_na = false) . It is calculated as [Link](high - low, [Link]
s(high - close[1]), [Link](low - close[1])) .
TYPE
series float
SEE ALSO
[Link]() [Link]()
[Link]
Volume Weighted Average Price. It uses hlc3 as its source series.
TYPE
series float
SEE ALSO
[Link]()
[Link]
Williams Accumulation/Distribution.
TYPE
series float
EXAMPLE
//@version=6
indicator("Williams Accumulation/Distribution")
plot([Link], color=[Link])
plot(f_wad())
[Link]
Williams Variable Accumulation/Distribution.
TYPE
series float
EXAMPLE
//@version=6
indicator("Williams Variable Accumulation/Distribution")
plot([Link], color=[Link])
plot(f_wvad())
[Link]
Returns an array filled with all the current tables drawn by the script.
TYPE
array<table>
EXAMPLE
//@version=6
indicator("[Link]")
//delete all tables
[Link](position = position.top_right, columns = 2, rows = 1, bgcolor = [Link], border_width =
1)
a_allTables = [Link]
if [Link](a_allTables) > 0
for i = 0 to [Link](a_allTables) - 1
[Link]([Link](a_allTables, i))
REMARKS
The array is read-only. Index zero of the array is the ID of the oldest object on the chart.
SEE ALSO
time
Current bar time in UNIX format. It is the number of milliseconds that have elapsed since 00:00:00 UTC, 1 January
1970.
TYPE
series int
REMARKS
Note that this variable returns the timestamp based on the time of the bar's open. Because of that, for overnight
sessions (e.g. EURUSD, where Monday session starts on Sunday, 17:00) this variable can return time before the
specified date of the trading day. For example, on EURUSD, dayofmonth(time) can be lower by 1 than the date of
the trading day, because the bar for the current day actually opens one day prior.
SEE ALSO
time() time_close timenow year month weekofyear dayofmonth dayofweek hour minute second
time_close
The time of the current bar's close in UNIX format. It represents the number of milliseconds elapsed since 00:00:00
UTC, 1 January 1970. On tick charts and price-based charts such as Renko, line break, Kagi, point & figure, and range,
this variable's series holds an na timestamp for the latest realtime bar (because the future closing time is
unpredictable), but valid timestamps for all previous bars.
TYPE
series int
SEE ALSO
time timenow year month weekofyear dayofmonth dayofweek hour minute second
time_tradingday
The timestamp that represents 00:00 UTC of the trading day the current bar belongs to, in UNIX format (the number of
milliseconds that have elapsed since 00:00:00 UTC, 1 January 1970).
TYPE
series int
EXAMPLE
//@version=6
indicator("Friday session")
REMARKS
This variable is helpful when working with overnight sessions, where the day's session can begin on the previous
calendar day. For example, on the "FXCM:EURUSD" symbol, the Monday session starts on Sunday, 17:00, exchange
time. Unlike time , which returns the timestamp for Sunday at 17:00 on the Monday daily bar, time_tradingday
returns the timestamp for Monday at 00:00 UTC. When used on timeframes higher than "1D", time_tradingday
returns the timestamp of the last trading day inside that bar (e.g., on "1W", it returns the timestamp of the final trading
day within the week).
SEE ALSO
time time_close
[Link]
Returns true if current resolution is a daily resolution, false otherwise.
TYPE
simple bool
SEE ALSO
[Link] [Link]
[Link]
Returns true if current resolution is a daily or weekly or monthly resolution, false otherwise.
TYPE
simple bool
SEE ALSO
[Link] [Link]
[Link]
Returns true if current resolution is an intraday (minutes or seconds) resolution, false otherwise.
TYPE
simple bool
SEE ALSO
[Link]
[Link]
Returns true if current resolution is a minutes resolution, false otherwise.
TYPE
simple bool
SEE ALSO
[Link]
[Link]
Returns true if current resolution is a monthly resolution, false otherwise.
TYPE
simple bool
SEE ALSO
[Link] [Link]
[Link]
Returns true if current resolution is a seconds resolution, false otherwise.
TYPE
simple bool
SEE ALSO
[Link]
[Link]
Returns true if current resolution is a ticks resolution, false otherwise.
TYPE
simple bool
SEE ALSO
[Link] [Link]
[Link]
Returns true if current resolution is a weekly resolution, false otherwise.
TYPE
simple bool
SEE ALSO
[Link] [Link]
timeframe.main_period
A string representation of the script's main timeframe. If the script is an indicator() that specifies a timeframe value
in its declaration statement, this variable holds that value. Otherwise, its value represents the chart's timeframe. Unlike
[Link], this variable's value does not change when used in the expression argument of a request.*
() function call.
The string's format is "<quantity>[<unit>]", where <unit> is "T" for ticks, "S" for seconds, "D" for days, "W" for weeks,
and "M" for months, but is absent for minutes. No <unit> exists for hours: hourly timeframes are expressed in minutes.
The variable's value is: "10S" for 10 seconds, "30" for 30 minutes, "240" for four hours, "1D" for one day, "2W" for
two weeks, and "3M" for one quarter.
TYPE
simple string
SEE ALSO
[Link]
Multiplier of resolution, e.g. '60' - 60, 'D' - 1, '5D' - 5, '12M' - 12.
TYPE
simple int
SEE ALSO
[Link]
A string representation of the script's main timeframe or a requested timeframe, depending on how the script uses it.
The variable's value represents the timeframe of a requested dataset when used in the expression argument of a
request.*() function call. Otherwise, its value represents the script's main timeframe (timeframe.main_period),
which equals either the timeframe argument of the indicator() declaration statement or the chart's timeframe.
The string's format is "<quantity>[<unit>]", where <unit> is "T" for ticks, "S" for seconds, "D" for days, "W" for weeks,
and "M" for months, but is absent for minutes. No <unit> exists for hours: hourly timeframes are expressed in minutes.
The variable's value is: "10S" for 10 seconds, "30" for 30 minutes, "240" for four hours, "1D" for one day, "2W" for
two weeks, and "3M" for one quarter.
TYPE
simple string
REMARKS
To always access the script's main timeframe, even within another context, use the timeframe.main_period variable.
SEE ALSO
timenow
Current time in UNIX format. It is the number of milliseconds that have elapsed since 00:00:00 UTC, 1 January 1970.
TYPE
series int
REMARKS
Please note that using this variable/function can cause indicator repainting.
SEE ALSO
timestamp() time time_close year month weekofyear dayofmonth dayofweek hour minute second
volume
Current bar volume.
TYPE
series float
REMARKS
Previous values may be accessed with square brackets operator [], e.g. volume[1], volume[2].
SEE ALSO
open high low close time() hl2 hlc3 hlcc4 ohlc4 ask bid
weekofyear
The week number of the year, in the exchange time zone, calculated from the bar's opening UNIX timestamp.
TYPE
series int
REMARKS
This variable always references the week number corresponding to the bar's opening time. Consequently, for symbols
with overnight sessions (e.g., "EURUSD", where the "Monday" session starts on Sunday at 17:00 in exchange time),
the value may represent a previous calendar week rather than the week of the session's primary trading day.
SEE ALSO
year
Current bar year in exchange timezone.
TYPE
series int
REMARKS
Note that this variable returns the year based on the time of the bar's open. For overnight sessions (e.g. EURUSD,
where Monday session starts on Sunday, 17:00) this value can be lower by 1 than the year of the trading day.
SEE ALSO
Constants
[Link]
Constant for dividends adjustment type (dividends adjustment is applied).
TYPE
const string
SEE ALSO
[Link]
Constant for none adjustment type (no adjustment is applied).
TYPE
const string
SEE ALSO
[Link]
Constant for splits adjustment type (splits adjustment is applied).
TYPE
const string
SEE ALSO
alert.freq_all
A named constant for use with the freq parameter of the alert() function.
TYPE
const string
SEE ALSO
alert()
alert.freq_once_per_bar
A named constant for use with the freq parameter of the alert() function.
The first function call during the bar triggers the alert.
TYPE
const string
SEE ALSO
alert()
alert.freq_once_per_bar_close
A named constant for use with the freq parameter of the alert() function.
The function call triggers the alert only when it occurs during the last script iteration of the real-time bar, when it
closes.
TYPE
const string
SEE ALSO
alert()
[Link]
A constant to specify the value of the backadjustment parameter in [Link]() and [Link]() functions.
TYPE
const backadjustment
SEE ALSO
[Link]
A constant to specify the value of the backadjustment parameter in [Link]() and [Link]() functions.
TYPE
const backadjustment
SEE ALSO
[Link]
A constant to specify the value of the backadjustment parameter in [Link]() and [Link]() functions.
TYPE
const backadjustment
SEE ALSO
barmerge.gaps_off
Merge strategy for requested data. Data is merged continuously without gaps, all the gaps are filled with the previous
nearest existing value.
TYPE
const barmerge_gaps
SEE ALSO
[Link]() barmerge.gaps_on
barmerge.gaps_on
Merge strategy for requested data. Data is merged with possible gaps (na values).
TYPE
const barmerge_gaps
SEE ALSO
[Link]() barmerge.gaps_off
barmerge.lookahead_off
Merge strategy for the requested data position. Requested barset is merged with current barset in the order of sorting
bars by their close time. This merge strategy disables effect of getting data from "future" on calculation on history.
TYPE
const barmerge_lookahead
SEE ALSO
[Link]() barmerge.lookahead_on
barmerge.lookahead_on
Merge strategy for the requested data position. Requested barset is merged with current barset in the order of sorting
bars by their opening time. This merge strategy can lead to undesirable effect of getting data from "future" on
calculation on history. This is unacceptable in backtesting strategies, but can be useful in indicators.
TYPE
const barmerge_lookahead
SEE ALSO
[Link]() barmerge.lookahead_off
[Link]
Is a named constant for #00BCD4 color.
TYPE
const color
SEE ALSO
[Link]
Is a named constant for #363A45 color.
TYPE
const color
SEE ALSO
[Link]
Is a named constant for #2962ff color.
TYPE
const color
SEE ALSO
[Link]
Is a named constant for #E040FB color.
TYPE
const color
SEE ALSO
[Link]
Is a named constant for #787B86 color.
TYPE
const color
SEE ALSO
[Link]
Is a named constant for #4CAF50 color.
TYPE
const color
SEE ALSO
[Link]
Is a named constant for #00E676 color.
TYPE
const color
SEE ALSO
[Link]
Is a named constant for #880E4F color.
TYPE
const color
SEE ALSO
[Link]
Is a named constant for #311B92 color.
TYPE
const color
SEE ALSO
[Link]
Is a named constant for #808000 color.
TYPE
const color
SEE ALSO
[Link]
Is a named constant for #FF9800 color.
TYPE
const color
SEE ALSO
[Link]
Is a named constant for #9C27B0 color.
TYPE
const color
SEE ALSO
[Link]
Is a named constant for #F23645 color.
TYPE
const color
SEE ALSO
[Link]
Is a named constant for #B2B5BE color.
TYPE
const color
SEE ALSO
TYPE
const color
SEE ALSO
[Link]
Is a named constant for #FFFFFF color.
TYPE
const color
SEE ALSO
[Link]
Is a named constant for #FDD835 color.
TYPE
const color
SEE ALSO
[Link]
Arab Emirates Dirham.
TYPE
const string
SEE ALSO
strategy()
[Link]
Argentine Pesos.
TYPE
const string
SEE ALSO
strategy()
[Link]
Australian dollar.
TYPE
const string
SEE ALSO
strategy()
[Link]
Bangladeshi Taka.
TYPE
const string
SEE ALSO
strategy()
[Link]
Bahraini Dinar.
TYPE
const string
SEE ALSO
strategy()
[Link]
Brazilian real.
TYPE
const string
SEE ALSO
strategy()
[Link]
Bitcoin.
TYPE
const string
SEE ALSO
strategy()
[Link]
Canadian dollar.
TYPE
const string
SEE ALSO
strategy()
[Link]
Swiss franc.
TYPE
const string
SEE ALSO
strategy()
[Link]
Chilean Peso.
TYPE
const string
SEE ALSO
strategy()
[Link]
Chinese Yuan.
TYPE
const string
SEE ALSO
strategy()
[Link]
Colombian Peso.
TYPE
const string
SEE ALSO
strategy()
[Link]
Czech Koruna.
TYPE
const string
SEE ALSO
strategy()
[Link]
Danish Krone.
TYPE
const string
SEE ALSO
strategy()
[Link]
Egyptian pound.
TYPE
const string
SEE ALSO
strategy()
[Link]
Ethereum.
TYPE
const string
SEE ALSO
strategy()
[Link]
Euro.
TYPE
const string
SEE ALSO
strategy()
[Link]
Pound sterling.
TYPE
const string
SEE ALSO
strategy()
[Link]
Hong Kong dollar.
TYPE
const string
SEE ALSO
strategy()
[Link]
Hungarian Forint.
TYPE
const string
SEE ALSO
strategy()
[Link]
Indonesian Rupiah.
TYPE
const string
SEE ALSO
strategy()
[Link]
Israeli New Shekel.
TYPE
const string
SEE ALSO
strategy()
[Link]
Indian rupee.
TYPE
const string
SEE ALSO
strategy()
[Link]
Icelandic Krona.
TYPE
const string
SEE ALSO
strategy()
[Link]
Japanese yen.
TYPE
const string
SEE ALSO
strategy()
[Link]
Kenyan Shilling.
TYPE
const string
SEE ALSO
strategy()
[Link]
South Korean won.
TYPE
const string
SEE ALSO
strategy()
[Link]
Kuwaiti Dinar.
TYPE
const string
SEE ALSO
strategy()
[Link]
Sri Lankan Rupee.
TYPE
const string
SEE ALSO
strategy()
[Link]
Moroccan Dirham.
TYPE
const string
SEE ALSO
strategy()
[Link]
Mexican Peso.
TYPE
const string
SEE ALSO
strategy()
[Link]
Malaysian ringgit.
TYPE
const string
SEE ALSO
strategy()
[Link]
Nigerian Naira.
TYPE
const string
SEE ALSO
strategy()
[Link]
Norwegian krone.
TYPE
const string
SEE ALSO
strategy()
[Link]
Unspecified currency.
TYPE
const string
SEE ALSO
strategy()
[Link]
New Zealand dollar.
TYPE
const string
SEE ALSO
strategy()
[Link]
Peruvian sol.
TYPE
const string
SEE ALSO
strategy()
[Link]
Philippine Peso.
TYPE
const string
SEE ALSO
strategy()
[Link]
Pakistani rupee.
TYPE
const string
SEE ALSO
strategy()
[Link]
Polish zloty.
TYPE
const string
SEE ALSO
strategy()
[Link]
Qatari Riyal.
TYPE
const string
SEE ALSO
strategy()
[Link]
Romanian Leu.
TYPE
const string
SEE ALSO
strategy()
[Link]
Serbian Dinar.
TYPE
const string
SEE ALSO
strategy()
[Link]
Russian ruble.
TYPE
const string
SEE ALSO
strategy()
[Link]
Saudi Riyal.
TYPE
const string
SEE ALSO
strategy()
[Link]
Swedish krona.
TYPE
const string
SEE ALSO
strategy()
[Link]
Singapore dollar.
TYPE
const string
SEE ALSO
strategy()
[Link]
Thai Baht.
TYPE
const string
SEE ALSO
strategy()
[Link]
Tunisian Dinar.
TYPE
const string
SEE ALSO
strategy()
[Link]
Turkish lira.
TYPE
const string
SEE ALSO
strategy()
[Link]
New Taiwan Dollar.
TYPE
const string
SEE ALSO
strategy()
[Link]
United States dollar.
TYPE
const string
SEE ALSO
strategy()
[Link]
Tether.
TYPE
const string
SEE ALSO
strategy()
[Link]
Venezuelan Bolivar.
TYPE
const string
SEE ALSO
strategy()
[Link]
Vietnamese Dong.
TYPE
const string
SEE ALSO
strategy()
[Link]
South African rand.
TYPE
const string
SEE ALSO
strategy()
[Link]
Is a named constant for return value of dayofweek() function and value of dayofweek variable.
TYPE
const int
SEE ALSO
[Link] [Link] [Link] [Link] [Link]
[Link]
[Link]
Is a named constant for return value of dayofweek() function and value of dayofweek variable.
TYPE
const int
SEE ALSO
[Link]
[Link]
Is a named constant for return value of dayofweek() function and value of dayofweek variable.
TYPE
const int
SEE ALSO
[Link]
[Link]
Is a named constant for return value of dayofweek() function and value of dayofweek variable.
TYPE
const int
SEE ALSO
[Link]
[Link]
Is a named constant for return value of dayofweek() function and value of dayofweek variable.
TYPE
const int
SEE ALSO
[Link]
[Link]
Is a named constant for return value of dayofweek() function and value of dayofweek variable.
TYPE
const int
SEE ALSO
[Link]
[Link]
Is a named constant for return value of dayofweek() function and value of dayofweek variable.
TYPE
const int
SEE ALSO
[Link]
[Link]
A named constant for use with the display parameter of the plot*() , input*() , fill(), bgcolor(), barcolor(),
and hline() functions. Specifies that the values or visuals appear in all possible locations by default.
TYPE
const plot_simple_display
REMARKS
The display.* constants support + and - operations, enabling custom combinations of display settings. For
example, [Link] - display.data_window specifies that the data for an input or plot appears in all
possible locations except for the Data Window.
Selecting a deselected plot in the script's "Settings/Style" tab changes its display settings, causing the plotted data to
appear in all available chart locations. To restore the display settings coded in the script, select "Reset settings" from
the "Defaults" dropdown menu at the bottom of the "Settings" dialog box.
SEE ALSO
display.data_window
A named constant for use with the display parameter of the plot*() and input*() functions. Specifies that
the values are available in the Data Window by default. The Data Window tab is accessible by clicking the "Object Tree
and Data Window" icon in the chart's right sidebar.
TYPE
const plot_display
REMARKS
The display.* constants support + and - operations, enabling custom combinations of display settings. For
example, display.data_window + display.status_line specifies that the data for an input or plot appears in
the Data Window and the script's status line, and [Link] - display.data_window specifies that the data
appears in all possible locations except for the Data Window.
Selecting a deselected plot in the script's "Settings/Style" tab changes its display settings, causing the plotted data to
appear in all available chart locations. To restore the display settings coded in the script, select "Reset settings" from
the "Defaults" dropdown menu at the bottom of the "Settings" dialog box.
SEE ALSO
plot() plotshape() plotchar() plotarrow() plotbar() plotcandle()
[Link]
A named constant for use with the display parameter of the plot*() , input*() , fill(), bgcolor(), barcolor(),
and hline() functions. Specifies that the values or visuals are not displayed anywhere by default.
TYPE
const plot_simple_display
REMARKS
Selecting a deselected plot in the script's "Settings/Style" tab changes its display settings, causing the plotted data to
appear in all available chart locations. To restore the display settings coded in the script, select "Reset settings" from
the "Defaults" dropdown menu at the bottom of the "Settings" dialog box.
SEE ALSO
[Link]
A named constant for use with the display parameter of the plot*() functions. Specifies that the plotted values
are displayed in a chart pane by default.
TYPE
const plot_display
REMARKS
The display.* constants support + and - operations, enabling custom combinations of display settings. For
example, [Link] + display.data_window specifies that the plot's values appear in the chart pane and
the Data Window, and [Link] - [Link] specifies that the values appear in all possible locations
except for the chart pane.
Selecting a deselected plot in the script's "Settings/Style" tab changes its display settings, causing the plotted data to
appear in all available chart locations. To restore the display settings coded in the script, select "Reset settings" from
the "Defaults" dropdown menu at the bottom of the "Settings" dialog box.
SEE ALSO
display.pine_screener
A named constant for use with the display parameter of the plot() function. Specifies that, by default, the Pine
Screener displays a column for the plot's values when the user applies the indicator to the chosen watchlist.
TYPE
const plot_display
REMARKS
The display.* constants support + and - operations, enabling custom combinations of display settings. For
example, display.data_window + display.pine_screener specifies that the plotted values appear in the
Data Window and the Pine Screener, and [Link] - display.pine_screener specifies that the values
appear in all possible locations except for the Pine Screener.
The Pine Screener displays columns for only the first 10 enabled plots from a script by default. If a plot's default
display settings do not include the screener, or if the screener already shows columns for 10 other plots from the
script, users can configure the screener to show a column for the plot by using the "Manage columns" menu at the far
right of the table header.
SEE ALSO
display.price_scale
A named constant for use with the display parameter of the plot*() functions. Specifies that the price scale
displays a label for the plot's data, but only if the chart's settings allow it.
TYPE
const plot_display
REMARKS
The display.* constants support + and - operations, enabling custom combinations of display settings. For
example, display.price_scale + display.data_window specifies that the plot's data appears on the price
scale and in the Data Window, and [Link] - display.price_scale specifies that the data appears in all
possible locations except for the price scale.
Selecting a deselected plot in the script's "Settings/Style" tab changes its display settings, causing the plotted data to
appear in all available chart locations. To restore the display settings coded in the script, select "Reset settings" from
the "Defaults" dropdown menu at the bottom of the "Settings" dialog box.
SEE ALSO
display.status_line
A named constant for use with the display parameter of the plot*() and input*() functions. Specifies that
the values are available in the script's status line, but only if the chart's settings allow it.
TYPE
const plot_display
REMARKS
The display.* constants support + and - operations, enabling custom combinations of display settings. For
example, display.data_window + display.status_line specifies that the data for an input or plot appears in
the Data Window and the script's status line, and [Link] - display.status_line specifies that the data
appears in all possible locations except for the status line.
Selecting a deselected plot in the script's "Settings/Style" tab changes its display settings, causing the plotted data to
appear in all available chart locations. To restore the display settings coded in the script, select "Reset settings" from
the "Defaults" dropdown menu at the bottom of the "Settings" dialog box.
SEE ALSO
[Link]
A named constant for the [Link]() function. Is used to request the dividends return on a stock before
deductions.
TYPE
const string
SEE ALSO
[Link]()
[Link]
A named constant for the [Link]() function. Is used to request the dividends return on a stock after
deductions.
TYPE
const string
SEE ALSO
[Link]()
[Link]
A named constant for the [Link]() function. Is used to request the earnings value as it was reported.
TYPE
const string
SEE ALSO
[Link]()
[Link]
A named constant for the [Link]() function. Is used to request the estimated earnings value.
TYPE
const string
SEE ALSO
[Link]()
[Link]
A named constant for the [Link]() function. Is used to request the standardized earnings value.
TYPE
const string
SEE ALSO
[Link]()
[Link]
A named constant for [Link]() and line.set_extend() functions.
TYPE
const string
SEE ALSO
[Link]
A named constant for [Link]() and line.set_extend() functions.
TYPE
const string
SEE ALSO
[Link]
A named constant for [Link]() and line.set_extend() functions.
TYPE
const string
SEE ALSO
[Link]
A named constant for [Link]() and line.set_extend() functions.
TYPE
const string
SEE ALSO
false
Literal representing a bool value, and result of a comparison operation.
REMARKS
See the User Manual for comparison operators and logical operators.
SEE ALSO
bool
font.family_default
Default text font for [Link](), box.set_text_font_family(), [Link](), label.set_text_font_family(), [Link]() and
table.cell_set_text_font_family() functions.
TYPE
const string
SEE ALSO
table.cell_set_text_font_family() font.family_monospace
font.family_monospace
Monospace text font for [Link](), box.set_text_font_family(), [Link](), label.set_text_font_family(), [Link]()
and table.cell_set_text_font_family() functions.
TYPE
const string
SEE ALSO
table.cell_set_text_font_family() font.family_default
[Link]
Is a named constant for selecting the formatting of the script output values from the parent series in the indicator()
function.
TYPE
const string
SEE ALSO
[Link]
Is a named constant to use with the [Link]() function. Passing a number to [Link]() with this argument rounds
the number to the nearest value that can be divided by [Link], without the remainder, with ties rounding up,
and returns the string version of said value with trailing zeros.
TYPE
const string
SEE ALSO
[Link]
Is a named constant for selecting the formatting of the script output values as a percentage in the indicator function. It
adds a percent sign after values.
TYPE
const string
REMARKS
The default precision is 2, regardless of the precision of the chart itself. This can be changed with the 'precision'
argument of the indicator() function.
SEE ALSO
[Link]
Is a named constant for selecting the formatting of the script output values as prices in the indicator() function.
TYPE
const string
REMARKS
If format is [Link], default precision value is set. You can use the precision argument of indicator function to
change the precision value.
SEE ALSO
indicator() [Link] [Link] [Link]
[Link]
Is a named constant for selecting the formatting of the script output values as volume in the indicator() function, e.g.
'5183' will be formatted as '5.183K'.
The decimal precision rules defined by this variable take precedence over other precision settings. When an
indicator(), strategy(), or plot*() call uses this format option, the function's precision parameter will not
affect the result.
TYPE
const string
SEE ALSO
hline.style_dashed
Is a named constant for dashed linestyle of hline() function.
TYPE
const hline_style
SEE ALSO
hline.style_solid hline.style_dotted
hline.style_dotted
Is a named constant for dotted linestyle of hline() function.
TYPE
const hline_style
SEE ALSO
hline.style_solid hline.style_dashed
hline.style_solid
Is a named constant for solid linestyle of hline() function.
TYPE
const hline_style
SEE ALSO
hline.style_dotted hline.style_dashed
label.style_arrowdown
Label style for [Link]() and label.set_style() functions.
TYPE
const string
SEE ALSO
[Link]() label.set_style() label.set_textalign() label.style_none label.style_xcross label.style_cross
label.style_square label.style_diamond
label.style_arrowup
Label style for [Link]() and label.set_style() functions.
TYPE
const string
SEE ALSO
label.style_square label.style_diamond
label.style_circle
Label style for [Link]() and label.set_style() functions.
TYPE
const string
SEE ALSO
label.style_square label.style_diamond
label.style_cross
Label style for [Link]() and label.set_style() functions.
TYPE
const string
SEE ALSO
[Link]() label.set_style() label.set_textalign() label.style_none label.style_xcross label.style_triangleup
label.style_square label.style_diamond
label.style_diamond
Label style for [Link]() and label.set_style() functions.
TYPE
const string
SEE ALSO
label.style_label_center label.style_square
label.style_flag
Label style for [Link]() and label.set_style() functions.
TYPE
const string
SEE ALSO
label.style_square label.style_diamond
label.style_label_center
Label style for [Link]() and label.set_style() functions.
TYPE
const string
SEE ALSO
[Link]() label.set_style() label.set_textalign() label.style_none label.style_xcross label.style_cross
label.style_square label.style_diamond
label.style_label_down
Label style for [Link]() and label.set_style() functions.
TYPE
const string
SEE ALSO
label.style_square label.style_diamond
label.style_label_left
Label style for [Link]() and label.set_style() functions.
TYPE
const string
SEE ALSO
label.style_square label.style_diamond
label.style_label_lower_left
Label style for [Link]() and label.set_style() functions.
TYPE
const string
SEE ALSO
[Link]() label.set_style() label.set_textalign() label.style_none label.style_xcross label.style_cross
label.style_square label.style_diamond
label.style_label_lower_right
Label style for [Link]() and label.set_style() functions.
TYPE
const string
SEE ALSO
label.style_square label.style_diamond
label.style_label_right
Label style for [Link]() and label.set_style() functions.
TYPE
const string
SEE ALSO
label.style_square label.style_diamond
label.style_label_up
Label style for [Link]() and label.set_style() functions.
TYPE
const string
SEE ALSO
[Link]() label.set_style() label.set_textalign() label.style_none label.style_xcross label.style_cross
label.style_square label.style_diamond
label.style_label_upper_left
Label style for [Link]() and label.set_style() functions.
TYPE
const string
SEE ALSO
label.style_square label.style_diamond
label.style_label_upper_right
Label style for [Link]() and label.set_style() functions.
TYPE
const string
SEE ALSO
label.style_square label.style_diamond
label.style_none
Label style for [Link]() and label.set_style() functions.
TYPE
const string
SEE ALSO
label.style_square label.style_diamond
label.style_square
Label style for [Link]() and label.set_style() functions.
TYPE
const string
SEE ALSO
label.style_label_center label.style_diamond
label.style_text_outline
Label style for [Link]() and label.set_style() functions.
TYPE
const string
SEE ALSO
label.style_triangledown
Label style for [Link]() and label.set_style() functions.
TYPE
const string
SEE ALSO
label.style_square label.style_diamond
label.style_triangleup
Label style for [Link]() and label.set_style() functions.
TYPE
const string
SEE ALSO
label.style_square label.style_diamond
label.style_xcross
Label style for [Link]() and label.set_style() functions.
TYPE
const string
SEE ALSO
label.style_square label.style_diamond
line.style_arrow_both
Line style for [Link]() and line.set_style() functions. Solid line with arrows on both points.
TYPE
const string
SEE ALSO
line.style_arrow_right
line.style_arrow_left
Line style for [Link]() and line.set_style() functions. Solid line with arrow on the first point.
TYPE
const string
SEE ALSO
line.style_arrow_both
line.style_arrow_right
Line style for [Link]() and line.set_style() functions. Solid line with arrow on the second point.
TYPE
const string
SEE ALSO
line.style_arrow_both
line.style_dashed
Line style for [Link]() and line.set_style() functions.
TYPE
const string
SEE ALSO
line.style_arrow_both
line.style_dotted
Line style for [Link]() and line.set_style() functions.
TYPE
const string
SEE ALSO
line.style_arrow_both
line.style_solid
Line style for [Link]() and line.set_style() functions.
TYPE
const string
SEE ALSO
line.style_arrow_both
[Link]
Location value for plotshape(), plotchar() functions. Shape is plotted above main series bars.
TYPE
const string
SEE ALSO
[Link]
Location value for plotshape(), plotchar() functions. Shape is plotted on chart using indicator value as a price
coordinate.
TYPE
const string
SEE ALSO
[Link]
Location value for plotshape(), plotchar() functions. Shape is plotted below main series bars.
TYPE
const string
SEE ALSO
[Link]
Location value for plotshape(), plotchar() functions. Shape is plotted near the bottom chart border.
TYPE
const string
SEE ALSO
[Link]
Location value for plotshape(), plotchar() functions. Shape is plotted near the top chart border.
TYPE
const string
SEE ALSO
math.e
Is a named constant for Euler's number. It is equal to 2.7182818284590452.
TYPE
const float
SEE ALSO
[Link]
Is a named constant for the golden ratio. It is equal to 1.6180339887498948.
TYPE
const float
SEE ALSO
[Link]
Is a named constant for Archimedes' constant. It is equal to 3.1415926535897932.
TYPE
const float
SEE ALSO
[Link]
Is a named constant for the golden ratio conjugate. It is equal to 0.6180339887498948.
TYPE
const float
SEE ALSO
[Link]
Determines the sort order of the array from the smallest to the largest value.
TYPE
const sort_order
SEE ALSO
array.new_float() [Link]()
[Link]
Determines the sort order of the array from the largest to the smallest value.
TYPE
const sort_order
SEE ALSO
array.new_float() [Link]()
plot.linestyle_dashed
A named constant for use with the plot() function's linestyle parameter, which modifies the appearance of plotted
lines. If the style argument of the function call specifies a plot style that displays a line, using this constant as the
linestyle argument specifies that the plotted line is dashed.
TYPE
const plot_line_style
SEE ALSO
TYPE
const plot_line_style
SEE ALSO
plot.linestyle_solid
A named constant for use with the plot() function's linestyle parameter, which modifies the appearance of plotted
lines. If the style argument of the function call specifies a plot style that displays a line, using this constant as the
linestyle argument specifies that the plotted line is solid.
TYPE
const plot_line_style
SEE ALSO
plot.style_area
A named constant for the 'Area' style, to be used as an argument for the style parameter in the plot() function.
TYPE
const plot_style
SEE ALSO
plot.style_areabr
A named constant for the 'Area With Breaks' style, to be used as an argument for the style parameter in the plot()
function. Similar to plot.style_area, except the gaps in the data are not filled.
TYPE
const plot_style
SEE ALSO
plot.style_circles
A named constant for the 'Circles' style, to be used as an argument for the style parameter in the plot() function.
TYPE
const plot_style
SEE ALSO
plot.style_columns
A named constant for the 'Columns' style, to be used as an argument for the style parameter in the plot() function.
TYPE
const plot_style
SEE ALSO
plot.style_cross
A named constant for the 'Cross' style, to be used as an argument for the style parameter in the plot() function.
TYPE
const plot_style
SEE ALSO
plot.style_histogram
A named constant for the 'Histogram' style, to be used as an argument for the style parameter in the plot()
function.
TYPE
const plot_style
SEE ALSO
plot.style_line
A named constant for the 'Line' style, to be used as an argument for the style parameter in the plot() function.
TYPE
const plot_style
SEE ALSO
plot.style_linebr
A named constant for the 'Line With Breaks' style, to be used as an argument for the style parameter in the plot()
function. Similar to plot.style_line, except the gaps in the data are not filled.
TYPE
const plot_style
SEE ALSO
plot.style_stepline
A named constant for the 'Step Line' style, to be used as an argument for the style parameter in the plot() function.
TYPE
const plot_style
SEE ALSO
plot.style_stepline_diamond
A named constant for the 'Step Line With Diamonds' style, to be used as an argument for the style parameter in the
plot() function. Similar to plot.style_stepline, except the data changes are also marked with the Diamond shapes.
TYPE
const plot_style
SEE ALSO
plot.style_steplinebr
A named constant for the 'Step line with Breaks' style, to be used as an argument for the style parameter in the
plot() function.
TYPE
const plot_style
SEE ALSO
position.bottom_center
Table position is used in [Link](), [Link]() functions.
TYPE
const string
SEE ALSO
position.bottom_left
Table position is used in [Link](), [Link]() functions.
TYPE
const string
SEE ALSO
position.bottom_right
Table position is used in [Link](), [Link]() functions.
TYPE
const string
SEE ALSO
position.middle_center
Table position is used in [Link](), [Link]() functions.
TYPE
const string
SEE ALSO
position.middle_left
Table position is used in [Link](), [Link]() functions.
TYPE
const string
SEE ALSO
TYPE
const string
SEE ALSO
position.top_center
Table position is used in [Link](), [Link]() functions.
Binds the table to the top edge in the center.
TYPE
const string
SEE ALSO
position.top_left
Table position is used in [Link](), [Link]() functions.
TYPE
const string
SEE ALSO
position.top_right
Table position is used in [Link](), [Link]() functions.
TYPE
const string
SEE ALSO
[Link]
Scale value for indicator() function. Indicator is added to the left price scale.
TYPE
const scale_type
SEE ALSO
indicator()
[Link]
Scale value for indicator() function. Indicator is added in 'No Scale' mode. Can be used only with 'overlay=true'.
TYPE
const scale_type
SEE ALSO
indicator()
[Link]
Scale value for indicator() function. Indicator is added to the right price scale.
TYPE
const scale_type
SEE ALSO
indicator()
[Link]
Constant for extended session type (with extended hours data).
TYPE
const string
SEE ALSO
[Link] [Link]
[Link]
Constant for regular session type (no extended hours data).
TYPE
const string
SEE ALSO
[Link] [Link]
settlement_as_close.inherit
A constant to specify the value of the settlement_as_close parameter in [Link]() and [Link]()
functions.
TYPE
const settlement
SEE ALSO
settlement_as_close.off
A constant to specify the value of the settlement_as_close parameter in [Link]() and [Link]()
functions.
TYPE
const settlement
SEE ALSO
settlement_as_close.on
A constant to specify the value of the settlement_as_close parameter in [Link]() and [Link]()
functions.
TYPE
const settlement
SEE ALSO
[Link]
Shape style for plotshape() function.
TYPE
const string
SEE ALSO
plotshape()
[Link]
Shape style for plotshape() function.
TYPE
const string
SEE ALSO
plotshape()
[Link]
Shape style for plotshape() function.
TYPE
const string
SEE ALSO
plotshape()
[Link]
Shape style for plotshape() function.
TYPE
const string
SEE ALSO
plotshape()
[Link]
Shape style for plotshape() function.
TYPE
const string
SEE ALSO
plotshape()
[Link]
Shape style for plotshape() function.
TYPE
const string
SEE ALSO
plotshape()
[Link]
Shape style for plotshape() function.
TYPE
const string
SEE ALSO
plotshape()
[Link]
Shape style for plotshape() function.
TYPE
const string
SEE ALSO
plotshape()
[Link]
Shape style for plotshape() function.
TYPE
const string
SEE ALSO
plotshape()
[Link]
Shape style for plotshape() function.
TYPE
const string
SEE ALSO
plotshape()
[Link]
Shape style for plotshape() function.
TYPE
const string
SEE ALSO
plotshape()
[Link]
Shape style for plotshape() function.
TYPE
const string
SEE ALSO
plotshape()
[Link]
A constant to specify the size of the graphics drawn by plotchar(), plotshape(), [Link](), and [Link](). Adjusts the
size of the graphics automatically.
TYPE
const string
SEE ALSO
[Link]
A constant to specify the size of the graphics drawn by plotchar(), plotshape(), [Link](), [Link](), and [Link]().
Sets the size to huge.
TYPE
const string
SEE ALSO
plotshape() plotchar() label.set_size() [Link] [Link] [Link] [Link] [Link]
[Link]
A constant to specify the size of the graphics drawn by plotchar(), plotshape(), [Link](), [Link](), and [Link]().
Sets the size to large.
TYPE
const string
SEE ALSO
[Link]
A constant to specify the size of the graphics drawn by plotchar(), plotshape(), [Link](), [Link](), and [Link]().
Sets the size to normal.
TYPE
const string
SEE ALSO
[Link]
A constant to specify the size of the graphics drawn by plotchar(), plotshape(), [Link](), [Link](), and [Link]().
Sets the size to small.
TYPE
const string
SEE ALSO
[Link]
A constant to specify the size of the graphics drawn by plotchar(), plotshape(), [Link](), [Link](), and [Link]().
Sets the size to tiny.
TYPE
const string
SEE ALSO
[Link]
A named constant for the [Link]() function. Is used to request the denominator (the number below the line in a
fraction) of a splits.
TYPE
const string
SEE ALSO
[Link]()
[Link]
A named constant for the [Link]() function. Is used to request the numerator (the number above the line in a
fraction) of a splits.
TYPE
const string
SEE ALSO
[Link]()
[Link]
This is one of the arguments that can be supplied to the default_qty_type parameter in the strategy() declaration
statement. It is only relevant when no value is used for the ‘qty’ parameter in [Link]() or [Link]()
function calls. It specifies that an amount of cash in the strategy.account_currency will be used to enter
trades.
TYPE
const string
EXAMPLE
//@version=6
strategy("[Link]", overlay = true, default_qty_value = 50, default_qty_type = [Link], ini
tial_capital = 1000000)
if bar_index == 0
// As ‘qty’ is not defined, the previously defined values for the `default_qty_type` and `default_q
ty_value` parameters are used to enter trades, namely 50 units of cash in the currency of `[Link]
ount_currency`.
// `qty` is calculated as (default_qty_value)/(close price). If current price is $5, then qty = 50/
5 = 10.
[Link]("EN", [Link])
if bar_index == 2
[Link]("EN")
SEE ALSO
strategy()
[Link].cash_per_contract
Commission type for an order. Money displayed in the account currency per contract.
TYPE
const string
SEE ALSO
strategy()
[Link].cash_per_order
Commission type for an order. Money displayed in the account currency per order.
TYPE
const string
SEE ALSO
strategy()
[Link]
Commission type for an order. A percentage of the cash volume of order.
TYPE
const string
SEE ALSO
strategy()
[Link]
It allows strategy to open both long and short positions.
TYPE
const string
SEE ALSO
[Link].allow_entry_in()
[Link]
It allows strategy to open only long positions.
TYPE
const string
SEE ALSO
[Link].allow_entry_in()
[Link]
It allows strategy to open only short positions.
TYPE
const string
SEE ALSO
[Link].allow_entry_in()
[Link]
This is one of the arguments that can be supplied to the default_qty_type parameter in the strategy() declaration
statement. It is only relevant when no value is used for the ‘qty’ parameter in [Link]() or [Link]()
function calls. It specifies that a number of contracts/shares/lots will be used to enter trades.
TYPE
const string
EXAMPLE
//@version=6
strategy("[Link]", overlay = true, default_qty_value = 50, default_qty_type = [Link], i
nitial_capital = 1000000)
if bar_index == 0
// As ‘qty’ is not defined, the previously defined values for the `default_qty_type` and `default_q
ty_value` parameters are used to enter trades, namely 50 contracts.
// qty = 50
[Link]("EN", [Link])
if bar_index == 2
[Link]("EN")
SEE ALSO
strategy()
[Link]
A named constant for use with the direction parameter of the [Link]() and [Link]() commands. It
specifies that the command creates a buy order.
TYPE
const strategy_direction
SEE ALSO
[Link]
A named constant for use with the oca_type parameter of the [Link]() and [Link]() commands. It
specifies that the strategy cancels the unfilled order when another order with the same oca_name and oca_type
executes.
TYPE
const string
REMARKS
Strategies cannot cancel or reduce pending orders from an OCA group if they execute on the same tick. For example, if
the market price triggers two stop orders from [Link]() calls with the same oca_* arguments, the strategy
cannot fully or partially cancel either one.
SEE ALSO
[Link]
A named constant for use with the oca_type parameter of the [Link]() and [Link]() commands. It
specifies that the order executes independently of all other orders, including those with the same oca_name .
TYPE
const string
SEE ALSO
[Link]
A named constant for use with the oca_type parameter of the [Link]() and [Link]() commands. It
specifies that when another order with the same oca_name and oca_type executes, the strategy reduces the
unfilled order by that order's size. If the unfilled order's size reaches 0 after reduction, it is the same as canceling the
order entirely.
TYPE
const string
REMARKS
Strategies cannot cancel or reduce pending orders from an OCA group if they execute on the same tick. For example, if
the market price triggers two stop orders from [Link]() calls with the same oca_* arguments, the strategy
cannot fully or partially cancel either one.
Orders from [Link]() automatically use this OCA type, and they belong to the same OCA group by default.
SEE ALSO
strategy.percent_of_equity
This is one of the arguments that can be supplied to the default_qty_type parameter in the strategy() declaration
statement. It is only relevant when no value is used for the ‘qty’ parameter in [Link]() or [Link]()
function calls. It specifies that a percentage (0-100) of equity will be used to enter trades.
TYPE
const string
EXAMPLE
//@version=6
strategy("strategy.percent_of_equity", overlay = false, default_qty_value = 100, default_qty_type = str
ategy.percent_of_equity, initial_capital = 1000000)
// As ‘qty’ is not defined, the previously defined values for the `default_qty_type` and `default_qty_v
alue` parameters are used to enter trades, namely 100% of available equity.
if bar_index == 0
[Link]("EN", [Link])
if bar_index == 2
[Link]("EN")
plot([Link])
// The ‘qty’ parameter is set to 10. Entering position with fixed size of 10 contracts and entry marke
t price = (10 * close).
if bar_index == 4
[Link]("EN", [Link], qty = 10)
if bar_index == 6
[Link]("EN")
SEE ALSO
strategy()
[Link]
A named constant for use with the direction parameter of the [Link]() and [Link]() commands. It
specifies that the command creates a sell order.
TYPE
const strategy_direction
SEE ALSO
TYPE
const string
SEE ALSO
text.align_center
Text alignment for [Link](), box.set_text_halign(), box.set_text_valign(), [Link]() and label.set_textalign()
functions.
TYPE
const string
SEE ALSO
text.align_left
Horizontal text alignment for [Link](), box.set_text_halign(), [Link]() and label.set_textalign() functions.
TYPE
const string
SEE ALSO
text.align_right
Horizontal text alignment for [Link](), box.set_text_halign(), [Link]() and label.set_textalign() functions.
TYPE
const string
SEE ALSO
text.align_top
Vertical text alignment for [Link](), box.set_text_valign(), [Link]() and table.cell_set_text_valign() functions.
TYPE
const string
SEE ALSO
text.format_bold
A named constant for use with the text_formatting parameter of the [Link]() , [Link]() , [Link]
ll() , and *set_text_formatting() functions. Makes the text bold.
TYPE
const text_format
SEE ALSO
text.format_italic
A named constant for use with the text_formatting parameter of the [Link]() , [Link]() , [Link]
ll() , and *set_text_formatting() functions. Italicizes the text.
TYPE
const text_format
SEE ALSO
text.format_none
A named constant for use with the text_formatting parameter of the [Link]() , [Link]() , [Link]
ll() , and *set_text_formatting() functions. Signifies no special text formatting.
TYPE
const text_format
SEE ALSO
text.wrap_auto
Automatic wrapping mode for [Link]() and box.set_text_wrap() functions.
TYPE
const string
SEE ALSO
text.wrap_none
Disabled wrapping mode for [Link]() and box.set_text_wrap() functions.
TYPE
const string
SEE ALSO
true
Literal representing one of the values a bool variable can hold, or an expression can evaluate to when it uses
comparison or logical operators.
REMARKS
See the User Manual for comparison operators and logical operators.
SEE ALSO
bool
xloc.bar_index
A constant that specifies how functions that create and modify Pine drawings interpret x-coordinates. If xloc = xlo
c.bar_index , the drawing object treats each x-coordinate as a bar_index value.
TYPE
const string
SEE ALSO
xloc.bar_time
A constant that specifies how functions that create and modify Pine drawings interpret x-coordinates. If xloc = xlo
c.bar_time , the drawing object treats each x-coordinate as a UNIX timestamp, expressed in milliseconds.
TYPE
const string
SEE ALSO
[Link]
A named constant that specifies the algorithm of interpretation of y-value in function [Link]().
TYPE
const string
SEE ALSO
[Link]
A named constant that specifies the algorithm of interpretation of y-value in function [Link]().
TYPE
const string
SEE ALSO
[Link]
A named constant that specifies the algorithm of interpretation of y-value in function [Link]().
TYPE
const string
SEE ALSO
Functions
alert()
Creates an alert trigger for an indicator or strategy, with a specified frequency, when called on the latest realtime bar.
To activate alerts for a script containing calls to this function, open the "Create Alert" dialog box, then select the script
name and "Any alert() function call" in the "Condition" section.
SYNTAX
ARGUMENTS
message (series string) The message to send when the alert occurs.
freq (input string) Optional. Determines the allowed frequency of the alert trigger. Possible values are: alert.freq_all
(allows an alert on any realtime update), alert.freq_once_per_bar (allows an alert only on the first execution for each
realtime bar), or alert.freq_once_per_bar_close (allows an alert only when a realtime bar closes). The default is
alert.freq_once_per_bar.
EXAMPLE
//@version=6
indicator("`alert()` example", "", true)
ma = [Link](close, 14)
xUp = [Link](close, ma)
if xUp
// Trigger the alert the first time a cross occurs during the real-time bar.
alert("Price (" + [Link](close) + ") crossed over MA (" + [Link](ma) + ").", [Link]
_once_per_bar)
plot(ma)
plotchar(xUp, "xUp", "▲", [Link], size = [Link])
REMARKS
In contrast to alertcondition(), calls to this function do not count toward a script's plot count. Additionally, alert()
calls are allowed in local scopes, including the scopes of exported library functions.
See this article in our Help Center to learn more about activating alerts from alert() calls.
SEE ALSO
alertcondition()
alertcondition()
Creates alert condition, that is available in Create Alert dialog. Please note, that alertcondition() does NOT create an
alert, it just gives you more options in Create Alert dialog. Also, alertcondition() effect is invisible on chart.
SYNTAX
ARGUMENTS
condition (series bool) Series of boolean values that is used for alert. True values mean alert fire, false - no alert.
Required argument.
title (const string) Title of the alert condition. Optional argument.
message (const string) Message to display when alert fires. Optional argument.
EXAMPLE
//@version=6
indicator("alertcondition", overlay=true)
alertcondition(close >= open, title='Alert on Green Bar', message='Green Bar!')
REMARKS
Please note that an alertcondition call generates an additional plot. All such calls are taken into account when we
calculate the number of the output series per script.
SEE ALSO
alert()
[Link]() 2 overloads
Returns an array containing the absolute value of each element in the original array.
[Link](id) → array<float>
[Link](id) → array<int>
ARGUMENTS
SEE ALSO
[Link]() 2 overloads
ARGUMENTS
EXAMPLE
//@version=6
indicator("[Link] example")
a = array.new_float(0)
for i = 0 to 9
[Link](a, close[i])
plot([Link](a))
RETURNS
Mean of array's elements.
REMARKS
SEE ALSO
array.binary_search()
The function returns the index of the value, or -1 if the value is not found. The array to search must be sorted in
ascending order.
SYNTAX
ARGUMENTS
EXAMPLE
//@version=6
indicator("array.binary_search")
a = [Link](5, -2, 0, 9, 1)
[Link](a) // [-2, 0, 1, 5, 9]
position = array.binary_search(a, 0) // 1
plot(position)
REMARKS
A binary search works on arrays pre-sorted in ascending order. It begins by comparing an element in the middle of the
array with the target value. If the element matches the target value, its position in the array is returned. If the element's
value is greater than the target value, the search continues in the lower half of the array. If the element's value is less
than the target value, the search continues in the upper half of the array. By doing this recursively, the algorithm
progressively eliminates smaller and smaller portions of the array in which the target value cannot lie.
SEE ALSO
array.binary_search_leftmost()
The function returns the index of the value if it is found. When the value is not found, the function returns the index of
the next smallest element to the left of where the value would lie if it was in the array. The array to search must be
sorted in ascending order.
SYNTAX
ARGUMENTS
EXAMPLE
//@version=6
indicator("array.binary_search_leftmost")
a = [Link](5, -2, 0, 9, 1)
[Link](a) // [-2, 0, 1, 5, 9]
position = array.binary_search_leftmost(a, 3) // 2
plot(position)
EXAMPLE
//@version=6
indicator("array.binary_search_leftmost, repetitive elements")
a = [Link](4, 5, 5, 5)
// Returns the index of the first instance.
position = array.binary_search_leftmost(a, 5)
plot(position) // Plots 1
REMARKS
A binary search works on arrays pre-sorted in ascending order. It begins by comparing an element in the middle of the
array with the target value. If the element matches the target value, its position in the array is returned. If the element's
value is greater than the target value, the search continues in the lower half of the array. If the element's value is less
than the target value, the search continues in the upper half of the array. By doing this recursively, the algorithm
progressively eliminates smaller and smaller portions of the array in which the target value cannot lie.
SEE ALSO
array.binary_search_rightmost()
The function returns the index of the value if it is found. When the value is not found, the function returns the index of
the element to the right of where the value would lie if it was in the array. The array must be sorted in ascending order.
SYNTAX
ARGUMENTS
EXAMPLE
//@version=6
indicator("array.binary_search_rightmost")
a = [Link](5, -2, 0, 9, 1)
[Link](a) // [-2, 0, 1, 5, 9]
position = array.binary_search_rightmost(a, 3) // 3
plot(position)
EXAMPLE
//@version=6
indicator("array.binary_search_rightmost, repetitive elements")
a = [Link](4, 5, 5, 5)
// Returns the index of the last instance.
position = array.binary_search_rightmost(a, 5)
plot(position) // Plots 3
REMARKS
A binary search works on sorted arrays in ascending order. It begins by comparing an element in the middle of the
array with the target value. If the element matches the target value, its position in the array is returned. If the element's
value is greater than the target value, the search continues in the lower half of the array. If the element's value is less
than the target value, the search continues in the upper half of the array. By doing this recursively, the algorithm
progressively eliminates smaller and smaller portions of the array in which the target value cannot lie.
SEE ALSO
[Link]()
The function removes all elements from an array.
SYNTAX
[Link](id) → void
ARGUMENTS
EXAMPLE
//@version=6
indicator("[Link] example")
a = array.new_float(5,high)
[Link](a)
[Link](a, close)
plot([Link](a,0))
plot([Link](a))
SEE ALSO
[Link]()
The function is used to merge two arrays. It pushes all elements from the second array to the first array, and returns
the first array.
SYNTAX
ARGUMENTS
EXAMPLE
//@version=6
indicator("[Link] example")
a = array.new_float(0,0)
b = array.new_float(0,0)
for i = 0 to 4
[Link](a, high[i])
[Link](b, low[i])
c = [Link](a,b)
plot([Link](a))
plot([Link](b))
plot([Link](c))
RETURNS
The first array with merged elements from the second array.
SEE ALSO
[Link]()
The function creates a copy of an existing array.
SYNTAX
[Link](id) → array<type>
ARGUMENTS
EXAMPLE
//@version=6
indicator("[Link] example")
length = 5
a = array.new_float(length, close)
b = [Link](a)
a := array.new_float(length, open)
plot([Link](a) / length)
plot([Link](b) / length)
RETURNS
A copy of an array.
SEE ALSO
[Link]()
The function returns the covariance of two arrays.
SYNTAX
ARGUMENTS
biased (series bool) Determines which estimate should be used. Optional. The default is true.
EXAMPLE
//@version=6
indicator("[Link] example")
a = array.new_float(0)
b = array.new_float(0)
for i = 0 to 9
[Link](a, close[i])
[Link](b, open[i])
plot([Link](a, b))
RETURNS
REMARKS
If biased is true, function will calculate using a biased estimate of the entire population, if false - unbiased estimate
of a sample. Returns na if both arrays are empty.
SEE ALSO
[Link]()
Returns true if all elements of the id array are true, false otherwise.
SYNTAX
ARGUMENTS
REMARKS
This function also works with arrays of int and float types, in which case zero values are considered false, and all
others true.
SEE ALSO
[Link]() [Link]()
[Link]()
The function sets elements of an array to a single value. If no index is specified, all elements are set. If only a start
index (default 0) is supplied, the elements starting at that index are set. If both index parameters are used, the
elements from the starting index up to but not including the end index (default na) are set.
SYNTAX
ARGUMENTS
value (series <type of the array's elements>) Value to fill the array with.
index_from (series int) Start index, default is 0.
index_to (series int) End index, default is na. Must be one greater than the index of the last element to set.
EXAMPLE
//@version=6
indicator("[Link] example")
a = array.new_float(10)
[Link](a, close)
plot([Link](a))
SEE ALSO
SYNTAX
ARGUMENTS
EXAMPLE
//@version=6
indicator("[Link] example")
arr = array.new_int(3, 10)
plot([Link](arr))
SEE ALSO
[Link]() [Link]()
[Link]() 12 overloads
The function takes a variable number of arguments with one of the types: int, float, bool, string, label, line, color, box,
table, linefill, and returns an array of the corresponding type.
EXAMPLE
//@version=6
indicator("array.from_example", overlay = false)
arr = [Link]("Hello", "World!") // arr (array<string>) will contain 2 elements: {Hello}, {World!}.
plot(close)
RETURNS
REMARKS
This function can accept up to 4,000 'int', 'float', 'bool', or 'color' arguments. For all other types, including user-defined
types, the limit is 999.
[Link]()
The function returns the value of the element at the specified index.
SYNTAX
ARGUMENTS
EXAMPLE
//@version=6
indicator("[Link] example")
a = array.new_float(0)
for i = 0 to 9
[Link](a, close[i] - open[i])
plot([Link](a, 9))
RETURNS
REMARKS
If the index is positive, the function counts forwards from the beginning of the array to the end. The index of the first
element is 0, and the index of the last element is [Link]() - 1 . If the index is negative, the function counts
backwards from the end of the array to the beginning. In this case, the index of the last element is -1, and the index of
the first element is negative [Link]() . For example, for an array that contains three elements, all of the
following are valid arguments for the index parameter: 0, 1, 2, -1, -2, -3.
SEE ALSO
[Link]()
The function returns true if the value was found in an array, false otherwise.
SYNTAX
[Link](id, value) → series bool
ARGUMENTS
EXAMPLE
//@version=6
indicator("[Link] example")
a = array.new_float(5,high)
p = close
if [Link](a, high)
p := open
plot(p)
RETURNS
SEE ALSO
[Link]()
The function returns the index of the first occurrence of the value, or -1 if the value is not found.
SYNTAX
ARGUMENTS
EXAMPLE
//@version=6
indicator("[Link] example")
a = array.new_float(5,high)
index = [Link](a, high)
plot(index)
RETURNS
SEE ALSO
[Link]()
The function changes the contents of an array by adding new elements in place.
SYNTAX
EXAMPLE
//@version=6
indicator("[Link] example")
a = array.new_float(5, close)
[Link](a, 0, open)
plot([Link](a, 5))
REMARKS
If the index is positive, the function counts forwards from the beginning of the array to the end. The index of the first
element is 0, and the index of the last element is [Link]() - 1 . If the index is negative, the function counts
backwards from the end of the array to the beginning. In this case, the index of the last element is -1, and the index of
the first element is negative [Link]() . For example, for an array that contains three elements, all of the
following are valid arguments for the index parameter: 0, 1, 2, -1, -2, -3.
SEE ALSO
[Link]()
The function creates and returns a new string by concatenating all the elements of an array, separated by the specified
separator string.
SYNTAX
ARGUMENTS
EXAMPLE
//@version=6
indicator("[Link] example")
a = array.new_float(5, 5)
[Link](bar_index, close, [Link](a, ","))
SEE ALSO
[Link]()
Returns the array's last element. Throws a runtime error if the array is empty.
SYNTAX
ARGUMENTS
id (any array type) An array object.
EXAMPLE
//@version=6
indicator("[Link] example")
arr = array.new_int(3, 10)
plot([Link](arr))
SEE ALSO
[Link]() [Link]()
[Link]()
The function returns the index of the last occurrence of the value, or -1 if the value is not found.
SYNTAX
ARGUMENTS
EXAMPLE
//@version=6
indicator("[Link] example")
a = array.new_float(5,high)
index = [Link](a, high)
plot(index)
RETURNS
SEE ALSO
[Link]() 2 overloads
The function returns the greatest value, or the nth greatest value in a given array.
ARGUMENTS
EXAMPLE
//@version=6
indicator("[Link]")
a = [Link](5, -2, 0, 9, 1)
thirdHighest = [Link](a, 2) // 1
plot(thirdHighest)
RETURNS
REMARKS
SEE ALSO
[Link]() 2 overloads
ARGUMENTS
EXAMPLE
//@version=6
indicator("[Link] example")
a = array.new_float(0)
for i = 0 to 9
[Link](a, close[i])
plot([Link](a))
RETURNS
REMARKS
SEE ALSO
[Link]() 2 overloads
The function returns the smallest value, or the nth smallest value in a given array.
ARGUMENTS
id (array<int/float>) An array object.
nth (series int) The nth smallest value to return, where zero is the smallest. Optional. The default is zero.
EXAMPLE
//@version=6
indicator("[Link]")
a = [Link](5, -2, 0, 9, 1)
secondLowest = [Link](a, 1) // 0
plot(secondLowest)
RETURNS
REMARKS
SEE ALSO
[Link]() 2 overloads
The function returns the mode of an array's elements. If there are several values with the same frequency, it returns
the smallest value.
ARGUMENTS
EXAMPLE
//@version=6
indicator("[Link] example")
a = array.new_float(0)
for i = 0 to 9
[Link](a, close[i])
plot([Link](a))
RETURNS
The most frequently occurring value from the id array. If none exists, returns the smallest value instead.
REMARKS
SEE ALSO
array.new_bool()
The function creates a new array object of bool type elements.
SYNTAX
array.new_bool(size, initial_value) → array<bool>
ARGUMENTS
EXAMPLE
//@version=6
indicator("array.new_bool example")
length = 5
a = array.new_bool(length, close > open)
plot([Link](a, 0) ? close : open)
RETURNS
REMARKS
SEE ALSO
array.new_box()
The function creates a new array object of box type elements.
SYNTAX
ARGUMENTS
initial_value (series box) Initial value of all array elements. Optional. The default is 'na'.
EXAMPLE
//@version=6
indicator("array.new_box example")
boxes = array.new_box()
[Link](boxes, [Link](time, close, time+2, low, xloc=xloc.bar_time))
plot(1)
RETURNS
REMARKS
SEE ALSO
array.new_color()
The function creates a new array object of color type elements.
SYNTAX
ARGUMENTS
EXAMPLE
//@version=6
indicator("array.new_color example")
length = 5
a = array.new_color(length, [Link])
plot(close, color = [Link](a, 0))
RETURNS
REMARKS
SEE ALSO
array.new_float()
The function creates a new array object of float type elements.
SYNTAX
ARGUMENTS
initial_value (series int/float) Initial value of all array elements. Optional. The default is 'na'.
EXAMPLE
//@version=6
indicator("array.new_float example")
length = 5
a = array.new_float(length, close)
plot([Link](a) / length)
RETURNS
REMARKS
SEE ALSO
array.new_int()
The function creates a new array object of int type elements.
SYNTAX
ARGUMENTS
initial_value (series int) Initial value of all array elements. Optional. The default is 'na'.
EXAMPLE
//@version=6
indicator("array.new_int example")
length = 5
a = array.new_int(length, int(close))
plot([Link](a) / length)
RETURNS
REMARKS
SEE ALSO
array.new_label()
The function creates a new array object of label type elements.
SYNTAX
ARGUMENTS
initial_value (series label) Initial value of all array elements. Optional. The default is 'na'.
EXAMPLE
//@version=6
indicator("array.new_label example", overlay = true, max_labels_count = 500)
// Add a new label to the `labelArray` when the chart bar closed at a new value.
if close != open
[Link]([Link](labelPoint, labelText, color = labelColor, style = labelStyle))
// Remove the first element and delete its label when the size of the `labelArray` exceeds the `labelCo
unt`.
if [Link]() > labelCount
[Link]([Link]())
RETURNS
REMARKS
SEE ALSO
array.new_line()
The function creates a new array object of line type elements.
SYNTAX
ARGUMENTS
EXAMPLE
//@version=6
indicator("array.new_line example")
// draw last 15 lines
var a = array.new_line()
[Link](a, [Link](bar_index - 1, close[1], bar_index, close))
if [Link](a) > 15
ln = [Link](a)
[Link](ln)
RETURNS
REMARKS
SEE ALSO
array.new_linefill()
The function creates a new array object of linefill type elements.
SYNTAX
ARGUMENTS
RETURNS
REMARKS
array.new_string()
The function creates a new array object of string type elements.
SYNTAX
ARGUMENTS
EXAMPLE
//@version=6
indicator("array.new_string example")
length = 5
a = array.new_string(length, "text")
[Link](bar_index, close, [Link](a, 0))
RETURNS
REMARKS
SEE ALSO
array.new_table()
The function creates a new array object of table type elements.
SYNTAX
ARGUMENTS
EXAMPLE
//@version=6
indicator("table array")
tables = array.new_table()
[Link](tables, [Link](position = position.top_left, rows = 1, columns = 2, bgcolor = [Link]
w, border_width=1))
plot(1)
RETURNS
REMARKS
SEE ALSO
[Link]<type>()
The function creates a new array object of <type> elements.
SYNTAX
ARGUMENTS
initial_value (<array_type>) Initial value of all array elements. Optional. The default is 'na'.
EXAMPLE
//@version=6
indicator("[Link]<string> example")
a = [Link]<string>(1, "Hello, World!")
[Link](bar_index, close, [Link](a, 0))
EXAMPLE
//@version=6
indicator("[Link]<color> example")
a = [Link]<color>()
[Link](a, [Link])
[Link](a, [Link])
plot(close, color = [Link](a, close > open ? 1 : 0))
EXAMPLE
//@version=6
indicator("[Link]<float> example")
length = 5
var a = [Link]<float>(length, close)
if [Link](a) == length
[Link](a, 0)
[Link](a, close)
plot([Link](a) / length, "SMA")
EXAMPLE
//@version=6
indicator("[Link]<line> example")
// draw last 15 lines
var a = [Link]<line>()
[Link](a, [Link](bar_index - 1, close[1], bar_index, close))
if [Link](a) > 15
ln = [Link](a)
[Link](ln)
RETURNS
REMARKS
If you want to initialize an array and specify all its elements at the same time, then use the function [Link].
SEE ALSO
array.percentile_linear_interpolation() 2 overloads
Returns the value for which the specified percentage of array values (percentile) are less than or equal to it, using
linear interpolation.
ARGUMENTS
percentage (series int/float) The percentage of values that must be equal or less than the returned value.
REMARKS
In statistics, the percentile is the percent of ranking items that appear at or below a certain score. This measurement
shows the percentage of scores within a standard frequency distribution that is lower than the percentile rank being
measured. Linear interpolation estimates the value between two ranks.
Returns na if the id array is empty.
SEE ALSO
array.percentile_nearest_rank() 2 overloads
Returns the value for which the specified percentage of array values (percentile) are less than or equal to it, using the
nearest-rank method.
ARGUMENTS
REMARKS
In statistics, the percentile is the percent of ranking items that appear at or below a certain score. This measurement
shows the percentage of scores within a standard frequency distribution that is lower than the percentile rank you're
measuring.
Returns na if the id array is empty.
SEE ALSO
[Link]() 2 overloads
ARGUMENTS
index (series int) The index of the element for which the percentile rank should be calculated.
REMARKS
Percentile rank is the number of elements in the array that are less than or equal to the reference value, expressed as a
percentage.
SEE ALSO
[Link]()
The function removes the last element from an array and returns its value.
SYNTAX
ARGUMENTS
EXAMPLE
//@version=6
indicator("[Link] example")
a = array.new_float(5,high)
removedEl = [Link](a)
plot([Link](a))
plot(removedEl)
RETURNS
[Link]()
The function appends a value to an array.
SYNTAX
ARGUMENTS
value (series <type of the array's elements>) The value of the element added to the end of the array.
EXAMPLE
//@version=6
indicator("[Link] example")
a = array.new_float(5, 0)
[Link](a, open)
plot([Link](a, 5))
SEE ALSO
[Link]() 2 overloads
The function returns the difference between the min and max values from a given array.
ARGUMENTS
EXAMPLE
//@version=6
indicator("[Link] example")
a = array.new_float(0)
for i = 0 to 9
[Link](a, close[i])
plot([Link](a))
RETURNS
The difference between the min and max values in the array.
REMARKS
SEE ALSO
SYNTAX
ARGUMENTS
EXAMPLE
//@version=6
indicator("[Link] example")
a = array.new_float(5,high)
removedEl = [Link](a, 0)
plot([Link](a))
plot(removedEl)
RETURNS
REMARKS
If the index is positive, the function counts forwards from the beginning of the array to the end. The index of the first
element is 0, and the index of the last element is [Link]() - 1 . If the index is negative, the function counts
backwards from the end of the array to the beginning. In this case, the index of the last element is -1, and the index of
the first element is negative [Link]() . For example, for an array that contains three elements, all of the
following are valid arguments for the index parameter: 0, 1, 2, -1, -2, -3.
SEE ALSO
[Link]()
The function reverses an array. The first array element becomes the last, and the last array element becomes the first.
SYNTAX
[Link](id) → void
ARGUMENTS
EXAMPLE
//@version=6
indicator("[Link] example")
a = array.new_float(0)
for i = 0 to 9
[Link](a, close[i])
plot([Link](a, 0))
[Link](a)
plot([Link](a, 0))
SEE ALSO
array.new_float() [Link]() [Link]() [Link]() [Link]()
[Link]()
The function sets the value of the element at the specified index.
SYNTAX
ARGUMENTS
EXAMPLE
//@version=6
indicator("[Link] example")
a = array.new_float(10)
for i = 0 to 9
[Link](a, i, close[i])
plot([Link](a) / 10)
REMARKS
If the index is positive, the function counts forwards from the beginning of the array to the end. The index of the first
element is 0, and the index of the last element is [Link]() - 1 . If the index is negative, the function counts
backwards from the end of the array to the beginning. In this case, the index of the last element is -1, and the index of
the first element is negative [Link]() . For example, for an array that contains three elements, all of the
following are valid arguments for the index parameter: 0, 1, 2, -1, -2, -3.
SEE ALSO
[Link]()
The function removes an array's first element and returns its value.
SYNTAX
ARGUMENTS
EXAMPLE
//@version=6
indicator("[Link] example")
a = array.new_float(5,high)
removedEl = [Link](a)
plot([Link](a))
plot(removedEl)
RETURNS
[Link]()
The function returns the number of elements in an array.
SYNTAX
ARGUMENTS
EXAMPLE
//@version=6
indicator("[Link] example")
a = array.new_float(0)
for i = 0 to 9
[Link](a, close[i])
// note that changes in slice also modify original array
slice = [Link](a, 0, 5)
[Link](slice, open)
// size was changed in slice and in original array
plot([Link](a))
plot([Link](slice))
RETURNS
SEE ALSO
[Link]()
The function creates a slice from an existing array. If an object from the slice changes, the changes are applied to both
the new and the original arrays.
SYNTAX
ARGUMENTS
index_to (series int) Zero-based index before which to end extraction. The function extracts up to but not including
the element with this index.
EXAMPLE
//@version=6
indicator("[Link] example")
a = array.new_float(0)
for i = 0 to 9
[Link](a, close[i])
// take elements from 0 to 4
// *note that changes in slice also modify original array
slice = [Link](a, 0, 5)
plot([Link](a) / 10)
plot([Link](slice) / 5)
RETURNS
SEE ALSO
[Link]()
Returns true if at least one element of the id array is true, false otherwise.
SYNTAX
ARGUMENTS
REMARKS
This function also works with arrays of int and float types, in which case zero values are considered false, and all
others true.
SEE ALSO
[Link]() [Link]()
[Link]()
The function sorts the elements of an array.
SYNTAX
ARGUMENTS
EXAMPLE
//@version=6
indicator("[Link] example")
a = array.new_float(0,0)
for i = 0 to 5
[Link](a, high[i])
[Link](a, [Link])
if [Link]
[Link](bar_index, close, [Link](a))
SEE ALSO
array.sort_indices()
Returns an array of indices which, when used to index the original array, will access its elements in their sorted order. It
does not modify the original array.
SYNTAX
ARGUMENTS
EXAMPLE
//@version=6
indicator("array.sort_indices")
a = [Link](5, -2, 0, 9, 1)
sortedIndices = array.sort_indices(a) // [1, 2, 4, 0, 3]
indexOfSmallestValue = [Link](sortedIndices, 0) // 1
smallestValue = [Link](a, indexOfSmallestValue) // -2
plot(smallestValue)
SEE ALSO
[Link]() 2 overloads
[Link](id) → array<float>
[Link](id) → array<int>
ARGUMENTS
EXAMPLE
//@version=6
indicator("[Link] example")
a = array.new_float(0)
for i = 0 to 9
[Link](a, close[i])
b = [Link](a)
plot([Link](b))
plot([Link](b))
RETURNS
SEE ALSO
[Link]() 2 overloads
ARGUMENTS
EXAMPLE
//@version=6
indicator("[Link] example")
a = array.new_float(0)
for i = 0 to 9
[Link](a, close[i])
plot([Link](a))
RETURNS
REMARKS
If biased is true, the function calculates using a biased estimate of the entire population. If biased is false, it uses
an unbiased estimate of a sample.
SEE ALSO
[Link]() 2 overloads
ARGUMENTS
EXAMPLE
//@version=6
indicator("[Link] example")
a = array.new_float(0)
for i = 0 to 9
[Link](a, close[i])
plot([Link](a))
RETURNS
REMARKS
[Link]()
The function inserts the value at the beginning of the array.
SYNTAX
ARGUMENTS
value (series <type of the array's elements>) The value to add to the start of the array.
EXAMPLE
//@version=6
indicator("[Link] example")
a = array.new_float(5, 0)
[Link](a, open)
plot([Link](a, 0))
SEE ALSO
[Link]() 2 overloads
ARGUMENTS
EXAMPLE
//@version=6
indicator("[Link] example")
a = array.new_float(0)
for i = 0 to 9
[Link](a, close[i])
plot([Link](a))
RETURNS
REMARKS
If biased is true, function will calculate using a biased estimate of the entire population, if false - unbiased estimate
of a sample.
Returns na if the id array is empty.
SEE ALSO
barcolor()
Set color of bars.
SYNTAX
ARGUMENTS
color (series color) Color of bars. You can use constants like 'red' or '#ff001a' as well as complex expressions like
'close >= open ? [Link] : [Link]'. Required argument.
offset (simple int) Shifts the color series to the left or to the right on the given number of bars. Default is 0.
editable (input bool) If true then barcolor style will be editable in Format dialog. Default is true.
show_last (input int) Optional. The number of bars, counting backwards from the most recent bar, on which the
function can draw.
EXAMPLE
//@version=6
indicator("barcolor example", overlay=true)
barcolor(close < open ? [Link] : [Link])
SEE ALSO
bgcolor()
Fill background of bars with specified color.
SYNTAX
ARGUMENTS
color (series color) Color of the filled background. You can use constants like 'red' or '#ff001a' as well as complex
expressions like 'close >= open ? [Link] : [Link]'. Required argument.
offset (simple int) Shifts the color series to the left or to the right on the given number of bars. Default is 0.
editable (input bool) If true then bgcolor style will be editable in Format dialog. Default is true.
show_last (input int) Optional. The number of bars, counting backwards from the most recent bar, on which the
function can draw.
//@version=6
indicator("bgcolor example", overlay=true)
bgcolor(close < open ? [Link]([Link],70) : [Link]([Link], 70))
SEE ALSO
bool() 4 overloads
Converts the x value to a bool value. Returns false if x is na, false, or an int/float value equal to 0. Returns true for
all other possible values.
ARGUMENTS
x (simple int/float/bool) The value to convert to the specified type, usually na.
RETURNS
SEE ALSO
box()
Casts na to box.
SYNTAX
ARGUMENTS
x (series box) The value to convert to the specified type, usually na.
RETURNS
SEE ALSO
[Link]()
Clones the box object.
SYNTAX
ARGUMENTS
EXAMPLE
//@version=6
indicator('Last 50 bars price ranges', overlay = true)
LOOKBACK = 50
highest = [Link](LOOKBACK)
lowest = [Link](LOOKBACK)
if [Link]
var BoxLast = [Link](bar_index[LOOKBACK], highest, bar_index, lowest, bgcolor = [Link]([Link]
een, 80))
var BoxPrev = [Link](BoxLast)
box.set_lefttop(BoxPrev, bar_index[LOOKBACK * 2], highest[50])
box.set_rightbottom(BoxPrev, bar_index[LOOKBACK], lowest[50])
box.set_bgcolor(BoxPrev, [Link]([Link], 80))
SEE ALSO
[Link]() [Link]()
[Link]()
Deletes the specified box object. If it has already been deleted, does nothing.
SYNTAX
[Link](id) → void
ARGUMENTS
SEE ALSO
[Link]()
box.get_bottom()
Returns the price value of the bottom border of the box.
SYNTAX
ARGUMENTS
RETURNS
SEE ALSO
[Link]() box.set_bottom()
box.get_left()
Returns the bar index or the UNIX time (depending on the last value used for 'xloc') of the left border of the box.
SYNTAX
ARGUMENTS
RETURNS
SEE ALSO
[Link]() box.set_left()
box.get_right()
Returns the bar index or the UNIX time (depending on the last value used for 'xloc') of the right border of the box.
SYNTAX
ARGUMENTS
RETURNS
SEE ALSO
[Link]() box.set_right()
box.get_top()
Returns the price value of the top border of the box.
SYNTAX
ARGUMENTS
RETURNS
SEE ALSO
[Link]() box.set_top()
[Link]() 2 overloads
[Link](top_left, bottom_right, border_color, border_width, border_style, extend, xloc, bgcolor, text, text
_size, text_color, text_halign, text_valign, text_wrap, text_font_family, force_overlay, text_formatting) →
series box
[Link](left, top, right, bottom, border_color, border_width, border_style, extend, xloc, bgcolor, text, te
xt_size, text_color, text_halign, text_valign, text_wrap, text_font_family, force_overlay, text_formatting)
→ series box
ARGUMENTS
top_left ([Link]) A [Link] object that specifies the top-left corner location of the box.
bottom_right ([Link]) A [Link] object that specifies the bottom-right corner location of the box.
border_color (series color) Color of the four borders. Optional. The default is [Link].
border_width (series int) Width of the four borders, in pixels. Optional. The default is 1 pixel.
border_style (series string) Style of the four borders. Possible values: line.style_solid, line.style_dotted,
line.style_dashed. Optional. The default value is line.style_solid.
extend (series string) When [Link] is used, the horizontal borders start at the left border and end at the right
border. With [Link] or [Link], the horizontal borders are extended indefinitely to the left or right of the box,
respectively. With [Link], the horizontal borders are extended on both sides. Optional. The default value is
[Link].
xloc (series string) Determines whether the arguments to 'left' and 'right' are a bar index or a time value. If xloc =
xloc.bar_index, the arguments must be a bar index. If xloc = xloc.bar_time, the arguments must be a UNIX time.
Possible values: xloc.bar_index and xloc.bar_time. Optional. The default is xloc.bar_index.
bgcolor (series color) Background color of the box. Optional. The default is [Link].
text (series string) The text to be displayed inside the box. Optional. The default is empty string.
text_size (series int/string) Optional. Size of the box's text. The size can be any positive integer, or one of the siz
e.* built-in constant strings. The constant strings and their equivalent integer values are: [Link] (0), [Link] (8),
[Link] (10), [Link] (14), [Link] (20), [Link] (36). The default value is [Link] or 0.
text_color (series color) The color of the text. Optional. The default is [Link].
text_halign (series string) The horizontal alignment of the box's text. Optional. The default value is text.align_center.
Possible values: text.align_left, text.align_center, text.align_right.
text_valign (series string) The vertical alignment of the box's text. Optional. The default value is text.align_center.
Possible values: text.align_top, text.align_center, text.align_bottom.
text_wrap (series string) Optional. Whether to wrap text. Wrapped text starts a new line when it reaches the side of
the box. Wrapped text lower than the bottom of the box is not displayed. Unwrapped text stays on a single line and is
displayed past the width of the box if it is too long. If the text_size is 0 or text.wrap_auto, this setting has no
effect. The default value is text.wrap_none. Possible values: text.wrap_none, text.wrap_auto.
text_font_family (series string) The font family of the text. Optional. The default value is font.family_default. Possible
values: font.family_default, font.family_monospace.
force_overlay (const bool) If true, the drawing will display on the main chart pane, even when the script occupies a
separate pane. Optional. The default is false.
text_formatting (const text_format) The formatting of the displayed text. Formatting options support addition. For
example, text.format_bold + text.format_italic will make the text both bold and italicized. Possible
values: text.format_none, text.format_bold, text.format_italic. Optional. The default is text.format_none.
EXAMPLE
//@version=6
indicator("[Link]")
var b = [Link](time, open, time + 60 * 60 * 24, close, xloc=xloc.bar_time, border_style=line.style_das
hed)
box.set_lefttop(b, time, 100)
box.set_rightbottom(b, time + 60 * 60 * 24, 500)
box.set_bgcolor(b, [Link])
RETURNS
The ID of a box object which may be used in box.set_*() and box.get_*() functions.
SEE ALSO
box.set_text_formatting() box.set_xloc()
box.set_bgcolor()
Sets the background color of the box.
SYNTAX
ARGUMENTS
SEE ALSO
[Link]()
box.set_border_color()
Sets the border color of the box.
SYNTAX
ARGUMENTS
SEE ALSO
[Link]()
box.set_border_style()
Sets the border style of the box.
SYNTAX
ARGUMENTS
SEE ALSO
SYNTAX
ARGUMENTS
SEE ALSO
[Link]()
box.set_bottom()
Sets the bottom coordinate of the box.
SYNTAX
ARGUMENTS
SEE ALSO
[Link]() box.get_bottom()
box.set_bottom_right_point()
Sets the bottom-right corner location of the id box to point .
SYNTAX
ARGUMENTS
box.set_extend()
Sets extending type of the border of this box object. When [Link] is used, the horizontal borders start at the left
border and end at the right border. With [Link] or [Link], the horizontal borders are extended indefinitely to
the left or right of the box, respectively. With [Link], the horizontal borders are extended on both sides.
SYNTAX
ARGUMENTS
SEE ALSO
box.set_left()
Sets the left coordinate of the box.
SYNTAX
ARGUMENTS
left (series int) Bar index or bar time of the left border. Note that objects positioned using xloc.bar_index cannot be
drawn further than 500 bars into the future.
SEE ALSO
[Link]() box.get_left()
box.set_lefttop()
Sets the left and top coordinates of the box.
SYNTAX
ARGUMENTS
left (series int) Bar index or bar time of the left border.
top (series int/float) Price value of the top border.
SEE ALSO
box.set_right()
Sets the right coordinate of the box.
SYNTAX
ARGUMENTS
right (series int) Bar index or bar time of the right border. Note that objects positioned using xloc.bar_index cannot be
drawn further than 500 bars into the future.
SEE ALSO
[Link]() box.get_right()
box.set_rightbottom()
Sets the right and bottom coordinates of the box.
SYNTAX
ARGUMENTS
right (series int) Bar index or bar time of the right border.
bottom (series int/float) Price value of the bottom border.
SEE ALSO
box.set_text()
The function sets the text in the box.
SYNTAX
ARGUMENTS
SEE ALSO
box.set_text_color()
The function sets the color of the text inside the box.
SYNTAX
ARGUMENTS
SEE ALSO
box.set_text_font_family()
The function sets the font family of the text inside the box.
SYNTAX
text_font_family (series string) The font family of the text. Possible values: font.family_default,
font.family_monospace.
EXAMPLE
//@version=6
indicator("Example of setting the box font")
if [Link]
b = [Link](bar_index, [Link], bar_index-50, [Link]*5, text="monospace")
box.set_text_font_family(b, font.family_monospace)
SEE ALSO
box.set_text_formatting()
Sets the formatting attributes the drawing applies to displayed text.
SYNTAX
ARGUMENTS
SEE ALSO
box.set_text_halign()
The function sets the horizontal alignment of the box's text.
SYNTAX
ARGUMENTS
text_halign (series string) The horizontal alignment of a box's text. Possible values: text.align_left, text.align_center,
text.align_right.
SEE ALSO
box.set_text_size()
The function sets the size of the box's text.
SYNTAX
box.set_text_size(id, text_size) → void
ARGUMENTS
SEE ALSO
box.set_text_valign()
The function sets the vertical alignment of a box's text.
SYNTAX
ARGUMENTS
text_valign (series string) The vertical alignment of the box's text. Possible values: text.align_top, text.align_center,
text.align_bottom.
SEE ALSO
box.set_text_wrap()
The function sets the mode of wrapping of the text inside the box.
SYNTAX
ARGUMENTS
text_wrap (series string) Whether to wrap text. Wrapped text starts a new line when it reaches the side of the box.
Wrapped text lower than the bottom of the box is not displayed. Unwrapped text stays on a single line and is displayed
past the width of the box if it is too long. If the text_size is 0 or text.wrap_auto, this setting has no effect. Possible
values: text.wrap_none, text.wrap_auto.
SEE ALSO
box.set_top()
Sets the top coordinate of the box.
SYNTAX
ARGUMENTS
id (series box) A box object.
SEE ALSO
[Link]() box.get_top()
box.set_top_left_point()
Sets the top-left corner location of the id box to point .
SYNTAX
ARGUMENTS
box.set_xloc()
Sets the left and right borders of a box and updates its xloc property.
SYNTAX
ARGUMENTS
right (series int) The bar index or timestamp for the right border of the box.
xloc (series string) Determines whether the box treats the left and right arguments as bar indices or
timestamps. Possible values: xloc.bar_index and xloc.bar_time. If the value is xloc.bar_index, the arguments represent
bar indices. If xloc.bar_time, the arguments represent UNIX timestamps.
SEE ALSO
[Link]()
Creates a copy of a [Link] object with the specified id .
SYNTAX
[Link](id) → [Link]
ARGUMENTS
[Link].from_index()
Returns a [Link] object with index as its x-coordinate and price as its y-coordinate.
SYNTAX
[Link].from_index(index, price) → [Link]
ARGUMENTS
index (series int) The x-coordinate of the point, expressed as a bar index value.
price (series int/float) The y-coordinate of the point.
REMARKS
The time field values of [Link] instances returned from this function will be na, meaning drawing objects with x
loc values set to xloc.bar_time will not work with them.
[Link].from_time()
Returns a [Link] object with time as its x-coordinate and price as its y-coordinate.
SYNTAX
ARGUMENTS
time (series int) The x-coordinate of the point, expressed as a UNIX time value, in milliseconds.
REMARKS
The index field values of [Link] instances returned from this function will be na, meaning drawing objects with
xloc values set to xloc.bar_index will not work with them.
[Link]()
Creates a new [Link] object with the specified time , index , and price .
SYNTAX
ARGUMENTS
time (series int) The x-coordinate of the point, expressed as a UNIX time value, in milliseconds.
index (series int) The x-coordinate of the point, expressed as a bar index value.
REMARKS
Whether a drawing object uses a point's time or index field as an x-coordinate depends on the xloc type used
in the function call that returned the drawing.
It's important to note that this function does not verify that the time and index values refer to the same bar.
SEE ALSO
[Link]()
[Link]()
Returns a [Link] object with price as the y-coordinate
SYNTAX
[Link](price) → [Link]
ARGUMENTS
price (series int/float) The y-coordinate of the point. Optional. The default is close.
REMARKS
The [Link] instance returned from this function records values for its index and time fields on the bar it
executed on, making it suitable for use with drawing objects of any xloc type.
color() 4 overloads
Casts na to color
ARGUMENTS
x (const color) The value to convert to the specified type, usually na.
RETURNS
SEE ALSO
color.b() 4 overloads
ARGUMENTS
EXAMPLE
//@version=6
indicator("color.b", overlay=true)
plot(color.b([Link]))
RETURNS
The value (0 to 255) of the color's blue component.
color.from_gradient()
Based on the relative position of value in the bottom_value to top_value range, the function returns a color from the
gradient defined by bottom_color to top_color.
SYNTAX
ARGUMENTS
EXAMPLE
//@version=6
indicator("color.from_gradient", overlay=true)
color1 = color.from_gradient(close, low, high, [Link], [Link])
color2 = color.from_gradient([Link](close, 7), 0, 100, [Link](255, 0, 0), [Link](0, 255, 0, 50))
plot(close, color=color1)
plot([Link](close,7), color=color2)
RETURNS
REMARKS
Using this function will have an impact on the colors displayed in the script's "Settings/Style" tab. See the User Manual
for more information.
color.g() 4 overloads
ARGUMENTS
EXAMPLE
//@version=6
indicator("color.g", overlay=true)
plot(color.g([Link]))
RETURNS
[Link]() 4 overloads
ARGUMENTS
EXAMPLE
//@version=6
indicator("[Link]", overlay=true)
plot(close, color=[Link]([Link], 50))
RETURNS
REMARKS
Using arguments that are not constants (e.g., 'simple', 'input' or 'series') will have an impact on the colors displayed in
the script's "Settings/Style" tab. See the User Manual for more information.
color.r() 4 overloads
ARGUMENTS
//@version=6
indicator("color.r", overlay=true)
plot(color.r([Link]))
RETURNS
[Link]() 4 overloads
Creates a new color with transparency using the RGB color model.
ARGUMENTS
red (const int/float) Red color component. Possible values are from 0 to 255.
green (const int/float) Green color component. Possible values are from 0 to 255.
blue (const int/float) Blue color component. Possible values are from 0 to 255.
transp (const int/float) Optional. Color transparency. Possible values are from 0 (opaque) to 100 (invisible). Default
value is 0.
EXAMPLE
//@version=6
indicator("[Link]", overlay=true)
plot(close, color=[Link](255, 0, 0, 50))
RETURNS
REMARKS
Using arguments that are not constants (e.g., 'simple', 'input' or 'series') will have an impact on the colors displayed in
the script's "Settings/Style" tab. See the User Manual for more information.
color.t() 4 overloads
ARGUMENTS
EXAMPLE
//@version=6
indicator("color.t", overlay=true)
plot(color.t([Link]([Link], 50)))
RETURNS
dayofmonth()
Calculates the day number of the month, in a specified time zone, from a UNIX timestamp.
SYNTAX
ARGUMENTS
RETURNS
The calculated day of the month, expressed in the specified time zone.
REMARKS
A UNIX timestamp represents the number of milliseconds elapsed since 00:00 UTC on 1970-01-01. The meaning of a
UNIX timestamp does not change relative to any time zone.
SEE ALSO
dayofweek()
Calculates the day number of the week, in a specified time zone, from a UNIX timestamp.
SYNTAX
ARGUMENTS
timezone (series string) Optional. Specifies the time zone of the returned day number. The value can be a time zone
string in UTC/GMT offset notation (e.g., "UTC-5") or IANA time zone database notation (e.g., "America/New_York").
The default is [Link].
RETURNS
The calculated day number, expressed in the specified time zone.
REMARKS
A UNIX timestamp represents the number of milliseconds elapsed since 00:00 UTC on 1970-01-01. The meaning of a
UNIX timestamp does not change relative to any time zone.
SEE ALSO
fill() 3 overloads
fill(plot1, plot2, top_value, bottom_value, top_color, bottom_color, title, display, fillgaps, editable) →
void
ARGUMENTS
editable (input bool) If true then fill style will be editable in Format dialog. Default is true.
fillgaps (const bool) Controls continuing fills on gaps, i.e., when one of the plot() calls returns an na value. When true,
the last fill will continue on gaps. The default is false.
display (input plot_simple_display) Controls where the fill is displayed. Possible values are: [Link], [Link].
Default is [Link].
Fill between two horizontal lines
EXAMPLE
//@version=6
indicator("Fill between hlines", overlay = false)
h1 = hline(20)
h2 = hline(10)
fill(h1, h2, color = [Link]([Link], 90))
EXAMPLE
//@version=6
indicator("Fill between plots", overlay = true)
p1 = plot(open)
p2 = plot(close)
fill(p1, p2, color = [Link]([Link], 90))
//@version=6
indicator("Gradient Fill between hlines", overlay = false)
topVal = [Link](100)
botVal = [Link](0)
topCol = [Link]([Link])
botCol = [Link]([Link])
topLine = hline(100, color = topCol, linestyle = hline.style_solid)
botLine = hline(0, color = botCol, linestyle = hline.style_solid)
fill(topLine, botLine, topVal, botVal, topCol, botCol)
SEE ALSO
fixnan() 3 overloads
For a given series replaces NaN values with previous nearest non-NaN value.
ARGUMENTS
RETURNS
SEE ALSO
na() na nz()
float() 4 overloads
Casts na to float
ARGUMENTS
x (const int/float) The value to convert to the specified type, usually na.
RETURNS
footprint.buy_volume()
Returns the total buy volume in the specified footprint object.
SYNTAX
ARGUMENTS
RETURNS
[Link]()
Returns the volume delta (buy volume − sell volume) in the specified footprint object.
SYNTAX
ARGUMENTS
RETURNS
footprint.get_row_by_price()
Returns the volume_row within the specified footprint whose price interval contains the given price.
If the price does not belong to any level of the footprint, the function returns na .
SYNTAX
ARGUMENTS
price (series int/float) The price for which to find the corresponding footprint level.
RETURNS
The volume_row whose price interval contains price , or na if the price is outside all footprint levels.
[Link]()
Returns the Point of Control (POC) level of the specified footprint object.
The POC is the volume_row inside the footprint with the largest total volume.
SYNTAX
[Link](id) → volume_row
ARGUMENTS
RETURNS
[Link]()
Returns an array of all volume_row objects that make up the specified footprint object.
SYNTAX
[Link](id) → array<volume_row>
ARGUMENTS
RETURNS
footprint.sell_volume()
Returns the total sell volume in the specified footprint object.
SYNTAX
ARGUMENTS
RETURNS
footprint.total_volume()
Returns the total traded volume (buy + sell) in the specified footprint object.
SYNTAX
ARGUMENTS
RETURNS
[Link]()
Returns the Value Area High (VAH) level of the specified footprint object.
The VAH is the highest volume_row included in the Value Area as defined by the va_percent parameter of requ
[Link]() .
SYNTAX
[Link](id) → volume_row
ARGUMENTS
RETURNS
[Link]()
Returns the Value Area Low (VAL) level of the specified footprint object.
The VAL is the lowest volume_row included in the Value Area as defined by the va_percent parameter of reque
[Link]() .
SYNTAX
[Link](id) → volume_row
ARGUMENTS
RETURNS
hline()
Renders a horizontal line at a given fixed price level.
SYNTAX
ARGUMENTS
price (input int/float) Price value at which the object will be rendered. Required argument.
linestyle (input hline_style) Style of the rendered line. Possible values are: hline.style_solid, hline.style_dotted,
hline.style_dashed. Optional argument.
display (input plot_simple_display) Controls where the hline is displayed. Possible values are: [Link],
[Link]. Default is [Link].
EXAMPLE
//@version=6
indicator("[Link]", overlay=true)
hline(3.14, title='Pi', color=[Link], linestyle=hline.style_dotted, linewidth=2)
// You may fill the background between any two hlines with a fill() function:
h1 = hline(20)
h2 = hline(10)
fill(h1, h2, color=[Link]([Link], 90))
RETURNS
fill()
hour()
SYNTAX
ARGUMENTS
RETURNS
REMARKS
UNIX time is the number of milliseconds that have elapsed since 00:00:00 UTC, 1 January 1970.
SEE ALSO
indicator()
A declaration statement that identifies the script as an indicator and sets specific script-wide properties.
SYNTAX
ARGUMENTS
title (const string) A string representing the script's title. The script displays the string's text in all possible locations if
the declaration statement does not include a shorttitle argument. Additionally, the "Publish script" window uses
the text as the default title for a script publication.
shorttitle (const string) Optional. A string representing the script's display name on charts. If specified and not an
empty string, the value's text replaces the title string in most chart locations, including the "Settings" window, the
script's status line, the Data Window, and the "Create alert" dialog box. Otherwise, the title string appears as the
script's title in all locations. The default is an empty string.
overlay (const bool) Optional. If true , the script's visuals appear on the main chart pane if the user adds it to the
chart directly, or in another script's pane if the user applies it to that script. If false , the script's visuals appear in a
separate pane. However, if a function call that creates visuals includes force_overlay = true , its output always
appears on the main chart pane, even if the script occupies a separate pane. Changes to this argument apply only
after the user adds the script to the chart again. Additionally, if the user moves the script to another pane by selecting
a "Move to" option in the script's "More" menu, the script does not move back to its original pane after any updates to
the source code. The default is false .
format (const string) Optional. Specifies the format of the script's plotted values. Possible values are [Link],
[Link], [Link], and [Link]. The default is [Link].
precision (const int) Optional. Specifies the number of fractional digits that the script shows for plotted numbers. The
value must be an integer from 0 to 16. If specified and the format argument is [Link], the script uses
[Link] as the formatting option instead. If the format argument is {[Link]}, the script ignores the pre
cision value, because the decimal precision rules specified by [Link] supersede other precision settings. By
default, the script inherits the precision settings of the chart.
scale (const scale_type) Optional. Specifies the location of the script's price scale. Possible values are [Link] for
the right side of the pane, [Link] for the left side of the pane, or [Link] to use the pane's default scale. The
[Link] argument is allowed only if the overlay value is true . If the script overlays on the main chart pane and
uses [Link] or [Link], it adds a separate scale to the pane. Changes to the argument apply only after the user
adds the script to the chart again. If not specified, the script uses the pane's default scale.
max_bars_back (const int) Optional. Sets the minimum length of all the script's historical buffers, which determine
the number of bars back that the script can reference for each series using the [] operator or the functions that
retrieve history internally. The value must be an integer from 0 to 5000. By default, Pine's runtime system
automatically calculates appropriate historical buffer sizes for each series while loading a script. Manually setting
buffer sizes is necessary only in rare cases where automatic size detection fails. See the Historical buffers section of
our User Manual for advanced details.
timeframe (const string) Optional. A valid timeframe string that determines the main timeframe the script uses for its
calculations. If specified, the script automatically adds a "Timeframe" input to the "Settings/Inputs" tab. The input's
displayed default in the tab represents the same timeframe as the specified argument. If the value is an empty string or
not specified, the script uses the same timeframe as the chart. An argument is allowed for this parameter only if the
script does not use drawing types or alert() function calls.
timeframe_gaps (const bool) Optional. Controls how the script displays plotted values if the timeframe value
represents a higher timeframe than the chart's timeframe. An argument for this parameter is allowed only if the call
includes a timeframe argument. If specified, the script adds a "Wait for timeframe closes" input, where users can
change the setting, below the generated "Timeframe" input in the "Settings/Inputs" tab. If true , the indicator
displays values only on the chart bars where new higher-timeframe data is available, and na on all other bars. If fals
e , the indicator displays the last retrieved values on all chart bars where new data is not available. The default is tru
e.
explicit_plot_zorder (const bool) Optional. Specifies which rules the script uses to determine the visual order of
plots from plot*() calls, levels from hline() calls, and fills from fill() calls on the chart. If true , the indicator
displays these visuals in the order of their function calls in the code. If false , the script uses the default z-index
rules to determine the order of the visuals. The default is false .
max_lines_count (const int) Optional. Determines the maximum number of line objects that remain available to the
script. The system automatically deletes the oldest line objects when the number of lines exceeds the limit. The limit
specified by the argument is approximate; the script might display more drawings than specified. The default is ~50
lines.
max_labels_count (const int) Optional. Determines the maximum number of label objects that remain available to the
script. The system automatically deletes the oldest label objects when the number of labels exceeds the limit. The limit
specified by the argument is approximate; the script might display more drawings than specified. The default is ~50
labels.
max_boxes_count (const int) Optional. Determines the maximum number of box objects that remain available to the
script. The system automatically deletes the oldest box objects when the number of boxes exceeds the limit. The limit
specified by the argument is approximate; the script might display more drawings than specified. The default is ~50
boxes.
calc_bars_count (const int) Optional. Determines how many of the most recent historical bars are available to the
script. If specified, the script automatically adds a "Calculated bars" input to the "Settings/Inputs" tab. If the value is
positive and less than the number of historical bars in the dataset, the script starts its calculations that number of bars
before the most recent bar. If the value is 0, the script's calculations start on the dataset's first bar. The default is 0.
max_polylines_count (const int) Optional. Determines the maximum number of polyline objects that remain available
to the script. The system automatically deletes the oldest polyline objects when the number of polylines exceeds the
limit. The limit specified by the argument is approximate; the script might display more drawings than specified. The
default is ~50 polylines.
dynamic_requests (const bool) Optional. Specifies whether the script can use dynamic request.*() function
calls. Dynamic request.*() calls are allowed within the local scopes of conditional structures (e.g., if), loops (e.g.,
for), and exported functions. Additionally, such calls allow "series" arguments for several parameters that otherwise
require values with "simple" or weaker qualifiers. See the Dynamic requests section of our User Manual for more
information. The default is true .
behind_chart (const bool) Optional. Controls whether all plots and drawings appear behind the chart display (if tru
e ) or in front of it (if false ). This parameter takes effect only when the overlay argument is true . Changes to
the argument apply only after the user adds the script to the chart again. The default is true .
EXAMPLE
//@version=6
indicator("My script", shorttitle="Script")
plot(close)
REMARKS
Every indicator script must include exactly one indicator() statement in the code.
SEE ALSO
strategy() library()
input() 6 overloads
Adds an input to the Inputs tab of your script's Settings, which allows you to provide configuration options to script
users. This function automatically detects the type of the argument used for 'defval' and uses the corresponding input
widget.
ARGUMENTS
defval (const int/float/bool/string/color or source-type built-ins) Determines the default value of the input variable
proposed in the script's "Settings/Inputs" tab, from where script users can change it. Source-type built-ins are built-in
series float variables that specify the source of the calculation: close , hlc3 , etc.
title (const string) Title of the input. If not specified, the variable name is used as the input's title. If the title is
specified, but it is empty, the name will be an empty string.
tooltip (const string) The string that will be shown to the user when hovering over the tooltip icon.
inline (const string) Combines all the input calls using the same argument in one line. The string used as an argument
is not displayed. It is only used to identify inputs belonging to the same line.
group (const string) Creates a header above all inputs using the same group argument string. The string is also used
as the header's text.
display (const plot_display) Controls where the script will display the input's information, aside from within the
script's settings. This option allows one to remove a specific input from the script's status line or the Data Window to
ensure only the most necessary inputs are displayed there. Possible values: [Link], display.data_window,
display.status_line, [Link]. Optional. The default depends on the type of the value passed to defval :
[Link] for bool and color values, [Link] for everything else.
active (input bool) Optional. Specifies whether users can change the value of the input in the script's
"Settings/Inputs" tab. The script can use this parameter to set the state of the input based on the values of other
inputs. If true, users can change the value of the input. If false, the input is grayed out, and users cannot change the
value. The default is true.
EXAMPLE
//@version=6
indicator("input", overlay=true)
i_switch = input(true, "On/Off")
plot(i_switch ? open : na)
RETURNS
REMARKS
Result of input() function always should be assigned to a variable, see examples above.
SEE ALSO
[Link]()
Adds an input to the Inputs tab of your script's Settings, which allows you to provide configuration options to script
users. This function adds a checkmark to the script's inputs.
SYNTAX
[Link](defval, title, tooltip, inline, group, confirm, display, active) → input bool
ARGUMENTS
defval (const bool) Determines the default value of the input variable proposed in the script's "Settings/Inputs" tab,
from where the user can change it.
title (const string) Title of the input. If not specified, the variable name is used as the input's title. If the title is
specified, but it is empty, the name will be an empty string.
tooltip (const string) The string that will be shown to the user when hovering over the tooltip icon.
inline (const string) Combines all the input calls using the same argument in one line. The string used as an argument
is not displayed. It is only used to identify inputs belonging to the same line.
group (const string) Creates a header above all inputs using the same group argument string. The string is also used
as the header's text.
confirm (const bool) If true, then user will be asked to confirm input value before indicator is added to chart. Default
value is false.
display (const plot_display) Controls where the script will display the input's information, aside from within the
script's settings. This option allows one to remove a specific input from the script's status line or the Data Window to
ensure only the most necessary inputs are displayed there. Possible values: [Link], display.data_window,
display.status_line, [Link]. Optional. The default is [Link].
active (input bool) Optional. Specifies whether users can change the value of the input in the script's
"Settings/Inputs" tab. The script can use this parameter to set the state of the input based on the values of other
inputs. If true, users can change the value of the input. If false, the input is grayed out, and users cannot change the
value. The default is true.
EXAMPLE
//@version=6
indicator("[Link]", overlay=true)
i_switch = [Link](true, "On/Off")
plot(i_switch ? open : na)
RETURNS
REMARKS
Result of [Link]() function always should be assigned to a variable, see examples above.
SEE ALSO
[Link]()
Adds an input to the Inputs tab of your script's Settings, which allows you to provide configuration options to script
users. This function adds a color picker that allows the user to select a color and transparency, either from a palette or
a hex value.
SYNTAX
[Link](defval, title, tooltip, inline, group, confirm, display, active) → input color
ARGUMENTS
defval (const color) Determines the default value of the input variable proposed in the script's "Settings/Inputs" tab,
from where the user can change it.
title (const string) Title of the input. If not specified, the variable name is used as the input's title. If the title is
specified, but it is empty, the name will be an empty string.
tooltip (const string) The string that will be shown to the user when hovering over the tooltip icon.
inline (const string) Combines all the input calls using the same argument in one line. The string used as an argument
is not displayed. It is only used to identify inputs belonging to the same line.
group (const string) Creates a header above all inputs using the same group argument string. The string is also used
as the header's text.
confirm (const bool) If true, then user will be asked to confirm input value before indicator is added to chart. Default
value is false.
display (const plot_display) Controls where the script will display the input's information, aside from within the
script's settings. This option allows one to remove a specific input from the script's status line or the Data Window to
ensure only the most necessary inputs are displayed there. Possible values: [Link], display.data_window,
display.status_line, [Link]. Optional. The default is [Link].
active (input bool) Optional. Specifies whether users can change the value of the input in the script's
"Settings/Inputs" tab. The script can use this parameter to set the state of the input based on the values of other
inputs. If true, users can change the value of the input. If false, the input is grayed out, and users cannot change the
value. The default is true.
EXAMPLE
//@version=6
indicator("[Link]", overlay=true)
i_col = [Link]([Link], "Plot Color")
plot(close, color=i_col)
RETURNS
REMARKS
Result of [Link]() function always should be assigned to a variable, see examples above.
SEE ALSO
[Link]()
Adds an input to the Inputs tab of your script's Settings, which allows you to provide configuration options to script
users. This function adds a dropdown with options based on the enum fields passed to its defval and options
parameters.
The text for each option in the resulting dropdown corresponds to the titles of the included fields. If a field's title is not
specified in the enum declaration, its title is the string representation of its name.
SYNTAX
[Link](defval, title, options, tooltip, inline, group, confirm, display, active) → input enum
ARGUMENTS
defval (const enum) Determines the default value of the input, which users can change in the script's
"Settings/Inputs" tab. When the options parameter has a specified tuple of enum fields, the tuple must include the
defval .
title (const string) Title of the input. If not specified, the variable name is used as the input's title. If the title is
specified, but it is empty, the name will be an empty string.
options (tuple of enum fields: [enumName.field1, enumName.field2, ...]) A list of options to choose from.
Optional. By default, the titles of all of the enum's fields are available in the dropdown. Passing a tuple as the option
s argument limits the list to only the included fields.
tooltip (const string) The string that will be shown to the user when hovering over the tooltip icon.
inline (const string) Combines all the input calls using the same argument in one line. The string used as an argument
is not displayed. It is only used to identify inputs belonging to the same line.
group (const string) Creates a header above all inputs using the same group argument string. The string is also used
as the header's text.
confirm (const bool) If true , then user will be asked to confirm input value before indicator is added to chart.
Default value is false .
display (const plot_display) Controls where the script will display the input's information, aside from within the
script's settings. This option allows one to remove a specific input from the script's status line or the Data Window to
ensure only the most necessary inputs are displayed there. Possible values: [Link], display.data_window,
display.status_line, [Link]. Optional. The default is [Link].
active (input bool) Optional. Specifies whether users can change the value of the input in the script's
"Settings/Inputs" tab. The script can use this parameter to set the state of the input based on the values of other
inputs. If true, users can change the value of the input. If false, the input is grayed out, and users cannot change the
value. The default is true.
EXAMPLE
//@version=6
indicator("Session highlight", overlay = true)
RETURNS
REMARKS
All fields included in the defval and options arguments must belong to the same enum.
SEE ALSO
[Link]() 2 overloads
Adds an input to the Inputs tab of your script's Settings, which allows you to provide configuration options to script
users. This function adds a field for a float input to the script's inputs.
[Link](defval, title, options, tooltip, inline, group, confirm, display, active) → input float
[Link](defval, title, minval, maxval, step, tooltip, inline, group, confirm, display, active) → input
float
ARGUMENTS
defval (const int/float) Determines the default value of the input variable proposed in the script's "Settings/Inputs"
tab, from where script users can change it. When a list of values is used with the options parameter, the value must
be one of them.
title (const string) Title of the input. If not specified, the variable name is used as the input's title. If the title is
specified, but it is empty, the name will be an empty string.
options (tuple of const int/float values: [val1, val2, ...]) A list of options to choose from a dropdown menu,
separated by commas and enclosed in square brackets: [val1, val2, ...]. When using this parameter, the minval , ma
xval and step parameters cannot be used.
tooltip (const string) The string that will be shown to the user when hovering over the tooltip icon.
inline (const string) Combines all the input calls using the same argument in one line. The string used as an argument
is not displayed. It is only used to identify inputs belonging to the same line.
group (const string) Creates a header above all inputs using the same group argument string. The string is also used
as the header's text.
confirm (const bool) If true, then user will be asked to confirm input value before indicator is added to chart. Default
value is false.
display (const plot_display) Controls where the script will display the input's information, aside from within the
script's settings. This option allows one to remove a specific input from the script's status line or the Data Window to
ensure only the most necessary inputs are displayed there. Possible values: [Link], display.data_window,
display.status_line, [Link]. Optional. The default is [Link].
active (input bool) Optional. Specifies whether users can change the value of the input in the script's
"Settings/Inputs" tab. The script can use this parameter to set the state of the input based on the values of other
inputs. If true, users can change the value of the input. If false, the input is grayed out, and users cannot change the
value. The default is true.
EXAMPLE
//@version=6
indicator("[Link]", overlay=true)
i_angle1 = [Link](0.5, "Sin Angle", minval=-3.14, maxval=3.14, step=0.02)
plot([Link](i_angle1) > 0 ? close : open, "sin", color=[Link])
RETURNS
REMARKS
Result of [Link]() function always should be assigned to a variable, see examples above.
SEE ALSO
[Link]() 2 overloads
Adds an input to the Inputs tab of your script's Settings, which allows you to provide configuration options to script
users. This function adds a field for an integer input to the script's inputs.
[Link](defval, title, options, tooltip, inline, group, confirm, display, active) → input int
[Link](defval, title, minval, maxval, step, tooltip, inline, group, confirm, display, active) → input in
t
ARGUMENTS
defval (const int) Determines the default value of the input variable proposed in the script's "Settings/Inputs" tab,
from where script users can change it. When a list of values is used with the options parameter, the value must be
one of them.
title (const string) Title of the input. If not specified, the variable name is used as the input's title. If the title is
specified, but it is empty, the name will be an empty string.
options (tuple of const int values: [val1, val2, ...]) A list of options to choose from a dropdown menu, separated by
commas and enclosed in square brackets: [val1, val2, ...]. When using this parameter, the minval , maxval and s
tep parameters cannot be used.
tooltip (const string) The string that will be shown to the user when hovering over the tooltip icon.
inline (const string) Combines all the input calls using the same argument in one line. The string used as an argument
is not displayed. It is only used to identify inputs belonging to the same line.
group (const string) Creates a header above all inputs using the same group argument string. The string is also used
as the header's text.
confirm (const bool) If true, then user will be asked to confirm input value before indicator is added to chart. Default
value is false.
display (const plot_display) Controls where the script will display the input's information, aside from within the
script's settings. This option allows one to remove a specific input from the script's status line or the Data Window to
ensure only the most necessary inputs are displayed there. Possible values: [Link], display.data_window,
display.status_line, [Link]. Optional. The default is [Link].
active (input bool) Optional. Specifies whether users can change the value of the input in the script's
"Settings/Inputs" tab. The script can use this parameter to set the state of the input based on the values of other
inputs. If true, users can change the value of the input. If false, the input is grayed out, and users cannot change the
value. The default is true.
EXAMPLE
//@version=6
indicator("[Link]", overlay=true)
i_len1 = [Link](10, "Length 1", minval=5, maxval=21, step=1)
plot([Link](close, i_len1))
RETURNS
REMARKS
Result of [Link]() function always should be assigned to a variable, see examples above.
SEE ALSO
[Link]()
Adds a price input to the script's "Settings/Inputs" tab. The user can change the price in the settings or by selecting
the indicator and dragging the price line.
SYNTAX
[Link](defval, title, tooltip, inline, group, confirm, display, active) → input float
ARGUMENTS
defval (const int/float) Determines the default value of the input variable proposed in the script's "Settings/Inputs"
tab, from where the user can change it.
title (const string) Title of the input. If not specified, the variable name is used as the input's title. If the title is
specified, but it is empty, the name will be an empty string.
tooltip (const string) The string that will be shown to the user when hovering over the tooltip icon.
inline (const string) Combines all the input calls using the same argument in one line. The string used as an argument
is not displayed. It is only used to identify inputs belonging to the same line.
group (const string) Creates a header above all inputs using the same group argument string. The string is also used
as the header's text.
confirm (const bool) Optional. If true, the script prompts the user to set the input's initial value by clicking a point on
the chart. If inputs of other types require confirmation, the "Confirm inputs" dialog box also displays this input's field,
allowing final adjustments to the value before the script starts to run. The default is false.
display (const plot_display) Controls where the script will display the input's information, aside from within the
script's settings. This option allows one to remove a specific input from the script's status line or the Data Window to
ensure only the most necessary inputs are displayed there. Possible values: [Link], display.data_window,
display.status_line, [Link]. Optional. The default is [Link].
active (input bool) Optional. Specifies whether users can change the value of the input in the script's
"Settings/Inputs" tab. The script can use this parameter to set the state of the input based on the values of other
inputs. If true, users can change the value of the input. If false, the input is grayed out, and users cannot change the
value. The default is true.
EXAMPLE
//@version=6
indicator("[Link]", overlay=true)
price1 = [Link](title="Date", defval=42)
plot(price1)
RETURNS
REMARKS
The user can change the input's value by specifying a new value in the "Settings/Inputs" tab, or by moving the input's
marker on the chart. Alternatively, they can select "Reset points" from the script's "More" menu and set a new input
value by clicking a point on the chart.
If an [Link]() and [Link]() function call in the script share a unique inline argument and have matching gr
oup arguments, those calls create a single interactive point marker on the chart. The user can move that marker to
adjust the input time and price values simultaneously.
SEE ALSO
[Link]()
Adds an input to the Inputs tab of your script's Settings, which allows you to provide configuration options to script
users. This function adds two dropdowns that allow the user to specify the beginning and the end of a session using
the session selector and returns the result as a string.
SYNTAX
[Link](defval, title, options, tooltip, inline, group, confirm, display, active) → input string
ARGUMENTS
defval (const string) Determines the default value of the input variable proposed in the script's "Settings/Inputs" tab,
from where the user can change it. When a list of values is used with the options parameter, the value must be one
of them.
title (const string) Title of the input. If not specified, the variable name is used as the input's title. If the title is
specified, but it is empty, the name will be an empty string.
options (tuple of const string values: [val1, val2, ...]) A list of options to choose from.
tooltip (const string) The string that will be shown to the user when hovering over the tooltip icon.
inline (const string) Combines all the input calls using the same argument in one line. The string used as an argument
is not displayed. It is only used to identify inputs belonging to the same line.
group (const string) Creates a header above all inputs using the same group argument string. The string is also used
as the header's text.
confirm (const bool) If true, then user will be asked to confirm input value before indicator is added to chart. Default
value is false.
display (const plot_display) Controls where the script will display the input's information, aside from within the
script's settings. This option allows one to remove a specific input from the script's status line or the Data Window to
ensure only the most necessary inputs are displayed there. Possible values: [Link], display.data_window,
display.status_line, [Link]. Optional. The default is [Link].
active (input bool) Optional. Specifies whether users can change the value of the input in the script's
"Settings/Inputs" tab. The script can use this parameter to set the state of the input based on the values of other
inputs. If true, users can change the value of the input. If false, the input is grayed out, and users cannot change the
value. The default is true.
EXAMPLE
//@version=6
indicator("[Link]", overlay=true)
i_sess = [Link]("1300-1700", "Session", options=["0930-1600", "1300-1700", "1700-2100"])
t = time([Link], i_sess)
bgcolor(time == t ? [Link] : na)
RETURNS
REMARKS
Result of [Link]() function always should be assigned to a variable, see examples above.
SEE ALSO
[Link]()
Adds an input to the Inputs tab of your script's Settings, which allows you to provide configuration options to script
users. This function adds a dropdown that allows the user to select a source for the calculation, e.g. close, hl2, etc.
The user can also select an output from another indicator on their chart as the source.
SYNTAX
[Link](defval, title, tooltip, inline, group, display, active, confirm) → series float
ARGUMENTS
defval (open/high/low/close/hl2/hlc3/ohlc4/hlcc4) Determines the default value of the input variable proposed in
the script's "Settings/Inputs" tab, from where the user can change it.
title (const string) Title of the input. If not specified, the variable name is used as the input's title. If the title is
specified, but it is empty, the name will be an empty string.
tooltip (const string) The string that will be shown to the user when hovering over the tooltip icon.
inline (const string) Combines all the input calls using the same argument in one line. The string used as an argument
is not displayed. It is only used to identify inputs belonging to the same line.
group (const string) Creates a header above all inputs using the same group argument string. The string is also used
as the header's text.
display (const plot_display) Controls where the script will display the input's information, aside from within the
script's settings. This option allows one to remove a specific input from the script's status line or the Data Window to
ensure only the most necessary inputs are displayed there. Possible values: [Link], display.data_window,
display.status_line, [Link]. Optional. The default is [Link].
active (input bool) Optional. Specifies whether users can change the value of the input in the script's
"Settings/Inputs" tab. The script can use this parameter to set the state of the input based on the values of other
inputs. If true, users can change the value of the input. If false, the input is grayed out, and users cannot change the
value. The default is true.
confirm (const bool) If true, then user will be asked to confirm input value before indicator is added to chart. Default
value is false.
EXAMPLE
//@version=6
indicator("[Link]", overlay=true)
i_src = [Link](close, "Source")
plot(i_src)
RETURNS
REMARKS
Result of [Link]() function always should be assigned to a variable, see examples above.
SEE ALSO
[Link]()
Adds an input to the Inputs tab of your script's Settings, which allows you to provide configuration options to script
users. This function adds a field for a string input to the script's inputs.
SYNTAX
[Link](defval, title, options, tooltip, inline, group, confirm, display, active) → input string
ARGUMENTS
defval (const string) Determines the default value of the input variable proposed in the script's "Settings/Inputs" tab,
from where the user can change it. When a list of values is used with the options parameter, the value must be one
of them.
title (const string) Title of the input. If not specified, the variable name is used as the input's title. If the title is
specified, but it is empty, the name will be an empty string.
options (tuple of const string values: [val1, val2, ...]) A list of options to choose from.
tooltip (const string) The string that will be shown to the user when hovering over the tooltip icon.
inline (const string) Combines all the input calls using the same argument in one line. The string used as an argument
is not displayed. It is only used to identify inputs belonging to the same line.
group (const string) Creates a header above all inputs using the same group argument string. The string is also used
as the header's text.
confirm (const bool) If true, then user will be asked to confirm input value before indicator is added to chart. Default
value is false.
display (const plot_display) Controls where the script will display the input's information, aside from within the
script's settings. This option allows one to remove a specific input from the script's status line or the Data Window to
ensure only the most necessary inputs are displayed there. Possible values: [Link], display.data_window,
display.status_line, [Link]. Optional. The default is [Link].
active (input bool) Optional. Specifies whether users can change the value of the input in the script's
"Settings/Inputs" tab. The script can use this parameter to set the state of the input based on the values of other
inputs. If true, users can change the value of the input. If false, the input is grayed out, and users cannot change the
value. The default is true.
EXAMPLE
//@version=6
indicator("[Link]", overlay=true)
i_text = [Link]("Hello!", "Message")
l = [Link](bar_index, high, i_text)
[Link](l[1])
RETURNS
REMARKS
Result of [Link]() function always should be assigned to a variable, see examples above.
SEE ALSO
[Link]()
Adds an input to the Inputs tab of your script's Settings, which allows you to provide configuration options to script
users. This function adds a field that allows the user to select a specific symbol using the symbol search and returns
that symbol, paired with its exchange prefix, as a string.
SYNTAX
[Link](defval, title, tooltip, inline, group, confirm, display, active) → input string
ARGUMENTS
defval (const string) Determines the default value of the input variable proposed in the script's "Settings/Inputs" tab,
from where the user can change it.
title (const string) Title of the input. If not specified, the variable name is used as the input's title. If the title is
specified, but it is empty, the name will be an empty string.
tooltip (const string) The string that will be shown to the user when hovering over the tooltip icon.
inline (const string) Combines all the input calls using the same argument in one line. The string used as an argument
is not displayed. It is only used to identify inputs belonging to the same line.
group (const string) Creates a header above all inputs using the same group argument string. The string is also used
as the header's text.
confirm (const bool) If true, then user will be asked to confirm input value before indicator is added to chart. Default
value is false.
display (const plot_display) Controls where the script will display the input's information, aside from within the
script's settings. This option allows one to remove a specific input from the script's status line or the Data Window to
ensure only the most necessary inputs are displayed there. Possible values: [Link], display.data_window,
display.status_line, [Link]. Optional. The default is [Link].
active (input bool) Optional. Specifies whether users can change the value of the input in the script's
"Settings/Inputs" tab. The script can use this parameter to set the state of the input based on the values of other
inputs. If true, users can change the value of the input. If false, the input is grayed out, and users cannot change the
value. The default is true.
EXAMPLE
//@version=6
indicator("[Link]", overlay=true)
i_sym = [Link]("DELL", "Symbol")
s = [Link](i_sym, 'D', close)
plot(s)
RETURNS
REMARKS
Result of [Link]() function always should be assigned to a variable, see examples above.
SEE ALSO
input.text_area()
Adds an input to the Inputs tab of your script's Settings, which allows you to provide configuration options to script
users. This function adds a field for a multiline text input.
SYNTAX
ARGUMENTS
defval (const string) Determines the default value of the input variable proposed in the script's "Settings/Inputs" tab,
from where the user can change it.
title (const string) Title of the input. If not specified, the variable name is used as the input's title. If the title is
specified, but it is empty, the name will be an empty string.
tooltip (const string) The string that will be shown to the user when hovering over the tooltip icon.
group (const string) Creates a header above all inputs using the same group argument string. The string is also used
as the header's text.
confirm (const bool) If true, then user will be asked to confirm input value before indicator is added to chart. Default
value is false.
display (const plot_display) Controls where the script will display the input's information, aside from within the
script's settings. This option allows one to remove a specific input from the script's status line or the Data Window to
ensure only the most necessary inputs are displayed there. Possible values: [Link], display.data_window,
display.status_line, [Link]. Optional. The default is [Link].
active (input bool) Optional. Specifies whether users can change the value of the input in the script's
"Settings/Inputs" tab. The script can use this parameter to set the state of the input based on the values of other
inputs. If true, users can change the value of the input. If false, the input is grayed out, and users cannot change the
value. The default is true.
EXAMPLE
//@version=6
indicator("input.text_area")
i_text = input.text_area(defval = "Hello \nWorld!", title = "Message")
plot(close)
RETURNS
Result of input.text_area() function always should be assigned to a variable, see examples above.
SEE ALSO
[Link]()
Adds two inputs to the script's "Settings/Inputs" tab on the same line: one for the date and one for the time. The user
can change the price in the settings or by selecting the indicator and dragging the price line. The function returns a
date/time value in UNIX format.
SYNTAX
[Link](defval, title, tooltip, inline, group, confirm, display, active) → input int
ARGUMENTS
defval (const int) Determines the default value of the input variable proposed in the script's "Settings/Inputs" tab,
from where the user can change it. The value can be a timestamp() function, but only if it uses a date argument in
const string format.
title (const string) Title of the input. If not specified, the variable name is used as the input's title. If the title is
specified, but it is empty, the name will be an empty string.
tooltip (const string) The string that will be shown to the user when hovering over the tooltip icon.
inline (const string) Combines all the input calls using the same argument in one line. The string used as an argument
is not displayed. It is only used to identify inputs belonging to the same line.
group (const string) Creates a header above all inputs using the same group argument string. The string is also used
as the header's text.
confirm (const bool) Optional. If true, the script prompts the user to set the input's initial value by clicking a point on
the chart. If inputs of other types require confirmation, the "Confirm inputs" dialog box also displays this input's field,
allowing final adjustments to the value before the script starts to run. The default is false.
display (const plot_display) Controls where the script will display the input's information, aside from within the
script's settings. This option allows one to remove a specific input from the script's status line or the Data Window to
ensure only the most necessary inputs are displayed there. Possible values: [Link], display.data_window,
display.status_line, [Link]. Optional. The default is [Link].
active (input bool) Optional. Specifies whether users can change the value of the input in the script's
"Settings/Inputs" tab. The script can use this parameter to set the state of the input based on the values of other
inputs. If true, users can change the value of the input. If false, the input is grayed out, and users cannot change the
value. The default is true.
EXAMPLE
//@version=6
indicator("[Link]", overlay=true)
i_date = [Link](timestamp("20 Jul 2021 00:00 +0300"), "Date")
l = [Link](i_date, high, "Date", xloc=xloc.bar_time)
[Link](l[1])
RETURNS
REMARKS
The user can change the input's value by specifying a new value in the "Settings/Inputs" tab, or by moving the input's
marker on the chart. Alternatively, they can select "Reset points" from the script's "More" menu and set a new input
value by clicking a point on the chart.
If an [Link]() and [Link]() function call in the script share a unique inline argument and have matching gr
oup arguments, those calls create a single interactive point marker on the chart. The user can move that marker to
adjust the input time and price values simultaneously.
SEE ALSO
[Link]()
Adds an input to the Inputs tab of your script's Settings, which allows you to provide configuration options to script
users. This function adds a dropdown that allows the user to select a specific timeframe via the timeframe selector and
returns it as a string. The selector includes the custom timeframes a user may have added using the chart's Timeframe
dropdown.
SYNTAX
[Link](defval, title, options, tooltip, inline, group, confirm, display, active) → input string
ARGUMENTS
defval (const string) Determines the default value of the input variable proposed in the script's "Settings/Inputs" tab,
from where the user can change it. When a list of values is used with the options parameter, the value must be one
of them.
title (const string) Title of the input. If not specified, the variable name is used as the input's title. If the title is
specified, but it is empty, the name will be an empty string.
options (tuple of const string values: [val1, val2, ...]) A list of options to choose from.
tooltip (const string) The string that will be shown to the user when hovering over the tooltip icon.
inline (const string) Combines all the input calls using the same argument in one line. The string used as an argument
is not displayed. It is only used to identify inputs belonging to the same line.
group (const string) Creates a header above all inputs using the same group argument string. The string is also used
as the header's text.
confirm (const bool) If true, then user will be asked to confirm input value before indicator is added to chart. Default
value is false.
display (const plot_display) Controls where the script will display the input's information, aside from within the
script's settings. This option allows one to remove a specific input from the script's status line or the Data Window to
ensure only the most necessary inputs are displayed there. Possible values: [Link], display.data_window,
display.status_line, [Link]. Optional. The default is [Link].
active (input bool) Optional. Specifies whether users can change the value of the input in the script's
"Settings/Inputs" tab. The script can use this parameter to set the state of the input based on the values of other
inputs. If true, users can change the value of the input. If false, the input is grayed out, and users cannot change the
value. The default is true.
EXAMPLE
//@version=6
indicator("[Link]", overlay=true)
i_res = [Link]('D', "Resolution", options=['D', 'W', 'M'])
s = [Link]("AAPL", i_res, close)
plot(s)
RETURNS
REMARKS
Result of [Link]() function always should be assigned to a variable, see examples above.
SEE ALSO
int() 4 overloads
ARGUMENTS
x (const int/float) The value to convert to the specified type, usually na.
RETURNS
SEE ALSO
label()
Casts na to label
SYNTAX
ARGUMENTS
x (series label) The value to convert to the specified type, usually na.
RETURNS
SEE ALSO
[Link]()
Clones the label object.
SYNTAX
EXAMPLE
//@version=6
indicator('Last 100 bars highest/lowest', overlay = true)
LOOKBACK = 100
highest = [Link](LOOKBACK)
highestBars = [Link](LOOKBACK)
lowest = [Link](LOOKBACK)
lowestBars = [Link](LOOKBACK)
if [Link]
var labelHigh = [Link](bar_index + highestBars, highest, [Link](highest), color = [Link]
een)
var labelLow = [Link](labelHigh)
label.set_xy(labelLow, bar_index + lowestBars, lowest)
label.set_text(labelLow, [Link](lowest))
label.set_color(labelLow, [Link])
label.set_style(labelLow, label.style_label_up)
RETURNS
New label ID object which may be passed to [Link] and [Link] functions.
SEE ALSO
[Link]() [Link]()
[Link]()
Deletes the specified label object. If it has already been deleted, does nothing.
SYNTAX
[Link](id) → void
ARGUMENTS
SEE ALSO
[Link]()
label.get_text()
Returns the text of this label object.
SYNTAX
ARGUMENTS
EXAMPLE
//@version=6
indicator("label.get_text")
my_label = [Link](time, open, text="Open bar text", xloc=xloc.bar_time)
a = label.get_text(my_label)
[Link](time, close, text = a + " new", xloc=xloc.bar_time)
RETURNS
SEE ALSO
[Link]()
label.get_x()
Returns UNIX time or bar index (depending on the last xloc value set) of this label's position.
SYNTAX
ARGUMENTS
EXAMPLE
//@version=6
indicator("label.get_x")
my_label = [Link](time, open, text="Open bar text", xloc=xloc.bar_time)
a = label.get_x(my_label)
plot(time - label.get_x(my_label)) //draws zero plot
RETURNS
SEE ALSO
[Link]()
label.get_y()
Returns price of this label's position.
SYNTAX
ARGUMENTS
RETURNS
SEE ALSO
[Link]()
[Link]() 2 overloads
[Link](point, text, xloc, yloc, color, style, textcolor, size, textalign, tooltip, text_font_family, for
ce_overlay, text_formatting) → series label
[Link](x, y, text, xloc, yloc, color, style, textcolor, size, textalign, tooltip, text_font_family, forc
e_overlay, text_formatting) → series label
ARGUMENTS
text_font_family (series string) The font family of the text. Optional. The default value is font.family_default. Possible
values: font.family_default, font.family_monospace.
force_overlay (const bool) If true, the drawing will display on the main chart pane, even when the script occupies a
separate pane. Optional. The default is false.
text_formatting (const text_format) The formatting of the displayed text. Formatting options support addition. For
example, text.format_bold + text.format_italic will make the text both bold and italicized. Possible
values: text.format_none, text.format_bold, text.format_italic. Optional. The default is text.format_none.
EXAMPLE
//@version=6
indicator("[Link]")
var label1 = [Link](bar_index, low, text="Hello, world!", style=label.style_circle)
label.set_x(label1, 0)
label.set_xloc(label1, time, xloc.bar_time)
label.set_color(label1, [Link])
label.set_size(label1, [Link])
RETURNS
SEE ALSO
label.set_text_formatting()
label.set_color()
Sets label border and arrow color.
SYNTAX
ARGUMENTS
SEE ALSO
[Link]()
label.set_point()
Sets the location of the id label to point .
SYNTAX
ARGUMENTS
label.set_size()
Sets arrow and text size of the specified label object.
SYNTAX
ARGUMENTS
size (series int/string) Size of the label. Accepts a positive int value or one of the built-in size.* constants. The
constants and their equivalent numeric sizes are: [Link] (0), [Link] (~7), [Link] (~10), [Link] (12),
[Link] (18), [Link] (24). The default value is [Link], which represents the numeric size of 12.
SEE ALSO
label.set_style()
Sets label style.
SYNTAX
ARGUMENTS
SEE ALSO
[Link]()
label.set_text()
Sets label text
SYNTAX
ARGUMENTS
SEE ALSO
[Link]() label.set_text_formatting()
label.set_text_font_family()
The function sets the font family of the text inside the label.
SYNTAX
ARGUMENTS
text_font_family (series string) The font family of the text. Possible values: font.family_default,
font.family_monospace.
EXAMPLE
//@version=6
indicator("Example of setting the label font")
if [Link]
l = [Link](bar_index, 0, "monospace", yloc=[Link])
label.set_text_font_family(l, font.family_monospace)
SEE ALSO
label.set_text_formatting()
Sets the formatting attributes the drawing applies to displayed text.
SYNTAX
text_formatting (const text_format) The formatting of the displayed text. Formatting options support addition. For
example, text.format_bold + text.format_italic will make the text both bold and italicized. Possible
values: text.format_none, text.format_bold, text.format_italic. Optional. The default is text.format_none.
SEE ALSO
[Link]() label.set_text()
label.set_textalign()
Sets the alignment for the label text.
SYNTAX
ARGUMENTS
SEE ALSO
label.set_textcolor()
Sets color of the label text.
SYNTAX
ARGUMENTS
SEE ALSO
[Link]()
label.set_tooltip()
Sets the tooltip text.
SYNTAX
ARGUMENTS
SEE ALSO
[Link]()
label.set_x()
Sets bar index or bar time (depending on the xloc) of the label position.
SYNTAX
label.set_x(id, x) → void
ARGUMENTS
x (series int) New bar index or bar time of the label position. Note that objects positioned using xloc.bar_index cannot
be drawn further than 500 bars into the future.
SEE ALSO
[Link]()
label.set_xloc()
Sets x-location and new bar index/time value.
SYNTAX
ARGUMENTS
x (series int) New bar index or bar time of the label position.
xloc (series string) New x-location value.
SEE ALSO
label.set_xy()
Sets bar index/time and price of the label position.
SYNTAX
label.set_xy(id, x, y) → void
ARGUMENTS
x (series int) New bar index or bar time of the label position. Note that objects positioned using xloc.bar_index cannot
be drawn further than 500 bars into the future.
SEE ALSO
[Link]()
label.set_y()
Sets price of the label position
SYNTAX
label.set_y(id, y) → void
ARGUMENTS
SEE ALSO
[Link]()
label.set_yloc()
Sets new y-location calculation algorithm.
SYNTAX
ARGUMENTS
SEE ALSO
library()
Declaration statement identifying a script as a library.
SYNTAX
ARGUMENTS
title (const string) The title of the library and its identifier. It cannot contain spaces, special characters or begin with a
digit. It is used as the publication's default title, and to uniquely identify the library in the import statement, when
another script uses it. It is also used as the script's name on the chart.
overlay (const bool) If true, the script's visuals appear on the main chart pane if the user adds it to the chart directly,
or in another script's pane if the user applies it to that script. If false, the script's visuals appear in a separate pane.
Changes to the overlay value apply only after the user adds the script to the chart again. Additionally, if the user
moves the script to another pane by selecting a "Move to" option in the script's "More" menu, it does not move back
to its original pane after any updates to the source code. The default is false. Strategy-specific labels that display
entries and exits will be displayed over the main chart regardless of this setting.
dynamic_requests (const bool) Specifies whether the script can dynamically call functions from the request.*()
namespace. Dynamic request.*() calls are allowed within the local scopes of conditional structures (e.g., if), loops
(e.g., for), and exported functions. Additionally, such calls allow "series" arguments for many of their parameters.
Optional. The default is true. See the User Manual's Dynamic requests section for more information.
EXAMPLE
//@version=6
// @description Math library
library("num_methods", overlay = true)
// Calculate "sinh()" from the float parameter `x`
export sinh(float x) =>
([Link](x) - [Link](-x)) / 2.0
plot(sinh(0))
SEE ALSO
indicator() strategy()
line()
Casts na to line
SYNTAX
ARGUMENTS
x (series line) The value to convert to the specified type, usually na.
RETURNS
SEE ALSO
[Link]()
Clones the line object.
SYNTAX
ARGUMENTS
EXAMPLE
//@version=6
indicator('Last 100 bars price range', overlay = true)
LOOKBACK = 100
highest = [Link](LOOKBACK)
lowest = [Link](LOOKBACK)
if [Link]
var lineTop = [Link](bar_index[LOOKBACK], highest, bar_index, highest, color = [Link])
var lineBottom = [Link](lineTop)
line.set_y1(lineBottom, lowest)
line.set_y2(lineBottom, lowest)
line.set_color(lineBottom, [Link])
RETURNS
New line ID object which may be passed to [Link] and [Link] functions.
SEE ALSO
[Link]() [Link]()
[Link]()
Deletes the specified line object. If it has already been deleted, does nothing.
SYNTAX
[Link](id) → void
ARGUMENTS
SEE ALSO
[Link]()
line.get_price()
Returns the price level of a line at a given bar index.
SYNTAX
ARGUMENTS
EXAMPLE
//@version=6
indicator("GetPrice", overlay=true)
var line l = na
if bar_index == 10
l := [Link](0, high[5], bar_index, high)
plot(line.get_price(l, bar_index), color=[Link])
RETURNS
REMARKS
SEE ALSO
[Link]()
line.get_x1()
Returns UNIX time or bar index (depending on the last xloc value set) of the first point of the line.
SYNTAX
ARGUMENTS
EXAMPLE
//@version=6
indicator("line.get_x1")
my_line = [Link](time, open, time + 60 * 60 * 24, close, xloc=xloc.bar_time)
a = line.get_x1(my_line)
plot(time - line.get_x1(my_line)) //draws zero plot
RETURNS
SEE ALSO
[Link]()
line.get_x2()
Returns UNIX time or bar index (depending on the last xloc value set) of the second point of the line.
SYNTAX
ARGUMENTS
RETURNS
SEE ALSO
[Link]()
line.get_y1()
Returns price of the first point of the line.
SYNTAX
ARGUMENTS
RETURNS
Price value.
SEE ALSO
[Link]()
line.get_y2()
Returns price of the second point of the line.
SYNTAX
ARGUMENTS
RETURNS
Price value.
SEE ALSO
[Link]()
[Link]() 2 overloads
[Link](first_point, second_point, xloc, extend, color, style, width, force_overlay) → series line
[Link](x1, y1, x2, y2, xloc, extend, color, style, width, force_overlay) → series line
ARGUMENTS
first_point ([Link]) A [Link] object that specifies the line's starting coordinate.
second_point ([Link]) A [Link] object that specifies the line's ending coordinate.
xloc (series string) See description of x1 argument. Possible values: xloc.bar_index and xloc.bar_time. Default is
xloc.bar_index.
extend (series string) If extend=[Link], draws segment starting at point (x1, y1) and ending at point (x2, y2). If
extend is equal to [Link] or [Link], draws a ray starting at point (x1, y1) or (x2, y2), respectively. If
extend=[Link], draws a straight line that goes through these points. Default value is [Link].
color (series color) Line color.
style (series string) Line style. Possible values: line.style_solid, line.style_dotted, line.style_dashed,
line.style_arrow_left, line.style_arrow_right, line.style_arrow_both.
EXAMPLE
//@version=6
indicator("[Link]")
var line1 = [Link](0, low, bar_index, high, extend=[Link])
var line2 = [Link](time, open, time + 60 * 60 * 24, close, xloc=xloc.bar_time, style=line.style_dashe
d)
line.set_x2(line1, 0)
line.set_xloc(line1, time, time + 60 * 60 * 24, xloc.bar_time)
line.set_color(line2, [Link])
line.set_width(line2, 5)
RETURNS
SEE ALSO
line.set_color()
Sets the line color
SYNTAX
SEE ALSO
[Link]()
line.set_extend()
Sets extending type of this line object. If extend=[Link], draws segment starting at point (x1, y1) and ending at
point (x2, y2). If extend is equal to [Link] or [Link], draws a ray starting at point (x1, y1) or (x2, y2),
respectively. If extend=[Link], draws a straight line that goes through these points.
SYNTAX
ARGUMENTS
SEE ALSO
line.set_first_point()
Sets the first point of the id line to point .
SYNTAX
ARGUMENTS
line.set_second_point()
Sets the second point of the id line to point .
SYNTAX
ARGUMENTS
line.set_style()
Sets the line style
SYNTAX
SEE ALSO
[Link]()
line.set_width()
Sets the line width.
SYNTAX
ARGUMENTS
SEE ALSO
[Link]()
line.set_x1()
Sets bar index or bar time (depending on the xloc) of the first point.
SYNTAX
line.set_x1(id, x) → void
ARGUMENTS
x (series int) Bar index or bar time. Note that objects positioned using xloc.bar_index cannot be drawn further than
500 bars into the future.
SEE ALSO
[Link]()
line.set_x2()
Sets bar index or bar time (depending on the xloc) of the second point.
SYNTAX
line.set_x2(id, x) → void
ARGUMENTS
x (series int) Bar index or bar time. Note that objects positioned using xloc.bar_index cannot be drawn further than
500 bars into the future.
SEE ALSO
[Link]()
line.set_xloc()
Sets x-location and new bar index/time values.
SYNTAX
ARGUMENTS
SEE ALSO
line.set_xy1()
Sets bar index/time and price of the first point.
SYNTAX
line.set_xy1(id, x, y) → void
ARGUMENTS
x (series int) Bar index or bar time. Note that objects positioned using xloc.bar_index cannot be drawn further than
500 bars into the future.
SEE ALSO
[Link]()
line.set_xy2()
Sets bar index/time and price of the second point
SYNTAX
line.set_xy2(id, x, y) → void
ARGUMENTS
SEE ALSO
[Link]()
line.set_y1()
Sets price of the first point
SYNTAX
line.set_y1(id, y) → void
ARGUMENTS
SEE ALSO
[Link]()
line.set_y2()
Sets price of the second point.
SYNTAX
line.set_y2(id, y) → void
ARGUMENTS
SEE ALSO
[Link]()
linefill()
Casts na to linefill.
SYNTAX
ARGUMENTS
x (series linefill) The value to convert to the specified type, usually na.
RETURNS
SEE ALSO
[Link]()
Deletes the specified linefill object. If it has already been deleted, does nothing.
SYNTAX
[Link](id) → void
ARGUMENTS
linefill.get_line1()
Returns the ID of the first line used in the id linefill.
SYNTAX
ARGUMENTS
linefill.get_line2()
Returns the ID of the second line used in the id linefill.
SYNTAX
ARGUMENTS
[Link]()
Creates a new linefill object and displays it on the chart, filling the space between line1 and line2 with the color
specified in color .
SYNTAX
ARGUMENTS
RETURNS
REMARKS
If any line of the two is deleted, the linefill object is also deleted. If the lines are moved (e.g. via line.set_xy() functions),
the linefill object is also moved.
If both lines are extended in the same direction relative to the lines themselves (e.g. both have [Link] as the
value of their extend= parameter), the space between line extensions will also be filled.
linefill.set_color()
The function sets the color of the linefill object passed to it.
SYNTAX
[Link]() 2 overloads
Converts the formatting string and value(s) into a formatted string, and sends the result to the "Pine logs" menu
tagged with the "error" debug level.
The formatting string can contain literal text and one placeholder in curly braces {} for each value to be formatted.
Each placeholder consists of the index of the required argument (beginning at 0) that will replace it, and an optional
format specifier. The index represents the position of that argument in the function's argument list.
[Link](message) → void
ARGUMENTS
EXAMPLE
//@version=6
strategy("My strategy", overlay = true, process_orders_on_close = true)
bracketTickSizeInput = [Link](1000, "Stoploss/Take-Profit distance (in ticks)")
[Link]("Exit orders have been placed: Take-profit at {0}, Stop-loss at {1}", close, limitLevel)
[Link]("Exit", "My Long Entry Id", profit = bracketTickSizeInput, loss = bracketTickSizeInpu
t)
if [Link] > 10
[Link]("{0} positions opened in the same direction in a row. Try adjusting `bracketTickSizeInp
ut`", [Link])
RETURNS
REMARKS
Any curly braces within an unquoted pattern must be balanced. For example, "ab {0} de" and "ab '}' de" are valid
patterns, but "ab {0'}' de", "ab } de" and "''{''" are not.
The function can apply additional formatting to some values inside of the {} . The list of additional formatting options
can be found in the EXAMPLE section of the [Link]() article.
The string used as the formatString argument can contain single quote characters ('). However, one must pair all
single quotes in that string to avoid unexpected formatting results.
The "Pine logs..." button is accessible from the "More" dropdown in the Pine Editor and from the "More" dropdown in
the status line of any script that uses log.*() functions.
[Link]() 2 overloads
Converts the formatting string and value(s) into a formatted string, and sends the result to the "Pine logs" menu
tagged with the "info" debug level.
The formatting string can contain literal text and one placeholder in curly braces {} for each value to be formatted.
Each placeholder consists of the index of the required argument (beginning at 0) that will replace it, and an optional
format specifier. The index represents the position of that argument in the function's argument list.
[Link](message) → void
ARGUMENTS
EXAMPLE
//@version=6
strategy("My strategy", overlay = true, process_orders_on_close = true)
bracketTickSizeInput = [Link](1000, "Stoploss/Take-Profit distance (in ticks)")
[Link]("Exit orders have been placed: Take-profit at {0}, Stop-loss at {1}", close, limitLevel)
[Link]("Exit", "My Long Entry Id", profit = bracketTickSizeInput, loss = bracketTickSizeInpu
t)
if [Link] > 10
[Link]("{0} positions opened in the same direction in a row. Try adjusting `bracketTickSizeInp
ut`", [Link])
RETURNS
REMARKS
Any curly braces within an unquoted pattern must be balanced. For example, "ab {0} de" and "ab '}' de" are valid
patterns, but "ab {0'}' de", "ab } de" and "''{''" are not.
The function can apply additional formatting to some values inside of the {} . The list of additional formatting options
can be found in the EXAMPLE section of the [Link]() article.
The string used as the formatString argument can contain single quote characters ('). However, one must pair all
single quotes in that string to avoid unexpected formatting results.
The "Pine logs..." button is accessible from the "More" dropdown in the Pine Editor and from the "More" dropdown in
the status line of any script that uses log.*() functions.
[Link]() 2 overloads
Converts the formatting string and value(s) into a formatted string, and sends the result to the "Pine logs" menu
tagged with the "warning" debug level.
The formatting string can contain literal text and one placeholder in curly braces {} for each value to be formatted.
Each placeholder consists of the index of the required argument (beginning at 0) that will replace it, and an optional
format specifier. The index represents the position of that argument in the function's argument list.
SYNTAX & OVERLOADS
[Link](message) → void
ARGUMENTS
EXAMPLE
//@version=6
strategy("My strategy", overlay = true, process_orders_on_close = true)
bracketTickSizeInput = [Link](1000, "Stoploss/Take-Profit distance (in ticks)")
[Link]("Exit orders have been placed: Take-profit at {0}, Stop-loss at {1}", close, limitLevel)
[Link]("Exit", "My Long Entry Id", profit = bracketTickSizeInput, loss = bracketTickSizeInpu
t)
if [Link] > 10
[Link]("{0} positions opened in the same direction in a row. Try adjusting `bracketTickSizeInp
ut`", [Link])
RETURNS
REMARKS
Any curly braces within an unquoted pattern must be balanced. For example, "ab {0} de" and "ab '}' de" are valid
patterns, but "ab {0'}' de", "ab } de" and "''{''" are not.
The function can apply additional formatting to some values inside of the {} . The list of additional formatting options
can be found in the EXAMPLE section of the [Link]() article.
The string used as the formatString argument can contain single quote characters ('). However, one must pair all
single quotes in that string to avoid unexpected formatting results.
The "Pine logs..." button is accessible from the "More" dropdown in the Pine Editor and from the "More" dropdown in
the status line of any script that uses log.*() functions.
[Link]()
Clears the map, removing all key-value pairs from it.
SYNTAX
[Link](id) → void
ARGUMENTS
EXAMPLE
//@version=6
indicator("[Link] example")
oddMap = [Link]<int, bool>()
[Link](1, true)
[Link](2, false)
[Link](3, true)
[Link](oddMap)
plot([Link]())
SEE ALSO
[Link]()
Returns true if the key was found in the id map, false otherwise.
SYNTAX
ARGUMENTS
EXAMPLE
//@version=6
indicator("[Link] example")
a = [Link]<string, float>()
[Link]("open", open)
p = close
if [Link](a, "open")
p := [Link]("open")
plot(p)
SEE ALSO
[Link]()
Creates a copy of an existing map.
SYNTAX
ARGUMENTS
EXAMPLE
//@version=6
indicator("[Link] example")
a = [Link]<string, int>()
[Link]("example", 1)
b = [Link](a)
a := [Link]<string, int>()
[Link]("example", 2)
plot([Link]("example"))
plot([Link]("example"))
RETURNS
SEE ALSO
[Link]()
Returns the value associated with the specified key in the id map.
SYNTAX
ARGUMENTS
key (series <type of the map's elements>) The key of the value to retrieve.
EXAMPLE
//@version=6
indicator("[Link] example")
a = [Link]<int, int>()
size = 10
for i = 0 to size
[Link](i, size-i)
plot([Link](a, 1))
SEE ALSO
[Link]()
Returns an array of all the keys in the id map. The resulting array is a copy and any changes to it are not reflected in
the original map.
SYNTAX
[Link](id) → array<type>
ARGUMENTS
EXAMPLE
//@version=6
indicator("[Link] example")
a = [Link]<string, float>()
[Link]("open", open)
[Link]("high", high)
[Link]("low", low)
[Link]("close", close)
keys = [Link](a)
ohlc = 0.0
for key in keys
ohlc += [Link](key)
plot(ohlc/4)
REMARKS
Maps maintain insertion order. The elements within the array returned by this function will also be in the insertion
order.
SEE ALSO
[Link]<type,type>()
Creates a new map object: a collection that consists of key-value pairs, where all keys are of the keyType , and all
values are of the valueType .
keyType can be a primitive type or enum. For example: int, float, bool, string, color.
valueType can be of any type except array<> , matrix<> , and map<> . User-defined types are allowed, even
if they have array<> , matrix<> , or map<> as one of their fields.
SYNTAX
EXAMPLE
//@version=6
indicator("[Link]<string, int> example")
a = [Link]<string, int>()
[Link]("example", 1)
[Link](bar_index, close, [Link]([Link]("example")))
RETURNS
REMARKS
Each key is unique and can only appear once. When adding a new value with a key that the map already contains, that
value replaces the old value associated with the key.
Maps maintain insertion order. Note that the order does not change when inserting a pair with a key that's already in
the map. The new pair replaces the existing pair with the key in such cases.
SEE ALSO
[Link]()
Puts a new key-value pair into the id map.
SYNTAX
ARGUMENTS
key (series <type of the map's elements>) The key to put into the map.
value (series <type of the map's elements>) The key value to put into the map.
EXAMPLE
//@version=6
indicator("[Link] example")
a = [Link]<string, float>()
[Link](a, "first", 10)
[Link](a, "second", 15)
prevFirst = [Link](a, "first", 20)
currFirst = [Link]("first")
plot(prevFirst)
plot(currFirst)
RETURNS
The previous value associated with key if the key was already present in the map, or na if the key is new.
REMARKS
Maps maintain insertion order. Note that the order does not change when inserting a pair with a key that's already in
the map. The new pair replaces the existing pair with the key in such cases.
SEE ALSO
map.put_all()
Puts all key-value pairs from the id2 map into the id map.
SYNTAX
ARGUMENTS
EXAMPLE
//@version=6
indicator("map.put_all example")
a = [Link]<string, float>()
b = [Link]<string, float>()
[Link]("first", 10)
[Link]("second", 15)
[Link]("third", 20)
map.put_all(a, b)
plot([Link]("third"))
SEE ALSO
[Link]()
Removes a key-value pair from the id map.
SYNTAX
ARGUMENTS
EXAMPLE
//@version=6
indicator("[Link] example")
a = [Link]<string, color>()
[Link]("firstColor", [Link])
oldColorValue = [Link](a, "firstColor")
plot(close, color = oldColorValue)
RETURNS
The previous value associated with key if the key was present in the map, or na if there was no such key.
SEE ALSO
[Link]()
Returns the number of key-value pairs in the id map.
SYNTAX
ARGUMENTS
EXAMPLE
//@version=6
indicator("[Link] example")
a = [Link]<int, int>()
size = 10
for i = 0 to size
[Link](i, size-i)
plot([Link](a))
SEE ALSO
[Link]()
Returns an array of all the values in the id map. The resulting array is a copy and any changes to it are not reflected
in the original map.
SYNTAX
[Link](id) → array<type>
ARGUMENTS
EXAMPLE
//@version=6
indicator("[Link] example")
a = [Link]<string, float>()
[Link]("open", open)
[Link]("high", high)
[Link]("low", low)
[Link]("close", close)
values = [Link](a)
ohlc = 0.0
for value in values
ohlc += value
plot(ohlc/4)
REMARKS
Maps maintain insertion order. The elements within the array returned by this function will also be in the insertion
order.
SEE ALSO
[Link]() 8 overloads
ARGUMENTS
RETURNS
[Link]() 4 overloads
The acos function returns the arccosine (in radians) of number such that cos(acos(y)) = y for y in range [-1, 1].
ARGUMENTS
RETURNS
The arc cosine of a value; the returned angle is in the range [0, Pi], or na if y is outside of range [-1, 1].
[Link]() 4 overloads
The asin function returns the arcsine (in radians) of number such that sin(asin(y)) = y for y in range [-1, 1].
ARGUMENTS
RETURNS
The arcsine of a value; the returned angle is in the range [-Pi/2, Pi/2], or na if y is outside of range [-1, 1].
[Link]() 4 overloads
The atan function returns the arctangent (in radians) of number such that tan(atan(y)) = y for any y.
ARGUMENTS
RETURNS
The arc tangent of a value; the returned angle is in the range [-Pi/2, Pi/2].
[Link]() 2 overloads
ARGUMENTS
number0, number1, ... (simple int/float) A sequence of numbers to use in the calculation.
RETURNS
Average.
SEE ALSO
[Link]() 4 overloads
Rounds the specified number up to the smallest whole number ("int" value) that is greater than or equal to it.
ARGUMENTS
RETURNS
The smallest "int" value that is greater than or equal to the number .
SEE ALSO
[Link]() [Link]()
[Link]() 4 overloads
ARGUMENTS
[Link]() 4 overloads
The exp function of number is e raised to the power of number , where e is Euler's number.
ARGUMENTS
RETURNS
SEE ALSO
[Link]()
[Link]() 4 overloads
Rounds the specified number down to the largest whole number ("int" value) that is less than or equal to it.
ARGUMENTS
RETURNS
The largest "int" value that is less than or equal to the number .
SEE ALSO
[Link]() [Link]()
[Link]() 4 overloads
Natural logarithm of any number > 0 is the unique y such that e^y = number .
SYNTAX & OVERLOADS
ARGUMENTS
RETURNS
SEE ALSO
math.log10()
math.log10() 4 overloads
The common (or base 10) logarithm of number is the power to which 10 must be raised to obtain the number .
10^y = number .
ARGUMENTS
RETURNS
SEE ALSO
[Link]()
[Link]() 8 overloads
ARGUMENTS
number0, number1, ... (const int) A sequence of numbers to use in the calculation.
EXAMPLE
//@version=6
indicator("[Link]", overlay=true)
plot([Link](close, open))
plot([Link](close, [Link](open, 42)))
RETURNS
SEE ALSO
[Link]()
[Link]() 8 overloads
ARGUMENTS
number0, number1, ... (const int) A sequence of numbers to use in the calculation.
EXAMPLE
//@version=6
indicator("[Link]", overlay=true)
plot([Link](close, open))
plot([Link](close, [Link](open, 42)))
RETURNS
SEE ALSO
[Link]()
[Link]() 4 overloads
ARGUMENTS
EXAMPLE
//@version=6
indicator("[Link]", overlay=true)
plot([Link](close, 2))
RETURNS
SEE ALSO
[Link]() [Link]()
[Link]()
Returns a pseudo-random value. The function will generate a different sequence of values for each script execution.
Using the same value for the optional seed argument will produce a repeatable sequence.
SYNTAX
min (series int/float) The lower bound of the range of random values. The value is not included in the range. The
default is 0.
max (series int/float) The upper bound of the range of random values. The value is not included in the range. The
default is 1.
seed (series int) Optional argument. When the same seed is used, allows successive calls to the function to produce
a repeatable set of values.
RETURNS
A random value.
[Link]() 8 overloads
Returns the value of number rounded to the nearest integer, with ties rounding up. If the precision parameter is
used, returns a float value rounded to that amount of decimal places.
ARGUMENTS
RETURNS
REMARKS
SEE ALSO
[Link]() [Link]()
math.round_to_mintick() 2 overloads
Returns the value rounded to the symbol's mintick, i.e. the nearest value that can be divided by [Link],
without the remainder, with ties rounding up.
ARGUMENTS
RETURNS
REMARKS
SEE ALSO
[Link]() [Link]()
[Link]() 4 overloads
Sign (signum) of number is zero if number is zero, 1.0 if number is greater than zero, -1.0 if number is less
than zero.
ARGUMENTS
RETURNS
[Link]() 4 overloads
ARGUMENTS
angle (const int/float) Angle, in radians.
RETURNS
[Link]() 4 overloads
Square root of any number >= 0 is the unique y >= 0 such that y^2 = number .
ARGUMENTS
RETURNS
SEE ALSO
[Link]()
[Link]()
The sum function returns the sliding sum of last y values of x.
SYNTAX
ARGUMENTS
RETURNS
REMARKS
na values in the source series are ignored; the function calculates on the length quantity of non- na values.
SEE ALSO
[Link]() for
[Link]() 4 overloads
ARGUMENTS
RETURNS
[Link]()
Returns an approximately equivalent angle in degrees from an angle measured in radians.
SYNTAX
ARGUMENTS
RETURNS
[Link]()
Returns an approximately equivalent angle in radians from an angle measured in degrees.
SYNTAX
ARGUMENTS
RETURNS
matrix.add_col()
Inserts a new column at the column index of the id matrix.
SYNTAX
ARGUMENTS
array_id (any array type) Optional. The ID of an array to use as the new column. If the matrix is empty, the array can
be of any size. Otherwise, its size must equal [Link](id) . By default, the function inserts a column of na
values.
EXAMPLE
//@version=6
indicator("`matrix.add_col()` Example 1")
EXAMPLE
//@version=6
indicator("`matrix.add_col()` Example 2")
if [Link]
// Create an empty matrix object.
var m = [Link]<int>()
// Add the `a` array as the first column of the empty matrix.
matrix.add_col(m, 0, a)
REMARKS
Rather than add columns to an empty matrix, it is far more efficient to declare a matrix with explicit dimensions and fill
it with values. Adding a column is also much slower than adding a row with the matrix.add_row() function.
SEE ALSO
matrix.add_row()
Inserts a new row at the row index of the id matrix.
SYNTAX
ARGUMENTS
array_id (any array type) Optional. The ID of an array to use as the new row. If the matrix is empty, the array can be of
any size. Otherwise, its size must equal [Link](id) . By default, the function inserts a row of na values.
EXAMPLE
//@version=6
indicator("`matrix.add_row()` Example 1")
EXAMPLE
//@version=6
indicator("`matrix.add_row()` Example 2")
if [Link]
// Create an empty matrix object.
var m = [Link]<int>()
// Add the `a` array as the first row of the empty matrix.
matrix.add_row(m, 0, a)
REMARKS
Indexing of rows and columns starts at zero. Rather than add rows to an empty matrix, it is far more efficient to declare
a matrix with explicit dimensions and fill it with values.
SEE ALSO
[Link]() 2 overloads
EXAMPLE
//@version=6
indicator("`[Link]()` Example")
RETURNS
SEE ALSO
[Link]()
The function creates a one-dimensional array from the elements of a matrix column.
SYNTAX
ARGUMENTS
EXAMPLE
//@version=6
indicator("`[Link]()` Example", "", true)
// Return an array with the values of the first column of matrix `m`.
a = [Link](m, 0)
RETURNS
REMARKS
SEE ALSO
SYNTAX
ARGUMENTS
EXAMPLE
//@version=6
indicator("`[Link]()` Example")
RETURNS
SEE ALSO
[Link]()
The function appends the m2 matrix to the m1 matrix.
SYNTAX
ARGUMENTS
EXAMPLE
//@version=6
indicator("`[Link]()` Example")
REMARKS
SEE ALSO
[Link]()
The function creates a new matrix which is a copy of the original.
SYNTAX
[Link](id) → matrix<type>
ARGUMENTS
EXAMPLE
//@version=6
indicator("`[Link]()` Example")
RETURNS
SEE ALSO
[Link]() 2 overloads
EXAMPLE
//@version=6
indicator("`[Link]` Example")
RETURNS
REMARKS
SEE ALSO
[Link]() 2 overloads
The function returns a new matrix resulting from the subtraction between matrices id1 and id2 , or of matrix id1
and an id2 scalar (a numerical value).
ARGUMENTS
EXAMPLE
//@version=6
indicator("`[Link]()` Example 1")
EXAMPLE
//@version=6
indicator("`[Link]()` Example 2")
// Create a new matrix containing the difference between the `m1` matrix and the "int" value `1`.
var m2 = [Link](m1, 1)
RETURNS
A new matrix object containing the difference between id2 and id1 .
SEE ALSO
[Link]() 2 overloads
[Link](id) → array<float>
[Link](id) → array<int>
ARGUMENTS
EXAMPLE
//@version=6
indicator("`[Link]()` Example")
REMARKS
SEE ALSO
[Link]() 2 overloads
[Link](id) → matrix<float>
[Link](id) → matrix<int>
ARGUMENTS
EXAMPLE
//@version=6
indicator("`[Link]()` Example")
RETURNS
REMARKS
SEE ALSO
matrix.elements_count()
The function returns the total number of all matrix elements.
SYNTAX
ARGUMENTS
SEE ALSO
[Link]()
The function fills a rectangular area of the id matrix defined by the indices from_column to to_column (not
including it) and from_row to to_row (not including it) with the value .
SYNTAX
ARGUMENTS
value (series <type of the matrix's elements>) The value to fill with.
from_row (series int) Row index from which the fill will begin (inclusive). Optional. The default value is 0.
to_row (series int) Row index where the fill will end (not inclusive). Optional. The default value is [Link]().
from_column (series int) Column index from which the fill will begin (inclusive). Optional. The default value is 0.
to_column (series int) Column index where the fill will end (non inclusive). Optional. The default value is
[Link]().
EXAMPLE
//@version=6
indicator("`[Link]()` Example")
// Fill the intersection of rows 1 to 2 and columns 2 to 3 of the matrix with `hl2` values.
[Link](m, hl2, 0, 2, 1, 3)
SEE ALSO
[Link]()
The function returns the element with the specified index of the matrix.
SYNTAX
ARGUMENTS
EXAMPLE
//@version=6
indicator("`[Link]()` Example", "", true)
plot(x)
RETURNS
The value of the element at the row and column index of the id matrix.
REMARKS
SEE ALSO
[Link]() 2 overloads
[Link](id) → matrix<float>
[Link](id) → matrix<int>
ARGUMENTS
EXAMPLE
//@version=6
indicator("`[Link]()` Example")
REMARKS
SEE ALSO
matrix.is_antidiagonal()
The function determines if the matrix is anti-diagonal (all elements outside the secondary diagonal are zero).
SYNTAX
ARGUMENTS
RETURNS
REMARKS
SEE ALSO
matrix.is_antisymmetric()
The function determines if a matrix is antisymmetric (its transpose equals its negative).
SYNTAX
ARGUMENTS
RETURNS
REMARKS
SEE ALSO
matrix.is_binary()
The function determines if the matrix is binary (when all elements of the matrix are 0 or 1).
SYNTAX
RETURNS
SEE ALSO
matrix.is_diagonal()
The function determines if the matrix is diagonal (all elements outside the main diagonal are zero).
SYNTAX
ARGUMENTS
RETURNS
REMARKS
SEE ALSO
matrix.is_identity()
The function determines if a matrix is an identity matrix (elements with ones on the main diagonal and zeros
elsewhere).
SYNTAX
ARGUMENTS
RETURNS
REMARKS
SEE ALSO
matrix.is_square()
The function determines if the matrix is square (it has the same number of rows and columns).
SYNTAX
RETURNS
SEE ALSO
matrix.is_stochastic()
The function determines if the matrix is stochastic.
SYNTAX
ARGUMENTS
RETURNS
SEE ALSO
[Link]<type>() [Link]()
matrix.is_symmetric()
The function determines if a square matrix is symmetric (elements are symmetric with respect to the main diagonal).
SYNTAX
ARGUMENTS
RETURNS
REMARKS
SEE ALSO
matrix.is_triangular()
The function determines if the matrix is triangular (if all elements above or below the main diagonal are zero).
SYNTAX
ARGUMENTS
id (matrix<int/float>) Matrix object to test.
RETURNS
REMARKS
SEE ALSO
matrix.is_zero()
The function determines if all elements of the matrix are zero.
SYNTAX
ARGUMENTS
RETURNS
Returns true if all elements of the id matrix are zero, false otherwise.
SEE ALSO
[Link]() 2 overloads
The function returns the Kronecker product for the id1 and id2 matrices.
ARGUMENTS
EXAMPLE
//@version=6
indicator("`[Link]()` Example")
RETURNS
SEE ALSO
[Link]() 2 overloads
The function returns the largest value from the matrix elements.
ARGUMENTS
EXAMPLE
//@version=6
indicator("`[Link]()` Example")
RETURNS
SEE ALSO
[Link]() 2 overloads
The function calculates the median ("the middle" value) of matrix elements.
EXAMPLE
//@version=6
indicator("`[Link]()` Example")
REMARKS
Note that na elements of the matrix are not considered when calculating the median.
SEE ALSO
[Link]() 2 overloads
The function returns the smallest value from the matrix elements.
ARGUMENTS
EXAMPLE
//@version=6
indicator("`[Link]()` Example")
RETURNS
SEE ALSO
[Link]<type>() [Link]() [Link]() [Link]()
[Link]() 2 overloads
The function calculates the mode of the matrix, which is the most frequently occurring value from the matrix elements.
When there are multiple values occurring equally frequently, the function returns the smallest of those values.
ARGUMENTS
EXAMPLE
//@version=6
indicator("`[Link]()` Example")
RETURNS
The most frequently occurring value from the id matrix. If none exists, returns the smallest value instead.
REMARKS
Note that na elements of the matrix are not considered when calculating the mode.
SEE ALSO
[Link]() 4 overloads
The function returns a new matrix resulting from the product between the matrices id1 and id2 , or between an i
d1 matrix and an id2 scalar (a numerical value), or between an id1 matrix and an id2 vector (an array of
values).
EXAMPLE
//@version=6
indicator("`[Link]()` Example 1")
EXAMPLE
//@version=6
indicator("`[Link]()` Example 2")
EXAMPLE
//@version=6
indicator("`[Link]()` Example 3")
RETURNS
SEE ALSO
[Link]<type>()
The function creates a new matrix object. A matrix is a two-dimensional data structure containing rows and columns.
All elements in the matrix must be of the type specified in the type template ("<type>").
SYNTAX
ARGUMENTS
rows (series int) Initial row count of the matrix. Optional. The default value is 0.
columns (series int) Initial column count of the matrix. Optional. The default value is 0.
initial_value (<matrix_type>) Initial value of all matrix elements. Optional. The default is 'na'.
Create a matrix of elements with the same initial value
EXAMPLE
//@version=6
indicator("`[Link]<type>()` Example 1")
EXAMPLE
//@version=6
indicator("`[Link]<type>()` Example 2")
// Function to create a matrix whose rows are filled with array values.
matrixFromArray(int rows, int columns, array<float> data) =>
m = [Link]<float>(rows, columns)
for i = 0 to rows <= 0 ? na : rows - 1
for j = 0 to columns <= 0 ? na : columns - 1
[Link](m, i, j, [Link](data, i * columns + j))
m
EXAMPLE
//@version=6
indicator("`[Link]<type>()` Example 3")
EXAMPLE
//@version=6
indicator("`[Link]<type>()` Example 4")
RETURNS
SEE ALSO
[Link]() 2 overloads
The function returns the pseudoinverse of a matrix.
[Link](id) → matrix<float>
[Link](id) → matrix<int>
ARGUMENTS
EXAMPLE
//@version=6
indicator("`[Link]()` Example")
RETURNS
REMARKS
The function is calculated using a Moore–Penrose inverse formula based on singular-value decomposition of a matrix.
For non-singular square matrices this function returns the result of [Link]().
SEE ALSO
[Link]() 2 overloads
The function calculates the product of the matrix by itself power times.
ARGUMENTS
power (series int) The number of times the matrix will be multiplied by itself.
EXAMPLE
//@version=6
indicator("`[Link]()` Example")
RETURNS
SEE ALSO
[Link]()
The function calculates the rank of the matrix.
SYNTAX
ARGUMENTS
EXAMPLE
//@version=6
indicator("`[Link]()` Example")
RETURNS
SEE ALSO
[Link]<type>() [Link]() [Link]()
matrix.remove_col()
The function removes the column at column index of the id matrix and returns an array containing the removed
column's values.
SYNTAX
ARGUMENTS
column (series int) The index of the column to be removed. Optional. The default value is [Link]().
EXAMPLE
//@version=6
indicator("matrix_remove_col", overlay = true)
RETURNS
An array containing the elements of the column removed from the id matrix.
REMARKS
Indexing of rows and columns starts at zero. It is far more efficient to declare matrices with explicit dimensions than to
build them by adding or removing columns. Deleting a column is also much slower than deleting a row with the
matrix.remove_row() function.
SEE ALSO
matrix.remove_row()
The function removes the row at row index of the id matrix and returns an array containing the removed row's
values.
SYNTAX
matrix.remove_row(id, row) → array<type>
ARGUMENTS
row (series int) The index of the row to be deleted. Optional. The default value is [Link]().
EXAMPLE
//@version=6
indicator("matrix_remove_row", overlay = true)
RETURNS
An array containing the elements of the row removed from the id matrix.
REMARKS
Indexing of rows and columns starts at zero. It is far more efficient to declare matrices with explicit dimensions than to
build them by adding or removing rows.
SEE ALSO
[Link]()
The function rebuilds the id matrix to rows x cols dimensions.
SYNTAX
ARGUMENTS
EXAMPLE
//@version=6
indicator("`[Link]()` Example")
// For efficiency, execute this code only once.
if [Link]
// Create a 2x3 matrix.
var m1 = [Link]<float>(2, 3)
// Fill the matrix with values.
[Link](m1, 0, 0, 1)
[Link](m1, 0, 1, 2)
[Link](m1, 0, 2, 3)
[Link](m1, 1, 0, 4)
[Link](m1, 1, 1, 5)
[Link](m1, 1, 2, 6)
SEE ALSO
[Link]()
The function reverses the order of rows and columns in the matrix id . The first row and first column become the last,
and the last become the first.
SYNTAX
[Link](id) → void
ARGUMENTS
EXAMPLE
//@version=6
indicator("`[Link]()` Example")
[Link]()
The function creates a one-dimensional array from the elements of a matrix row.
SYNTAX
ARGUMENTS
EXAMPLE
//@version=6
indicator("`[Link]()` Example", "", true)
// Return an array with the values of the first row of the matrix.
a = [Link](m, 0)
RETURNS
REMARKS
SEE ALSO
[Link]()
The function returns the number of rows in the matrix.
SYNTAX
ARGUMENTS
EXAMPLE
//@version=6
indicator("`[Link]()` Example")
RETURNS
SEE ALSO
[Link]()
The function assigns value to the element at the row and column of the id matrix.
SYNTAX
ARGUMENTS
value (series <type of the matrix's elements>) The new value to be set.
EXAMPLE
//@version=6
indicator("`[Link]()` Example")
// Replace the value of element at row 1 and column 2 with value `3`.
[Link](m, 0, 1, 3)
SEE ALSO
[Link]()
The function rearranges the rows in the id matrix following the sorted order of the values in the column .
SYNTAX
ARGUMENTS
//@version=6
indicator("`[Link]()` Example")
SEE ALSO
[Link]()
The function extracts a submatrix of the id matrix within the specified indices.
SYNTAX
ARGUMENTS
from_row (series int) Index of the row from which the extraction will begin (inclusive). Optional. The default value is
0.
to_row (series int) Index of the row where the extraction will end (non inclusive). Optional. The default value is
[Link]().
from_column (series int) Index of the column from which the extraction will begin (inclusive). Optional. The default
value is 0.
to_column (series int) Index of the column where the extraction will end (non inclusive). Optional. The default value is
[Link]().
EXAMPLE
//@version=6
indicator("`[Link]()` Example")
RETURNS
A new matrix object containing the submatrix of the id matrix defined by the from_row , to_row , from_colum
n and to_column indices.
REMARKS
SEE ALSO
[Link]() 2 overloads
The function returns a new matrix resulting from the sum of two matrices id1 and id2 , or of an id1 matrix and
an id2 scalar (a numerical value).
ARGUMENTS
EXAMPLE
//@version=6
indicator("`[Link]()` Example 1")
EXAMPLE
//@version=6
indicator("`[Link]()` Example 2")
// Create a new matrix containing the sum of the `m1` matrix with the "int" value `1`.
var m2 = [Link](m1, 1)
RETURNS
SEE ALSO
matrix.swap_columns()
The function swaps the columns at the index column1 and column2 in the id matrix.
SYNTAX
ARGUMENTS
EXAMPLE
//@version=6
indicator("`matrix.swap_columns()` Example")
REMARKS
matrix.swap_rows()
The function swaps the rows at the index row1 and row2 in the id matrix.
SYNTAX
ARGUMENTS
EXAMPLE
//@version=6
indicator("`matrix.swap_rows()` Example")
REMARKS
SEE ALSO
[Link]() 2 overloads
The function calculates the trace of a matrix (the sum of the main diagonal's elements).
EXAMPLE
//@version=6
indicator("`[Link]()` Example")
RETURNS
SEE ALSO
[Link]()
The function creates a new, transposed version of the id . This interchanges the row and column index of each
element.
SYNTAX
[Link](id) → matrix<type>
ARGUMENTS
EXAMPLE
//@version=6
indicator("`[Link]()` Example")
RETURNS
SEE ALSO
max_bars_back()
Function sets the maximum number of bars that is available for historical reference of a given built-in or user variable.
When operator '[]' is applied to a variable - it is a reference to a historical value of that variable.
If an argument of an operator '[]' is a compile time constant value (e.g. 'v[10]', 'close[500]') then there is no need to
use 'max_bars_back' function for that variable. Pine Script® compiler will use that constant value as history buffer
size.
If an argument of an operator '[]' is a value, calculated at runtime (e.g. 'v[i]' where 'i' - is a series variable) then Pine
Script® attempts to autodetect the history buffer size at runtime. Sometimes it fails and the script crashes at runtime
because it eventually refers to historical values that are out of the buffer. In that case you should use 'max_bars_back'
to fix that problem manually.
SYNTAX
ARGUMENTS
var (series int/float/bool/color/label/line) Series variable identifier for which history buffer should be resized.
Possible values are: 'open', 'high', 'low', 'close', 'volume', 'time', or any user defined variable id.
num (const int) History buffer size which is the number of bars that could be referenced for variable 'var'.
EXAMPLE
//@version=6
indicator("max_bars_back")
close_() => close
depth() => 400
d = depth()
v = close_()
max_bars_back(v, 500)
out = if bar_index > 0
v[d]
else
v
plot(out)
RETURNS
void
REMARKS
At the moment 'max_bars_back' cannot be applied to built-ins like 'hl2', 'hlc3', 'ohlc4'. Please use multiple
'max_bars_back' calls as workaround here (e.g. instead of a single ‘max_bars_back(hl2, 100)’ call you should call the
function twice: ‘max_bars_back(high, 100), max_bars_back(low, 100)’).
If the indicator() or strategy() 'max_bars_back' parameter is used, all variables in the indicator are affected. This may
result in excessive memory usage and cause runtime problems. When possible (i.e. when the cause is a variable rather
than a function), please use the max_bars_back() function instead.
SEE ALSO
indicator()
minute()
SYNTAX
ARGUMENTS
RETURNS
REMARKS
UNIX time is the number of milliseconds that have elapsed since 00:00:00 UTC, 1 January 1970.
SEE ALSO
month()
SYNTAX
ARGUMENTS
timezone (series string) Allows adjusting the returned value to a time zone specified in either UTC/GMT notation
(e.g., "UTC-5", "GMT+0530") or as an IANA time zone database name (e.g., "America/New_York"). Optional. The
default is [Link].
RETURNS
REMARKS
UNIX time is the number of milliseconds that have elapsed since 00:00:00 UTC, 1 January 1970.
Note that this function returns the month based on the time of the bar's open. For overnight sessions (e.g. EURUSD,
where Monday session starts on Sunday, 17:00 UTC-4) this value can be lower by 1 than the month of the trading day.
SEE ALSO
na() 2 overloads
Tests if x is na.
ARGUMENTS
EXAMPLE
//@version=6
indicator("na")
// Use the `na()` function to test for `na`.
plot(na(close[1]) ? close : close[1])
// ALTERNATIVE
// `nz()` also tests `close[1]` for `na`. It returns `close[1]` if it is not `na`, and `close` if it i
s.
plot(nz(close[1], close))
RETURNS
SEE ALSO
na fixnan() nz()
nz() 6 overloads
Replaces na (undefined) values with either a type-specific default value or a specified replacement.
ARGUMENTS
EXAMPLE
//@version=6
indicator("nz", overlay=true)
plot(nz([Link](close, 100)))
RETURNS
The value of source if it is not na . If the value of source is na , returns zero, or the replacement argument
when one is used.
SEE ALSO
na na() fixnan()
plot()
Plots a series of data on the chart.
SYNTAX
plot(series, title, color, linewidth, style, trackprice, histbase, offset, join, editable, show_last, displ
ay, format, precision, force_overlay, linestyle) → plot
ARGUMENTS
style (input plot_style) Type of plot. Possible values are: plot.style_line, plot.style_stepline,
plot.style_stepline_diamond, plot.style_histogram, plot.style_cross, plot.style_area, plot.style_columns,
plot.style_circles, plot.style_linebr, plot.style_areabr, plot.style_steplinebr. Default value is plot.style_line.
trackprice (input bool) If true then a horizontal price line will be shown at the level of the last indicator value. Default
is false.
histbase (input int/float) The price value used as the reference level when rendering plot with plot.style_histogram,
plot.style_columns or plot.style_area style. Default is 0.0.
offset (simple int) Shifts the plot to the left or to the right on the given number of bars. Default is 0.
join (input bool) If true then plot points will be joined with line, applicable only to plot.style_cross and plot.style_circles
styles. Default is false.
editable (input bool) If true then plot style will be editable in Format dialog. Default is true.
show_last (input int) Optional. The number of bars, counting backwards from the most recent bar, on which the
function can draw.
display (input plot_display) Controls where the plot's information is displayed. Display options support addition and
subtraction, meaning that using [Link] - display.status_line will display the plot's information
everywhere except in the script's status line. display.price_scale + display.status_line will display the
plot only in the price scale and status line. When display arguments such as display.price_scale have user-
controlled chart settings equivalents, the relevant plot information will only appear when all settings allow for it.
Possible values: [Link], [Link], display.data_window, display.price_scale, display.status_line, [Link].
Optional. The default is [Link].
format (input string) Determines whether the script formats the plot's values as prices, percentages, or volume
values. The argument passed to this parameter supersedes the format parameter of the indicator(), and strategy()
functions. Optional. The default is the format value used by the indicator()/strategy() function. Possible values:
[Link], [Link], [Link].
precision (input int) The number of digits after the decimal point the plot's values show on the chart pane's y-axis,
the script's status line, and the Data Window. Accepts a non-negative integer less than or equal to 16. The argument
passed to this parameter supersedes the precision parameter of the indicator() and strategy() functions. When
the function's format parameter uses [Link], the precision parameter will not affect the result, as the
decimal precision rules defined by [Link] supersede other precision settings. Optional. The default is the pre
cision value used by the indicator()/strategy() function.
force_overlay (const bool) If true, the plotted results will display on the main chart pane, even when the script
occupies a separate pane. Optional. The default is false.
linestyle (input plot_line_style) Optional. A modifier for plot styles that display lines. It specifies whether the plotted
line is solid (plot.linestyle_solid), dashed (plot.linestyle_dashed), or dotted (plot.linestyle_dotted). The modifier applies
only when the function uses one of the following style arguments: plot.style_line, plot.style_linebr,
plot.style_stepline, plot.style_stepline_diamond, and plot.style_area. The default is plot.linestyle_solid.
EXAMPLE
//@version=6
indicator("plot")
plot(high+low, title='Title', color=[Link](#00ffaa, 70), linewidth=2, style=plot.style_area, offset=
15, trackprice=true)
// You may fill the background between any two plots with a fill() function:
p1 = plot(open)
p2 = plot(close)
fill(p1, p2, color=[Link]([Link], 90))
RETURNS
SEE ALSO
plotarrow()
Plots up and down arrows on the chart. Up arrow is drawn at every indicator positive value, down arrow is drawn at
every negative value. If indicator returns na then no arrow is drawn. Arrows has different height, the more absolute
indicator value the longer arrow is drawn.
SYNTAX
plotarrow(series, title, colorup, colordown, offset, minheight, maxheight, editable, show_last, display, fo
rmat, precision, force_overlay) → void
ARGUMENTS
offset (simple int) Shifts arrows to the left or to the right on the given number of bars. Default is 0.
minheight (input int) Minimal possible arrow height in pixels. Default is 5.
maxheight (input int) Maximum possible arrow height in pixels. Default is 100.
editable (input bool) If true then plotarrow style will be editable in Format dialog. Default is true.
show_last (input int) Optional. The number of bars, counting backwards from the most recent bar, on which the
function can draw.
display (input plot_display) Controls where the plot's information is displayed. Display options support addition and
subtraction, meaning that using [Link] - display.status_line will display the plot's information
everywhere except in the script's status line. display.price_scale + display.status_line will display the
plot only in the price scale and status line. When display arguments such as display.price_scale have user-
controlled chart settings equivalents, the relevant plot information will only appear when all settings allow for it.
Possible values: [Link], [Link], display.data_window, display.price_scale, display.status_line, [Link].
Optional. The default is [Link].
format (input string) Determines whether the script formats the plot's values as prices, percentages, or volume
values. The argument passed to this parameter supersedes the format parameter of the indicator(), and strategy()
functions. Optional. The default is the format value used by the indicator()/strategy() function. Possible values:
[Link], [Link], [Link].
precision (input int) The number of digits after the decimal point the plot's values show on the chart pane's y-axis,
the script's status line, and the Data Window. Accepts a non-negative integer less than or equal to 16. The argument
passed to this parameter supersedes the precision parameter of the indicator() and strategy() functions. When
the function's format parameter uses [Link], the precision parameter will not affect the result, as the
decimal precision rules defined by [Link] supersede other precision settings. Optional. The default is the pre
cision value used by the indicator()/strategy() function.
force_overlay (const bool) If true, the plotted results will display on the main chart pane, even when the script
occupies a separate pane. Optional. The default is false.
EXAMPLE
//@version=6
indicator("plotarrow example", overlay=true)
codiff = close - open
plotarrow(codiff, colorup=[Link]([Link],40), colordown=[Link]([Link], 40))
REMARKS
SEE ALSO
plotbar()
Plots ohlc bars on the chart.
SYNTAX
plotbar(open, high, low, close, title, color, editable, show_last, display, format, precision, force_overla
y) → void
ARGUMENTS
open (series int/float) Open series of data to be used as open values of bars. Required argument.
high (series int/float) High series of data to be used as high values of bars. Required argument.
low (series int/float) Low series of data to be used as low values of bars. Required argument.
close (series int/float) Close series of data to be used as close values of bars. Required argument.
title (const string) Title of the plotbar. Optional argument.
color (series color) Color of the ohlc bars. You can use constants like 'color=[Link]' or 'color=#ff001a' as well as
complex expressions like 'color = close >= open ? [Link] : [Link]'. Optional argument.
editable (input bool) If true then plotbar style will be editable in Format dialog. Default is true.
show_last (input int) Optional. The number of bars, counting backwards from the most recent bar, on which the
function can draw.
display (input plot_display) Controls where the plot's information is displayed. Display options support addition and
subtraction, meaning that using [Link] - display.status_line will display the plot's information
everywhere except in the script's status line. display.price_scale + display.status_line will display the
plot only in the price scale and status line. When display arguments such as display.price_scale have user-
controlled chart settings equivalents, the relevant plot information will only appear when all settings allow for it.
Possible values: [Link], [Link], display.data_window, display.price_scale, display.status_line, [Link].
Optional. The default is [Link].
format (input string) Determines whether the script formats the plot's values as prices, percentages, or volume
values. The argument passed to this parameter supersedes the format parameter of the indicator(), and strategy()
functions. Optional. The default is the format value used by the indicator()/strategy() function. Possible values:
[Link], [Link], [Link].
precision (input int) The number of digits after the decimal point the plot's values show on the chart pane's y-axis,
the script's status line, and the Data Window. Accepts a non-negative integer less than or equal to 16. The argument
passed to this parameter supersedes the precision parameter of the indicator() and strategy() functions. When
the function's format parameter uses [Link], the precision parameter will not affect the result, as the
decimal precision rules defined by [Link] supersede other precision settings. Optional. The default is the pre
cision value used by the indicator()/strategy() function.
force_overlay (const bool) If true, the plotted results will display on the main chart pane, even when the script
occupies a separate pane. Optional. The default is false.
EXAMPLE
//@version=6
indicator("plotbar example", overlay=true)
plotbar(open, high, low, close, title='Title', color = open < close ? [Link] : [Link])
REMARKS
Even if one value of open, high, low or close equal NaN then bar no draw.
The maximal value of open, high, low or close will be set as 'high', and the minimal value will be set as 'low'.
SEE ALSO
plotcandle()
plotcandle()
Plots candles on the chart.
SYNTAX
plotcandle(open, high, low, close, title, color, wickcolor, editable, show_last, bordercolor, display, form
at, precision, force_overlay) → void
ARGUMENTS
open (series int/float) Open series of data to be used as open values of candles. Required argument.
high (series int/float) High series of data to be used as high values of candles. Required argument.
low (series int/float) Low series of data to be used as low values of candles. Required argument.
close (series int/float) Close series of data to be used as close values of candles. Required argument.
color (series color) Color of the candles. You can use constants like 'color=[Link]' or 'color=#ff001a' as well as
complex expressions like 'color = close >= open ? [Link] : [Link]'. Optional argument.
wickcolor (series color) The color of the wick of candles. An optional argument.
editable (input bool) If true then plotcandle style will be editable in Format dialog. Default is true.
show_last (input int) Optional. The number of bars, counting backwards from the most recent bar, on which the
function can draw.
force_overlay (const bool) If true, the plotted results will display on the main chart pane, even when the script
occupies a separate pane. Optional. The default is false.
EXAMPLE
//@version=6
indicator("plotcandle example", overlay=true)
plotcandle(open, high, low, close, title='Title', color = open < close ? [Link] : [Link], wickc
olor=[Link])
REMARKS
Even if one value of open, high, low or close equal NaN then bar no draw.
The maximal value of open, high, low or close will be set as 'high', and the minimal value will be set as 'low'.
SEE ALSO
plotbar()
plotchar()
Plots visual shapes using any given one Unicode character on the chart.
SYNTAX
plotchar(series, title, char, location, color, offset, text, textcolor, editable, size, show_last, display,
format, precision, force_overlay) → void
ARGUMENTS
series (series int/float/bool) Series of data to be plotted as shapes. Series is treated as a series of boolean values for
all location values except [Link]. Required argument.
title (const string) Title of the plot.
text (const string) Text to display with the shape. You can use multiline text, to separate lines use '\n' escape
sequence. Example: 'line one\nline two'.
textcolor (series color) Color of the text. You can use constants like 'textcolor=[Link]' or 'textcolor=#ff001a' as
well as complex expressions like 'textcolor = close >= open ? [Link] : [Link]'. Optional argument.
editable (input bool) If true then plotchar style will be editable in Format dialog. Default is true.
size (const string) Size of characters on the chart. Possible values are: [Link], [Link], [Link], [Link],
[Link], [Link]. Default is [Link].
show_last (input int) Optional. The number of bars, counting backwards from the most recent bar, on which the
function can draw.
display (input plot_display) Controls where the plot's information is displayed. Display options support addition and
subtraction, meaning that using [Link] - display.status_line will display the plot's information
everywhere except in the script's status line. display.price_scale + display.status_line will display the
plot only in the price scale and status line. When display arguments such as display.price_scale have user-
controlled chart settings equivalents, the relevant plot information will only appear when all settings allow for it.
Possible values: [Link], [Link], display.data_window, display.price_scale, display.status_line, [Link].
Optional. The default is [Link].
format (input string) Determines whether the script formats the plot's values as prices, percentages, or volume
values. The argument passed to this parameter supersedes the format parameter of the indicator(), and strategy()
functions. Optional. The default is the format value used by the indicator()/strategy() function. Possible values:
[Link], [Link], [Link].
precision (input int) The number of digits after the decimal point the plot's values show on the chart pane's y-axis,
the script's status line, and the Data Window. Accepts a non-negative integer less than or equal to 16. The argument
passed to this parameter supersedes the precision parameter of the indicator() and strategy() functions. When
the function's format parameter uses [Link], the precision parameter will not affect the result, as the
decimal precision rules defined by [Link] supersede other precision settings. Optional. The default is the pre
cision value used by the indicator()/strategy() function.
force_overlay (const bool) If true, the plotted results will display on the main chart pane, even when the script
occupies a separate pane. Optional. The default is false.
EXAMPLE
//@version=6
indicator("plotchar example", overlay=true)
data = close >= open
plotchar(data, char='❄')
REMARKS
SEE ALSO
plotshape()
Plots visual shapes on the chart.
SYNTAX
plotshape(series, title, style, location, color, offset, text, textcolor, editable, size, show_last, displa
y, format, precision, force_overlay) → void
ARGUMENTS
series (series int/float/bool) Series of data to be plotted as shapes. Series is treated as a series of boolean values for
all location values except [Link]. Required argument.
location (input string) Location of shapes on the chart. Possible values are: [Link], [Link],
[Link], [Link], [Link]. Default value is [Link].
color (series color) Color of the shapes. You can use constants like 'color=[Link]' or 'color=#ff001a' as well as
complex expressions like 'color = close >= open ? [Link] : [Link]'. Optional argument.
offset (simple int) Shifts shapes to the left or to the right on the given number of bars. Default is 0.
text (const string) Text to display with the shape. You can use multiline text, to separate lines use '\n' escape
sequence. Example: 'line one\nline two'.
textcolor (series color) Color of the text. You can use constants like 'textcolor=[Link]' or 'textcolor=#ff001a' as
well as complex expressions like 'textcolor = close >= open ? [Link] : [Link]'. Optional argument.
editable (input bool) If true then plotshape style will be editable in Format dialog. Default is true.
size (const string) Size of shapes on the chart. Possible values are: [Link], [Link], [Link], [Link],
[Link], [Link]. Default is [Link].
show_last (input int) Optional. The number of bars, counting backwards from the most recent bar, on which the
function can draw.
display (input plot_display) Controls where the plot's information is displayed. Display options support addition and
subtraction, meaning that using [Link] - display.status_line will display the plot's information
everywhere except in the script's status line. display.price_scale + display.status_line will display the
plot only in the price scale and status line. When display arguments such as display.price_scale have user-
controlled chart settings equivalents, the relevant plot information will only appear when all settings allow for it.
Possible values: [Link], [Link], display.data_window, display.price_scale, display.status_line, [Link].
Optional. The default is [Link].
format (input string) Determines whether the script formats the plot's values as prices, percentages, or volume
values. The argument passed to this parameter supersedes the format parameter of the indicator(), and strategy()
functions. Optional. The default is the format value used by the indicator()/strategy() function. Possible values:
[Link], [Link], [Link].
precision (input int) The number of digits after the decimal point the plot's values show on the chart pane's y-axis,
the script's status line, and the Data Window. Accepts a non-negative integer less than or equal to 16. The argument
passed to this parameter supersedes the precision parameter of the indicator() and strategy() functions. When
the function's format parameter uses [Link], the precision parameter will not affect the result, as the
decimal precision rules defined by [Link] supersede other precision settings. Optional. The default is the pre
cision value used by the indicator()/strategy() function.
force_overlay (const bool) If true, the plotted results will display on the main chart pane, even when the script
occupies a separate pane. Optional. The default is false.
EXAMPLE
//@version=6
indicator("plotshape example 1", overlay=true)
data = close >= open
plotshape(data, style=[Link])
REMARKS
SEE ALSO
[Link]()
Deletes the specified polyline object. It has no effect if the id doesn't exist.
SYNTAX
[Link](id) → void
ARGUMENTS
[Link]()
Creates a new polyline instance and displays it on the chart, sequentially connecting all of the points in the points
array with line segments. The segments in the drawing can be straight or curved depending on the curved
parameter.
SYNTAX
ARGUMENTS
points (array<[Link]>) An array of [Link] objects for the drawing to sequentially connect.
curved (series bool) If true, the drawing will connect all points from the points array using curved line segments.
Optional. The default is false.
closed (series bool) If true, the drawing will also connect the first point to the last point from the points array,
resulting in a closed polyline. Optional. The default is false.
xloc (series string) Determines the field of the [Link] objects in the points array that the polyline will use for
its x-coordinates. If xloc.bar_index, the polyline will use the index field from each point. If xloc.bar_time, it will use
the time field. Optional. The default is xloc.bar_index.
line_color (series color) The color of the line segments. Optional. The default is [Link].
fill_color (series color) The fill color of the polyline. Optional. The default is na.
line_style (series string) The style of the polyline. Possible values: line.style_solid, line.style_dotted,
line.style_dashed, line.style_arrow_left, line.style_arrow_right, line.style_arrow_both. Optional. The default is
line.style_solid.
line_width (series int) The width of the line segments, expressed in pixels. Optional. The default is 1.
force_overlay (const bool) If true, the drawing will display on the main chart pane, even when the script occupies a
separate pane. Optional. The default is false.
EXAMPLE
//@version=6
indicator("Polylines example", overlay = true)
//@variable If `true`, connects all points in the polyline with curved line segments.
bool curvedInput = [Link](false, "Curve Polyline")
//@variable If `true`, connects the first point in the polyline to the last point.
bool closedInput = [Link](true, "Close Polyline")
//@variable The color of the space filled by the polyline.
color fillcolor = [Link]([Link]([Link], 90), "Fill Color")
if [Link]
//@variable An array of `[Link]` objects for the new polyline.
var points = [Link]<[Link]>()
// Push new `[Link]` instances into the `points` array.
[Link]([Link].from_time(p1x, p1y))
[Link]([Link].from_time(p2x, p2y))
[Link]([Link].from_time(p3x, p3y))
[Link]([Link].from_time(p4x, p4y))
[Link]([Link].from_time(p5x, p5y))
// Add labels for each `[Link]` in `points`.
l1p1 = [Link]([Link](0), text = "p1", xloc = xloc.bar_time, color = na)
l1p2 = [Link]([Link](1), text = "p2", xloc = xloc.bar_time, color = na)
l2p1 = [Link]([Link](2), text = "p3", xloc = xloc.bar_time, color = na)
l2p2 = [Link]([Link](3), text = "p4", xloc = xloc.bar_time, color = na)
// Create a new polyline that connects each `[Link]` in the `points` array, starting from the
first.
[Link](points, curved = curvedInput, closed = closedInput, fill_color = fillcolor, xloc = xlo
c.bar_time)
RETURNS
The ID of a new polyline object that a script can use in other polyline.*() functions.
SEE ALSO
[Link]()
request.currency_rate()
Provides a daily rate that can be used to convert a value expressed in the from currency to another in the to
currency.
SYNTAX
ARGUMENTS
from (series string) The currency in which the value to be converted is expressed. Possible values: a three-letter
string with the currency code in the ISO 4217 format (e.g. "USD"), or one of the built-in variables that return currency
codes, like [Link] or [Link].
to (series string) The currency in which the value is to be converted. Possible values: a three-letter string with the
currency code in the ISO 4217 format (e.g. "USD"), or one of the built-in variables that return currency codes, like
[Link] or [Link].
ignore_invalid_currency (series bool) Determines the behavior of the function if a conversion rate between the two
currencies cannot be calculated: if false, the script will halt and return a runtime error; if true, the function will return na
and execution will continue. Optional. The default is false.
EXAMPLE
//@version=6
indicator("Close in British Pounds")
rate = request.currency_rate([Link], "GBP")
plot(close * rate)
REMARKS
If from and to arguments are equal, function returns 1. Please note that using this variable/function can cause
indicator repainting.
[Link]()
Requests dividends data for the specified symbol.
SYNTAX
ARGUMENTS
ticker (series string) Symbol. Note that the symbol should be passed with a prefix. For example: "NASDAQ:AAPL"
instead of "AAPL". Using [Link] will cause an error. Use [Link] instead.
field (series string) Input string. Possible values include: [Link], [Link]. Default value is
[Link].
gaps (simple barmerge_gaps) Merge strategy for the requested data (requested data automatically merges with the
main series OHLC data). Possible values: barmerge.gaps_on, barmerge.gaps_off. barmerge.gaps_on - requested data
is merged with possible gaps (na values). barmerge.gaps_off - requested data is merged continuously without gaps,
all the gaps are filled with the previous nearest existing values. Default value is barmerge.gaps_off.
lookahead (simple barmerge_lookahead) Merge strategy for the requested data position. Possible values:
barmerge.lookahead_on, barmerge.lookahead_off. Default value is barmerge.lookahead_off starting from version 3.
Note that behavour is the same on real-time, and differs only on history.
ignore_invalid_symbol (input bool) An optional parameter. Determines the behavior of the function if the specified
symbol is not found: if false, the script will halt and return a runtime error; if true, the function will return na and
execution will continue. The default value is false.
currency (series string) Currency into which the symbol's currency-related dividends values (e.g. [Link])
are to be converted. The conversion rate depends on the previous daily value of a corresponding currency pair from
the most popular exchange. A spread symbol is used if no exchange provides the rate directly. Possible values: a
"string" representing a valid currency code (e.g., "USD" or "USDT") or a constant from the currency.* namespace
(e.g., [Link] or [Link]). The default is [Link].
EXAMPLE
//@version=6
indicator("[Link]")
s1 = [Link]("NASDAQ:BELFA")
plot(s1)
s2 = [Link]("NASDAQ:BELFA", [Link], gaps=barmerge.gaps_on, lookahead=[Link]
ad_on)
plot(s2)
RETURNS
Requested series, or n/a if there is no dividends data for the specified symbol.
SEE ALSO
[Link]()
Requests earnings data for the specified symbol.
SYNTAX
ARGUMENTS
ticker (series string) Symbol. Note that the symbol should be passed with a prefix. For example: "NASDAQ:AAPL"
instead of "AAPL". Using [Link] will cause an error. Use [Link] instead.
field (series string) Input string. Possible values include: [Link], [Link], [Link].
Default value is [Link].
gaps (simple barmerge_gaps) Merge strategy for the requested data (requested data automatically merges with the
main series OHLC data). Possible values: barmerge.gaps_on, barmerge.gaps_off. barmerge.gaps_on - requested data
is merged with possible gaps (na values). barmerge.gaps_off - requested data is merged continuously without gaps,
all the gaps are filled with the previous nearest existing values. Default value is barmerge.gaps_off.
lookahead (simple barmerge_lookahead) Merge strategy for the requested data position. Possible values:
barmerge.lookahead_on, barmerge.lookahead_off. Default value is barmerge.lookahead_off starting from version 3.
Note that behavour is the same on real-time, and differs only on history.
ignore_invalid_symbol (input bool) An optional parameter. Determines the behavior of the function if the specified
symbol is not found: if false, the script will halt and return a runtime error; if true, the function will return na and
execution will continue. The default value is false.
currency (series string) Currency into which the symbol's currency-related earnings values (e.g. [Link]) are
to be converted. The conversion rate depends on the previous daily value of a corresponding currency pair from the
most popular exchange. A spread symbol is used if no exchange provides the rate directly. Possible values: a "string"
representing a valid currency code (e.g., "USD" or "USDT") or a constant from the currency.* namespace (e.g.,
[Link] or [Link]). The default is [Link].
EXAMPLE
//@version=6
indicator("[Link]")
s1 = [Link]("NASDAQ:BELFA")
plot(s1)
s2 = [Link]("NASDAQ:BELFA", [Link], gaps=barmerge.gaps_on, lookahead=[Link]
ead_on)
plot(s2)
RETURNS
Requested series, or n/a if there is no earnings data for the specified symbol.
SEE ALSO
[Link]()
Requests economic data for a symbol. Economic data includes information such as the state of a country's economy
(GDP, inflation rate, etc.) or of a particular industry (steel production, ICU beds, etc.).
SYNTAX
ARGUMENTS
country_code (series string) The code of the country (e.g. "US") or the region (e.g. "EU") for which the economic
data is requested. The Help Center article lists the countries and their codes. The countries for which information is
available vary with metrics. The Help Center article for each metric lists the countries for which the metric is available.
field (series string) The code of the requested economic metric (e.g., "GDP"). The Help Center article lists the
metrics and their codes.
gaps (simple barmerge_gaps) Specifies how the returned values are merged on chart bars. Possible values:
barmerge.gaps_off, barmerge.gaps_on. With barmerge.gaps_on, a value only appears on the current chart bar when it
first becomes available from the function's context, otherwise na is returned (thus a "gap" occurs). With
barmerge.gaps_off, what would otherwise be gaps are filled with the latest known value returned, avoiding na values.
Optional. The default is barmerge.gaps_off.
ignore_invalid_symbol (input bool) Determines the behavior of the function if the specified symbol is not found: if
false, the script will halt and return a runtime error; if true, the function will return na and execution will continue.
Optional. The default is false.
EXAMPLE
//@version=6
indicator("US GDP")
e = [Link]("US", "GDP")
plot(e)
RETURNS
Requested series.
REMARKS
Economic data can also be accessed from charts, just like a regular symbol. Use "ECONOMIC" as the exchange name
and {country_code}{field} as the ticker. The name of US GDP data is thus "ECONOMIC:USGDP".
SEE ALSO
[Link]()
[Link]()
Requests financial series for symbol.
SYNTAX
ARGUMENTS
symbol (series string) Symbol. Note that the symbol should be passed with a prefix. For example: "NASDAQ:AAPL"
instead of "AAPL".
financial_id (series string) Financial identifier. You can find the list of available ids via our Help Center.
period (series string) Reporting period. Possible values are "TTM", "FY", "FQ", "FH", "D".
gaps (simple barmerge_gaps) Merge strategy for the requested data (requested data automatically merges with the
main series: OHLC data). Possible values include: barmerge.gaps_on, barmerge.gaps_off. barmerge.gaps_on -
requested data is merged with possible gaps (na values). barmerge.gaps_off - requested data is merged continuously
without gaps, all the gaps are filled with the previous, nearest existing values. Default value is barmerge.gaps_off.
ignore_invalid_symbol (input bool) An optional parameter. Determines the behavior of the function if the specified
symbol is not found: if false, the script will halt and return a runtime error; if true, the function will return na and
execution will continue. The default value is false.
currency (series string) Optional. Currency into which the symbol's financial metrics (e.g. Net Income) are to be
converted. The conversion rate depends on the previous daily value of a corresponding currency pair from the most
popular exchange. A spread symbol is used if no exchange provides the rate directly. Possible values: a "string"
representing a valid currency code (e.g., "USD" or "USDT") or a constant from the currency.* namespace (e.g.,
[Link] or [Link]). The default is [Link].
EXAMPLE
//@version=6
indicator("[Link]")
f = [Link]("NASDAQ:MSFT", "ACCOUNTS_PAYABLE", "FY")
plot(f)
RETURNS
Requested series.
SEE ALSO
[Link]() [Link]
[Link]()
Requests footprint data for the symbol and timeframe of the current context and returns a footprint object for each
bar.
SYNTAX
ARGUMENTS
ticks_per_row (simple int) The number of ticks forming a single price level (a volume_row ) in the footprint.
va_percent (simple int/float) The percentage of total volume used to construct the Value Area (VA). Optional. The
default is 70 .
imbalance_percent (simple int/float) The imbalance threshold in percent. When the volume on one side exceeds this
threshold relative to the other side, the level is marked as imbalanced. Optional. The default is 300 .
RETURNS
A footprint object containing Volume Footprint data for the bar in the current context.
[Link]()
Note: This function has been deprecated due to the API change from NASDAQ Data Link. Requests for "QUANDL"
symbols are no longer valid and requests for them return a runtime error.
Some of the data previously provided by this function is available on TradingView through other feeds, such as
"BCHAIN" or "FRED". Use Symbol Search to look for such data based on its description. Commitment of Traders (COT)
data can be requested using the official LibraryCOT library.
Requests Nasdaq Data Link (formerly Quandl) data for a symbol.
SYNTAX
ARGUMENTS
ticker (series string) Symbol. Note that the name of a time series and Quandl data feed should be divided by a
forward slash. For example: "CFTC/SB_FO_ALL".
gaps (simple barmerge_gaps) Merge strategy for the requested data (requested data automatically merges with the
main series: OHLC data). Possible values include: barmerge.gaps_on, barmerge.gaps_off. barmerge.gaps_on -
requested data is merged with possible gaps (na values). barmerge.gaps_off - requested data is merged continuously
without gaps, all the gaps are filled with the previous, nearest existing values. Default value is barmerge.gaps_off.
index (series int) A Quandl time-series column index.
ignore_invalid_symbol (input bool) An optional parameter. Determines the behavior of the function if the specified
symbol is not found: if false, the script will halt and return a runtime error; if true, the function will return na and
execution will continue. The default value is false.
EXAMPLE
//@version=6
indicator("[Link]")
f = [Link]("CFTC/SB_FO_ALL", barmerge.gaps_off, 0)
plot(f)
RETURNS
Requested series.
SEE ALSO
[Link]() [Link]
[Link]()
Requests the result of an expression from a specified context (symbol and timeframe).
SYNTAX
ARGUMENTS
symbol (series string) Symbol or ticker identifier of the requested data. Use an empty string or [Link] to
request data using the chart's symbol. To retrieve data with additional modifiers (extended sessions, dividend
adjustments, non-standard chart types like Heikin Ashi and Renko, etc.), create a custom ticker ID for the request
using the functions in the ticker.* namespace.
timeframe (series string) Timeframe of the requested data. Use an empty string or [Link] to request data
from the chart's timeframe or the timeframe specified in the indicator() function. To request data from a different
timeframe, supply a valid timeframe string. See here to learn about specifying timeframe strings.
expression (variable, function, object, array, matrix, or map of series int/float/bool/string/color/enum, or a tuple
of these) The expression to calculate and return from the requested context. It can accept a built-in variable like close,
a user-defined variable, an expression such as [Link](close) / (high - low) , a function call that does
not use Pine Script® drawings, an object, a collection, or a tuple of expressions.
gaps (simple barmerge_gaps) Specifies how the returned values are merged on chart bars. Possible values:
barmerge.gaps_on, barmerge.gaps_off. With barmerge.gaps_on a value only appears on the current chart bar when it
first becomes available from the function's context, otherwise na is returned (thus a "gap" occurs). With
barmerge.gaps_off what would otherwise be gaps are filled with the latest known value returned, avoiding na values.
Optional. The default is barmerge.gaps_off.
lookahead (simple barmerge_lookahead) On historical bars only, returns data from the timeframe before it elapses.
Possible values: barmerge.lookahead_on, barmerge.lookahead_off. Has no effect on realtime values. Optional. The
default is barmerge.lookahead_off starting from Pine Script® v3. The default is barmerge.lookahead_on in v1 and v2.
WARNING: Using barmerge.lookahead_on at timeframes higher than the chart's without offsetting the expression
argument like in close[1] will introduce future leak in scripts, as the function will then return the close price
before it is actually known in the current context. As is explained in the User Manual's page on Repainting this will
produce misleading results.
ignore_invalid_symbol (input bool) Determines the behavior of the function if the specified symbol is not found: if
false, the script will halt and throw a runtime error; if true, the function will return na and execution will continue.
Optional. The default is false.
currency (series string) Optional. Specifies the target currency for converting values expressed in currency units
(e.g., open, high, low, close) or expressions involving such values. Literal values such as 200 are not converted. The
conversion rate for monetary values depends on the previous daily value of a corresponding currency pair from the
most popular exchange. A spread symbol is used if no exchange provides the rate directly. Possible values: a "string"
representing a valid currency code (e.g., "USD" or "USDT") or a constant from the currency.* namespace (e.g.,
[Link] or [Link]). The default is [Link].
calc_bars_count (simple int) Optional. Determines the maximum number of recent historical bars that the function
can request. If specified, the function evaluates the expression argument starting from that number of bars behind
the last historical bar in the requested dataset, treating those bars as the only available data. Limiting the number of
historical bars in a request can help improve calculation efficiency in some cases. The default is the same as the
number of chart bars available for the symbol and timeframe. The maximum number of bars that the function can
attempt to retrieve depends on the intrabar limit of the user's plan. However, the request cannot retrieve more bars
than are available in the dataset.
EXAMPLE
//@version=6
indicator("Simple `[Link]()` calls")
// Returns 1D close of the current symbol.
dailyClose = [Link]([Link], "1D", close)
plot(dailyClose)
// Returns the close of "AAPL" from the same timeframe as currently open on the chart.
aaplClose = [Link]("AAPL", [Link], close)
plot(aaplClose)
EXAMPLE
//@version=6
indicator("Advanced `[Link]()` calls")
// This calculates a 10-period moving average on the active chart.
sma = [Link](close, 10)
// This sends the `sma` calculation for execution in the context of the "AAPL" symbol at a "240" (4 hou
rs) timeframe.
aaplSma = [Link]("AAPL", "240", sma)
plot(aaplSma)
// To avoid differences on historical and realtime bars, you can use this technique, which only return
s a value from the higher timeframe on the bar after it completes:
indexHighTF = [Link] ? 1 : 0
indexCurrTF = [Link] ? 0 : 1
nonRepaintingClose = [Link]([Link], "1D", close[indexHighTF])[indexCurrTF]
plot(nonRepaintingClose, "Non-repainting close")
// Returns the 1H close of "AAPL", extended session included. The value is dividend-adjusted.
extendedTicker = [Link]("NASDAQ:AAPL", session = [Link], adjustment = [Link]
ends)
aaplExtAdj = [Link](extendedTicker, "60", close)
plot(aaplExtAdj)
// By using a tuple `expression`, we obtain several values with only one `[Link]()` call.
[open1D, high1D, low1D, close1D, ema1D] = [Link]([Link], "1D", [open, high, low, cl
ose, [Link](close, 10)])
plotcandle(open1D, high1D, low1D, close1D)
plot(ema1D)
// Returns an array containing the OHLC values of the chart's symbol from the 1D timeframe.
ohlcArray = [Link]([Link], "1D", [Link](open, high, low, close))
plotcandle([Link](ohlcArray, 0), [Link](ohlcArray, 1), [Link](ohlcArray, 2), [Link](ohlcArr
ay, 3))
RETURNS
REMARKS
Scripts using this function might calculate differently on historical and realtime bars, leading to repainting.
A single script can contain no more than 40 unique request.*() function calls. A call is unique only if it does not
call the same function with the same arguments.
When using two calls to a request.*() function to evaluate the same expression from the same context with
different calc_bars_count values, the second call requests the same number of historical bars as the first. For
example, if a script calls [Link]("AAPL", "", close, calc_bars_count = 3) after it calls req
[Link]("AAPL", "", close, calc_bars_count = 5) , the second call also uses five bars of
historical data, not three.
The symbol of a request.() call can be inherited if it is not specified precisely, i.e., if the symbol argument is an
empty string or [Link]. Similarly, the timeframe of a request.() call can be inherited if the timeframe
argument is an empty string or [Link]. These values are normally taken from the chart on which the script is
running. However, if request.*() function A is called from within the expression of request.*() function B,
then function A can inherit the values from function B. See here for more information.
SEE ALSO
request.security_lower_tf()
Requests the results of an expression from a specified symbol on a timeframe lower than or equal to the chart's
timeframe. It returns an array containing one element for each lower-timeframe bar within the chart bar. On a 5-minute
chart, requesting data using a timeframe argument of "1" typically returns an array with five elements representing
the value of the expression on each 1-minute bar, ordered by time with the earliest value first.
SYNTAX
request.security_lower_tf(symbol, timeframe, expression, ignore_invalid_symbol, currency, ignore_invalid_ti
meframe, calc_bars_count) → array<type>
ARGUMENTS
symbol (series string) Symbol or ticker identifier of the requested data. Use an empty string or [Link] to
request data using the chart's symbol. To retrieve data with additional modifiers (extended sessions, dividend
adjustments, non-standard chart types like Heikin Ashi and Renko, etc.), create a custom ticker ID for the request
using the functions in the ticker.* namespace.
timeframe (series string) Timeframe of the requested data. Use an empty string or [Link] to request data
from the chart's timeframe or the timeframe specified in the indicator() function. To request data from a different
timeframe, supply a valid timeframe string. See here to learn about specifying timeframe strings.
expression (variable, object or function of series int/float/bool/string/color/enum, or a tuple of these) The
expression to calculate and return from the requested context. It can accept a built-in variable like close, a user-
defined variable, an expression such as [Link](close) / (high - low) , a function call that does not use
Pine Script® drawings, an object, or a tuple of expressions. Collections are not allowed unless they are within the fields
of an object
ignore_invalid_symbol (series bool) Determines the behavior of the function if the specified symbol is not found: if
false, the script will halt and throw a runtime error; if true, the function will return na and execution will continue.
Optional. The default is false.
currency (series string) Optional. Specifies the target currency for converting values expressed in currency units
(e.g., open, high, low, close) or expressions involving such values. Literal values such as 200 are not converted. The
conversion rate for monetary values depends on the previous daily value of a corresponding currency pair from the
most popular exchange. A spread symbol is used if no exchange provides the rate directly. Possible values: a "string"
representing a valid currency code (e.g., "USD" or "USDT") or a constant from the currency.* namespace (e.g.,
[Link] or [Link]). The default is [Link].
ignore_invalid_timeframe (series bool) Determines the behavior of the function when the chart's timeframe is
smaller than the timeframe used in the function call. If false, the script will halt and throw a runtime error. If true, the
function will return na and execution will continue. Optional. The default is false.
calc_bars_count (simple int) Optional. Determines the maximum number of recent historical bars that the function
can request. If specified, the function evaluates the expression argument starting from that number of bars behind
the last historical bar in the requested dataset, treating those bars as the only available data. Limiting the number of
historical bars in a request can help improve calculation efficiency in some cases. The default is the same as the
number of chart bars available for the symbol and timeframe. The maximum number of bars that the function can
attempt to retrieve depends on the intrabar limit of the user's plan. However, the request cannot retrieve more bars
than are available in the dataset.
EXAMPLE
//@version=6
indicator("`request.security_lower_tf()` Example", overlay = true)
// If the current chart timeframe is set to 120 minutes, then the `arrayClose` array will contain two '
close' values from the 60 minute timeframe for each bar.
arrClose = request.security_lower_tf([Link], "60", close)
if bar_index == last_bar_index - 1
[Link](bar_index, high, [Link](arrClose))
RETURNS
REMARKS
Scripts using this function might calculate differently on historical and realtime bars, leading to repainting.
Please note that spreads (e.g., "AAPL+MSFT*TSLA") do not always return reliable data with this function.
A single script can contain no more than 40 unique request.*() function calls. A call is unique only if it does not
call the same function with the same arguments.
When using two calls to a request.*() function to evaluate the same expression from the same context with
different calc_bars_count values, the second call requests the same number of historical bars as the first. For
example, if a script calls [Link]("AAPL", "", close, calc_bars_count = 3) after it calls req
[Link]("AAPL", "", close, calc_bars_count = 5) , the second call also uses five bars of
historical data, not three.
The symbol of a request.() call can be inherited if it is not specified precisely, i.e., if the symbol argument is an
empty string or [Link]. Similarly, the timeframe of a request.() call can be inherited if the timeframe
argument is an empty string or [Link]. These values are normally taken from the chart that the script is
running on. However, if request.*() function A is called from within the expression of request.*() function B,
then function A can inherit the values from function B. See here for more information.
SEE ALSO
[Link]()
Requests the result of an expression evaluated on data from a user-maintained GitHub repository. **Note:**The
creation of new Pine Seeds repositories is suspended; only existing repositories are currently supported. See the Pine
Seeds documentation on GitHub to learn more.
SYNTAX
ARGUMENTS
calc_bars_count (simple int) Optional. If specified, the function requests only this number of values from the end of
the symbol's history and calculates expression as if these values are the only available data, which might improve
calculation speed in some cases. The default is the same as the number of chart bars available for the symbol and
timeframe. The maximum number of bars that the function can attempt to retrieve depends on the intrabar limit of the
user's plan. However, the request cannot retrieve more bars than are available in the dataset.
EXAMPLE
//@version=6
indicator("BTC Development Activity")
RETURNS
SYNTAX
ARGUMENTS
ticker (series string) Symbol. Note that the symbol should be passed with a prefix. For example: "NASDAQ:AAPL"
instead of "AAPL". Using [Link] will cause an error. Use [Link] instead.
field (series string) Input string. Possible values include: [Link], [Link].
gaps (simple barmerge_gaps) Merge strategy for the requested data (requested data automatically merges with the
main series OHLC data). Possible values: barmerge.gaps_on, barmerge.gaps_off. barmerge.gaps_on - requested data
is merged with possible gaps (na values). barmerge.gaps_off - requested data is merged continuously without gaps,
all the gaps are filled with the previous nearest existing values. Default value is barmerge.gaps_off.
lookahead (simple barmerge_lookahead) Merge strategy for the requested data position. Possible values:
barmerge.lookahead_on, barmerge.lookahead_off. Default value is barmerge.lookahead_off starting from version 3.
Note that behavour is the same on real-time, and differs only on history.
ignore_invalid_symbol (input bool) An optional parameter. Determines the behavior of the function if the specified
symbol is not found: if false, the script will halt and return a runtime error; if true, the function will return na and
execution will continue. The default value is false.
EXAMPLE
//@version=6
indicator("[Link]")
s1 = [Link]("NASDAQ:BELFA", [Link])
plot(s1)
s2 = [Link]("NASDAQ:BELFA", [Link], gaps=barmerge.gaps_on, lookahead=[Link]
head_on)
plot(s2)
RETURNS
Requested series, or n/a if there is no splits data for the specified symbol.
SEE ALSO
[Link]()
When called, causes a runtime error with the error message specified in the message argument.
SYNTAX
[Link](message) → void
ARGUMENTS
second()
SYNTAX
timezone (series string) Allows adjusting the returned value to a time zone specified in either UTC/GMT notation
(e.g., "UTC-5", "GMT+0530") or as an IANA time zone database name (e.g., "America/New_York"). Optional. The
default is [Link].
RETURNS
REMARKS
UNIX time is the number of milliseconds that have elapsed since 00:00:00 UTC, 1 January 1970.
SEE ALSO
[Link]() 3 overloads
Returns true if the source string contains the str substring, false otherwise.
ARGUMENTS
EXAMPLE
//@version=6
indicator("[Link]")
// If the current chart is a continuous futures chart, e.g “BTC1!”, then the function will return tru
e, false otherwise.
var isFutures = [Link]([Link], "!")
plot(isFutures ? 1 : 0)
RETURNS
True if the str was found in the source string, false otherwise.
SEE ALSO
[Link]() [Link]()
[Link]() 3 overloads
Returns true if the source string ends with the substring specified in str , false otherwise.
ARGUMENTS
RETURNS
True if the source string ends with the substring specified in str , false otherwise.
SEE ALSO
[Link]()
[Link]() 2 overloads
Creates a formatted string using a specified formatting string ( formatString ) and one or more additional
arguments ( arg0 , arg1 , etc.). The formatting string defines the structure of the returned string, where all
placeholders in curly brackets ( {} ) refer to the additional arguments. Each placeholder requires a number
representing an argument's position, starting from 0. For instance, the placeholder {0} refers to the first argument
after formatString ( arg0 ), {1} refers to the second ( arg1 ), and so on. The function replaces each
placeholder with a string representation of the corresponding argument.
ARGUMENTS
EXAMPLE
//@version=6
indicator("Simple `[Link]()` demo")
//@variable A formatted string that includes representations of the current `bar_index` and `close` val
ues.
// The placeholder `{0}` refers to the first argument after the formatting string (`bar_index
`), and
// `{1}` refers to the second (`close`).
string labelText = [Link]("Current bar index: {0}\nCurrent bar close: {1}", bar_index, close)
// Draw a label to display the `labelText` string at the current bar's `high` price.
[Link](bar_index, high, labelText)
EXAMPLE
//@version=6
indicator("Extensive `[Link]()` demo", overlay=true)
// The format specifier inside the curly braces accepts certain modifiers:
// - Specify the number of decimals to display:
s1 = [Link]("{0,number,#.#}", 1.34) // returns: 1.3
[Link](bar_index, close, text=s1)
// - Round a float value to an integer:
s2 = [Link]("{0,number,integer}", 1.34) // returns: 1
[Link](bar_index - 1, close, text=s2)
// - Display a number in currency:
s3 = [Link]("{0,number,currency}", 1.34) // returns: $1.34
[Link](bar_index - 2, close, text=s3)
// - Display a number as a percentage:
s4 = [Link]("{0,number,percent}", 0.5) // returns: 50%
[Link](bar_index - 3, close, text=s4)
// EXAMPLES WITH SEVERAL ARGUMENTS
// returns: Number 1 is not equal to 4
s5 = [Link]("Number {0} is not {1} to {2}", 1, "equal", 4)
[Link](bar_index - 4, close, text=s5)
// returns: 1.34 != 1.3
s6 = [Link]("{0} != {0, number, #.#}", 1.34)
[Link](bar_index - 5, close, text=s6)
// returns: 1 is equal to 1, but 2 is equal to 2
s7 = [Link]("{0, number, integer} is equal to 1, but {1, number, integer} is equal to 2", 1.34, 1.5
2)
[Link](bar_index - 6, close, text=s7)
// returns: The cash turnover amounted to $1,340,000.00
s8 = [Link]("The cash turnover amounted to {0, number, currency}", 1340000)
[Link](bar_index - 7, close, text=s8)
// returns: Expected return is 10% - 20%
s9 = [Link]("Expected return is {0, number, percent} - {1, number, percent}", 0.1, 0.2)
[Link](bar_index - 8, close, text=s9)
RETURNS
REMARKS
The string used as the formatString argument can contain single quote characters ('). However, programmers
must pair all single quotes in that string to avoid unexpected formatting results.
All non-quoted left curly brackets must have corresponding right curly brackets in the formatting string. If the string
contains imbalanced left curly brackets, it causes a runtime error. For example, "ab {0} de" and "ab }{0} de" are valid
formatting strings, but "ab {0'}' de", "ab }{0}{ de" and "''{''{0}" are not.
The placeholders for "int" or "float" values or arrays can include modifiers and formatting tokens to customize how the
resulting string represents them.
For example, the placeholder {0,number,#.#) specifies that the result inserts characters representing the arg0
number rounded to one fractional digit.
For detailed information about placeholders and supported formats, refer to the Formatting strings section of our User
Manual's Strings page.
The apostrophe ( ' ) acts as a quote character rather than a literal character inside formatting strings. If a formatting
string has a sequence of characters between two apostrophes, the function's result includes those characters literally.
For instance, the substring '{' adds a literal { character to the result instead of treating it as the start of a
placeholder. Note that if a formatting string uses apostrophes instead of quotation marks for its enclosing characters,
the string must escape any apostrophes within the character sequence using the backslash.
str.format_time()
Converts the time timestamp into a string formatted according to format and timezone .
SYNTAX
ARGUMENTS
format (series string) A format string specifying the date/time representation of the time in the returned string. All
letters used in the string, except those escaped by single quotation marks ' , are considered formatting tokens and
will be used as a formatting instruction. Refer to the Remarks section for a list of the most useful tokens. Optional. The
default is "yyyy-MM-dd'T'HH:mm:ssZ", which represents the ISO 8601 standard.
timezone (series string) Allows adjusting the returned value to a time zone specified in either UTC/GMT notation
(e.g., "UTC-5", "GMT+0530") or as an IANA time zone database name (e.g., "America/New_York"). Optional. The
default is [Link].
EXAMPLE
//@version=6
indicator("str.format_time")
if [Link]("1D")
formattedTime = str.format_time(time, "yyyy-MM-dd HH:mm", [Link])
[Link](bar_index, high, formattedTime)
RETURNS
REMARKS
The M , d , h , H , m and s tokens can all be doubled to generate leading zeros. For example, the month of
January will display as 1 with M , or 01 with MM .
y - Year. Use yy to output the last two digits of the year or yyyy to output all four. Year 2000 will be 00 with yy
or 2000 with yyyy .
a - AM/PM postfix.
h - Hour in the 12-hour format. The last hour of the day will be 11 in this format.
H - Hour in the 24-hour format. The last hour of the day will be 23 in this format.
m - Minute.
s - Second.
S - Fractions of a second.
[Link]() 3 overloads
ARGUMENTS
RETURNS
[Link]() 3 overloads
ARGUMENTS
RETURNS
SEE ALSO
[Link]()
[Link]() 2 overloads
Returns the new substring of the source string if it matches a regex regular expression, an empty string
otherwise.
ARGUMENTS
regex (simple string) The regular expression to which this string is to be matched.
EXAMPLE
//@version=6
indicator("[Link]")
if [Link]
[Link](bar_index, high, text = tickerid) // "NASDAQ:AAPL"
RETURNS
The new substring of the source string if it matches a regex regular expression, an empty string otherwise.
REMARKS
Function returns first occurrence of the regular expression in the source string.
The backslash "\" symbol in the regex string needs to be escaped with additional backslash, e.g. "\\d" stands for
regular expression "\d".
SEE ALSO
[Link]() [Link]()
[Link]() 3 overloads
Returns the position of the first occurrence of the str string in the source string, 'na' otherwise.
SYNTAX & OVERLOADS
ARGUMENTS
RETURNS
REMARKS
SEE ALSO
[Link]() 4 overloads
Constructs a new string containing the source string repeated repeat times with the separator injected
between each repeated instance.
ARGUMENTS
separator (const string) String to inject between repeated values. Optional. The default is empty string.
EXAMPLE
//@version=6
indicator("[Link]")
repeat = [Link]("?", 3, ",") // Returns "?,?,?"
[Link](bar_index,close,repeat)
REMARKS
[Link]() 3 overloads
Returns a new string with the Nth occurrence of the target string replaced by the replacement string, where N
is specified in occurrence .
ARGUMENTS
occurrence (const int) N-th occurrence of the target string to replace. Indexing starts at 0 for the first match.
Optional. Default value is 0.
EXAMPLE
//@version=6
indicator("[Link]")
var source = "FTX:BTCUSD / FTX:BTCEUR"
if [Link]
// Display "BINANCE:BTCUSD / FTX:BTCEUR"
[Link](bar_index, high, text = newSource)
RETURNS
Processed string.
SEE ALSO
str.replace_all() [Link]()
str.replace_all() 2 overloads
Replaces each occurrence of the target string in the source string with the replacement string.
ARGUMENTS
RETURNS
Processed string.
[Link]()
Divides a string into an array of substrings and returns its array id.
SYNTAX
ARGUMENTS
RETURNS
[Link]() 3 overloads
Returns true if the source string starts with the substring specified in str , false otherwise.
ARGUMENTS
RETURNS
True if the source string starts with the substring specified in str , false otherwise.
SEE ALSO
[Link]()
[Link]() 3 overloads
Returns a new string that is a substring of the source string. The substring begins with the character at the index
specified by begin_pos and extends to 'end_pos - 1' of the source string.
ARGUMENTS
source (const string) Source string from which to extract the substring.
begin_pos (const int) The beginning position of the extracted substring. It is inclusive (the extracted substring
includes the character at that position).
end_pos (const int) The ending position. It is exclusive (the extracted string does NOT include that position's
character). Optional. The default is the length of the source string.
EXAMPLE
//@version=6
indicator("[Link]", overlay = true)
sym= [Link]("NASDAQ:AAPL")
pos = [Link](sym, ":") // Get position of ":" character
tkr= [Link](sym, pos+1) // "AAPL"
if [Link]
[Link](bar_index, high, text = tkr)
RETURNS
REMARKS
Strings indexing starts from 0. If begin_pos is equal to end_pos , the function returns an empty string.
SEE ALSO
[Link]() 4 overloads
ARGUMENTS
string (const string) String containing the representation of an integer or floating point value.
RETURNS
A "float" equivalent of the value in string . If the value is not a properly formed integer or floating point value, the
function returns na.
[Link]() 5 overloads
ARGUMENTS
value (const enum) Value or array ID whose elements are converted to a string.
RETURNS
When the value is na, the function returns the string "NaN".
REMARKS
The formatting of float values will also round those values when necessary, e.g. [Link](3.99, '#') will return "4".
To display trailing zeros, use '0' instead of '#'. For example, '#.000'.
When using [Link], the value will be rounded to the nearest number that can be divided by [Link]
without the remainder. The string is returned with trailing zeros.
[Link]() 4 overloads
Constructs a new string with all consecutive whitespaces and other control characters (e.g., “\n”, “\t”, etc.) removed
from the left and right of the source .
ARGUMENTS
EXAMPLE
//@version=6
indicator("[Link]")
trim = [Link](" abc ") // Returns "abc"
[Link](bar_index,close,trim)
REMARKS
Returns an empty string ("") if the result is empty after the trim or if the source is na.
[Link]() 3 overloads
ARGUMENTS
RETURNS
SEE ALSO
[Link]()
strategy()
This declaration statement designates the script as a strategy and sets a number of strategy-related properties.
SYNTAX
ARGUMENTS
title (const string) The title of the script. It is displayed on the chart when no shorttitle argument is used, and
becomes the publication's default title when publishing the script.
shorttitle (const string) The script's display name on charts. If specified, it will replace the title argument in most
chart-related windows. Optional. The default is the argument used for title .
overlay (const bool) If true, the script's visuals appear on the main chart pane if the user adds it to the chart directly,
or in another script's pane if the user applies it to that script. If false, the script's visuals appear in a separate pane.
Changes to the overlay value apply only after the user adds the script to the chart again. Additionally, if the user
moves the script to another pane by selecting a "Move to" option in the script's "More" menu, it does not move back
to its original pane after any updates to the source code. The default is false. Strategy-specific labels that display
entries and exits will be displayed over the main chart regardless of this setting.
format (const string) Specifies the formatting of the script's displayed values. Possible values: [Link],
[Link], [Link], [Link]. Optional. The default is [Link].
precision (const int) Specifies the number of digits after the floating point of the script's displayed values. Must be a
non-negative integer no greater than 16. If format is set to [Link] and precision is specified, the format
will instead be set to [Link]. When the function's format parameter uses [Link], the precision
parameter will not affect the result, as the decimal precision rules defined by [Link] supersede other precision
settings. Optional. The default is inherited from the precision of the chart's symbol.
scale (const scale_type) The price scale used. Possible values: [Link], [Link], [Link]. The [Link]
value can only be applied in combination with overlay = true . Optional. By default, the script uses the same scale
as the chart.
pyramiding (const int) The maximum number of entries allowed in the same direction. If the value is 0, only one entry
order in the same direction can be opened, and additional entry orders are rejected. This setting can also be changed
in the strategy's "Settings/Properties" tab. Optional. The default is 0.
calc_on_order_fills (const bool) Specifies whether the strategy should be recalculated after an order is filled. If true,
the strategy recalculates after an order is filled, as opposed to recalculating only when the bar closes. This setting can
also be changed in the strategy's "Settings/Properties" tab. Optional. The default is false.
calc_on_every_tick (const bool) Specifies whether the strategy should be recalculated on each realtime tick. If true,
when the strategy is running on a realtime bar, it will recalculate on each chart update. If false, the strategy only
calculates when the realtime bar closes. The argument used does not affect strategy calculation on historical data.
This setting can also be changed in the strategy's "Settings/Properties" tab. Optional. The default is false.
max_bars_back (const int) The length of the historical buffer the script keeps for every variable and function, which
determines how many past values can be referenced using the [] history-referencing operator. The required buffer
size is automatically detected by the Pine Script® runtime. Using this parameter is only necessary when a runtime error
occurs because automatic detection fails. More information on the underlying mechanics of the historical buffer can be
found in our Help Center. Optional. The default is 0.
backtest_fill_limits_assumption (const int) Limit order execution threshold in ticks. When it is used, limit orders are
only filled if the market price exceeds the order's limit level by the specified number of ticks. Optional. The default is 0.
default_qty_type (const string) Specifies the units used for default_qty_value . Possible values are:
[Link] for contracts/shares/lots, [Link] for currency amounts, or strategy.percent_of_equity for a
percentage of available equity. This setting can also be changed in the strategy's "Settings/Properties" tab. Optional.
The default is [Link].
default_qty_value (const int/float) The default quantity to trade, in units determined by the argument used with the
default_qty_type parameter. This setting can also be changed in the strategy's "Settings/Properties" tab.
Optional. The default is 1.
initial_capital (const int/float) The amount of funds initially available for the strategy to trade, in units of currency .
Optional. The default is 1000000.
currency (const string) Currency used by the strategy in currency-related calculations. Market positions are still
opened by converting currency into the chart symbol's currency. The conversion rate depends on the previous
daily value of a corresponding currency pair from the most popular exchange. A spread symbol is used if no exchange
provides the rate directly. Possible values: a "string" representing a valid currency code (e.g., "USD" or "USDT") or a
constant from the currency.* namespace (e.g., [Link] or [Link]). The default is [Link].
slippage (const int) Slippage expressed in ticks. This value is added to or subtracted from the fill price of market/stop
orders to make the fill price less favorable for the strategy. E.g., if [Link] is 0.01 and slippage is set to 5, a
long market order will enter at 5 * 0.01 = 0.05 points above the actual price. This setting can also be changed in the
strategy's "Settings/Properties" tab. Optional. The default is 0.
commission_type (const string) Determines what the number passed to the commission_value expresses:
[Link] for a percentage of the cash volume of the order,
[Link].cash_per_contract for currency per contract, [Link].cash_per_order for currency
per order. This setting can also be changed in the strategy's "Settings/Properties" tab. Optional. The default is
[Link].
commission_value (const int/float) Commission applied to the strategy's orders in units determined by the argument
passed to the commission_type parameter. This setting can also be changed in the strategy's
"Settings/Properties" tab. Optional. The default is 0.
process_orders_on_close (const bool) When set to true, generates an additional attempt to execute orders after a
bar closes and strategy calculations are completed. If the orders are market orders, the broker emulator executes them
before the next bar's open. If the orders are price-dependent, they will only be filled if the price conditions are met.
This option is useful if you wish to close positions on the current bar. This setting can also be changed in the strategy's
"Settings/Properties" tab. Optional. The default is false.
close_entries_rule (const string) Determines the order in which trades are closed. Possible values are: "FIFO" (First-
In, First-Out) if the earliest exit order must close the earliest entry order, or "ANY" if the orders are closed based on the
from_entry parameter of the [Link]() function. "FIFO" can only be used with stocks, futures and US forex
(NFA Compliance Rule 2-43b), while "ANY" is allowed in non-US forex. Optional. The default is "FIFO".
margin_long (const int/float) Margin long is the percentage of the purchase price of a security that must be covered
by cash or collateral for long positions. Must be a non-negative number. The logic used to simulate margin calls is
explained in the Help Center. This setting can also be changed in the strategy's "Settings/Properties" tab. Optional. If
the value is 0, the strategy does not enforce any limits on position size. The default is 100, in which case the strategy
only uses its own funds and the long positions cannot be margin called.
margin_short (const int/float) Margin short is the percentage of the purchase price of a security that must be
covered by cash or collateral for short positions. Must be a non-negative number. The logic used to simulate margin
calls is explained in the Help Center. This setting can also be changed in the strategy's "Settings/Properties" tab.
Optional. If the value is 0, the strategy does not enforce any limits on position size. The default is 100, in which case
the strategy only uses its own funds. Note that even with no margin used, short positions can be margin called if the
loss exceeds available funds.
explicit_plot_zorder (const bool) Specifies the order in which the script's plots, fills, and hlines are rendered. If true,
plots are drawn in the order in which they appear in the script's code, each newer plot being drawn above the previous
ones. This only applies to plot*() functions, fill(), and hline(). Optional. The default is false.
max_lines_count (const int) The number of last line drawings displayed. Possible values: 1-500. Optional. The
default is 50.
max_labels_count (const int) The number of last label drawings displayed. Possible values: 1-500. Optional. The
default is 50.
max_boxes_count (const int) The number of last box drawings displayed. Possible values: 1-500. Optional. The
default is 50.
calc_bars_count (const int) Limits the initial calculation of a script to the last number of bars specified. When
specified, a "Calculated bars" field will be included in the "Calculation" section of the script's "Settings/Inputs" tab.
Optional. The default is 0, in which case the script executes on all available bars.
risk_free_rate (const int/float) The risk-free rate of return is the annual percentage change in the value of an
investment with minimal or zero risk. It is used to calculate the Sharpe and Sortino ratios. Optional. The default is 2.
use_bar_magnifier (const bool) Optional. When true, the Broker Emulator uses lower timeframe data during
backtesting on historical bars to achieve more realistic results. The default is false. Only Premium and higher-tier plans
have access to this feature.
fill_orders_on_standard_ohlc (const bool) When true, forces strategies running on Heikin Ashi charts to fill orders
using actual OHLC prices, for more realistic results. Optional. The default is false.
max_polylines_count (const int) The number of last polyline drawings displayed. Possible values: 1-100. The count
is approximate; more drawings than the specified count may be displayed. Optional. The default is 50.
dynamic_requests (const bool) Specifies whether the script can dynamically call functions from the request.*()
namespace. Dynamic request.*() calls are allowed within the local scopes of conditional structures (e.g., if), loops
(e.g., for), and exported functions. Additionally, such calls allow "series" arguments for many of their parameters.
Optional. The default is true. See the User Manual's Dynamic requests section for more information.
behind_chart (const bool) Optional. Controls whether all plots and drawings appear behind the chart display (if true)
or in front of it (if false). This parameter only takes effect when the overlay parameter is true . The default is true.
EXAMPLE
//@version=6
strategy("My strategy", overlay = true)
REMARKS
Strategies always use the chart's prices to enter and exit positions. Using them on non-standard chart types (Heikin
Ashi, Renko, etc.) will produce misleading results, as their prices are synthetic. Backtesting on non-standard charts is
thus not recommended.
The maximum number of orders a strategy can open, unless it uses Deep Backtesting mode, is 9000. If the strategy
exceeds this limit, it removes the oldest order's information when a new entry appears in the "List of Trades" tab. The
[Link].*() functions return na for trades opened or closed by removed orders. To retrieve the
index of the oldest available closed trade, use the [Link].first_index variable.
SEE ALSO
indicator() library()
[Link]()
Cancels a pending or unfilled order with a specific identifier. If multiple unfilled orders share the same ID, calling this
command with that ID as the id argument cancels all of them. If a script calls this command with an id
representing the ID of a filled order, it has no effect.
This command is most useful when working with price-based orders (e.g., limit orders). Calls to this command can also
cancel market orders, but only if they execute on the same ticks as the order placement commands.
SYNTAX
[Link](id) → void
ARGUMENTS
EXAMPLE
//@version=6
strategy(title = "Order cancellation demo")
strategy.cancel_all()
Cancels all pending or unfilled orders, regardless of their identifiers.
This command is most useful when working with price-based orders (e.g., limit orders). Calls to this command can also
cancel market orders, but only if they execute on the same ticks as the order placement commands.
SYNTAX
strategy.cancel_all() → void
EXAMPLE
//@version=6
strategy(title = "Cancel all orders demo")
conditionForBuy1 = open > high[1]
if conditionForBuy1
[Link]("Long entry 1", [Link], 1, limit = low) // Enter long using a limit order if
`conditionForBuy1` is `true`.
conditionForBuy2 = conditionForBuy1 and open[1] > high[2]
float lowest2 = [Link](low, 2)
if conditionForBuy2
[Link]("Long entry 2", [Link], 1, limit = lowest2) // Enter long using a limit orde
r if `conditionForBuy2` is `true`.
conditionForStopTrading = open < lowest2
if conditionForStopTrading
strategy.cancel_all() // Cancel both limit orders if `conditionForStopTrading` is `true`.
[Link]()
Creates an order to exit from the part of a position opened by entry orders with a specific identifier. If multiple entries
in the position share the same ID, the orders from this command apply to all those entries, starting from the first open
trade, when its calls use that ID as the id argument.
This command always generates market orders. To exit from a position using price-based orders (e.g., stop-loss
orders), use the [Link]() command.
SYNTAX
ARGUMENTS
qty (series int/float) Optional. The number of contracts/lots/shares/units to close when an exit order fills. If specified,
the command uses this value instead of qty_percent to determine the order size. The default is na, which means
the order size depends on the qty_percent value.
qty_percent (series int/float) Optional. A value between 0 and 100 representing the percentage of the open trade
quantity to close when an exit order fills. The percentage calculation depends on the total size of the open trades with
the id entry identifier. The command ignores this parameter if the qty value is not na. The default is 100.
alert_message (series string) Optional. Custom text for the alert that fires when an order fills. If the "Message" field
of the "Create Alert" dialog box contains the {{[Link].alert_message}} placeholder, the alert
message replaces the placeholder with this text. The default is an empty string.
immediately (series bool) Optional. If true, the closing order executes on the same tick when the strategy places it,
ignoring the strategy properties that restrict execution to the opening tick of the following bar. The default is false.
disable_alert (series bool) Optional. If true when the command creates an order, the strategy does not trigger an
alert when that order fills. This parameter accepts a "series" value, meaning users can control which orders trigger
alerts when they execute. The default is false.
EXAMPLE
//@version=6
strategy("Partial close strategy")
// Place a market order to enter a long position when `sma14` crosses over `sma28`.
if [Link](sma14, sma28)
[Link]("My Long Entry ID", [Link])
// Place a market order to close the long trade when `sma14` crosses under `sma28`.
if [Link](sma14, sma28)
[Link]("My Long Entry ID", "50% market close", qty_percent = 50)
REMARKS
When a position consists of several open trades and the close_entries_rule in the strategy() declaration
statement is "FIFO" (default), a [Link]() call exits from the position starting with the first open trade. This
behavior applies even if the id value is the entry ID of different open trades. However, in that case, the maximum exit
order size still depends on the trades opened by orders with the id identifier. For more information, see this section
of our User Manual.
strategy.close_all()
Creates an order to close an open position completely, regardless of the identifiers of the entry orders that opened or
added to it.
This command always generates market orders. To exit from a position using price-based orders (e.g., stop-loss
orders), use the [Link]() command.
SYNTAX
ARGUMENTS
comment (series string) Optional. Additional notes on the filled order. If the value is not an empty string, the Strategy
Tester and the chart show this text for the order instead of the automatically generated exit identifier. The default is an
empty string.
alert_message (series string) Optional. Custom text for the alert that fires when an order fills. If the "Message" field
of the "Create Alert" dialog box contains the {{[Link].alert_message}} placeholder, the alert
message replaces the placeholder with this text. The default is an empty string.
immediately (series bool) Optional. If true, the closing order executes on the same tick when the strategy places it,
ignoring the strategy properties that restrict execution to the opening tick of the following bar. The default is false.
disable_alert (series bool) Optional. If true when the command creates an order, the strategy does not trigger an
alert when that order fills. This parameter accepts a "series" value, meaning users can control which orders trigger
alerts when they execute. The default is false.
EXAMPLE
//@version=6
strategy("Multi-entry close strategy")
// Place a market order to enter a long trade every time `sma14` crosses over `sma28`.
if [Link](sma14, sma28)
[Link]("My Long Entry ID " + [Link]([Link]), [Link])
// Place a market order to close the entire position every 500 bars.
if bar_index % 500 == 0
strategy.close_all()
[Link]()
Returns the sum of entry and exit fees paid in the closed trade, expressed in strategy.account_currency.
SYNTAX
ARGUMENTS
trade_num (series int) The trade number of the closed trade. The number of the first trade is zero.
EXAMPLE
//@version=6
strategy("`[Link]` Example", commission_type = [Link], c
ommission_value = 0.1)
// Strategy calls to enter long trades every 15 bars and exit long trades every 20 bars.
if bar_index % 15 == 0
[Link]("Long", [Link])
if bar_index % 20 == 0
[Link]("Long")
SEE ALSO
strategy() [Link]()
[Link].entry_bar_index()
Returns the bar_index of the closed trade's entry.
SYNTAX
ARGUMENTS
trade_num (series int) The trade number of the closed trade. The number of the first trade is zero.
EXAMPLE
//@version=6
strategy("[Link].entry_bar_index Example")
// Enter long trades on three rising bars; exit on two falling bars.
if [Link](close, 3)
[Link]("Long", [Link])
if [Link](close, 2)
[Link]("Long")
// Function that calculates the average amount of bars in a trade.
avgBarsPerTrade() =>
sumBarsPerTrade = 0
for tradeNo = 0 to [Link] - 1
// Loop through all closed trades, starting with the oldest.
sumBarsPerTrade += [Link].exit_bar_index(tradeNo) - [Link].entry_
bar_index(tradeNo) + 1
result = nz(sumBarsPerTrade / [Link])
plot(avgBarsPerTrade())
SEE ALSO
[Link].exit_bar_index() [Link].entry_bar_index()
[Link].entry_comment()
Returns the comment message of the closed trade's entry, or na if there is no entry with this trade_num .
SYNTAX
ARGUMENTS
trade_num (series int) The trade number of the closed trade. The number of the first trade is zero.
EXAMPLE
//@version=6
strategy("`[Link].entry_comment()` Example", overlay = true)
if (longCondition)
[Link]("Long", [Link], stop = stopPrice, comment = [Link](stopPric
e, "#.####"))
[Link]("EXIT", trail_points = 1000, trail_offset = 0)
if [Link] or [Link]
[Link](testTable, 0, 0, 'Last closed trade:')
[Link](testTable, 0, 1, "Order stop price value: " + [Link].entry_comment(strate
[Link] - 1))
[Link](testTable, 0, 2, "Actual Entry Price: " + [Link]([Link].entry_pric
e([Link] - 1)))
SEE ALSO
[Link].entry_id()
Returns the id of the closed trade's entry.
SYNTAX
ARGUMENTS
trade_num (series int) The trade number of the closed trade. The number of the first trade is zero.
EXAMPLE
//@version=6
strategy("[Link].entry_id Example", overlay = true)
RETURNS
REMARKS
SEE ALSO
[Link].entry_price()
Returns the price of the closed trade's entry.
SYNTAX
ARGUMENTS
trade_num (series int) The trade number of the closed trade. The number of the first trade is zero.
EXAMPLE
//@version=6
strategy("[Link].entry_price Example 1")
// Strategy calls to enter long trades every 15 bars and exit long trades every 20 bars.
if bar_index % 15 == 0
[Link]("Long", [Link])
if bar_index % 20 == 0
[Link]("Long")
EXAMPLE
plot(avgProfitPct)
SEE ALSO
[Link].entry_time()
Returns the UNIX time of the closed trade's entry, expressed in milliseconds..
SYNTAX
ARGUMENTS
trade_num (series int) The trade number of the closed trade. The number of the first trade is zero.
EXAMPLE
//@version=6
strategy("[Link].entry_time Example", overlay = true)
// Enter long trades on three rising bars; exit on two falling bars.
if [Link](close, 3)
[Link]("Long", [Link])
if [Link](close, 2)
[Link]("Long")
// Display average duration converted to seconds and formatted using 2 decimal points
if [Link]
[Link](bar_index, high, [Link](avgTradeDuration() / 1000, "#.##") + " seconds")
SEE ALSO
[Link].exit_bar_index()
Returns the bar_index of the closed trade's exit.
SYNTAX
ARGUMENTS
trade_num (series int) The trade number of the closed trade. The number of the first trade is zero.
EXAMPLE
//@version=6
strategy("[Link].exit_bar_index Example 1")
// Strategy calls to place a single short trade. We enter the trade at the first bar and exit the trad
e at 10 bars before the last chart bar.
if bar_index == 0
[Link]("Short", [Link])
if bar_index == last_bar_index - 10
[Link]("Short")
EXAMPLE
// Enter long trades on three rising bars; exit on two falling bars.
if [Link](close, 3)
[Link]("Long", [Link])
if [Link](close, 2)
[Link]("Long")
// Function that calculates the average amount of bars per trade.
avgBarsPerTrade() =>
sumBarsPerTrade = 0
for tradeNo = 0 to [Link] - 1
// Loop through all closed trades, starting with the oldest.
sumBarsPerTrade += [Link].exit_bar_index(tradeNo) - [Link].entry_
bar_index(tradeNo) + 1
result = nz(sumBarsPerTrade / [Link])
plot(avgBarsPerTrade())
SEE ALSO
bar_index last_bar_index
[Link].exit_comment()
Returns the comment message of the closed trade's exit, or na if there is no entry with this trade_num .
SYNTAX
ARGUMENTS
trade_num (series int) The trade number of the closed trade. The number of the first trade is zero.
EXAMPLE
//@version=6
strategy("`[Link].exit_comment()` Example", overlay = true)
exitStats() =>
int slCount = 0
int tpCount = 0
int trailCount = 0
if [Link] > 0
for i = 0 to [Link] - 1
switch [Link].exit_comment(i)
"TP" => tpCount += 1
"SL" => slCount += 1
"TRAIL" => trailCount += 1
[slCount, tpCount, trailCount]
if [Link]
[slCount, tpCount, trailCount] = exitStats()
[Link](testTable, 0, 0, "Closed trades (" + [Link]([Link]) +") stats:")
[Link](testTable, 0, 1, "Stop Loss: " + [Link](slCount))
[Link](testTable, 0, 2, "Take Profit: " + [Link](tpCount))
[Link](testTable, 0, 3, "Trailing Stop: " + [Link](trailCount))
SEE ALSO
[Link].exit_id()
Returns the id of the closed trade's exit.
SYNTAX
ARGUMENTS
trade_num (series int) The trade number of the closed trade. The number of the first trade is zero.
EXAMPLE
//@version=6
strategy("[Link].exit_id Example", overlay = true)
// When a new open trade is detected then we create the exit strategy corresponding with the matching e
ntry id
// We detect the correct entry id by determining if a position is long or short based on the position q
uantity
if [Link]([Link]) != 0
posSign = [Link]([Link] - 1)
[Link](posSign > 0 ? "SL Long Exit" : "SL Short Exit", [Link].entry_id(strateg
[Link] - 1), stop = posSign > 0 ? high - [Link] : low + [Link])
// When a new closed trade is detected then we place a label above the bar with the exit info
if [Link]([Link]) != 0
msg = "Trade closed by: " + [Link].exit_id([Link] - 1)
[Link](bar_index, high + (3 * [Link]), msg)
RETURNS
REMARKS
SEE ALSO
[Link].exit_price()
Returns the price of the closed trade's exit.
SYNTAX
ARGUMENTS
trade_num (series int) The trade number of the closed trade. The number of the first trade is zero.
EXAMPLE
//@version=6
strategy("[Link].exit_price Example 1")
EXAMPLE
plot(avgProfitPct)
SEE ALSO
[Link].entry_price()
[Link].exit_time()
Returns the UNIX time of the closed trade's exit, expressed in milliseconds.
SYNTAX
ARGUMENTS
trade_num (series int) The trade number of the closed trade. The number of the first trade is zero.
EXAMPLE
//@version=6
strategy("[Link].exit_time Example 1")
// Enter long trades on three rising bars; exit on two falling bars.
if [Link](close, 3)
[Link]("Long", [Link])
if [Link](close, 2)
[Link]("Long")
// Display average duration converted to seconds and formatted using 2 decimal points.
if [Link]
[Link](bar_index, high, [Link](avgTradeDuration() / 1000, "#.##") + " seconds")
EXAMPLE
reopenPositionAfter(timeSec) =>
if [Link] > 0
if time - [Link].exit_time([Link] - 1) >= timeSec * 1000
[Link]("Long", [Link])
if [Link]([Link]) != 0
[Link]("Long", stop = low * 0.9, profit = high * 2.5)
SEE ALSO
[Link].entry_time()
[Link].max_drawdown()
Returns the maximum drawdown of the closed trade, i.e., the maximum possible loss during the trade, expressed in
strategy.account_currency.
SYNTAX
ARGUMENTS
trade_num (series int) The trade number of the closed trade. The number of the first trade is zero.
EXAMPLE
//@version=6
strategy("`[Link].max_drawdown` Example")
// Strategy calls to enter long trades every 15 bars and exit long trades every 20 bars.
if bar_index % 15 == 0
[Link]("Long", [Link])
if bar_index % 20 == 0
[Link]("Long")
// Get the biggest max trade drawdown value from all of the closed trades.
maxTradeDrawDown() =>
maxDrawdown = 0.0
for tradeNo = 0 to [Link] - 1
maxDrawdown := [Link](maxDrawdown, [Link].max_drawdown(tradeNo))
result = maxDrawdown
REMARKS
SEE ALSO
[Link].max_drawdown() strategy.max_drawdown
[Link].max_drawdown_percent()
Returns the maximum drawdown of the closed trade, i.e., the maximum possible loss during the trade, expressed as a
percentage and calculated by formula: Lowest Value During Trade / (Entry Price x Quantity) * 100 .
SYNTAX
ARGUMENTS
trade_num (series int) The trade number of the closed trade. The number of the first trade is zero.
SEE ALSO
[Link].max_drawdown() strategy.max_drawdown
[Link].max_runup()
Returns the maximum run up of the closed trade, i.e., the maximum possible profit during the trade, expressed in
strategy.account_currency.
SYNTAX
ARGUMENTS
trade_num (series int) The trade number of the closed trade. The number of the first trade is zero.
EXAMPLE
//@version=6
strategy("`[Link].max_runup` Example")
// Strategy calls to enter long trades every 15 bars and exit long trades every 20 bars.
if bar_index % 15 == 0
[Link]("Long", [Link])
if bar_index % 20 == 0
[Link]("Long")
// Get the biggest max trade runup value from all of the closed trades.
maxTradeRunUp() =>
maxRunup = 0.0
for tradeNo = 0 to [Link] - 1
maxRunup := [Link](maxRunup, [Link].max_runup(tradeNo))
result = maxRunup
SEE ALSO
[Link].max_runup() strategy.max_runup
[Link].max_runup_percent()
Returns the maximum run-up of the closed trade, i.e., the maximum possible profit during the trade, expressed as a
percentage and calculated by formula: Highest Value During Trade / (Entry Price x Quantity) * 10
0.
SYNTAX
ARGUMENTS
trade_num (series int) The trade number of the closed trade. The number of the first trade is zero.
SEE ALSO
[Link].max_runup() strategy.max_runup
[Link]()
Returns the profit/loss of the closed trade in the strategy's account currency, reduced by the trade's commissions. A
positive returned value represents a profit, and a negative value represents a loss.
SYNTAX
ARGUMENTS
trade_num (series int) The trade number of the closed trade. The number of the first trade is zero.
EXAMPLE
//@version=6
strategy("`[Link]()` example")
// Enter a long trade every 15 bars, and close a long trade every 20 bars.
if bar_index % 15 == 0
[Link]("Long", [Link])
if bar_index % 20 == 0
[Link]("Long")
//@function Calculates the average gross profit from all available closed trades.
avgGrossProfit() =>
var float result = 0.0
if result == 0.0 or [Link] > [Link][1]
float sumGrossProfit = 0.0
for tradeNo = 0 to [Link] - 1
sumGrossProfit += [Link](tradeNo)
result := nz(sumGrossProfit / [Link])
result
SEE ALSO
[Link].profit_percent()
Returns the profit/loss value of the closed trade, expressed as a percentage. Losses are expressed as negative values.
SYNTAX
ARGUMENTS
trade_num (series int) The trade number of the closed trade. The number of the first trade is zero.
SEE ALSO
[Link]()
[Link]()
Returns the direction and the number of contracts traded in the closed trade. If the value is > 0, the market position
was long. If the value is < 0, the market position was short.
SYNTAX
ARGUMENTS
trade_num (series int) The trade number of the closed trade. The number of the first trade is zero.
EXAMPLE
//@version=6
strategy("`[Link]` Example 1")
EXAMPLE
// Strategy calls to enter long trades every 15 bars and exit long trades every 20 bars.
if bar_index % 15 == 0
[Link]("Long", [Link])
if bar_index % 20 == 0
[Link]("Long")
plot(avgProfitPct)
SEE ALSO
strategy.convert_to_account()
Converts the value from the currency that the symbol on the chart is traded in ([Link]) to the currency used
by the strategy (strategy.account_currency).
SYNTAX
ARGUMENTS
EXAMPLE
//@version=6
strategy("`strategy.convert_to_account` Example 1", currency = [Link])
EXAMPLE
// Calculates the "Buy and hold return" using your account's currency.
//@version=6
strategy("`strategy.convert_to_account` Example 2", currency = [Link])
dateInput = [Link](timestamp("20 Jul 2021 00:00 +0300"), "From Date", confirm = true)
buyAndHoldReturnPct(fromDate) =>
if time >= fromDate
money = close * [Link]
var initialBal = strategy.convert_to_account(money)
(strategy.convert_to_account(money) - initialBal) / initialBal * 100
plot(buyAndHoldReturnPct(dateInput))
SEE ALSO
strategy() strategy.convert_to_symbol()
strategy.convert_to_symbol()
Converts the value from the currency used by the strategy (strategy.account_currency) to the currency that the
symbol on the chart is traded in ([Link]).
SYNTAX
ARGUMENTS
EXAMPLE
//@version=6
strategy("`strategy.convert_to_symbol` Example", currency = [Link])
// Calculate the max qty we can buy using current chart's currency.
calcContracts(accountMoney) =>
[Link](strategy.convert_to_symbol(accountMoney) / [Link] / close)
// Strategy calls to enter long trades every 15 bars and exit long trades every 20 bars using our custo
m qty.
if bar_index % 15 == 0
[Link]("Long", [Link], qty = qt)
if bar_index % 20 == 0
[Link]("Long")
SEE ALSO
strategy() strategy.convert_to_account()
strategy.default_entry_qty()
Calculates the default quantity, in units, of an entry order from [Link]() or [Link]() if it were to fill at the
specified fill_price value. The calculation depends on several strategy properties, including default_qty_typ
e , default_qty_value , currency , and other parameters in the strategy() function and their representation in
the "Properties" tab of the strategy's settings.
SYNTAX
ARGUMENTS
fill_price (series int/float) The fill price for which to calculate the default order quantity.
EXAMPLE
//@version=6
strategy("Supertrend Strategy", overlay = true, default_qty_type = strategy.percent_of_equity, default_
qty_value = 15)
if [Link](direction) < 0
//@variable The stop price of the entry order.
stopPrice = close + [Link] * stopOffsetInput
//@variable The expected default fill quantity at the `stopPrice`. This value may not reflect actua
l qty of the filled order, because fill price may be different.
calculatedQty = strategy.default_entry_qty(stopPrice)
[Link]("My Long Entry Id", [Link], stop = stopPrice)
[Link](bar_index, stopPrice, [Link]("Stop set at {0}\nExpected qty at {0}: {1}", math.round_
to_mintick(stopPrice), calculatedQty))
if [Link](direction) > 0
strategy.close_all()
REMARKS
This function does not consider open positions simulated by a strategy. For example, if a strategy script has an open
position from a long order with a qty of 10 units, using the [Link]() function to simulate a short order with a
qty of 5 will prompt the script to sell 15 units to reverse the position. This function will still return 5 in such a case
since it doesn't consider an open trade.
This value represents the default calculated quantity of an order.
Order placement commands can override the default value by explicitly passing a new qty value in the function call.
[Link]()
Creates a new order to open or add to a position. If an unfilled order with the same id exists, a call to this command
modifies that order.
The resulting order's type depends on the limit and stop parameters. If the call does not contain limit or st
op arguments, it creates a market order that executes on the next tick. If the call specifies a limit value but no st
op value, it places a limit order that executes after the market price reaches the limit value or a better price (lower
for buy orders and higher for sell orders). If the call specifies a stop value but no limit value, it places a stop
order that executes after the market price reaches the stop value or a worse price (higher for buy orders and lower
for sell orders). If the call contains limit and stop arguments, it creates a stop-limit order, which generates a limit
order at the limit price only after the market price reaches the stop value or a worse price.
Orders from this command, unlike those from [Link](), are affected by the pyramiding parameter of the
strategy() declaration statement. Pyramiding specifies the number of concurrent open entries allowed per position. For
example, with pyramiding = 3 , the strategy can have up to three open trades, and the command cannot create
orders to open additional trades until at least one existing trade closes.
By default, when a strategy executes an order from this command in the opposite direction of the current market
position, it reverses that position. For example, if there is an open long position of five shares, an order from this
command with a qty of 5 and a direction of [Link] triggers the sale of 10 shares to close the long
position and open a new five-share short position. Users can change this behavior by specifying an allowed direction
with the strategy.risk_allow_entry_in() function.
SYNTAX
[Link](id, direction, qty, limit, stop, oca_name, oca_type, comment, alert_message, disable_alert)
→ void
ARGUMENTS
id (series string) The identifier of the order, which corresponds to an entry ID in the strategy's trades after the order
fills. If the strategy opens a new position after filling the order, the order's ID becomes the
strategy.position_entry_name value. Strategy commands can reference the order ID to cancel or modify pending
orders and generate exit orders for specific open trades. The Strategy Tester and the chart display the order ID unless
the command specifies a comment value.
direction (series strategy_direction) The direction of the trade. Possible values: [Link] for a long trade,
[Link] for a short one.
qty (series int/float) Optional. The number of contracts/shares/lots/units in the resulting open trade when the order
fills. The default is na, which means that the command uses the default_qty_type and default_qty_value
parameters of the strategy() declaration statement to determine the quantity.
limit (series int/float) Optional. The limit price of the order. If specified, the command creates a limit or stop-limit
order, depending on whether the stop value is also specified. The default is na, which means the resulting order is
not of the limit or stop-limit type.
stop (series int/float) Optional. The stop price of the order. If specified, the command creates a stop or stop-limit
order, depending on whether the limit value is also specified. The default is na, which means the resulting order is
not of the stop or stop-limit type.
oca_name (series string) Optional. The name of the order's One-Cancels-All (OCA) group. When a pending order
with the same oca_name and oca_type parameters executes, that order affects all unfilled orders in the group.
The default is an empty string, which means the order does not belong to an OCA group.
oca_type (input string) Optional. Specifies how an unfilled order behaves when another pending order with the same
oca_name and oca_type values executes. Possible values: [Link], [Link],
[Link]. The default is [Link].
comment (series string) Optional. Additional notes on the filled order. If the value is not an empty string, the Strategy
Tester and the chart show this text for the order instead of the specified id . The default is an empty string.
alert_message (series string) Optional. Custom text for the alert that fires when an order fills. If the "Message" field
of the "Create Alert" dialog box contains the {{[Link].alert_message}} placeholder, the alert
message replaces the placeholder with this text. The default is an empty string.
disable_alert (series bool) Optional. If true when the command creates an order, the strategy does not trigger an
alert when that order fills. This parameter accepts a "series" value, meaning users can control which orders trigger
alerts when they execute. The default is false.
EXAMPLE
//@version=6
strategy("Market order strategy", overlay = true)
// Place a market order to close the short trade and enter a long position when `sma14` crosses over `s
ma28`.
if [Link](sma14, sma28)
[Link]("My Long Entry ID", [Link])
// Place a market order to close the long trade and enter a short position when `sma14` crosses under `
sma28`.
if [Link](sma14, sma28)
[Link]("My Short Entry ID", [Link])
EXAMPLE
//@version=6
strategy("Limit order strategy", overlay=true, margin_long=100, margin_short=100)
//@variable The distance from the `close` price for each limit order.
float limitOffsetInput = [Link](100, "Limit offset, in ticks", 1) * [Link]
//@function Draws a label and line at the specified `price` to visualize a limit order's level.
drawLimit(float price, bool isLong) =>
color col = isLong ? [Link] : [Link]
[Link](
bar_index, price, (isLong ? "Long" : "Short") + " limit order created",
style = label.style_label_right, color = col, textcolor = [Link]
)
[Link](bar_index, price, bar_index + 1, price, extend = [Link], style = line.style_dashed,
color = col)
if [Link](sma14, sma28)
// Cancel any unfilled sell orders with the specified ID.
[Link]("My Short Entry ID")
//@variable The limit price level. Its value is `limitOffsetInput` ticks below the current `close`.
float limitLevel = close - limitOffsetInput
// Place a long limit order to close the short trade and enter a long position at the `limitLevel`.
[Link]("My Long Entry ID", [Link], limit = limitLevel)
// Make new drawings for the long limit and stop extending the `shortLimit` line.
longLimit := drawLimit(limitLevel, isLong = true)
[Link]()
if [Link](sma14, sma28)
// Cancel any unfilled buy orders with the specified ID.
[Link]("My Long Entry ID")
//@variable The limit price level. Its value is `limitOffsetInput` ticks above the current `close`.
float limitLevel = close + limitOffsetInput
// Place a short limit order to close the long trade and enter a short position at the `limitLevel
`.
[Link]("My Short Entry ID", [Link], limit = limitLevel)
// Make new drawings for the short limit and stop extending the `shortLimit` line.
shortLimit := drawLimit(limitLevel, isLong = false)
[Link]()
[Link]()
Creates price-based orders to exit from an open position. If unfilled exit orders with the same id exist, calls to this
command modify those orders. This command can generate more than one type of exit order, depending on the
specified parameters. However, it does not create market orders. To exit from a position with a market order, use
[Link]() or strategy.close_all().
If a call to this command contains a profit or limit argument, it creates take-profit orders to exit from applicable
trades at the determined price levels or better values (higher for long trades and lower for short ones). If the call
contains loss or stop arguments, it creates stop-loss orders to exit from applicable trades at the determined
levels or worse values (lower for long trades and higher for short ones). Calling this command with profit or limi
t and loss or stop arguments creates an order bracket with both order types.
This command can create trailing stop orders when its call specifies a trail_price or trail_points argument
and a trail_offset argument. A trailing stop order activates when the price moves trail_points ticks past
the entry price or touches the trail_price level. Once activated, the stop follows trail_offset ticks behind
the market price each time the trade's profit reaches a new high. The stop does not move when the trade does not
achieve a new best value.
Each call to this command reserves a portion of the position to close until the strategy fills or cancels its orders. For
example, if there is an open position of 50 contracts and a [Link]() call specifies a qty of 20, that call's orders
reserve 20 contracts out of the position. A second call can close a maximum of 30 contracts, even if its qty is 50
and one of its orders executes first. This behavior does not affect the orders from other commands, such as
[Link]() or [Link]().
If a call to this command occurs before a created entry order's execution, the strategy waits and does not create the
exit orders until after the entry order executes.
SYNTAX
[Link](id, from_entry, qty, qty_percent, profit, limit, loss, stop, trail_price, trail_points, trail
_offset, oca_name, comment, comment_profit, comment_loss, comment_trailing, alert_message, alert_profit, al
ert_loss, alert_trailing, disable_alert) → void
ARGUMENTS
id (series string) The identifier of the orders, which corresponds to an exit ID in the strategy's trades after an order
fills. Strategy commands can reference the order ID to cancel or modify pending exit orders. The Strategy Tester and
the chart display the order ID unless the command includes a comment* argument that applies to the filled order.
from_entry (series string) Optional. The entry order ID of the trade to exit from. If there is more than one open trade
with the specified entry ID, the command generates exit orders for all the entries from before or at the time of the call.
The default is an empty string, which means the command generates exit orders for all open trades until the position
closes.
qty (series int/float) Optional. The number of contracts/lots/shares/units to close when an exit order fills. If specified,
the command uses this value instead of qty_percent to determine the order size. The exit orders reserve this
quantity from the position, meaning other calls to this command cannot close this portion until the strategy fills or
cancels those orders. The default is na, which means the order size depends on the qty_percent value.
qty_percent (series int/float) Optional. A value between 0 and 100 representing the percentage of the open trade
quantity to close when an exit order fills. The exit orders reserve this percentage from the applicable open trades,
meaning other calls to this command cannot close this portion until the strategy fills or cancels those orders. The
percentage calculation depends on the total size of the applicable open trades without considering the reserved
amount from other [Link]() calls. The command ignores this parameter if the qty value is not na. The default is
100.
profit (series int/float) Optional. The take-profit distance, expressed in ticks. If specified, the command creates a limit
order to exit the trade profit ticks away from the entry price in the favorable direction. The order executes at the
calculated price or a better value. If this parameter and limit are not na, the command places a take-profit order
only at the price level expected to trigger an exit first. The default is na.
limit (series int/float) Optional. The take-profit price. If this parameter and profit are not na, the command places
a take-profit order only at the price level expected to trigger an exit first. The default is na.
loss (series int/float) Optional. The stop-loss distance, expressed in ticks. If specified, the command creates a stop
order to exit the trade loss ticks away from the entry price in the unfavorable direction. The order executes at the
calculated price or a worse value. If this parameter and stop are not na, the command places a stop-loss order only
at the price level expected to trigger an exit first. The default is na.
stop (series int/float) Optional. The stop-loss price. If this parameter and loss are not na, the command places a
stop-loss order only at the price level expected to trigger an exit first. The default is na.
trail_price (series int/float) Optional. The price of the trailing stop activation level. If the value is more favorable than
the entry price, the command creates a trailing stop when the market price reaches that value. If less favorable than
the entry price, the command creates the trailing stop immediately when the current market price is equal to or more
favorable than the value. If this parameter and trail_points are not na, the command sets the activation level
using the value expected to activate the stop first. The default is na.
trail_points (series int/float) Optional. The trailing stop activation distance, expressed in ticks. If the value is positive,
the command creates a trailing stop order when the market price moves trail_points ticks away from the trade's
entry price in the favorable direction. If the value is negative, the command creates the trailing stop immediately when
the market price is equal to or more favorable than the level trail_points ticks away from the entry price in the
unfavorable direction. The default is na.
trail_offset (series int/float) Optional. The trailing stop offset. When the market price reaches the activation level
determined by the trail_price or trail_points parameter, or exceeds the level in the favorable direction, the
command creates a trailing stop with an initial value trail_offset ticks away from that level in the unfavorable
direction. After activation, the trailing stop moves toward the market price each time the trade's profit reaches a better
value, maintaining the specified distance behind the best price. The default is na.
oca_name (series string) Optional. The name of the One-Cancels-All (OCA) group that the command's take-profit,
stop-loss, and trailing stop orders belong to. All orders from this command are of the [Link] OCA type.
When an order of this OCA type with the same oca_name executes, the strategy reduces the sizes of other unfilled
orders in the OCA group by the filled quantity. The default is an empty string, which means the strategy assigns the
OCA name automatically, and the resulting orders cannot reduce or be reduced by the orders from other commands.
comment (series string) Optional. Additional notes on the filled order. If the value is not an empty string, the Strategy
Tester and the chart show this text for the order instead of the specified id . The command ignores this value if the
call includes an argument for a comment_* parameter that applies to the order. The default is an empty string.
comment_profit (series string) Optional. Additional notes on the filled order. If the value is not an empty string, the
Strategy Tester and the chart show this text for the order instead of the specified id or comment . This comment
applies only to the command's take-profit orders created using the profit or limit parameter. The default is an
empty string.
comment_loss (series string) Optional. Additional notes on the filled order. If the value is not an empty string, the
Strategy Tester and the chart show this text for the order instead of the specified id or comment . This comment
applies only to the command's stop-loss orders created using the loss or stop parameter. The default is an
empty string.
comment_trailing (series string) Optional. Additional notes on the filled order. If the value is not an empty string, the
Strategy Tester and the chart show this text for the order instead of the specified id or comment . This comment
applies only to the command's trailing stop orders created using the trail_price or trail_points and trail
_offset parameters. The default is an empty string.
alert_message (series string) Optional. Custom text for the alert that fires when an order fills. If the "Message" field
of the "Create Alert" dialog box contains the {{[Link].alert_message}} placeholder, the alert
message replaces the placeholder with this text. The command ignores this value if the call includes an argument for
the other alert_* parameter that applies to the order. The default is an empty string.
alert_profit (series string) Optional. Custom text for the alert that fires when an order fills. If the "Message" field of
the "Create Alert" dialog box contains the {{[Link].alert_message}} placeholder, the alert message
replaces the placeholder with this text. This message applies only to the command's take-profit orders created using
the profit or limit parameter. The default is an empty string.
alert_loss (series string) Optional. Custom text for the alert that fires when an order fills. If the "Message" field of the
"Create Alert" dialog box contains the {{[Link].alert_message}} placeholder, the alert message
replaces the placeholder with this text. This message applies only to the command's stop-loss orders created using
the loss or stop parameter. The default is an empty string.
alert_trailing (series string) Optional. Custom text for the alert that fires when an order fills. If the "Message" field of
the "Create Alert" dialog box contains the {{[Link].alert_message}} placeholder, the alert message
replaces the placeholder with this text. This message applies only to the command's trailing stop orders created using
the trail_price or trail_points and trail_offset parameters. The default is an empty string.
disable_alert (series bool) Optional. If true when the command creates an order, the strategy does not trigger an
alert when that order fills. This parameter accepts a "series" value, meaning users can control which orders trigger
alerts when they execute. The default is false.
EXAMPLE
//@version=6
strategy("Exit bracket strategy", overlay = true)
// Inputs that define the profit and loss amount of each trade as a tick distance from the entry price.
int profitDistanceInput = [Link](100, "Profit distance, in ticks", 1)
int lossDistanceInput = [Link](100, "Loss distance, in ticks", 1)
if [Link]([Link]) == 1
//@variable The long entry price.
float entryPrice = [Link].entry_price(0)
// Update the `takeProfit` and `stopLoss` values.
takeProfit := entryPrice + profitDistanceInput * [Link]
stopLoss := entryPrice - lossDistanceInput * [Link]
if [Link]([Link]) == 1
// Reset the `takeProfit` and `stopLoss`.
takeProfit := na
stopLoss := na
EXAMPLE
//@version=6
strategy("Trailing stop strategy", overlay = true)
//@function Draws a label and line at the specified `price` to visualize a trailing stop order's activa
tion level.
drawActivation(float price) =>
[Link](
bar_index, price, "Activation level", style = label.style_label_right,
color = [Link], textcolor = [Link]
)
[Link](
bar_index, price, bar_index + 1, price, extend = [Link], style = line.style_dashed, colo
r = [Link]
)
// The activation line, active trailing stop price, and active trailing stop flag.
var line activationLine = na
var float trailingStopPrice = na
var bool isActive = false
// Close the trade with a market order if the trailing stop does not activate before the next 300th ba
r.
if not isActive and bar_index % 300 == 0
strategy.close_all("Market close")
// Reset the `trailingStopPrice` and `isActive` flags when the trade closes, and stop extending the `ac
tivationLine`.
if [Link]([Link]) > 0
if not isActive
[Link]()
trailingStopPrice := na
isActive := false
REMARKS
A single call to the [Link]() command can generate exit orders for several entries in an open position, depending
on the call's from_entry value. If the call does not include a from_entry argument, it creates exit orders for all
open trades, even the ones opened after the call, until the position closes. See this section of our User Manual to learn
more.
When a position consists of several open trades, and the close_entries_rule in the strategy() declaration
statement is "FIFO" (default), the orders from a [Link]() call exit from the position starting with the first open
trade. This behavior applies even if the from_entry value is the entry ID of different open trades. However, in that
case, the maximum size of the exit orders still depends on the trades opened by orders with the from_entry ID. For
more information, see this section of our User Manual.
If a [Link]() call includes arguments for creating stop-loss and trailing stop orders, the command places only the
order that is supposed to fill first, because both orders are of the "stop" type.
[Link]()
Returns the sum of entry and exit fees paid in the open trade, expressed in strategy.account_currency.
SYNTAX
ARGUMENTS
trade_num (series int) The trade number of the open trade. The number of the first trade is zero.
EXAMPLE
// Calculates the gross profit or loss for the current open position.
//@version=6
strategy("`[Link]` Example", commission_type = [Link], com
mission_value = 0.1)
// Strategy calls to enter long trades every 15 bars and exit long trades every 20 bars.
if bar_index % 15 == 0
[Link]("Long", [Link])
if bar_index % 20 == 0
[Link]("Long")
plot(tradeOpenGrossPL())
SEE ALSO
strategy() [Link]()
[Link].entry_bar_index()
Returns the bar_index of the open trade's entry.
SYNTAX
ARGUMENTS
trade_num (series int) The trade number of the open trade. The number of the first trade is zero.
EXAMPLE
barsSinceLastEntry() =>
[Link] > 0 ? bar_index - [Link].entry_bar_index([Link] -
1) : na
SEE ALSO
[Link].entry_bar_index() [Link].exit_bar_index()
[Link].entry_comment()
Returns the comment message of the open trade's entry, or na if there is no entry with this trade_num .
SYNTAX
ARGUMENTS
trade_num (series int) The trade number of the open trade. The number of the first trade is zero.
EXAMPLE
//@version=6
strategy("`[Link].entry_comment()` Example", overlay = true)
if (longCondition)
[Link]("Long", [Link], stop = stopPrice, comment = [Link](stopPric
e, "#.####"))
if [Link] or [Link]
[Link](testTable, 0, 0, 'Last entry stats')
[Link](testTable, 0, 1, "Order stop price value: " + [Link].entry_comment(strateg
[Link] - 1))
[Link](testTable, 0, 2, "Actual Entry Price: " + [Link]([Link].entry_price(s
[Link] - 1)))
SEE ALSO
[Link].entry_id()
Returns the id of the open trade's entry.
SYNTAX
ARGUMENTS
trade_num (series int) The trade number of the open trade. The number of the first trade is zero.
EXAMPLE
//@version=6
strategy("`[Link].entry_id` Example", overlay = true)
// We enter a long position when 14 period sma crosses over 28 period sma.
// We enter a short position when 14 period sma crosses under 28 period sma.
longCondition = [Link]([Link](close, 14), [Link](close, 28))
shortCondition = [Link]([Link](close, 14), [Link](close, 28))
// Strategy calls to enter a long or short position when the corresponding condition is met.
if longCondition
[Link]("Long entry at bar #" + [Link](bar_index), [Link])
if shortCondition
[Link]("Short entry at bar #" + [Link](bar_index), [Link])
RETURNS
REMARKS
SEE ALSO
[Link].entry_bar_index() [Link].entry_price() [Link].entry_time()
[Link].entry_price()
Returns the price of the open trade's entry.
SYNTAX
ARGUMENTS
trade_num (series int) The trade number of the open trade. The number of the first trade is zero.
EXAMPLE
//@version=6
strategy("[Link].entry_price Example 1", overlay = true)
// Strategy calls to enter long trades every 15 bars and exit long trades every 20 bars.
if [Link](close, [Link](close, 14))
[Link]("Long", [Link])
EXAMPLE
// Strategy calls to enter long trades every 15 bars and exit long trades every 20 bars.
if bar_index % 15 == 0
[Link]("Long", [Link])
if bar_index % 20 == 0
[Link]("Long")
plot(avgOpenPositionPrice())
SEE ALSO
[Link].exit_price()
[Link].entry_time()
Returns the UNIX time of the open trade's entry, expressed in milliseconds.
SYNTAX
trade_num (series int) The trade number of the open trade. The number of the first trade is zero.
EXAMPLE
//@version=6
strategy("[Link].entry_time Example")
// Strategy calls to enter long trades every 15 bars and exit long trades every 20 bars.
if bar_index % 15 == 0
[Link]("Long", [Link])
if bar_index % 20 == 0
[Link]("Long")
SEE ALSO
[Link].entry_time() [Link].exit_time()
[Link].max_drawdown()
Returns the maximum drawdown of the open trade, i.e., the maximum possible loss during the trade, expressed in
strategy.account_currency.
SYNTAX
ARGUMENTS
trade_num (series int) The trade number of the open trade. The number of the first trade is zero.
EXAMPLE
//@version=6
strategy("[Link].max_drawdown Example 1")
// Strategy calls to enter long trades every 15 bars and exit long trades every 20 bars.
if bar_index % 15 == 0
[Link]("Long", [Link])
if bar_index % 20 == 0
[Link]("Long")
EXAMPLE
// Calculates the max trade drawdown value for all open trades.
//@version=6
strategy("`[Link].max_drawdown` Example 2", pyramiding = 100)
// Strategy calls to enter long trades every 15 bars and exit long trades every 20 bars.
if bar_index % 15 == 0
[Link]("Long", [Link])
if bar_index % 20 == 0
[Link]("Long")
// Get the biggest max trade drawdown value from all of the open trades.
maxTradeDrawDown() =>
maxDrawdown = 0.0
for tradeNo = 0 to [Link] - 1
maxDrawdown := [Link](maxDrawdown, [Link].max_drawdown(tradeNo))
result = maxDrawdown
REMARKS
SEE ALSO
[Link].max_drawdown() strategy.max_drawdown
[Link].max_drawdown_percent()
Returns the maximum drawdown of the open trade, i.e., the maximum possible loss during the trade, expressed as a
percentage and calculated by formula: Lowest Value During Trade / (Entry Price x Quantity) * 100 .
SYNTAX
ARGUMENTS
trade_num (series int) The trade number of the closed trade. The number of the first trade is zero.
SEE ALSO
[Link].max_drawdown() strategy.max_drawdown
[Link].max_runup()
Returns the maximum run up of the open trade, i.e., the maximum possible profit during the trade, expressed in
strategy.account_currency.
SYNTAX
ARGUMENTS
trade_num (series int) The trade number of the open trade. The number of the first trade is zero.
EXAMPLE
//@version=6
strategy("[Link].max_runup Example 1")
// Strategy calls to enter long trades every 15 bars and exit long trades every 20 bars.
if bar_index % 15 == 0
[Link]("Long", [Link])
if bar_index % 20 == 0
[Link]("Long")
EXAMPLE
// Calculates the max trade runup value for all open trades.
//@version=6
strategy("[Link].max_runup Example 2", pyramiding = 100)
// Enter a long position every 30 bars.
if bar_index % 30 == 0
[Link]("Long", [Link])
// Calculate biggest max trade runup value from all of the open trades.
maxOpenTradeRunUp() =>
maxRunup = 0.0
for tradeNo = 0 to [Link] - 1
maxRunup := [Link](maxRunup, [Link].max_runup(tradeNo))
result = maxRunup
SEE ALSO
[Link].max_runup() strategy.max_drawdown
[Link].max_runup_percent()
Returns the maximum run-up of the open trade, i.e., the maximum possible profit during the trade, expressed as a
percentage and calculated by formula: Highest Value During Trade / (Entry Price x Quantity) * 10
0.
SYNTAX
ARGUMENTS
trade_num (series int) The trade number of the closed trade. The number of the first trade is zero.
SEE ALSO
[Link].max_runup() strategy.max_runup
[Link]()
Returns the profit/loss of the open trade, expressed in strategy.account_currency. Losses are expressed as negative
values.
SYNTAX
ARGUMENTS
trade_num (series int) The trade number of the open trade. The number of the first trade is zero.
EXAMPLE
// Strategy calls to enter long trades every 15 bars and exit long trades every 20 bars.
if bar_index % 15 == 0
[Link]("Long", [Link])
if bar_index % 20 == 0
[Link]("Long")
EXAMPLE
// Calculates the profit for all open trades.
//@version=6
strategy("`[Link]` Example 2", pyramiding = 5)
SEE ALSO
[Link].profit_percent()
Returns the profit/loss of the open trade, expressed as a percentage. Losses are expressed as negative values.
SYNTAX
ARGUMENTS
trade_num (series int) The trade number of the closed trade. The number of the first trade is zero.
SEE ALSO
[Link]()
[Link]()
Returns the direction and the number of contracts traded in the open trade. If the value is > 0, the market position was
long. If the value is < 0, the market position was short.
SYNTAX
ARGUMENTS
trade_num (series int) The trade number of the open trade. The number of the first trade is zero.
EXAMPLE
//@version=6
strategy("`[Link]` Example 1")
// Strategy calls to enter long trades every 15 bars and exit long trades every 20 bars.
if bar_index % 15 == 0
[Link]("Long", [Link])
if bar_index % 20 == 0
[Link]("Long")
SEE ALSO
[Link]()
Creates a new order to open, add to, or exit from a position. If an unfilled order with the same id exists, a call to this
command modifies that order.
The resulting order's type depends on the limit and stop parameters. If the call does not contain limit or st
op arguments, it creates a market order that executes on the next tick. If the call specifies a limit value but no st
op value, it places a limit order that executes after the market price reaches the limit value or a better price (lower
for buy orders and higher for sell orders). If the call specifies a stop value but no limit value, it places a stop
order that executes after the market price reaches the stop value or a worse price (higher for buy orders and lower
for sell orders). If the call contains limit and stop arguments, it creates a stop-limit order, which generates a limit
order at the limit price only after the market price reaches the stop value or a worse price.
Orders from this command, unlike those from [Link](), are not affected by the pyramiding parameter of the
strategy() declaration statement. Strategies can open any number of trades in the same direction with calls to this
function.
This command does not automatically reverse open positions because it does not exclusively create entry orders like
[Link]() does. For example, if there is an open long position of five shares, an order from this command with a
qty of 5 and a direction of [Link] triggers the sale of five shares, which closes the position.
SYNTAX
[Link](id, direction, qty, limit, stop, oca_name, oca_type, comment, alert_message, disable_alert)
→ void
ARGUMENTS
id (series string) The identifier of the order, which corresponds to an entry or exit ID in the strategy's trades after the
order fills. If the strategy opens a new position after filling the order, the order's ID becomes the
strategy.position_entry_name value. Strategy commands can reference the order ID to cancel or modify pending
orders and generate exit orders for specific open trades. The Strategy Tester and the chart display the order ID unless
the command specifies a comment value.
direction (series strategy_direction) The direction of the trade. Possible values: [Link] for a long trade,
[Link] for a short one.
qty (series int/float) Optional. The number of contracts/shares/lots/units to trade when the order fills. The default is
na, which means that the command uses the default_qty_type and default_qty_value parameters of the
strategy() declaration statement to determine the quantity.
limit (series int/float) Optional. The limit price of the order. If specified, the command creates a limit or stop-limit
order, depending on whether the stop value is also specified. The default is na, which means the resulting order is
not of the limit or stop-limit type.
stop (series int/float) Optional. The stop price of the order. If specified, the command creates a stop or stop-limit
order, depending on whether the limit value is also specified. The default is na, which means the resulting order is
not of the stop or stop-limit type.
oca_name (series string) Optional. The name of the order's One-Cancels-All (OCA) group. When a pending order
with the same oca_name and oca_type parameters executes, that order affects all unfilled orders in the group.
The default is an empty string, which means the order does not belong to an OCA group.
oca_type (input string) Optional. Specifies how an unfilled order behaves when another pending order with the same
oca_name and oca_type values executes. Possible values: [Link], [Link],
[Link]. The default is [Link].
comment (series string) Optional. Additional notes on the filled order. If the value is not an empty string, the Strategy
Tester and the chart show this text for the order instead of the specified id . The default is an empty string.
alert_message (series string) Optional. Custom text for the alert that fires when an order fills. If the "Message" field
of the "Create Alert" dialog box contains the {{[Link].alert_message}} placeholder, the alert
message replaces the placeholder with this text. The default is an empty string.
disable_alert (series bool) Optional. If true when the command creates an order, the strategy does not trigger an
alert when that order fills. This parameter accepts a "series" value, meaning users can control which orders trigger
alerts when they execute. The default is false.
EXAMPLE
//@version=6
strategy("Market order strategy", overlay = true)
// Place a market order to enter a long position when `sma14` crosses over `sma28`.
if [Link](sma14, sma28) and strategy.position_size == 0
[Link]("My Long Entry ID", [Link])
// Place a market order to sell the same quantity as the long trade when `sma14` crosses under `sma28`,
// effectively closing the long position.
if [Link](sma14, sma28) and strategy.position_size > 0
[Link]("My Long Exit ID", [Link])
EXAMPLE
//@version=6
strategy("Limit and stop exit strategy", overlay = true)
//@variable The distance from the long entry price for each short limit order.
float shortOffsetInput = [Link](200, "Sell limit/stop offset, in ticks", 1) * [Link]
//@function Draws a label and line at the specified `price` to visualize a limit order's level.
drawLimit(float price, bool isLong, bool isStop = false) =>
color col = isLong ? [Link] : [Link]
[Link](
bar_index, price, (isLong ? "Long " : "Short ") + (isStop ? "stop" : "limit") + " order create
d",
style = label.style_label_right, color = col, textcolor = [Link]
)
[Link](bar_index, price, bar_index + 1, price, extend = [Link], style = line.style_dashed,
color = col)
// Initialize two `line` variables to reference limit and stop line IDs.
var line profitLimit = na
var line lossStop = na
if [Link]([Link]) > 0
// Stop extending the `profitLimit` and `lossStop` lines.
[Link]()
[Link]()
[Link].allow_entry_in()
This function can be used to specify in which market direction the [Link]() function is allowed to open
positions.
SYNTAX
[Link].allow_entry_in(value) → void
ARGUMENTS
value (simple string) The allowed direction. Possible values: [Link], [Link],
[Link]
EXAMPLE
//@version=6
strategy("[Link].allow_entry_in")
[Link].allow_entry_in([Link])
if open > close
[Link]("Long", [Link])
// Instead of opening a short position with 10 contracts, this command will close long entries.
if open < close
[Link]("Short", [Link], qty = 10)
[Link].max_cons_loss_days()
The purpose of this rule is to cancel all pending orders, close all open positions and stop placing orders after a
specified number of consecutive days with losses. The rule affects the whole strategy.
SYNTAX
count (simple int) A required parameter. The allowed number of consecutive days with losses.
EXAMPLE
//@version=6
strategy("risk.max_cons_loss_days Demo 1")
[Link].max_cons_loss_days(3) // No orders will be placed after 3 days, if each day is with loss.
plot(strategy.position_size)
[Link].max_drawdown()
The purpose of this rule is to determine maximum drawdown. The rule affects the whole strategy. Once the maximum
drawdown value is reached, all pending orders are cancelled, all open positions are closed and no new orders can be
placed.
SYNTAX
ARGUMENTS
value (simple int/float) A required parameter. The maximum drawdown value. It is specified either in money (base
currency), or in percentage of maximum equity. For % of equity the range of allowed values is from 0 to 100.
type (simple string) A required parameter. The type of the value. Please specify one of the following values:
strategy.percent_of_equity or [Link]. Note: if equity drops down to zero or to a negative and the
'strategy.percent_of_equity' is specified, all pending orders are cancelled, all open positions are closed and no new
orders can be placed for good.
alert_message (simple string) An optional parameter which replaces the {{[Link].alert_message}}
placeholder when it is used in the "Create Alert" dialog box's "Message" field.
EXAMPLE
//@version=6
strategy("risk.max_drawdown Demo 1")
[Link].max_drawdown(50, strategy.percent_of_equity) // set maximum drawdown to 50% of maximum eq
uity
plot(strategy.position_size)
EXAMPLE
//@version=6
strategy("risk.max_drawdown Demo 2", currency = "EUR")
[Link].max_drawdown(2000, [Link]) // set maximum drawdown to 2000 EUR from maximum equity
plot(strategy.position_size)
[Link].max_intraday_filled_orders()
The purpose of this rule is to determine maximum number of filled orders per 1 day (per 1 bar, if chart resolution is
higher than 1 day). The rule affects the whole strategy. Once the maximum number of filled orders is reached, all
pending orders are cancelled, all open positions are closed and no new orders can be placed till the end of the current
trading session.
SYNTAX
[Link].max_intraday_filled_orders(count, alert_message) → void
ARGUMENTS
count (simple int) A required parameter. The maximum number of filled orders per 1 day.
EXAMPLE
//@version=6
strategy("risk.max_intraday_filled_orders Demo")
[Link].max_intraday_filled_orders(10) // After 10 orders are filled, no more strategy orders wil
l be placed (except for a market order to exit current open market position, if there is any).
if open > close
[Link]("buy", [Link])
if open < close
[Link]("sell", [Link])
[Link].max_intraday_loss()
The maximum loss value allowed during a day. It is specified either in money (base currency), or in percentage of
maximum intraday equity (0 -100).
SYNTAX
ARGUMENTS
value (simple int/float) A required parameter. The maximum loss value. It is specified either in money (base
currency), or in percentage of maximum intraday equity. For % of equity the range of allowed values is from 0 to 100.
type (simple string) A required parameter. The type of the value. Please specify one of the following values:
strategy.percent_of_equity or [Link]. Note: if equity drops down to zero or to a negative and the
strategy.percent_of_equity is specified, all pending orders are cancelled, all open positions are closed and no new
orders can be placed for good.
EXAMPLE
// Sets the maximum intraday loss using the strategy's equity value.
//@version=6
strategy("[Link].max_intraday_loss Example 1", overlay = false, default_qty_type = [Link]
ent_of_equity, default_qty_value = 100)
// Calculate change of the current equity from the beginning of the current day.
eqChgPct = 100 * (([Link] - eqFromDayStart) / [Link])
// Plot it
plot(eqChgPct)
hline(-lossPct)
EXAMPLE
// Sets the maximum intraday loss using the strategy's cash value.
//@version=6
strategy("[Link].max_intraday_loss Example 2", overlay = false)
// Input for maximum intraday loss in absolute cash value of the symbol.
absCashLoss = [Link](5)
// Store the open price value from the beginning of the day.
beginPrice = [Link]([Link](dayofweek) > 0, open, 0)
hline(absCashLoss)
plot(priceChg)
SEE ALSO
[Link].max_position_size()
The purpose of this rule is to determine maximum size of a market position. The rule affects the following function:
[Link](). The 'entry' quantity can be reduced (if needed) to such number of contracts/shares/lots/units, so the
total position size doesn't exceed the value specified in '[Link].max_position_size'. If minimum possible quantity
still violates the rule, the order will not be placed.
SYNTAX
[Link].max_position_size(contracts) → void
ARGUMENTS
EXAMPLE
//@version=6
strategy("risk.max_position_size Demo", default_qty_value = 100)
[Link].max_position_size(10)
if open > close
[Link]("buy", [Link])
plot(strategy.position_size) // max plot value will be 10
string() 4 overloads
Casts na to string
ARGUMENTS
x (const string) The value to convert to the specified type, usually na.
RETURNS
SEE ALSO
[Link]() 2 overloads
ARGUMENTS
symbol (simple string) Symbol. Note that the symbol should be passed with a prefix. For example: "NASDAQ:AAPL"
instead of "AAPL".
EXAMPLE
//@version=6
indicator("[Link] fun", overlay=true)
i_sym = [Link]("NASDAQ:AAPL")
pref = [Link](i_sym)
tick = [Link](i_sym)
t = [Link](pref, tick, [Link])
s = [Link](t, "1D", close)
plot(s)
RETURNS
REMARKS
SEE ALSO
[Link]() 2 overloads
ARGUMENTS
symbol (simple string) Symbol. Note that the symbol should be passed with a prefix. For example: "NASDAQ:AAPL"
instead of "AAPL".
EXAMPLE
//@version=6
indicator("[Link] fun", overlay=true)
i_sym = [Link]("NASDAQ:AAPL")
pref = [Link](i_sym)
tick = [Link](i_sym)
t = [Link](pref, tick, [Link])
s = [Link](t, "1D", close)
plot(s)
RETURNS
REMARKS
SEE ALSO
[Link]()
Arnaud Legoux Moving Average. It uses Gaussian distribution as weights for moving average.
SYNTAX
ARGUMENTS
offset (simple int/float) Controls tradeoff between smoothness (closer to 1) and responsiveness (closer to 0).
sigma (simple int/float) Changes the smoothness of ALMA. The larger sigma the smoother ALMA.
floor (simple bool) An optional parameter. Specifies whether the offset calculation is floored before ALMA is
calculated. Default value is false.
EXAMPLE
//@version=6
indicator("[Link]", overlay=true)
plot([Link](close, 9, 0.85, 6))
RETURNS
REMARKS
na values in the source series are included in calculations and will produce an na result.
SEE ALSO
[Link]()
Function atr (average true range) returns the RMA of true range. True range is max(high - low, abs(high - close[1]),
abs(low - close[1])).
SYNTAX
ARGUMENTS
EXAMPLE
//@version=6
indicator("[Link]")
plot([Link](14))
plot(pine_atr(14))
RETURNS
REMARKS
na values in the source series are ignored; the function calculates on the length quantity of non- na values.
SEE ALSO
[Link]() [Link]()
[Link]()
Counts the number of bars since the last time the condition was true.
SYNTAX
ARGUMENTS
//@version=6
indicator("[Link]")
// get number of bars since last [Link] bar
plot([Link](close >= open))
RETURNS
REMARKS
If the condition has never been met prior to the current bar, the function returns na.
Please note that using this variable/function can cause indicator repainting.
SEE ALSO
[Link]()
Bollinger Bands. A Bollinger Band is a technical analysis tool defined by a set of lines plotted two standard deviations
(positively and negatively) away from a simple moving average (SMA) of the security's price, but can be adjusted to
user preferences.
SYNTAX
ARGUMENTS
EXAMPLE
//@version=6
indicator("[Link]")
plot(pineMiddle)
plot(pineUpper)
plot(pineLower)
RETURNS
Bollinger Bands.
REMARKS
na values in the source series are ignored; the function calculates on the length quantity of non- na values.
SEE ALSO
[Link]() [Link]() [Link]()
[Link]()
Bollinger Bands Width. The Bollinger Band Width is the difference between the upper and the lower Bollinger Bands
divided by the middle band.
SYNTAX
ARGUMENTS
EXAMPLE
//@version=6
indicator("[Link]")
plot(f_bbw(close, 5, 4))
RETURNS
REMARKS
na values in the source series are ignored; the function calculates on the length quantity of non- na values.
SEE ALSO
[Link]()
The CCI (commodity channel index) is calculated as the difference between the typical price of a commodity and its
simple moving average, divided by the mean absolute deviation of the typical price. The index is scaled by an inverse
factor of 0.015 to provide more readable numbers.
SYNTAX
ARGUMENTS
RETURNS
REMARKS
na values in the source series are ignored.
[Link]() 3 overloads
Compares the current source value to its value length bars ago and returns the difference.
ARGUMENTS
length (series int) How far the past source value is offset from the current one, in bars. Optional. The default is 1.
EXAMPLE
//@version=6
indicator('Day and Direction Change', overlay = true)
dailyBarTime = time('1D')
isNewDay = [Link](dailyBarTime) != 0
bgcolor(isNewDay ? [Link]([Link], 80) : na)
RETURNS
The difference between the values when they are numerical. When a 'bool' source is used, returns true when the
current source is different from the previous source.
REMARKS
na values in the source series are included in calculations and will produce an na result.
SEE ALSO
[Link]() [Link]()
[Link]()
Chande Momentum Oscillator. Calculates the difference between the sum of recent gains and the sum of recent losses
and then divides the result by the sum of all price movement over the same period.
SYNTAX
ARGUMENTS
EXAMPLE
//@version=6
indicator("[Link]")
plot([Link](close, 5), color=[Link])
plot(f_cmo(close, 5))
RETURNS
REMARKS
SEE ALSO
[Link]()
The cog (center of gravity) is an indicator based on statistics and the Fibonacci golden ratio.
SYNTAX
ARGUMENTS
EXAMPLE
//@version=6
indicator("[Link]", overlay=true)
plot([Link](close, 10))
plot(pine_cog(close, 10))
RETURNS
Center of Gravity.
REMARKS
SEE ALSO
[Link]()
[Link]()
Correlation coefficient. Describes the degree to which two series tend to deviate from their [Link]() values.
SYNTAX
ARGUMENTS
RETURNS
Correlation coefficient.
REMARKS
na values in the source series are ignored; the function calculates on the length quantity of non- na values.
SEE ALSO
[Link]()
[Link]()
SYNTAX
ARGUMENTS
RETURNS
SEE ALSO
[Link]()
[Link]()
The source1 -series is defined as having crossed over source2 -series if, on the current bar, the value of source
1 is greater than the value of source2 , and on the previous bar, the value of source1 was less than or equal to
the value of source2 .
SYNTAX
ARGUMENTS
RETURNS
[Link]()
The source1 -series is defined as having crossed under source2 -series if, on the current bar, the value of sourc
e1 is less than the value of source2 , and on the previous bar, the value of source1 was greater than or equal to
the value of source2 .
SYNTAX
ARGUMENTS
RETURNS
[Link]()
Cumulative (total) sum of source . In other words it's a sum of all elements of source .
SYNTAX
ARGUMENTS
RETURNS
SEE ALSO
[Link]()
[Link]()
Measure of difference between the series and it's [Link]()
SYNTAX
ARGUMENTS
EXAMPLE
//@version=6
indicator("[Link]")
plot([Link](close, 10))
REMARKS
SEE ALSO
[Link]() [Link]()
[Link]()
The dmi function returns the directional movement index.
SYNTAX
ARGUMENTS
EXAMPLE
//@version=6
indicator(title="Directional Movement Index", shorttitle="DMI", format=[Link], precision=4)
len = [Link](17, minval=1, title="DI Length")
lensig = [Link](14, title="ADX Smoothing", minval=1)
[diplus, diminus, adx] = [Link](len, lensig)
plot(adx, color=[Link], title="ADX")
plot(diplus, color=[Link], title="+DI")
plot(diminus, color=[Link], title="-DI")
RETURNS
Tuple of three DMI series: Positive Directional Movement (+DI), Negative Directional Movement (-DI) and Average
Directional Movement Index (ADX).
SEE ALSO
[Link]()
The ema function returns the exponentially weighted moving average. In ema weighting factors decrease
exponentially. It calculates by using a formula: EMA = alpha * source + (1 - alpha) * EMA[1] , where alp
ha = 2 / (length + 1) .
SYNTAX
ARGUMENTS
EXAMPLE
//@version=6
indicator("[Link]")
plot([Link](close, 15))
RETURNS
REMARKS
Please note that using this variable/function can cause indicator repainting.
na values in the source series are ignored; the function calculates on the length quantity of non- na values.
SEE ALSO
[Link]()
Test if the source series is now falling for length bars long.
SYNTAX
ARGUMENTS
RETURNS
true if current source value is less than any previous source value for length bars back, false otherwise.
REMARKS
na values in the source series are ignored; the function calculates on the length quantity of non- na values.
SEE ALSO
[Link]()
[Link]()
Highest value for a given number of bars back.
SYNTAX
ARGUMENTS
RETURNS
REMARKS
Two args version: source is a series and length is the number of bars back.
One arg version: length is the number of bars back. Algorithm uses high as a source series.
SEE ALSO
[Link]()
Highest value offset for a given number of bars back.
SYNTAX
ARGUMENTS
RETURNS
REMARKS
Two args version: source is a series and length is the number of bars back.
One arg version: length is the number of bars back. Algorithm uses high as a source series.
SEE ALSO
[Link]()
The hma function returns the Hull Moving Average.
SYNTAX
ARGUMENTS
EXAMPLE
//@version=6
indicator("Hull Moving Average")
src = input(defval=close, title="Source")
length = input(defval=9, title="Length")
hmaBuildIn = [Link](src, length)
plot(hmaBuildIn, title="Hull MA", color=#674EA7)
RETURNS
REMARKS
na values in the source series are ignored.
SEE ALSO
[Link]()
Keltner Channels. Keltner channel is a technical analysis indicator showing a central moving average line plus channel
lines at a distance above and below.
SYNTAX
[Link](series, length, mult, useTrueRange) → [series float, series float, series float]
ARGUMENTS
useTrueRange (simple bool) An optional parameter. Specifies if True Range is used; default is true. If the value is
false, the range will be calculated with the expression (high - low).
EXAMPLE
//@version=6
indicator("[Link]")
plot(pineMiddle)
plot(pineUpper)
plot(pineLower)
RETURNS
Keltner Channels.
REMARKS
na values in the source series are ignored; the function calculates on the length quantity of non- na values.
SEE ALSO
[Link]()
Keltner Channels Width. The Keltner Channels Width is the difference between the upper and the lower Keltner
Channels divided by the middle channel.
SYNTAX
[Link](series, length, mult, useTrueRange) → series float
ARGUMENTS
useTrueRange (simple bool) An optional parameter. Specifies if True Range is used; default is true. If the value is
false, the range will be calculated with the expression (high - low).
EXAMPLE
//@version=6
indicator("[Link]")
plot(f_kcw(close, 5, 4, true))
RETURNS
REMARKS
na values in the source series are ignored; the function calculates on the length quantity of non- na values.
SEE ALSO
[Link]()
Linear regression curve. A line that best fits the prices specified over a user-defined time period. It is calculated using
the least squares method. The result of this function is calculated using the formula: linreg = intercept + slope * (length
- 1 - offset), where intercept and slope are the values calculated with the least squares method on source series.
SYNTAX
ARGUMENTS
RETURNS
REMARKS
na values in the source series are included in calculations and will produce an na result.
[Link]()
Lowest value for a given number of bars back.
SYNTAX
ARGUMENTS
RETURNS
REMARKS
Two args version: source is a series and length is the number of bars back.
One arg version: length is the number of bars back. Algorithm uses low as a source series.
SEE ALSO
[Link]()
Lowest value offset for a given number of bars back.
SYNTAX
ARGUMENTS
RETURNS
REMARKS
Two args version: source is a series and length is the number of bars back.
One arg version: length is the number of bars back. Algorithm uses low as a source series.
SEE ALSO
[Link]()
MACD (moving average convergence/divergence). It is supposed to reveal changes in the strength, direction,
momentum, and duration of a trend in a stock's price.
SYNTAX
[Link](source, fastlen, slowlen, siglen) → [series float, series float, series float]
ARGUMENTS
EXAMPLE
//@version=6
indicator("MACD")
[macdLine, signalLine, histLine] = [Link](close, 12, 26, 9)
plot(macdLine, color=[Link])
plot(signalLine, color=[Link])
plot(histLine, color=[Link], style=plot.style_histogram)
If you need only one value, use placeholders '_' like this:
EXAMPLE
//@version=6
indicator("MACD")
[_, signalLine, _] = [Link](close, 12, 26, 9)
plot(signalLine, color=[Link])
RETURNS
Tuple of three MACD series: MACD line, signal line and histogram line.
REMARKS
na values in the source series are ignored; the function calculates on the length quantity of non- na values.
SEE ALSO
[Link]() [Link]()
[Link]()
Returns the all-time high value of source from the beginning of the chart up to the current bar.
SYNTAX
ARGUMENTS
REMARKS
na
[Link]() 2 overloads
ARGUMENTS
source (series int) Series of values to process.
RETURNS
REMARKS
na values in the source series are ignored; the function calculates on the length quantity of non- na values.
[Link]()
Money Flow Index. The Money Flow Index (MFI) is a technical oscillator that uses price and volume for identifying
overbought or oversold conditions in an asset.
SYNTAX
ARGUMENTS
EXAMPLE
//@version=6
indicator("Money Flow Index")
plot(pine_mfi(hlc3, 14))
RETURNS
REMARKS
na values in the source series are ignored; the function calculates on the length quantity of non- na values.
SEE ALSO
[Link]() [Link]()
[Link]()
Returns the all-time low value of source from the beginning of the chart up to the current bar.
SYNTAX
ARGUMENTS
REMARKS
na
[Link]() 2 overloads
Returns the mode of the series. If there are several values with the same frequency, it returns the smallest value.
ARGUMENTS
RETURNS
The most frequently occurring value from the source . If none exists, returns the smallest value instead.
REMARKS
na values in the source series are ignored; the function calculates on the length quantity of non- na values.
[Link]()
Momentum of source price and source price length bars ago. This is simply a difference: source -
source[length].
SYNTAX
ARGUMENTS
RETURNS
REMARKS
na values in the source series are included in calculations and will produce an na result.
SEE ALSO
[Link]()
ta.percentile_linear_interpolation()
Calculates percentile using method of linear interpolation between the two nearest ranks.
SYNTAX
ARGUMENTS
RETURNS
REMARKS
Note that a percentile calculated using this method will NOT always be a member of the input data set.
na values in the source series are included in calculations and will produce an na result.
SEE ALSO
ta.percentile_nearest_rank()
ta.percentile_nearest_rank()
Calculates percentile using method of Nearest Rank.
SYNTAX
ARGUMENTS
RETURNS
REMARKS
Using the Nearest Rank method on lengths less than 100 bars back can result in the same number being used for
more than one percentile.
A percentile calculated using the Nearest Rank method will always be a member of the input data set.
The 100th percentile is defined to be the largest value in the input data set.
na values in the source series are ignored.
SEE ALSO
ta.percentile_linear_interpolation()
[Link]()
Percent rank is the percents of how many previous values was less than or equal to the current value of given series.
SYNTAX
ARGUMENTS
RETURNS
REMARKS
na values in the source series are included in calculations and will produce an na result.
ta.pivot_point_levels()
Calculates the pivot point levels using the specified type and anchor .
SYNTAX
ARGUMENTS
type (series string) The type of pivot point levels. Possible values: "Traditional", "Fibonacci", "Woodie", "Classic",
"DM", "Camarilla".
anchor (series bool) The condition that triggers the reset of the pivot point calculations. When true, calculations
reset; when false, results calculated at the last reset persist.
developing (series bool) If false, the values are those calculated the last time the anchor condition was true. They
remain constant until the anchor condition becomes true again. If true, the pivots are developing, i.e., they constantly
recalculate on the data developing between the point of the last anchor (or bar zero if the anchor condition was never
true) and the current bar. Optional. The default is false.
EXAMPLE
//@version=6
indicator("Weekly Pivots", max_lines_count=500, overlay=true)
timeframe = "1W"
typeInput = [Link]("Traditional", "Type", options=["Traditional", "Fibonacci", "Woodie", "Classi
c", "DM", "Camarilla"])
weekChange = [Link](timeframe)
pivotPointsArray = ta.pivot_point_levels(typeInput, weekChange)
if weekChange
for pivotLevel in pivotPointsArray
[Link](time, pivotLevel, time + timeframe.in_seconds(timeframe) * 1000, pivotLevel, xloc=xlo
c.bar_time)
RETURNS
An array<float> with numerical values representing 11 pivot point levels: [P, R1, S1, R2, S2, R3, S3, R4, S4, R5,
S5]. Levels absent from the specified type return na values (e.g., "DM" only calculates P, R1, and S1).
REMARKS
The developing parameter cannot be true when type is set to "Woodie", because the Woodie calculation for a
period depends on that period's open, which means that the pivot value is either available or unavailable, but never
developing. If used together, the indicator will return a runtime error.
[Link]() 2 overloads
This function returns price of the pivot high point. It returns 'NaN', if there was no pivot high point.
ARGUMENTS
EXAMPLE
//@version=6
indicator("PivotHigh", overlay=true)
leftBars = input(2)
rightBars=input(2)
ph = [Link](leftBars, rightBars)
plot(ph, style=plot.style_cross, linewidth=3, color= [Link], offset=-rightBars)
RETURNS
REMARKS
If parameters 'leftbars' or 'rightbars' are series you should use max_bars_back() function for the 'source' variable.
[Link]() 2 overloads
This function returns price of the pivot low point. It returns 'NaN', if there was no pivot low point.
ARGUMENTS
EXAMPLE
//@version=6
indicator("PivotLow", overlay=true)
leftBars = input(2)
rightBars=input(2)
pl = [Link](close, leftBars, rightBars)
plot(pl, style=plot.style_cross, linewidth=3, color= [Link], offset=-rightBars)
RETURNS
REMARKS
If parameters 'leftbars' or 'rightbars' are series you should use max_bars_back() function for the 'source' variable.
[Link]() 2 overloads
Returns the difference between the min and max values in a series.
ARGUMENTS
RETURNS
The difference between the min and max values in the series.
REMARKS
na values in the source series are ignored; the function calculates on the length quantity of non- na values.
[Link]()
Calculates the Rank Correlation Index (RCI), which measures the directional consistency of price movements. It
evaluates the monotonic relationship between a source series and the bar index over length bars using
Spearman's rank correlation coefficient. The resulting value is scaled to a range of -100 to 100, where 100 indicates
the source consistently increased over the period, and -100 indicates it consistently decreased. Values between
-100 and 100 reflect varying degrees of upward or downward consistency.
SYNTAX
ARGUMENTS
RETURNS
SEE ALSO
[Link]()
Test if the source series is now rising for length bars long.
SYNTAX
ARGUMENTS
RETURNS
true if current source is greater than any previous source for length bars back, false otherwise.
REMARKS
SEE ALSO
[Link]()
[Link]()
Moving average used in RSI. It is the exponentially weighted moving average with alpha = 1 / length.
SYNTAX
ARGUMENTS
source (series int/float) Series of values to process.
EXAMPLE
//@version=6
indicator("[Link]")
plot([Link](close, 15))
RETURNS
REMARKS
na values in the source series are ignored; the function calculates on the length quantity of non- na values.
SEE ALSO
[Link]()
Calculates the percentage of change (rate of change) between the current value of source and its value length
bars ago.
SYNTAX
ARGUMENTS
RETURNS
REMARKS
na values in the source series are included in calculations and will produce an na result.
[Link]()
Relative strength index. It is calculated using the [Link]() of upward and downward changes of source over the
last length bars.
SYNTAX
ARGUMENTS
//@version=6
indicator("[Link]")
plot([Link](close, 7))
plot(pine_rsi(close, 7))
RETURNS
REMARKS
na values in the source series are ignored; the function calculates on the length quantity of non- na values.
SEE ALSO
[Link]()
[Link]()
Parabolic SAR (parabolic stop and reverse) is a method devised by J. Welles Wilder, Jr., to find potential reversals in
the market price direction of traded goods.
SYNTAX
ARGUMENTS
EXAMPLE
//@version=6
indicator("[Link]")
plot([Link](0.02, 0.02, 0.2), style=plot.style_cross, linewidth=3)
if bar_index == 1
if close > close[1]
isBelow := true
maxMin := high
result := low[1]
else
isBelow := false
maxMin := low
result := high[1]
isFirstTrendBar := true
acceleration := start
result := result + acceleration * (maxMin - result)
if isBelow
if result > low
isFirstTrendBar := true
isBelow := false
result := [Link](high, maxMin)
maxMin := low
acceleration := start
else
if result < high
isFirstTrendBar := true
isBelow := true
result := [Link](low, maxMin)
maxMin := high
acceleration := start
if not isFirstTrendBar
if isBelow
if high > maxMin
maxMin := high
acceleration := [Link](acceleration + inc, max)
else
if low < maxMin
maxMin := low
acceleration := [Link](acceleration + inc, max)
if isBelow
result := [Link](result, low[1])
if bar_index > 1
result := [Link](result, low[2])
else
result := [Link](result, high[1])
if bar_index > 1
result := [Link](result, high[2])
result
RETURNS
Parabolic SAR.
[Link]()
The sma function returns the moving average, that is the sum of last y values of x, divided by y.
SYNTAX
ARGUMENTS
EXAMPLE
//@version=6
indicator("[Link]")
plot([Link](close, 15))
REMARKS
SEE ALSO
[Link]()
SYNTAX
ARGUMENTS
biased (series bool) Determines which estimate should be used. Optional. The default is true.
EXAMPLE
//@version=6
indicator("[Link]")
plot([Link](close, 5))
RETURNS
Standard deviation.
REMARKS
If biased is true, function will calculate using a biased estimate of the entire population, if false - unbiased estimate
of a sample.
na values in the source series are ignored; the function calculates on the length quantity of non- na values.
SEE ALSO
[Link]() [Link]()
[Link]()
Stochastic. It is calculated by a formula: 100 * (close - lowest(low, length)) / (highest(high, length) - lowest(low,
length)).
SYNTAX
ARGUMENTS
RETURNS
Stochastic.
REMARKS
SEE ALSO
[Link]()
[Link]()
The Supertrend Indicator. The Supertrend is a trend following indicator.
SYNTAX
ARGUMENTS
factor (series int/float) The multiplier by which the ATR will get multiplied.
EXAMPLE
//@version=6
indicator("Pine Script® Supertrend")
RETURNS
Tuple of two supertrend series: supertrend line and direction of trend. Possible values are 1 (down direction) and -1
(up direction).
SEE ALSO
[Link]()
[Link]()
Symmetrically weighted moving average with fixed length: 4. Weights: [1/6, 2/6, 2/6, 1/6].
SYNTAX
ARGUMENTS
EXAMPLE
//@version=6
indicator("[Link]")
plot([Link](close))
RETURNS
REMARKS
na values in the source series are included in calculations and will produce an na result.
SEE ALSO
[Link]()
Calculates the current bar's true range. Unlike a bar's actual range ( high - low ), true range accounts for potential
gaps by taking the maximum of the current bar's actual range and the absolute distances from the previous bar's close
to the current bar's high and low. The formula is: [Link](high - low, [Link](high - close[1]), mat
[Link](low - close[1])) .
SYNTAX
[Link](handle_na) → series float
ARGUMENTS
handle_na (simple bool) Defines how the function calculates the result when the previous bar's close is na. If true,
the function returns the bar's high - low value. If false, it returns na.
RETURNS
REMARKS
SEE ALSO
[Link] [Link]()
[Link]()
True strength index. It uses moving averages of the underlying momentum of a financial instrument.
SYNTAX
ARGUMENTS
RETURNS
REMARKS
na values in the source series are ignored; the function calculates on the length quantity of non- na values.
[Link]() 4 overloads
Returns the value of the source series on the bar where the condition was true on the nth most recent
occurrence.
ARGUMENTS
occurrence (simple int) The occurrence of the condition. The numbering starts from 0 and goes back in time, so '0' is
the most recent occurrence of condition , '1' is the second most recent and so forth. Must be an integer >= 0.
EXAMPLE
//@version=6
indicator("[Link]")
slow = [Link](close, 7)
fast = [Link](close, 14)
// Get value of `close` on second most recent cross
plot([Link]([Link](slow, fast), close, 1))
REMARKS
This function requires execution on every bar. It is not recommended to use it inside a for or while loop structure,
where its behavior can be unexpected. Please note that using this function can cause indicator repainting.
SEE ALSO
[Link]()
Variance is the expectation of the squared deviation of a series from its mean ([Link]()), and it informally measures
how far a set of numbers are spread out from their mean.
SYNTAX
ARGUMENTS
biased (series bool) Determines which estimate should be used. Optional. The default is true.
RETURNS
REMARKS
If biased is true, function will calculate using a biased estimate of the entire population, if false - unbiased estimate
of a sample.
na values in the source series are ignored; the function calculates on the length quantity of non- na values.
SEE ALSO
[Link]() [Link]()
[Link]() 2 overloads
ARGUMENTS
EXAMPLE
//@version=6
indicator("Simple VWAP")
vwap = [Link](open)
plot(vwap)
EXAMPLE
//@version=6
indicator("Advanced VWAP")
vwapAnchorInput = [Link]("Daily", "Anchor", options = ["Daily", "Weekly", "Monthly"])
stdevMultiplierInput = [Link](1.0, "Standard Deviation Multiplier")
anchorTimeframe = switch vwapAnchorInput
"Daily" => "1D"
"Weekly" => "1W"
"Monthly" => "1M"
anchor = [Link](anchorTimeframe)
[vwap, upper, lower] = [Link](open, anchor, stdevMultiplierInput)
plot(vwap)
plot(upper, color = [Link])
plot(lower, color = [Link])
RETURNS
REMARKS
Calculations only begin the first time the anchor condition becomes true. Until then, the function returns na.
SEE ALSO
[Link]
[Link]()
The vwma function returns volume-weighted moving average of source for length bars back. It is the same as:
sma(source * volume, length) / sma(volume, length).
SYNTAX
ARGUMENTS
EXAMPLE
//@version=6
indicator("[Link]")
plot([Link](close, 15))
REMARKS
SEE ALSO
[Link]()
The wma function returns weighted moving average of source for length bars back. In wma weighting factors
decrease in arithmetical progression.
SYNTAX
ARGUMENTS
EXAMPLE
//@version=6
indicator("[Link]")
plot([Link](close, 15))
RETURNS
REMARKS
SEE ALSO
[Link]()
Williams %R. The oscillator shows the current closing price in relation to the high and low of the past 'length' bars.
SYNTAX
ARGUMENTS
//@version=6
indicator("Williams %R", shorttitle="%R", format=[Link], precision=2)
plot([Link](14), title="%R", color=[Link](#ff6d00, 0))
RETURNS
Williams %R.
REMARKS
SEE ALSO
[Link]() [Link]()
table()
Casts na to table
SYNTAX
ARGUMENTS
x (series table) The value to convert to the specified type, usually na.
RETURNS
SEE ALSO
[Link]()
The function defines a cell in the table and sets its attributes.
SYNTAX
[Link](table_id, column, row, text, width, height, text_color, text_halign, text_valign, text_size, bgc
olor, tooltip, text_font_family, text_formatting) → void
ARGUMENTS
row (series int) The index of the cell's row. Numbering starts at 0.
text (series string) The text to be displayed inside the cell. Optional. The default is empty string.
width (series int/float) The width of the cell as a % of the indicator's visual space. Optional. By default, auto-adjusts
the width based on the text inside the cell. Value 0 has the same effect.
height (series int/float) The height of the cell as a % of the indicator's visual space. Optional. By default, auto-adjusts
the height based on the text inside of the cell. Value 0 has the same effect.
text_color (series color) The color of the text. Optional. The default is [Link].
text_halign (series string) The horizontal alignment of the cell's text. Optional. The default value is text.align_center.
Possible values: text.align_left, text.align_center, text.align_right.
text_valign (series string) The vertical alignment of the cell's text. Optional. The default value is text.align_center.
Possible values: text.align_top, text.align_center, text.align_bottom.
text_size (series int/string) Size of the object. The size can be any positive integer, or one of the size.* built-in
constant strings. The constant strings and their equivalent integer values are: [Link] (0), [Link] (8), [Link]
(10), [Link] (14), [Link] (20), [Link] (36). The default value is [Link] or 14.
bgcolor (series color) The background color of the text. Optional. The default is no color.
tooltip (series string) The tooltip to be displayed inside the cell. Optional.
text_font_family (series string) The font family of the text. Optional. The default value is font.family_default. Possible
values: font.family_default, font.family_monospace.
text_formatting (const text_format) The formatting of the displayed text. Formatting options support addition. For
example, text.format_bold + text.format_italic will make the text both bold and italicized. Possible
values: text.format_none, text.format_bold, text.format_italic. Optional. The default is text.format_none.
REMARKS
This function does not create the table itself, but defines the table’s cells. To use it, you first need to create a table
object with [Link]().
Each [Link]() call overwrites all previously defined properties of a cell. If you call [Link]() twice in a row, e.g., the
first time with text='Test Text', and the second time with text_color=[Link] but without a new text argument, the
default value of the 'text' being an empty string, it will overwrite 'Test Text', and your cell will display an empty string. If
you want, instead, to modify any of the cell's properties, use the table.cell_set_*() functions.
A single script can only display one table in each of the possible locations. If [Link]() is used on several bars to
change the same attribute of a cell (e.g. change the background color of the cell to red on the first bar, then to yellow
on the second bar), only the last change will be reflected in the table, i.e., the cell’s background will be yellow. Avoid
unnecessary setting of cell properties by enclosing function calls in an if [Link] block whenever possible, to
restrict their execution to the last bar of the series.
SEE ALSO
table.cell_set_width() table.cell_set_tooltip()
table.cell_set_bgcolor()
The function sets the background color of the cell.
SYNTAX
ARGUMENTS
row (series int) The index of the cell's row. Numbering starts at 0.
bgcolor (series color) The background color of the cell.
SEE ALSO
table.cell_set_height()
The function sets the height of cell.
SYNTAX
ARGUMENTS
row (series int) The index of the cell's row. Numbering starts at 0.
height (series int/float) The height of the cell as a % of the chart window. Passing 0 auto-adjusts the height based on
the text inside of the cell.
SEE ALSO
table.cell_set_text()
The function sets the text in the specified cell.
SYNTAX
ARGUMENTS
row (series int) The index of the cell's row. Numbering starts at 0.
EXAMPLE
//@version=6
indicator("TABLE example")
var tLog = [Link](position = position.top_left, rows = 1, columns = 2, bgcolor = [Link], borde
r_width=1)
[Link](tLog, row = 0, column = 0, text = "sometext", text_color = [Link])
table.cell_set_text(tLog, row = 0, column = 0, text = "sometext")
SEE ALSO
table.cell_set_text_formatting()
table.cell_set_text_color()
The function sets the color of the text inside the cell.
SYNTAX
ARGUMENTS
row (series int) The index of the cell's row. Numbering starts at 0.
text_color (series color) The color of the text.
SEE ALSO
table.cell_set_text_font_family()
The function sets the font family of the text inside the cell.
SYNTAX
ARGUMENTS
column (series int) The index of the cell's column. Numbering starts at 0.
row (series int) The index of the cell's row. Numbering starts at 0.
text_font_family (series string) The font family of the text. Possible values: font.family_default,
font.family_monospace.
EXAMPLE
//@version=6
indicator("Example of setting the table cell font")
var t = [Link](position.top_left, rows = 1, columns = 1)
[Link](t, 0, 0, "monospace", text_color = [Link])
table.cell_set_text_font_family(t, 0, 0, font.family_monospace)
SEE ALSO
table.cell_set_text_formatting()
Sets the formatting attributes the drawing applies to displayed text.
SYNTAX
ARGUMENTS
row (series int) The index of the cell's row. Numbering starts at 0.
text_formatting (const text_format) The formatting of the displayed text. Formatting options support addition. For
example, text.format_bold + text.format_italic will make the text both bold and italicized. Possible
values: text.format_none, text.format_bold, text.format_italic. Optional. The default is text.format_none.
SEE ALSO
table.cell_set_bgcolor() table.cell_set_height() table.cell_set_text_color() table.cell_set_text_halign()
table.cell_set_text()
table.cell_set_text_halign()
The function sets the horizontal alignment of the cell's text.
SYNTAX
ARGUMENTS
column (series int) The index of the cell's column. Numbering starts at 0.
row (series int) The index of the cell's row. Numbering starts at 0.
text_halign (series string) The horizontal alignment of a cell's text. Possible values: text.align_left, text.align_center,
text.align_right.
SEE ALSO
table.cell_set_text_size()
The function sets the size of the cell's text.
SYNTAX
ARGUMENTS
row (series int) The index of the cell's row. Numbering starts at 0.
text_size (series int/string) Size of the object. The size can be any positive integer, or one of the size.* built-in
constant strings. The constant strings and their equivalent integer values are: [Link] (0), [Link] (8), [Link]
(10), [Link] (14), [Link] (20), [Link] (36). The default value is [Link] or 14.
SEE ALSO
table.cell_set_text_valign()
The function sets the vertical alignment of a cell's text.
SYNTAX
column (series int) The index of the cell's column. Numbering starts at 0.
row (series int) The index of the cell's row. Numbering starts at 0.
text_valign (series string) The vertical alignment of the cell's text. Possible values: text.align_top, text.align_center,
text.align_bottom.
SEE ALSO
table.cell_set_tooltip()
The function sets the tooltip in the specified cell.
SYNTAX
ARGUMENTS
column (series int) The index of the cell's column. Numbering starts at 0.
row (series int) The index of the cell's row. Numbering starts at 0.
EXAMPLE
//@version=6
indicator("TABLE example")
var tLog = [Link](position = position.top_left, rows = 1, columns = 2, bgcolor = [Link], borde
r_width=1)
[Link](tLog, row = 0, column = 0, text = "sometext", text_color = [Link])
table.cell_set_tooltip(tLog, row = 0, column = 0, tooltip = "sometext")
SEE ALSO
table.cell_set_width()
The function sets the width of the cell.
SYNTAX
ARGUMENTS
row (series int) The index of the cell's row. Numbering starts at 0.
width (series int/float) The width of the cell as a % of the chart window. Passing 0 auto-adjusts the width based on
the text inside of the cell.
SEE ALSO
[Link]()
The function removes a cell or a sequence of cells from the table. The cells are removed in a rectangle shape where
the start_column and start_row specify the top-left corner, and end_column and end_row specify the bottom-right
corner.
SYNTAX
ARGUMENTS
start_column (series int) The index of the column of the first cell to delete. Numbering starts at 0.
start_row (series int) The index of the row of the first cell to delete. Numbering starts at 0.
end_column (series int) The index of the column of the last cell to delete. Optional. The default is the argument used
for start_column. Numbering starts at 0.
end_row (series int) The index of the row of the last cell to delete. Optional. The default is the argument used for
start_row. Numbering starts at 0.
EXAMPLE
//@version=6
indicator("A donut", overlay=true)
if [Link]
colNum = 8, rowNum = 8
padding = "◯"
donutTable = [Link](position.middle_right, colNum, rowNum)
for c = 0 to colNum - 1
for r = 0 to rowNum - 1
[Link](donutTable, c, r, text=padding, bgcolor=#face6e, text_color=[Link]([Link]
k, 100))
[Link](donutTable, 2, 2, 5, 5)
SEE ALSO
[Link]() [Link]()
[Link]()
The function deletes a table.
SYNTAX
[Link](table_id) → void
ARGUMENTS
EXAMPLE
//@version=6
indicator("[Link] example")
var testTable = [Link](position = position.top_right, columns = 2, rows = 1, bgcolor = [Link]
w, border_width = 1)
if [Link]
[Link](table_id = testTable, column = 0, row = 0, text = "Open is " + [Link](open))
[Link](table_id = testTable, column = 1, row = 0, text = "Close is " + [Link](close), bgc
olor=[Link])
if [Link]
[Link](testTable)
SEE ALSO
[Link]() [Link]()
table.merge_cells()
The function merges a sequence of cells in the table into one cell. The cells are merged in a rectangle shape where the
start_column and start_row specify the top-left corner, and end_column and end_row specify the bottom-right corner.
SYNTAX
ARGUMENTS
start_row (series int) The index of the row of the first cell to merge. Numbering starts at 0.
end_column (series int) The index of the column of the last cell to merge. Numbering starts at 0.
end_row (series int) The index of the row of the last cell to merge. Numbering starts at 0.
EXAMPLE
//@version=6
indicator("table.merge_cells example")
SMA50 = [Link](close, 50)
SMA100 = [Link](close, 100)
SMA200 = [Link](close, 200)
if [Link]
maTable = [Link](position.bottom_right, 3, 3, bgcolor = [Link], border_width = 1, border_col
or = [Link])
// Header
[Link](maTable, 0, 0, text = "SMA Table")
table.merge_cells(maTable, 0, 0, 2, 0)
// Cell Titles
[Link](maTable, 0, 1, text = "SMA 50")
[Link](maTable, 1, 1, text = "SMA 100")
[Link](maTable, 2, 1, text = "SMA 200")
// Values
[Link](maTable, 0, 2, bgcolor = [Link], text = [Link](SMA50))
[Link](maTable, 1, 2, bgcolor = [Link], text = [Link](SMA100))
[Link](maTable, 2, 2, bgcolor = [Link], text = [Link](SMA200))
REMARKS
This function will merge cells, even if their properties are not yet defined with [Link]().
The resulting merged cell inherits all of its values from the cell located at start_column : start_row , except
width and height. The width and height of the resulting merged cell are based on the width/height of other cells in the
neighboring columns/rows and cannot be set manually.
To modify the merged cell with any of the table.cell_set_* functions, target the cell at the start_column : st
art_row coordinates.
An attempt to merge a cell that has already been merged will result in an error.
SEE ALSO
[Link]() [Link]()
[Link]()
The function creates a new table.
SYNTAX
ARGUMENTS
position (series string) Position of the table. Possible values are: position.top_left, position.top_center,
position.top_right, position.middle_left, position.middle_center, position.middle_right, position.bottom_left,
position.bottom_center, position.bottom_right.
bgcolor (series color) The background color of the table. Optional. The default is no color.
frame_color (series color) The color of the outer frame of the table. Optional. The default is no color.
frame_width (series int) The width of the outer frame of the table. Optional. The default is 0.
border_color (series color) The color of the borders of the cells (excluding the outer frame). Optional. The default is
no color.
border_width (series int) The width of the borders of the cells (excluding the outer frame). Optional. The default is 0.
force_overlay (const bool) If true, the drawing will display on the main chart pane, even when the script occupies a
separate pane. Optional. The default is false.
EXAMPLE
//@version=6
indicator("[Link] example")
var testTable = [Link](position = position.top_right, columns = 2, rows = 1, bgcolor = [Link]
w, border_width = 1)
if [Link]
[Link](table_id = testTable, column = 0, row = 0, text = "Open is " + [Link](open))
[Link](table_id = testTable, column = 1, row = 0, text = "Close is " + [Link](close), bgc
olor=[Link])
RETURNS
REMARKS
This function creates the table object itself, but the table will not be displayed until its cells are populated. To define a
cell and change its contents or attributes, use [Link]() and other table.cell_*() functions.
One [Link]() call can only display one table (the last one drawn), but the function itself will be recalculated on each
bar it is used on. For performance reasons, it is wise to use [Link]() in conjunction with either the var keyword (so
the table object is only created on the first bar) or in an if [Link] block (so the table object is only created on
the last bar).
SEE ALSO
table.set_bgcolor()
The function sets the background color of a table.
SYNTAX
table.set_bgcolor(table_id, bgcolor) → void
ARGUMENTS
SEE ALSO
table.set_frame_width() table.set_position()
table.set_border_color()
The function sets the color of the borders (excluding the outer frame) of the table's cells.
SYNTAX
ARGUMENTS
border_color (series color) The color of the borders. Optional. The default is no color.
SEE ALSO
table.set_frame_width() table.set_position()
table.set_border_width()
The function sets the width of the borders (excluding the outer frame) of the table's cells.
SYNTAX
ARGUMENTS
border_width (series int) The width of the borders. Optional. The default is 0.
SEE ALSO
table.set_border_color() table.set_position()
table.set_frame_color()
The function sets the color of the outer frame of a table.
SYNTAX
ARGUMENTS
SEE ALSO
table.set_frame_width() table.set_position()
table.set_frame_width()
The function set the width of the outer frame of a table.
SYNTAX
ARGUMENTS
frame_width (series int) The width of the outer frame of the table. Optional. The default is 0.
SEE ALSO
table.set_border_color() table.set_position()
table.set_position()
The function sets the position of a table.
SYNTAX
ARGUMENTS
position (series string) Position of the table. Possible values are: position.top_left, position.top_center,
position.top_right, position.middle_left, position.middle_center, position.middle_right, position.bottom_left,
position.bottom_center, position.bottom_right.
SEE ALSO
table.set_frame_color() table.set_frame_width()
[Link]() 2 overloads
ARGUMENTS
//@version=6
indicator("[Link]", overlay=true)
heikinashi_close = [Link]([Link]([Link]), [Link], close)
RETURNS
SEE ALSO
[Link]() 2 overloads
Constructs a ticker ID for the specified symbol with additional parameters inherited from the ticker ID passed into
the function call, allowing the script to request a symbol's data using the same modifiers that the from_tickerid
has, including extended session, dividend adjustment, currency conversion, non-standard chart types, back-
adjustment, settlement-as-close, etc.
ARGUMENTS
symbol (simple string) The symbol to construct the new ticker ID for.
EXAMPLE
//@version=6
indicator("[Link]")
//@variable The `close` price requested using "NASDAQ:MSFT" with inherited modifiers.
secData = [Link](testSymbolHAtickerExtHours, "60", close, ignore_invalid_symbol = true)
//@variable The `close` price requested using "NASDAQ:MSFT" without modifiers.
compareData = [Link](testSymbol, "60", close, ignore_invalid_symbol = true)
REMARKS
If the constructed ticker ID inherits a modifier that doesn't apply to the symbol (e.g., if the from_tickerid has
Extended Hours enabled, but no such option is available for the symbol ), the script will ignore the modifier when
requesting data using the ID.
[Link]() 4 overloads
ARGUMENTS
EXAMPLE
//@version=6
indicator("[Link]", overlay=true)
kagi_tickerid = [Link]([Link], 3)
kagi_close = [Link](kagi_tickerid, [Link], close)
plot(kagi_close)
RETURNS
SEE ALSO
[Link]()
[Link]() 2 overloads
ARGUMENTS
EXAMPLE
//@version=6
indicator("[Link]", overlay=true)
linebreak_tickerid = [Link]([Link], 3)
linebreak_close = [Link](linebreak_tickerid, [Link], close)
plot(linebreak_close)
RETURNS
SEE ALSO
[Link]()
[Link]() 2 overloads
Creates a ticker identifier for requesting additional data for the script.
ARGUMENTS
tickerid (simple string) Symbol name with exchange prefix, e.g. 'BATS:MSFT', 'NASDAQ:MSFT' or tickerid with
session and adjustment from the [Link]() function.
session (simple string) Session type. Optional argument. Possible values: [Link], [Link]. Session
type of the current chart is [Link]. If session is not given, then [Link] value is used.
adjustment (simple string) Adjustment type. Optional argument. Possible values: [Link], [Link],
[Link]. If adjustment is not given, then default adjustment value is used (can be different depending on
particular instrument).
backadjustment (simple backadjustment) Specifies whether past contract data on continuous futures symbols is
back-adjusted. This setting only affects the data from symbols with this option available on their charts. Optional. The
default is [Link], meaning that the modified ticker ID inherits the setting from the ticker ID passed to
the tickerid parameter, or it inherits the symbol's default if the tickerid does not specify this setting. Possible
values: [Link], [Link], [Link].
settlement_as_close (simple settlement) Specifies whether a futures symbol's close value represents the actual
closing price or the settlement price on "1D" and higher timeframes. This setting only affects the data from symbols
with this option available on their charts. Optional. The default is settlement_as_close.inherit, meaning that the
modified ticker ID inherits the setting from the tickerid passed into the function, or it inherits the chart symbol's
default if the tickerid does not specify this setting. Possible values: settlement_as_close.inherit,
settlement_as_close.on, settlement_as_close.off.
EXAMPLE
//@version=6
indicator("ticker_modify", overlay=true)
t1 = [Link]([Link], [Link], [Link], [Link])
c1 = [Link](t1, "D", close)
t2 = [Link](t1, [Link])
c2 = [Link](t2, "2D", close)
plot(c1)
plot(c2)
RETURNS
SEE ALSO
[Link] [Link] [Link] [Link] [Link] [Link]()
[Link]() 2 overloads
Creates a ticker identifier for requesting additional data for the script.
ARGUMENTS
prefix (simple string) Exchange prefix. For example: 'BATS', 'NYSE', 'NASDAQ'. Exchange prefix of main series is
[Link].
ticker (simple string) Ticker name. For example 'AAPL', 'MSFT', 'EURUSD'. Ticker name of the main series is
[Link].
session (simple string) Session type. Optional argument. Possible values: [Link], [Link]. Session
type of the current chart is [Link]. If session is not given, then [Link] value is used.
adjustment (simple string) Adjustment type. Optional argument. Possible values: [Link], [Link],
[Link]. If adjustment is not given, then default adjustment value is used (can be different depending on
particular instrument).
backadjustment (simple backadjustment) Specifies whether past contract data on continuous futures symbols is
back-adjusted. This setting only affects the data from symbols with this option available on their charts. Optional. The
default is [Link], meaning that the new ticker ID inherits the symbol's default setting. Possible values:
[Link], [Link], [Link].
settlement_as_close (simple settlement) Specifies whether a futures symbol's close value represents the actual
closing price or the settlement price on "1D" and higher timeframes. This setting only affects the data from symbols
with this option available on their charts. Optional. The default is settlement_as_close.inherit, meaning that the new
ticker ID inherits the chart symbol's default setting. Possible values: settlement_as_close.inherit,
settlement_as_close.on, settlement_as_close.off.
EXAMPLE
//@version=6
indicator("[Link]", overlay=true)
t = [Link]([Link], [Link], [Link], [Link])
t2 = [Link](t)
c = [Link](t2, [Link], low, barmerge.gaps_on)
plot(c, style=plot.style_linebr)
RETURNS
REMARKS
You may use return value of [Link]() function as input argument for [Link](), [Link](),
[Link](), [Link](), [Link]() functions.
SEE ALSO
[Link] [Link] [Link] [Link] [Link] [Link]()
[Link]() 2 overloads
ARGUMENTS
style (simple string) Specifies the ticker's box size assignment method. Possible values: "ATR" for Average True
Range sizing, "Traditional" to use a fixed size, or "PercentageLTP" to use a percentage of the last trading price.
param (simple int/float) Represents the ticker's "ATR length" value if the style value is "ATR", "Box size" value if
the style is "Traditional", or "Percentage" value if the style is "PercentageLTP".
EXAMPLE
//@version=6
indicator("[Link]", overlay=true)
pnf_tickerid = [Link]([Link], "hl", "Traditional", 1, 3)
pnf_close = [Link](pnf_tickerid, [Link], close)
plot(pnf_close)
RETURNS
SEE ALSO
[Link]() 2 overloads
ARGUMENTS
style (simple string) Specifies the ticker's box size assignment method. Possible values: "ATR" for Average True
Range sizing, "Traditional" to use a fixed size, or "PercentageLTP" to use a percentage of the last trading price.
param (simple int/float) Represents the ticker's "ATR length" value if the style value is "ATR", "Box size" value if
the style is "Traditional", or "Percentage" value if the style is "PercentageLTP".
request_wicks (simple bool) Specifies if wick values are returned for Renko bricks. When true, high and low values
requested from a symbol using the ticker formed by this function will include wick values when they are present. When
false, high and low will always be equal to either open or close. Optional. The default is false. A detailed explanation of
how Renko wicks are calculated can be found in our Help Center.
source (simple string) The source used to calculate bricks. Optional. Possible values: "Close", "OHLC". The default is
"Close".
EXAMPLE
//@version=6
indicator("[Link]", overlay=true)
renko_tickerid = [Link]([Link], "ATR", 10)
renko_close = [Link](renko_tickerid, [Link], close)
plot(renko_close)
EXAMPLE
//@version=6
indicator("Renko candles", overlay=false)
renko_tickerid = [Link]([Link], "ATR", 10)
[renko_open, renko_high, renko_low, renko_close] = [Link](renko_tickerid, [Link], [
open, high, low, close])
plotcandle(renko_open, renko_high, renko_low, renko_close, color = renko_close > renko_open ? [Link]
en : [Link])
RETURNS
SEE ALSO
[Link]()
[Link]() 2 overloads
Creates a ticker to request data from a standard chart that is unaffected by modifiers like extended session, dividend
adjustment, currency conversion, and the calculations of non-standard chart types: Heikin Ashi, Renko, etc. Among
other things, this makes it possible to retrieve standard chart values when the script is running on a non-standard
chart.
ARGUMENTS
symbol (simple string) A ticker ID to be converted into its standard form. Optional. The default is [Link].
EXAMPLE
//@version=6
indicator("[Link]", overlay = true)
// This script should be run on a non-standard chart such as HA, Renko...
// Requests data from the chart type the script is running on.
chartTypeValue = [Link]([Link], "1D", close)
// Request data from the standard chart type, regardless of the chart type the script is running on.
standardChartValue = [Link]([Link]([Link]), "1D", close)
// This will not use a standard ticker ID because the `symbol` argument contains only the ticker — not
the prefix (exchange).
standardChartValue2 = [Link]([Link]([Link]), "1D", close)
plot(chartTypeValue)
plot(standardChartValue, color = [Link])
RETURNS
A string representing the ticker of a standard chart in the "prefix:ticker" format. If the symbol argument does not
contain the prefix and ticker information, the function returns the supplied argument as is.
SEE ALSO
[Link]()
time() 2 overloads
Returns the opening UNIX timestamp for the specified timeframe and session, or na if the time point is outside the
session.
ARGUMENTS
timeframe (series string) The timeframe of the timestamp calculation. If the value is an empty string, the function
uses the script's main timeframe.
session (series string) Optional. The session string for filtering times. The function returns a timestamp if the time is
in the specified session, or na if the time is outside the session. If the argument is an empty string, the function uses
the default, which is the symbol's session.
bars_back (series int) Optional. The bar offset on the script's main timeframe. If the value is positive, the function
finds the bar that is N bars before the current bar on the main timeframe, then retrieves the timestamp of the
corresponding bar on the timeframe specified by the timeframe argument. If the value is a negative number from
-1 to -500, the function calculates the expected timestamp of the timeframe bar corresponding to N bars after the
current bar on the main timeframe. The default is 0.
timeframe_bars_back (series int) Optional. The additional bar offset on the timeframe specified by the timefram
e argument. If the value is positive, the function retrieves the timestamp of the bar that is N timeframe bars before
the one corresponding to the bars_back offset. If the value is a negative number from -1 to -500, the function
calculates the expected timestamp of the timeframe bar that is N timeframe bars after the one corresponding
to the bars_back offset. The default is 0.
EXAMPLE
//@version=6
indicator("Time", overlay=true)
// Try this on chart AAPL,1
timeinrange(res, sess) => not na(time(res, sess, "America/New_York")) ? 1 : 0
plot(timeinrange("1", "1300-1400"), color=[Link])
While setting up a session you can specify not just the hours and minutes but also the days of the week that will be
included in that session.
If the days aren't specified, the session is considered to have been set from Sunday (1) to Saturday (7), i.e. "1100-
2000" is the same as "1100-1200:1234567".
You can change that by specifying the days. For example, on a symbol that is traded seven days a week with the 24-
hour trading session the following script will not color Saturdays and Sundays:
EXAMPLE
//@version=6
indicator("Time", overlay=true)
t1 = time([Link], "0000-0000:23456")
bgcolor(not na(t1) ? [Link]([Link], 90) : na)
One session argument can include several different sessions, separated by commas. For example, the following
script will highlight the bars from 10:00 to 11:00 and from 14:00 to 15:00 (workdays only):
EXAMPLE
//@version=6
indicator("Time", overlay=true)
t1 = time([Link], "1000-1100,1400-1500:23456")
bgcolor(not na(t1) ? [Link]([Link], 90) : na)
RETURNS
REMARKS
UNIX time is a standardized date and time representation that measures the number of non-leap seconds elapsed
since January 1, 1970 at 00:00:00 UTC. Pine Script expresses UNIX time values in milliseconds. See the UNIX
timestamps section of the User Manual's Time page to learn more.
SEE ALSO
time
time_close() 2 overloads
Returns the closing UNIX timestamp for the specified timeframe and session, or na if the time point is outside the
session. On tick charts and price-based charts such as Renko, line break, Kagi, point & figure, and range, the function
returns na on the latest realtime bar because the future closing time is unpredictable. However, it returns a valid
timestamp for any previous bar.
ARGUMENTS
timeframe (series string) The timeframe of the timestamp calculation. If the value is an empty string, the function
uses the script's main timeframe.
session (series string) Optional. The session string for filtering times. The function returns a timestamp if the time is
in the specified session, or na if the time is outside the session. If the argument is an empty string, the function uses
the default, which is the symbol's session.
bars_back (series int) Optional. The bar offset on the script's main timeframe. If the value is positive, the function
finds the bar that is N bars before the current bar on the main timeframe, then retrieves the timestamp of the
corresponding bar on the timeframe specified by the timeframe argument. If the value is a negative number from
-1 to -500, the function calculates the expected timestamp of the timeframe bar corresponding to N bars after the
current bar on the main timeframe. The default is 0.
timeframe_bars_back (series int) Optional. The additional bar offset on the timeframe specified by the timefram
e argument. If the value is positive, the function retrieves the timestamp of the bar that is N timeframe bars before
the one corresponding to the bars_back offset. If the value is a negative number from -1 to -500, the function
calculates the expected timestamp of the timeframe bar that is N timeframe bars after the one corresponding
to the bars_back offset. The default is 0.
EXAMPLE
//@version=6
indicator("Time", overlay=true)
t1 = time_close([Link], "1200-1300", "America/New_York")
bgcolor(not na(t1) ? [Link]([Link], 90) : na)
RETURNS
REMARKS
UNIX time is a standardized date and time representation that measures the number of non-leap seconds elapsed
since January 1, 1970 at 00:00:00 UTC. Pine Script expresses UNIX time values in milliseconds. See the UNIX
timestamps section of the User Manual's Time page to learn more.
SEE ALSO
time_close
[Link]()
Detects changes in the specified timeframe .
SYNTAX
ARGUMENTS
timeframe (series string) String formatted according to the User manual's timeframe string specifications.
EXAMPLE
//@version=6
// Run this script on an intraday chart.
indicator("New day started", overlay = true)
// Highlights the first bar of the new day.
isNewDay = [Link]("1D")
bgcolor(isNewDay ? [Link]([Link], 80) : na)
RETURNS
timeframe.from_seconds() 2 overloads
EXAMPLE
//@version=6
indicator("HTF Close", "", true)
int chartTf = timeframe.in_seconds()
string tfTimes5 = timeframe.from_seconds(chartTf * 5)
float htfClose = [Link]([Link], tfTimes5, close)
plot(htfClose)
RETURNS
REMARKS
If no valid timeframe exists for the quantity of seconds supplied, the next higher valid timeframe will be returned.
Accordingly, one second or less will return "1S", 2-5 seconds will return "5S", and 604,799 seconds (one second less
than 7 days) will return "7D".
If the seconds exactly represent two or more valid timeframes, the one with the larger base unit will be used. Thus
604,800 seconds (7 days) returns "1W", not "7D".
SEE ALSO
timeframe.in_seconds() 2 overloads
ARGUMENTS
timeframe (simple string) Timeframe string in timeframe string specifications format. Optional. The default is
[Link].
EXAMPLE
//@version=6
indicator("`timeframe_in_seconds()`"),
plot(secondsInTf)
RETURNS
REMARKS
When the timeframe is "1M" or more, calculations use 2628003 as the number of seconds in one month, which
represents 30.4167 (365/12) days.
SEE ALSO
timestamp() 6 overloads
ARGUMENTS
dateString (const string) A string containing the date and, optionally, the time and time zone. Its format must comply
with either the IETF RFC 2822 or ISO 8601 standards ("DD MMM YYYY hh:mm:ss ±hhmm" or "YYYY-MM-
DDThh:mm:ss±hh:mm", so "20 Feb 2020" or "2020-02-20"). If no time is supplied, "00:00" is used. If no time zone is
supplied, GMT+0 will be used. Note that this diverges from the usual behavior of the function where it returns time in
the exchange's timezone.
EXAMPLE
//@version=6
indicator("timestamp")
plot(timestamp(2016, 01, 19, 09, 30), linewidth=3, color=[Link])
plot(timestamp([Link], 2016, 01, 19, 09, 30), color=[Link])
plot(timestamp(2016, 01, 19, 09, 30), color=[Link])
plot(timestamp("GMT+6", 2016, 01, 19, 09, 30))
plot(timestamp(2019, 06, 19, 09, 30, 15), color=[Link])
plot(timestamp("GMT+3", 2019, 06, 19, 09, 30, 15), color=[Link])
plot(timestamp("Feb 01 2020 22:10:05"))
plot(timestamp("2011-10-10T14:48:00"))
plot(timestamp("04 Dec 1995 00:12:00 GMT+5"))
RETURNS
UNIX time.
REMARKS
UNIX time is the number of milliseconds that have elapsed since 00:00:00 UTC, 1 January 1970.
SEE ALSO
volume_row.buy_volume()
Returns the buy volume in the specified volume_row .
SYNTAX
ARGUMENTS
RETURNS
volume_row.delta()
Returns the volume delta (buy volume − sell volume) in the specified volume_row .
SYNTAX
ARGUMENTS
RETURNS
volume_row.down_price()
Returns the lower boundary of the price interval for the specified volume_row .
SYNTAX
ARGUMENTS
RETURNS
volume_row.has_buy_imbalance()
Returns true if the specified volume_row contains a buy imbalance according to the imbalance_percent
used in [Link]() .
SYNTAX
ARGUMENTS
RETURNS
volume_row.has_sell_imbalance()
Returns true if the specified volume_row contains a sell imbalance according to the imbalance_percent
used in [Link]() .
SYNTAX
ARGUMENTS
RETURNS
volume_row.sell_volume()
Returns the sell volume in the specified volume_row .
SYNTAX
ARGUMENTS
RETURNS
volume_row.total_volume()
Returns the total traded volume (buy + sell) in the specified volume_row .
SYNTAX
ARGUMENTS
RETURNS
volume_row.up_price()
Returns the upper boundary of the price interval for the specified volume_row .
SYNTAX
ARGUMENTS
RETURNS
weekofyear()
Calculates the week number of the year, in a specified time zone, from a UNIX timestamp.
SYNTAX
ARGUMENTS
timezone (series string) Optional. Specifies the time zone of the returned week number. The value can be a time
zone string in UTC/GMT offset notation (e.g., "UTC-5") or IANA time zone database notation (e.g.,
"America/New_York"). The default is [Link].
RETURNS
REMARKS
A UNIX timestamp represents the number of milliseconds elapsed since 00:00 UTC on 1970-01-01. The meaning of a
UNIX timestamp does not change relative to any time zone.
SEE ALSO
year()
SYNTAX
ARGUMENTS
timezone (series string) Allows adjusting the returned value to a time zone specified in either UTC/GMT notation
(e.g., "UTC-5", "GMT+0530") or as an IANA time zone database name (e.g., "America/New_York"). Optional. The
default is [Link].
RETURNS
REMARKS
UNIX time is the number of milliseconds that have elapsed since 00:00:00 UTC, 1 January 1970.
Note that this function returns the year based on the time of the bar's open. For overnight sessions (e.g. EURUSD,
where Monday session starts on Sunday, 17:00 UTC-4) this value can be lower by 1 than the year of the trading day.
SEE ALSO
Keywords
and
Logical AND. Applicable to boolean expressions.
SYNTAX
REMARKS
If expr1 evaluates to false, the and operator returns false without evaluating expr2 .
enum
This keyword allows the creation of an enumeration, enum for short. Enums are unique constructs that hold groups of
predefined constants.
Each field in an enum has a const string title. Scripts can access the fields in an enum using dot notation, similar
to accessing the fields of a user-defined type.
Each field represents a value of the enumName enum. Scripts can declare each field in an enum with an optional co
nst string title. If a field's title is not specified, its title is the string representation of its name. Use [Link]() on
an enum field to retrieve its title.
SYNTAX
One can use an enum to quickly create a dropdown input with the help of the [Link]() function. The options that
appear in the dropdown represent the titles of the enum fields.
EXAMPLE
//@version=6
indicator("Session highlight", overlay = true)
Additionally, one can use an enum in a collection's type template to restrict the values it will allow as elements. When
used inside a type template, the collection will only accept fields that belong to the specified enum.
EXAMPLE
//@version=6
indicator("Map with enum keys")
//@variable A map that accepts fields from the `symbols` enum as keys and "float" values.
map<symbols, float> data = [Link]<symbols, float>()
// Put key-value pairs into the `data` map.
[Link]([Link], [Link]([Link]([Link]), [Link], close))
[Link]([Link], [Link]([Link]([Link]), [Link], close))
[Link]([Link], [Link]([Link]([Link]), [Link], close))
// Plot the value from the `data` map accessed by the `[Link]` key.
plot([Link]([Link]))
export
Used in libraries to prefix the declaration of functions or user-defined type definitions that will be available from other
scripts importing the library.
EXAMPLE
//@version=6
//@description Library of debugging functions.
library("Debugging_library", overlay = true)
//@function Displays a string as a table cell for debugging purposes.
//@param txt String to display.
//@returns Void.
export print(string txt) =>
var table t = [Link](position.middle_right, 1, 1)
[Link](t, 0, 0, txt, bgcolor = [Link])
// Using the function from inside the library to show an example on the published chart.
// This has no impact on scripts using the library.
print("Library Test")
REMARKS
Each library must have at least one exported function or user-defined type (UDT).
Exported functions cannot use variables from the global scope if they are arrays, mutable variables (reassigned with :
= ), or variables of 'input' form.
Exported functions must explicitly declare each parameter's type and all parameters must be used in the function's
body. By default, all arguments passed to exported functions are of the series form, unless they are explicitly specified
as simple in the function's signature.
The @description, @function, @param, @type, @field, and @returns compiler annotations are used to automatically
generate the library's description and release notes, and in the Pine Script® Editor's tooltips.
SEE ALSO
for
Creates a count-controlled loop, which uses a counter variable to manage the iterative executions of its local code
block. The loop continues new iterations until the counter reaches a specified final value.
SYNTAX
counter (series int/float) The counter variable. The loop increments the variable's value from the initial value ( from_
num ) to the final value ( to_num ) by a fixed amount ( step_num ) after each iteration. The last possible iteration
occurs when the variable's value reaches the to_num value.
from_num (series int/float) The value of the counter variable on the loop's first iteration.
to_num (series int/float) The final counter value for which the loop's header allows a new iteration. The loop
increments the counter value by the step_num until it reaches or passes this value. If the script modifies this
value during a loop iteration, the loop header uses the new value to control the allowed subsequent iterations.
step_num (series int/float) Optional. A positive value specifying the amount by which the counter value increases
or decreases until it reaches or passes the to_num value. If the from_num value is greater than the initial to_num
value, the loop subtracts this amount from the counter value after each iteration. Otherwise, the loop adds this
amount after each iteration. The default is 1.
statements The code statements and expressions within the loop's body, i.e., the indented block of code beneath the
loop header.
return_expression (any type) The last expression or statement within the loop's body. The loop returns the results
from this code after the final iteration. If the loop stops prematurely due to a continue or break statement, the
returned values or references are those of the latest iteration that evaluated this code. To use the loop's returned
results, assign them to a variable or tuple.
continue A loop-specific keyword that instructs the script to skip the remainder of the current loop iteration and
continue to the next iteration.
break A loop-specific keyword that prompts the script to stop the current iteration and exit the loop entirely.
EXAMPLE
//@version=6
indicator("Basic `for` loop")
//@function Calculates the number of bars in the last `length` bars that have their `close` above the c
urrent `close`.
//@param length The number of bars used in the calculation.
greaterCloseCount(length) =>
int result = 0
for i = 1 to length
if close[i] > close
result += 1
result
plot(greaterCloseCount(14))
EXAMPLE
//@version=6
indicator("`for` loop with a step")
a = [Link](0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
sum = 0.0
for i = 0 to 9 by 5
// Because the step is set to 5, we are adding only the first (0) and the sixth (5) value from the
array `a`.
sum += [Link](a, i)
plot(sum)
REMARKS
Modifying a loop's to_num value during an iteration does not change the direction of the loop's counter. For a loop
that counts upward, setting the to_num to a value less than the from_num value on an iteration stops the loop
immediately after that iteration ends. Likewise, a loop that counts downward stops after an iteration where the to_nu
m value becomes greater than the from_num value.
If a script initializes a variable declared with var or varip using a loop's result, the loop stops after the first iteration,
even if the header's criteria allow more iterations. Instead of initializing the variable with the result of this structure
directly, declare the variable first and use := to update it with the result. Alternatively, move the loop into a Declaring
functions and initialize the variable using a call to that function.
See the Loops page of our User Manual to learn more about loops and how they work.
SEE ALSO
for...in while
for...in
Creates a collection-controlled loop, which iterates over the elements of an array, the rows of a matrix, or the key-
value pairs of a map in order. The loop's local code block executes once for each element, row, or pair in the specified
collection.
SYNTAX
variables (return_expression type) - Optional. A variable or tuple to hold the values or references from the last
evaluation of return_expression after the loop terminates. The script can assign the loop's returned results to
variables only if the results are not of the "void" type. If the loop's conditions prevent iteration, or if no iterations
evaluate return_expression , the variables' assigned values or references are na, or false if the return type is
"bool".
index - A variable to track the array element index, matrix row index, or map key of the current iteration. The loop
cannot modify this variable using reassignment or compound assignment operators. This variable is valid only in the
second form of the loop structure.
item - A variable to track the array element, matrix row, or map value element of the current iteration. The loop cannot
modify this variable using reassignment or compound assignment operators.
collection_id (array/matrix/map) - The ID of the array, matrix, or map whose items the loop iterates over.
statements - The code statements and expressions within the loop's body, i.e., the indented block of code beneath
the loop header.
return_expression (any type) - The last expression or statement within the loop's body. The loop returns the results
from this code after the final iteration. If the loop stops prematurely due to a continue or break statement, the
returned values or references are those of the latest iteration that evaluated this code. To use the loop's returned
results, assign them to a variable or tuple.
continue - A loop-specific keyword that instructs the script to skip the remainder of the current loop iteration and
continue to the next iteration.
break - A loop-specific keyword that prompts the script to stop the current iteration and exit the loop entirely.
The following example uses the first form of the for...in loop to count the number of array element values that are
greater than a specified value:
EXAMPLE
//@version=6
indicator("'for...in' array (first form) demo")
//@function Counts the number of 'id' array elements that are greater than the specified value.
numGreaterThan(array<float> id, float value) =>
int result = 0
for element in id
if element > value
result += 1
result
// Plot the number of 'ohlcValues' elements that are greater than the 20-bar SMA of 'close'.
plot(numGreaterThan(ohlcValues, [Link](close, 20)))
The example below uses the second form of the loop structure to perform element-wise addition between two arrays:
EXAMPLE
//@version=6
indicator("`for...in` array (second form) demo")
//@function Creates a new array whose elements are the sums of corresponding elements in the `id1` and
`id2` arrays.
elementWiseAdd(array<float> id1, array<float> id2) =>
array<float> result = [Link]<float>()
// Loop through the `id1` array while tracking each element's index *and* value.
for [index, element1] in id1
// Use `index` to retrieve the corresponding element in the `id2` array, then push the sum int
o the new array.
float element2 = [Link](index)
[Link](element1 + element2)
result
if [Link]
// Create two arrays for which to perform element-wise addition.
array<float> array1 = [Link](1.0, 2.0, 3.0, 4.0)
array<float> array2 = [Link](2.0, 3.0, 4.0, 5.0)
This example uses the first form of the loop structure to iterate over the rows of a matrix and create an array containing
each one's sum. The header's loop variable, rowArrayID , references an array containing the current row's values:
EXAMPLE
//@version=6
indicator("`for...in` matrix (first form) demo")
//@function Creates a matrix that organizes the contents of the `arrayID` array into a specified shape.
matrixFromArray(array<float> arrayID, int rows, int columns) =>
matrix<float> result = [Link]<float>()
result.add_row(0, arrayID)
[Link](rows, columns)
result
//@function Creates an array containing the sum of elements in each row of the `matrixID` matrix.
calcRowSums(matrix<float> matrixID) =>
array<float> result = [Link]<float>()
// Iterate over the matrix rows, where `rowArrayID` references an *array* containing the current ro
w's values.
for rowArrayID in matrixID
// Push the sum of `rowArrayID` elements into the `result` array.
[Link]([Link]())
result
if [Link]
// Create a 2x2 matrix of pseudorandom values.
array<float> randArray = [Link]([Link](), [Link](), [Link](), [Link]())
matrix<float> randMat = matrixFromArray(randArray, 2, 2)
// Log string representation of the `randMat` matrix and the calculated array of row sums in the Pi
ne Logs pane.
[Link]("\n" + [Link](randMat))
[Link]([Link](calcRowSums(randMat)))
The following example uses a for...in loop to iterate over a map's key-value pairs and construct a custom string
representation of its contents:
EXAMPLE
//@version=6
indicator("`for...in` map demo")
//@function Creates a custom string representation of a map containing "string" keys and "float" value
s.
toString(map<string, float> id) =>
string result = "{"
// Iterate through the key-value pairs of the `id` map, in insertion order.
for [key, value] in id
result += [Link]("''{0}'': {1}, ", key, value)
result += "}"
result := [Link](result, ", }", "}")
if [Link]
//@variable References a map to store "float" OHLC values with corresponding "string" keys.
map<string, float> ohlcMap = [Link]<string, float>()
// Put key-value pairs into the map.
[Link]("Open", open)
[Link]("High", high)
[Link]("Low", low)
[Link]("Close", close)
// Log the `toString()` result for the map referenced by `ohlcMap`.
[Link](toString(ohlcMap))
REMARKS
Only the second form of the for...in loop is compatible with maps. The loop iterates over the key-value pairs of a
map in the insertion order of its keys.
Scripts can modify the sizes of arrays and matrices while iterating over their contents with a for...in loop.
However, they cannot modify the sizes of maps while looping over them directly with this structure. To modify a map
while using a for...in loop, use the loop on a copy of the map or on the map's [Link]() array.
If a script initializes a variable declared with var or varip using a loop's result, the loop stops after the first iteration,
even if the header's criteria allow more iterations. Instead of initializing the variable with the result of this structure
directly, declare the variable first and use := to update it with the result. Alternatively, move the loop into a Declaring
functions and initialize the variable using a call to that function.
See the Loops page of our User Manual to learn more about loops and how they work.
SEE ALSO
if
If statement defines what block of statements must be executed when conditions of the expression are satisfied.
To have access to and use the if statement, one should specify the version >= 2 of Pine Script® language in the very
first line of code, for example: //@version=6
The 4th version of Pine Script® Language allows you to use “else if” syntax.
General code form:
SYNTAX
var_declarationX = if condition
var_decl_then0
var_decl_then1
…
var_decl_thenN
else if [optional block]
var_decl_else0
var_decl_else1
…
var_decl_elseN
else
var_decl_else0
var_decl_else1
…
var_decl_elseN
return_expression_else
where
If the condition is false, the logic from the block 'else' (var_decl_else0, var_decl_else1, etc.) is used.
return_expression_then, return_expression_else — the last expression from the block then or from the block else
will return the final value of the statement. If declaration of the variable is in the end, its value will be the result.
The type of returning value of the if statement depends on return_expression_then and return_expression_else type
(their types must match: it is not possible to return an integer value from then, while you have a string value in else
block).
EXAMPLE
//@version=6
indicator("if")
// This code compiles
x = if close > open
close
else
open
It is possible to omit the else block. In this case if the condition is false, an “empty” value (na, false, or “”) will be
assigned to the var_declarationX variable:
EXAMPLE
//@version=6
indicator("if")
x = if close > open
close
// If current close > current open, then x = close.
// Otherwise the x = na.
plot(x)
It is possible to use either multiple “else if” blocks or none at all. The blocks “then”, “else if”, “else” are shifted by four
spaces:
EXAMPLE
//@version=6
indicator("if")
x = if open > close
5
else if high > low
close
else
open
plot(x)
It is possible to ignore the resulting value of an if statement (“var_declarationX=“ can be omitted). It may be useful if
you need the side effect of the expression, for example in strategy trading:
EXAMPLE
//@version=6
strategy("if")
if ([Link](high, low))
[Link]("BBandLE", [Link], stop=low, oca_name="BollingerBands", oca_type=[Link]
[Link], comment="BBandLE")
else
[Link](id="BBandLE")
EXAMPLE
//@version=6
indicator("if")
float x = na
if close > open
if close > close[1]
x := close
else
x := close[1]
else
x := open
plot(x)
import
Used to load an external library() into a script and bind its functions to a namespace. The importing script can be an
indicator, a strategy, or another library. A library must be published (privately or publicly) before it can be imported.
SYNTAX
ARGUMENTS
EXAMPLE
//@version=6
indicator("num_methods import")
// Import the first version of the username’s "num_methods" library and assign it to the "m" namespac
e",
import username/num_methods/1 as m
// Call the “sinh()” function from the imported library
y = [Link](3.14)
// Plot value returned by the "sinh()" function",
plot(y)
REMARKS
Using an alias that replaces a built-in namespace such as math.* or strategy.* is allowed, but if the library contains
function names that shadow Pine Script®'s built-in functions, the built-ins will become unavailable. The same version
of a library can only be imported once. Aliases must be distinct for each imported library. When calling library
functions, casting their arguments to types other than their declared type is not allowed. An import statement cannot
use 'as' or 'import' as username , libraryName , or alias identifiers.
SEE ALSO
library() export
method
This keyword is used to prefix a function declaration, indicating it can then be invoked using dot notation by appending
its name to a variable of the type of its first parameter and omitting that first parameter. Alternatively, functions
declared as methods can also be invoked like normal user-defined functions. In that case, an argument must be
supplied for its first parameter.
SYNTAX
EXAMPLE
//@version=6
indicator("")
//@function Pushes a new value into the array and removes the first one if the resulting array is great
er than `maxSize`. Can be used as a method.
method maintainArray(array<float> id, maxSize, value) =>
[Link](value)
if [Link]() > maxSize
[Link]()
[Link](50, close)
// The method can also be called like a function, without using dot notation.
// In this case an argument must be supplied for its first parameter.
// maintainArray(prices, 50, close)
// This calls the `[Link]()` built-in using dot notation with the `prices` array.
// It is possible because built-in functions belonging to some namespaces that are a special Pine type
// can be invoked with method notation when the function's first parameter is an ID of that type.
// Those namespaces are: `array`, `matrix`, `line`, `linefill`, `label`, `box`, and `table`.
plot([Link]())
not
Logical negation (NOT). Applicable to boolean expressions.
SYNTAX
not expr1
RETURNS
or
Logical OR. Applicable to boolean expressions.
SYNTAX
expr1 or expr2
RETURNS
REMARKS
If expr1 evaluates to true, the or operator returns true without evaluating expr2 .
switch
The switch operator transfers control to one of the several statements, depending on the values of a condition and
expressions.
SYNTAX
[variable_declaration = ] switch
condition1 => local_block
condition2 => local_block
…
=> default_local_block
EXAMPLE
//@version=6
indicator("Switch using an expression")
string i_maType = [Link]("EMA", "MA type", options = ["EMA", "SMA", "RMA", "WMA"])
plot(ma)
EXAMPLE
//@version=6
strategy("Switch without an expression", overlay = true)
switch
longCondition => [Link]("Long ID", [Link])
shortCondition => [Link]("Short ID", [Link])
RETURNS
The value of the last expression in the local block of statements that is executed.
REMARKS
Only one of the local_block instances or the default_local_block can be executed. The default_local_
block is introduced with the => token alone and is only executed when none of the preceding blocks are executed.
If the result of the switch statement is assigned to a variable and a default_local_block is not specified, the
statement returns na if no local_block is executed. When assigning the result of the switch statement to a
variable, all local_block instances must return the same type of value.
SEE ALSO
if ?:
type
This keyword allows the declaration of user-defined types (UDT) from which scripts can instantiate objects. UDTs are
composite types that contain an arbitrary number of fields of any built-in or user-defined type, including the defined
UDT itself. The syntax to define a UDT is:
SYNTAX
Once a UDT is defined, scripts can instantiate objects from it with the UDT_identifier.new() construct. When
creating a new type instance, the fields of the resulting object will initialize with the default values from the UDT's
definition. Any type fields without specified defaults will initialize as na. Alternatively, users can pass initial values as
arguments in the *.new() method to override the type's defaults. For example, newFooObject = [Link](x =
true) assigns a new foo object to the newFooObject variable with its x field initialized using a value of true.
Field declarations can include the varip keyword, in which case the field values persist between successive script
iterations on the same bar.
For more information see the User Manual's sections on defining UDTs and using objects.
Libraries can export UDTs. See the Libraries page of our User Manual to learn more.
EXAMPLE
//@version=6
indicator("Multi Time Period Chart", overlay = true)
timeframeInput = [Link]("1D")
type bar
float o = open
float h = high
float l = low
float c = close
int t = time
if not na(secBar)
// To avoid a runtime error, only process data when an object exists.
if not [Link]
if [Link](timeframeInput)
// On historical bars, draw a new box in the past when the HTF closes.
drawBox(secBar, time[1])
else
var box lastBox = na
if na(lastBox) or [Link](timeframeInput)
// On the last bar, only draw a new current box the first time we get there or when HTF cha
nges.
lastBox := drawBox(secBar, time)
else
// On other chart updates, use setters to modify the current box.
updateBox(lastBox, secBar)
var
var is the keyword used for assigning and one-time initializing of the variable.
Normally, a syntax of assignment of variables, which doesn’t include the keyword var, results in the value of the
variable being overwritten with every update of the data. Contrary to that, when assigning variables with the keyword
var, they can “keep the state” despite the data updating, only changing it when conditions within if-expressions are
met.
SYNTAX
where:
variable_name - any name of the user’s variable that’s allowed in Pine Script® (can contain capital and lowercase
Latin characters, numbers, and underscores (_), but can’t start with a number).
expression - any arithmetic expression, just as with defining a regular variable. The expression will be calculated and
assigned to a variable once.
EXAMPLE
//@version=6
indicator("Var keyword example")
var a = close
var b = 0.0
var c = 0.0
var green_bars_count = 0
if close > open
var x = close
b := x
green_bars_count := green_bars_count + 1
if green_bars_count >= 10
var y = close
c := y
plot(a)
plot(b)
plot(c)
The variable 'a' keeps the closing price of the first bar for each bar in the series.
The variable 'b' keeps the closing price of the first "green" bar in the series.
The variable 'c' keeps the closing price of the tenth "green" bar in the series.
varip
varip (var intrabar persist) is the keyword used for the assignment and one-time initialization of a variable or a field of
a user-defined type. It’s similar to the var keyword, but variables and fields declared with varip retain their values
between executions of the script on the same bar.
SYNTAX
varip [<variable_type> ]<variable_name> = <expression>
where:
variable_type - An optional fundamental type (int, float, bool, color, string) or a user-defined type, or an array or
matrix of one of those types. Special types are not compatible with this keyword.
variable_name - A valid identifier. The variable can also be an object created from a UDT.
expression - Any arithmetic expression, just as when defining a regular variable. The expression will be calculated and
assigned to the variable only once, on the first bar.
UDT_identifier, field_type, field_name, value - Constructs related to user-defined types as described in the type
section.
EXAMPLE
//@version=6
indicator("varip")
varip int v = -1
v := v + 1
plot(v)
With var, v would equal the value of the bar_index. On historical bars, where the script calculates only once per chart
bar, the value of v is the same as with var. However, on realtime bars, the script will evaluate the expression on each
new chart update, producing a different result.
EXAMPLE
//@version=6
indicator("varip with types")
type barData
int index = -1
varip int ticks = -1
The same += operation applied to both the index and ticks fields results in different real-time values because t
icks increases on every chart update, while index only does so once per bar. Note how the currBar object
does not use the varip keyword. The ticks field of the object can increment on every tick, but the reference itself is
defined once and then stays unchanged. If we were to declare currBar using varip, the behavior of index would
remain unchanged because while the reference to the type instance would persist between chart updates, the index
field of the object would not.
REMARKS
When using varip to declare variables in strategies that may execute more than once per historical chart bar, the values
of such variables are preserved across successive iterations of the script on the same bar.
The effect of varip eliminates the rollback of variables before each successive execution of a script on the same bar.
while
Creates a condition-controlled loop whose local code block executes repeatedly while the value of a conditional
expression remains true . The loop's iterations end after the condition's value becomes false .
SYNTAX
variables (return_expression type) - Optional. A variable or tuple to hold the values or references from the last
evaluation of return_expression after the loop terminates. The script can assign the loop's returned results to
variables only if the results are not of the "void" type. If the loop's conditions prevent iteration, or if no iterations
evaluate return_expression , the variables' assigned values or references are na, or false if the return type is
"bool".
condition (series bool) - The conditional expression that controls the loop's iterations. If true , the script performs
a new iteration. If false , the script exits the loop without performing a new iteration.
statements - The code statements and expressions within the loop's body, i.e., the indented block of code beneath
the loop header.
return_expression (any type) - The last expression or statement within the loop's body. The loop returns the results
from this code after the final iteration. If the loop stops prematurely due to a continue or break statement, the
returned values or references are those of the latest iteration that evaluated this code. To use the loop's returned
results, assign them to a variable or tuple.
continue - A loop-specific keyword that instructs the script to skip the remainder of the current loop iteration and
continue to the next iteration.
break - A loop-specific keyword that prompts the script to stop the current iteration and exit the loop entirely.
EXAMPLE
//@version=6
indicator("`while` demo")
if [Link]
// Repeatedly multiply `factorial` by `counter` and decrease the `counter` value by 1.
// The loop ends after the value of `counter` becomes 0.
while counter > 0
factorial *= counter
counter -= 1
plot(factorial, "N!")
REMARKS
If a script initializes a variable declared with var or varip using a loop's result, the loop stops after the first iteration,
even if the header's criteria allow more iterations. Instead of initializing the variable with the result of this structure
directly, declare the variable first and use := to update it with the result. Alternatively, move the loop into a Declaring
functions and initialize the variable using a call to that function.
See the Loops page of our User Manual to learn more about loops and how they work.
Types
array
Keyword used to explicitly declare the "array" type of a variable or a parameter. Array objects (or IDs) can be created
with the [Link]<type>(), [Link]() function.
EXAMPLE
//@version=6
indicator("array", overlay=true)
array<float> a = na
a := [Link]<float>(1, close)
plot([Link](a, 0))
REMARKS
SEE ALSO
bool
Keyword used to explicitly declare the "bool" (boolean) type of a variable or a parameter. "Bool" variables can have
values true or false.
EXAMPLE
//@version=6
indicator("bool")
bool b = true // Same as `b = true`
plot(b ? open : close)
REMARKS
Explicitly mentioning the type in a variable declaration is optional. Learn more about Pine Script® types in the User
Manual page on the Type System.
SEE ALSO
box
Keyword used to explicitly declare the "box" type of a variable or a parameter. Box objects (or IDs) can be created with
the [Link]() function.
EXAMPLE
//@version=6
indicator("box")
// Empty `box1` box ID.
var box box1 = na
// `box` type is unnecessary because `[Link]()` returns a "box" type.
var box2 = [Link](na, na, na, na)
box3 = [Link](time, open, time + 60 * 60 * 24, close, xloc=xloc.bar_time)
REMARKS
SEE ALSO
[Link]
Keyword to explicitly declare the type of a variable or parameter as [Link] . Scripts can produce [Link]
nt instances using the [Link].from_time(), [Link].from_index(), [Link](), and [Link]()
functions.
FIELDS
index (series int) The x-coordinate of the point, expressed as a bar index value.
time (series int) The x-coordinate of the point, expressed as a UNIX time value, in milliseconds.
SEE ALSO
polyline
color
Keyword used to explicitly declare the "color" type of a variable or a parameter.
EXAMPLE
//@version=6
indicator("color", overlay = true)
// When declaring variables with color literals, built-in constants([Link]) or functions ([Link]
w(), [Link]()), the "color" keyword for the type can be omitted.
c = [Link](0,255,0,0)
plot(close, color = c)
REMARKS
Color literals have the following format: #RRGGBB or #RRGGBBAA. The letter pairs represent 00 to FF hexadecimal
values (0 to 255 in decimal) where RR, GG and BB pairs are the values for the color's red, green and blue components.
AA is an optional value for the color's transparency (or alpha component) where 00 is invisible and FF opaque. When
no AA pair is supplied, FF is used. The hexadecimal letters can be upper or lower case.
Explicitly mentioning the type in a variable declaration is optional, except when it is initialized with na. Learn more
about Pine Script® types in the User Manual page on the Type System.
SEE ALSO
const
The const keyword explicitly assigns the "const" type qualifier to variables and the parameters of non-exported
functions. Variables and parameters with the "const" qualifier reference values established at compile time that never
change in the script's execution.
In variable declarations, the compiler can usually infer the qualified type automatically based on the values assigned to
a variable, and it can automatically change a variable's qualifier to a stronger one when necessary. The type qualifier
hierarchy is "const" < "input" < "simple" < "series", where "const" is the weakest.
Explicitly declaring a variable with the const keyword restricts the type qualifier to "const", meaning the variable
cannot accept a value with a stronger qualifier (e.g., "input"), nor can the value assigned to the variable change at any
point in the script's execution.
When using this keyword to specify the type qualifier, one must also use a type keyword to declare the allowed type.
SYNTAX
[method ]<functionName>([const <paramType> ]<paramName>[ = <defaultValue>])
EXAMPLE
//@version=6
indicator("custom plot title")
plot(close, myTitle)
EXAMPLE
//@version=6
indicator("can't assign input to const")
//@variable A variable declared as "const float" that attempts to assign the result of `[Link]()`
as its value.
// This declaration causes an error. The "input float" qualified type is stronger than "const
float".
const float myVar = [Link](2.0)
plot(myVar)
REMARKS
SEE ALSO
simple series
float
Keyword used to explicitly declare the "float" (floating point) type of a variable or a parameter.
EXAMPLE
//@version=6
indicator("float")
float f = 3.14 // Same as `f = 3.14`
f := na
plot(f)
REMARKS
Explicitly mentioning the type in a variable declaration is optional, except when it is initialized with na. Learn more
about Pine Script® types in the User Manual page on the Type System.
SEE ALSO
footprint
Keyword to explicitly declare the type of a variable or parameter as footprint . Script can produce footprint
instances using the [Link]() function.
SEE ALSO
int
Keyword used to explicitly declare the "int" (integer) type of a variable or a parameter.
EXAMPLE
//@version=6
indicator("int")
int i = 14 // Same as `i = 14`
i := na
plot(i)
REMARKS
Explicitly mentioning the type in a variable declaration is optional, except when it is initialized with na. Learn more
about Pine Script® types in the User Manual page on the Type System.
SEE ALSO
label
Keyword used to explicitly declare the "label" type of a variable or a parameter. Label objects (or IDs) can be created
with the [Link]() function.
EXAMPLE
//@version=6
indicator("label")
// Empty `label1` label ID.
var label label1 = na
// `label` type is unnecessary because `[Link]()` returns "label" type.
var label2 = [Link](na, na, na)
if [Link]
label3 = [Link](bar_index, high, text = "label3 text")
REMARKS
SEE ALSO
line
Keyword used to explicitly declare the "line" type of a variable or a parameter. Line objects (or IDs) can be created with
the [Link]() function.
EXAMPLE
//@version=6
indicator("line")
// Empty `line1` line ID.
var line line1 = na
// `line` type is unnecessary because `[Link]()` returns "line" type.
var line2 = [Link](na, na, na, na)
line3 = [Link](bar_index - 1, high, bar_index, high, extend = [Link])
REMARKS
SEE ALSO
linefill
Keyword used to explicitly declare the "linefill" type of a variable or a parameter. Linefill objects (or IDs) can be created
with the [Link]() function.
EXAMPLE
//@version=6
indicator("linefill", overlay=true)
// Empty `linefill1` line ID.
var linefill linefill1 = na
// `linefill` type is unnecessary because `[Link]()` returns "linefill" type.
var linefill2 = [Link](na, na, na)
if [Link]
line1 = [Link](bar_index - 10, high+1, bar_index, high+1, extend = [Link])
line2 = [Link](bar_index - 10, low+1, bar_index, low+1, extend = [Link])
linefill3 = [Link](line1, line2, color = [Link]([Link], 80))
REMARKS
SEE ALSO
map
Keyword used to explicitly declare the "map" type of a variable or a parameter. Map objects (or IDs) can be created
with the [Link]<type,type>() function.
EXAMPLE
//@version=6
indicator("map", overlay=true)
map<int, float> a = na
a := [Link]<int, float>()
[Link](bar_index, close)
[Link](bar_index, [Link](bar_index), "Current close")
REMARKS
SEE ALSO
[Link]<type,type>()
matrix
Keyword used to explicitly declare the "matrix" type of a variable or a parameter. Matrix objects (or IDs) can be created
with the [Link]<type>() function.
EXAMPLE
//@version=6
indicator("matrix example")
// `matrix<int>` is unnecessary because the `[Link]<int>()` function returns an `int` type matrix o
bject.
m2 = [Link]<int>(2, 3, 0)
REMARKS
SEE ALSO
polyline
Keyword to explicitly declare the type of a variable or parameter as polyline . Scripts can produce polyline
instances using the [Link]() function.
SEE ALSO
[Link]
series
The series keyword explicitly assigns the "series" type qualifier to variables and function parameters. Variables and
parameters that use the "series" qualifier can reference values that change throughout a script's execution.
Explicit use of the series keyword when declaring the parameters of a library's exported functions is typically
unnecessary, as the compiler can usually automatically detect whether a parameter is compatible with "series" or
"simple" qualified values. By default, all exported function parameters are qualified as "series" wherever possible.
In variable declarations, the compiler can usually infer the qualified type automatically based on the values assigned to
a variable, and it can automatically change a variable's qualifier to a stronger one when necessary. The type qualifier
hierarchy is "const" < "input" < "simple" < "series", where "series" is the strongest.
Explicitly declaring a variable with the series keyword restricts the type qualifier to "series", meaning the script
cannot pass its value to any variable or function parameter that requires a value with a weaker qualifier ("const",
"input", or "simple").
When using this keyword to specify the type qualifier, one must also use a type keyword to declare the allowed type.
SYNTAX
EXAMPLE
//@version=6
//@description A library with custom functions.
library("CustomFunctions", overlay = true)
//@function Finds the highest `source` value over `length` bars, filtered by the `cond` condition.
export conditionalHighest(series float source, series bool cond, series int length) =>
//@variable The highest `source` value from when the `cond` was `true` over `length` bars.
series float result = na
// Loop to find the highest value.
for i = 0 to length - 1
if cond[i]
value = source[i]
result := [Link](nz(result, value), value)
// Return the `result`.
result
//@variable The highest `close` value from every fifth bar over the last 100 bars.
series float hiValue = conditionalHighest(close, condition, 100)
plot(hiValue)
bgcolor(condition ? [Link]([Link], 80) : na)
EXAMPLE
//@version=6
indicator("series variable not allowed")
REMARKS
SEE ALSO
simple const
simple
The simple keyword explicitly assigns the "simple" type qualifier to variables and function parameters. Variables
and parameters that use the "simple" qualifier can reference values established at the beginning of a script's execution
that do not change later.
To restrict the parameters in a library's exported functions to only allow values with a "simple" or weaker type qualifier,
using the simple keyword when declaring parameters is often necessary, as libraries automatically qualify all
parameters as "series" wherever possible by default. Explicitly restricting functions to accept "simple" arguments also
allows them to return "simple" values in some cases, depending on the operations they execute, making them usable
with the parameters of built-in functions that do not allow "series" arguments.
In variable declarations, the compiler can usually infer the qualified type automatically based on the values assigned to
a variable, and it can automatically change a variable's qualifier to a stronger one when necessary. The type qualifier
hierarchy is "const" < "input" < "simple" < "series", where "simple" is stronger than "input" and "const".
Explicitly declaring a variable with the simple keyword restricts the type qualifier to "simple", meaning the script
cannot pass its value to any variable or function parameter that requires a value with a weaker qualifier ("const" or
"input"). Additionally, one cannot assign a "series" value to a variable explicitly declared with the simple keyword.
When using this keyword to specify the type qualifier, one must also use a type keyword to declare the allowed type.
SYNTAX
export [method ]<functionName>([[simple ]<paramType>] <paramName>[ = <defaultValue>])
EXAMPLE
//@version=6
//@description A library with custom functions.
library("CustomFunctions", overlay = true)
//@function Calculates the length values for a ribbon of four EMAs by multiplying the `baseLeng
th`.
//@param baseLength The initial EMA length. Requires "simple int" because you can't use "series int" i
n `[Link]()`.
//@returns A tuple of length values.
export ribbonLengths(simple int baseLength) =>
simple int length1 = baseLength
simple int length2 = baseLength * 2
simple int length3 = baseLength * 3
simple int length4 = baseLength * 4
[length1, length2, length3, length4]
EXAMPLE
//@version=6
indicator("can't change simple to series")
plot(myVar)
REMARKS
SEE ALSO
series const
string
Keyword used to explicitly declare the "string" type of a variable or a parameter.
EXAMPLE
//@version=6
indicator("string")
string s = "Hello World!" // Same as `s = "Hello world!"`
// string s = na // same as ""
plot(na, title=s)
REMARKS
Explicitly mentioning the type in a variable declaration is optional, except when it is initialized with na. Learn more
about Pine Script® types in the User Manual page on the Type System.
SEE ALSO
table
Keyword used to explicitly declare the "table" type of a variable or a parameter. Table objects (or IDs) can be created
with the [Link]() function.
EXAMPLE
//@version=6
indicator("table")
// Empty `table1` table ID.
var table table1 = na
// `table` type is unnecessary because `[Link]()` returns "table" type.
var table2 = [Link](position.top_left, na, na)
if [Link]
var table3 = [Link](position = position.top_right, columns = 1, rows = 1, bgcolor = [Link]
w, border_width = 1)
[Link](table_id = table3, column = 0, row = 0, text = "table3 text")
REMARKS
SEE ALSO
volume_row
Keyword to explicitly declare the type of a variable or parameter as volume_row . Script can produce volume_row
instances using the [Link](), [Link](), [Link]() functions.
SEE ALSO
Operators
-
Subtraction or unary minus. Applicable to numerical expressions.
SYNTAX
expr1 - expr2
RETURNS
REMARKS
You may use arithmetic operators with numbers as well as with series variables. In case of usage with series the
operators are applied elementwise.
-=
Subtraction assignment. Applicable to numerical expressions.
SYNTAX
expr1 -= expr2
EXAMPLE
//@version=6
indicator("-=")
// Equals to expr1 = expr1 - expr2.
a = 2
b = 3
a -= b
// Result: a = -1.
plot(a)
RETURNS
:=
Reassignment operator. It is used to assign a new value to a previously declared variable.
SYNTAX
<var_name> := <new_value>
EXAMPLE
//@version=6
indicator("My script")
myVar = 10
plot(myVar)
!=
Inequality operator. Returns true if the operands are considered not equal, and false otherwise. This operator is
compatible with all value types, including "int", "float", "bool", "color", and "string". The operator can also compare two
line or label IDs.
SYNTAX
expr1 != expr2
RETURNS
REMARKS
?:
Ternary conditional operator.
SYNTAX
EXAMPLE
//@version=6
indicator("?:")
// Draw circles at the bars where open crosses close
s2 = [Link](open, close) ? [Link](open,close) : na
plot(s2, style=plot.style_circles, linewidth=2, color=[Link])
RETURNS
expr2 if expr1 is evaluated to true, expr3 otherwise. Zero value (0 and also NaN, +Infinity, -Infinity) is considered to be
false, any other value is true.
REMARKS
You can combine two or more ?: operators to achieve the equivalent of a 'switch'-like statement (see examples above).
You may use arithmetic operators with numbers as well as with series variables. In case of usage with series the
operators are applied elementwise.
SEE ALSO
na
[]
Series subscript. Provides access to previous values of series expr1. expr2 is the number of bars back, and must be
numerical. Floats will be rounded down.
SYNTAX
expr1[expr2]
EXAMPLE
//@version=6
indicator("[]")
// [] can be used to "save" variable value between bars
a = 0.0 // declare `a`
a := a[1] // immediately set current value to the same as previous. `na` in the beginning of history
if high == low // if some condition - change `a` value to another
a := low
plot(a)
RETURNS
A series of values.
SEE ALSO
[Link]()
*
Multiplication. Applicable to numerical expressions.
SYNTAX
expr1 * expr2
RETURNS
*=
Multiplication assignment. Applicable to numerical expressions.
SYNTAX
expr1 *= expr2
EXAMPLE
//@version=6
indicator("*=")
// Equals to expr1 = expr1 * expr2.
a = 2
b = 3
a *= b
// Result: a = 6.
plot(a)
RETURNS
/
Division. Applicable to numerical expressions.
SYNTAX
expr1 / expr2
RETURNS
/=
Division assignment. Applicable to numerical expressions.
SYNTAX
expr1 /= expr2
EXAMPLE
//@version=6
indicator("/=")
// Equals to expr1 = expr1 / expr2.
float a = 3.0
b = 3
a /= b
// Result: a = 1.
plot(a)
RETURNS
%
Modulo (integer remainder). Applicable to numerical expressions.
SYNTAX
expr1 % expr2
RETURNS
REMARKS
In Pine Script®, when the integer remainder is calculated, the quotient is truncated, i.e. rounded towards the lowest
absolute value. The resulting value will have the same sign as the dividend.
%=
Modulo assignment. Applicable to numerical expressions.
SYNTAX
expr1 %= expr2
EXAMPLE
//@version=6
indicator("%=")
// Equals to expr1 = expr1 % expr2.
a = 3
b = 3
a %= b
// Result: a = 0.
plot(a)
RETURNS
+
Addition or unary plus. Applicable to numerical expressions or strings.
SYNTAX
expr1 + expr2
RETURNS
Unary + returns expr (does nothing added just for the symmetry with the unary - operator).
REMARKS
You may use arithmetic operators with numbers as well as with series variables. In case of usage with series the
operators are applied elementwise.
+=
Addition assignment. Applicable to numerical expressions or strings.
SYNTAX
expr1 += expr2
EXAMPLE
//@version=6
indicator("+=")
// Equals to expr1 = expr1 + expr2.
a = 2
b = 3
a += b
// Result: a = 5.
plot(a)
RETURNS
For strings returns concatenation of expr1 and expr2. For numbers returns integer or float value, or series of values.
REMARKS
You may use arithmetic operators with numbers as well as with series variables. In case of usage with series the
operators are applied elementwise.
<
Less than. Applicable to numerical expressions.
SYNTAX
RETURNS
<=
Less than or equal to. Applicable to numerical expressions.
SYNTAX
RETURNS
=
Assignment operator. Assigns an initial value or reference to a declared variable. It means this is a new variable, and it
starts with this value.
SYNTAX
<var_name> := <initial_value>
EXAMPLE
//@version=6
indicator("`=` showcase")
// The following are all valid variable declarations.
i = 1
MS_IN_ONE_MINUTE = 1000 * 60
showPlotInput = [Link](true, "Show plots")
pHi = [Link](5, 5)
plotColor = [Link]
==
Equality operator. Returns true if the operands are considered equal, and false otherwise. This operator is compatible
with all value types, including "int", "float", "bool", "color", and "string". The operator can also compare two line or label
IDs.
SYNTAX
expr1 == expr2
RETURNS
REMARKS
=>
The '=>' operator is used in user-defined function declarations and in switch statements.
The function declaration syntax is:
SYNTAX
//@version=6
indicator("=>")
// single-line function
f1(x, y) => x + y
// multi-line function
f2(x, y) =>
sum = x + y
sumChange = [Link](sum, 10)
// Function automatically returns the last expression used in it
plot(f1(30, 8) + f2(1, 3))
REMARKS
You can learn more about user-defined functions in the User Manual's pages on Declaring functions and Libraries.
>
Greater than. Applicable to numerical expressions.
SYNTAX
RETURNS
>=
Greater than or equal to. Applicable to numerical expressions.
SYNTAX
RETURNS
Annotations
@description
Sets a custom description for scripts that use the library() declaration statement. The text provided with this
annotation will be used to pre-fill the "Description" field in the publication dialogue.
EXAMPLE
//@version=6
// @description Provides a tool to quickly output a label on the chart.
library("MyLibrary")
EXAMPLE
//@version=6
indicator("Session highlight", overlay = true)
@field
If placed above a type or enum declaration, it adds a custom description for a field of the type/enum. After the
annotation, users should specify the field name, followed by its description.
The Pine Editor's autosuggest uses this description and displays it when a user hovers over the type/enum or field
name. When used in library() scripts, the descriptions of all types/enums using the export keyword will pre-fill the
"Description" field in the publication dialogue.
EXAMPLE
//@version=6
indicator("New high over the last 20 bars", overlay = true)
//@variable If the current `high` is the highest over the last 20 bars, returns a new `Point` instanc
e, `na` otherwise.
Point highest = na
if [Link](high, 20) == 0
highest := [Link](bar_index, high)
[Link]([Link], [Link], [Link]([Link]))
@function
If placed above a function declaration, it adds a custom description for the function.
The Pine Editor's autosuggest uses this description and displays it when a user hovers over the function name. When
used in library() scripts, the descriptions of all functions using the export keyword will pre-fill the "Description" field in
the publication dialogue.
EXAMPLE
//@version=6
// @description Provides a tool to quickly output a label on the chart.
library("MyLibrary")
@param
If placed above a function declaration, it adds a custom description for a function parameter. After the annotation,
users should specify the parameter name, then its description.
The Pine Editor's autosuggest uses this description and displays it when a user hovers over the function name. When
used in library() scripts, the descriptions of all functions using the export keyword will pre-fill the "Description" field in
the publication dialogue.
EXAMPLE
//@version=6
// @description Provides a tool to quickly output a label on the chart.
library("MyLibrary")
@returns
If placed above a function declaration, it adds a custom description for what that function returns.
The Pine Editor's autosuggest uses this description and displays it when a user hovers over the function name. When
used in library() scripts, the descriptions of all functions using the export keyword will pre-fill the "Description" field in
the publication dialogue.
EXAMPLE
//@version=6
// @description Provides a tool to quickly output a label on the chart.
library("MyLibrary")
@strategy_alert_message
If used within a strategy() script, it provides a default message to pre-fill the "Message" field in the alert creation
dialogue.
EXAMPLE
//@version=6
strategy("My strategy", overlay=true, margin_long=100, margin_short=100)
//@strategy_alert_message Strategy alert on symbol {{ticker}}
@type
If placed above a type declaration, it adds a custom description for the type.
The Pine Editor's autosuggest uses this description and displays it when a user hovers over the type name. When used
in library() scripts, the descriptions of all types using the export keyword will pre-fill the "Description" field in the
publication dialogue.
EXAMPLE
//@version=6
indicator("New high over the last 20 bars", overlay = true)
//@variable If the current `high` is the highest over the last 20 bars, returns a new `Point` instanc
e, `na` otherwise.
Point highest = na
if [Link](high, 20) == 0
highest := [Link](bar_index, high)
[Link]([Link], [Link], [Link]([Link]))
@variable
If placed above a variable declaration, it adds a custom description for the variable.
The Pine Editor's autosuggest uses this description and displays it when a user hovers over the variable name.
EXAMPLE
//@version=6
indicator("New high over the last 20 bars", overlay = true)
//@variable If the current `high` is the highest over the last 20 bars, returns a new `Point` instanc
e, `na` otherwise.
Point highest = na
if [Link](high, 20) == 0
highest := [Link](bar_index, high)
[Link]([Link], [Link], [Link]([Link]))
@version=
Specifies the Pine Script® version that the script will use. The number in this annotation should not be confused with
the script's version number, which updates on every saved change to the code.
EXAMPLE
//@version=6
indicator("Pine v6 Indicator")
plot(close)
EXAMPLE
REMARKS
The version should always be specified. Otherwise, for compatibility reasons, the script will be compiled using Pine
Script® v1, which lacks most of the newer features and is bound to confuse. This annotation can be anywhere within a
script, but we recommend placing it at the top of the code for readability.